Compare commits
No files matched your search
@@ -28,3 +28,14 @@ CODECRAFT_VERSION=latest
|
|||||||
|
|
||||||
# Log format: empty for text, "json" for one JSON object per line
|
# Log format: empty for text, "json" for one JSON object per line
|
||||||
CODECRAFT_LOG_FORMAT=
|
CODECRAFT_LOG_FORMAT=
|
||||||
|
|
||||||
|
# Test runner (optional): the factory's acceptance runs start the app under test in a
|
||||||
|
# throw-away container instead of inside CodeCraft. Uncomment all four lines.
|
||||||
|
#COMPOSE_PROFILES=runner
|
||||||
|
#CODECRAFT_RUNNER_URL=http://testrunner:8788
|
||||||
|
#RUNNER_TOKEN= # random string, at least 16 characters (openssl rand -hex 24)
|
||||||
|
#DOCKER_GID=999 # stat -c %g /var/run/docker.sock
|
||||||
|
# Optional limits per environment and the image used when .factory/setup.json names none:
|
||||||
|
#RUNNER_MEMORY=2g
|
||||||
|
#RUNNER_CPUS=2
|
||||||
|
#RUNNER_DEFAULT_IMAGE=git.familie-zink.org/zink/codecraft-testbase:latest
|
||||||
@@ -3,6 +3,361 @@
|
|||||||
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
|
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
|
||||||
until 1.0, minor versions may contain breaking changes.
|
until 1.0, minor versions may contain breaking changes.
|
||||||
|
|
||||||
|
## [v202611-00082] – 2026-11-27
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **The web UI uses Ant Design.** Buttons, fields, drop-downs, check boxes, tabs, dialogs and notices are Ant Design components for a uniform look. Their colours come from the app's theme variables, so all themes and the light/dark switch keep working; the language of the components follows the app. The first load grows by about 260 KB (gzip).
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory board:** every column has its own vertical scrollbar; its title stays visible.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Deleting the chat that is open left an empty page (the chat view rendered fewer hooks than before).
|
||||||
|
|
||||||
|
## [v202611-00081] – 2026-11-27
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Force a queued message.** While the agent works, a message you send is queued and delivered at the agent's next step. A further Enter on the empty input (terminal client and web UI) or Ctrl+Enter with text (web UI) now interrupts the running step and delivers the queued messages at once, so the model reads them immediately; the queue list in the web UI has a "Force now" button for the same. New endpoint `POST /api/sessions/{id}/queue/force`.
|
||||||
|
- **Web UI:** Ctrl+J inserts a new line in the message field, like Shift+Enter (and like Ctrl+J / Shift+Enter in the terminal client).
|
||||||
|
- **Terminal client:** messages waiting for the agent are shown above the input field (also for followed server chats).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Terminal client: long input and long questions are cut off.** The input field now wraps at its width instead of hiding the part beyond the edge, and questions, their options and your own answer in the question dialog wrap as well.
|
||||||
|
|
||||||
|
## [v202611-00080] – 2026-11-21
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Factory page made the server stall (HTTP 504, one CPU core at 100 %).** The overview sums tokens and cost of up to 300 runs per request from the `usage` table, which had no index on `session_id`: every request scanned the table 900 times (about 4 s while holding the database lock). The index `usage_session` makes it take milliseconds (measured on the production database: 4.0 s → 8 ms).
|
||||||
|
|
||||||
|
## [v202611-00079] – 2026-11-21
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Server binary keeps its symbols and line tables** (`strip = "none"`, `debug = "line-tables-only"` in the release profile), so a stack sample of the running server can be resolved to functions. The binary is a few tens of MB larger.
|
||||||
|
|
||||||
|
## [v202611-00078] – 2026-11-21
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Zombie processes:** the compose files start the containers with `init: true`, so children left behind by agents (Chromium, bwrap, npm) are reaped – a long-running container had collected about 1000 zombies.
|
||||||
|
- **Telegram:** request errors no longer contain the URL, which includes the bot token, so the token does not end up in the server log.
|
||||||
|
|
||||||
|
## [v202611-00077] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Shared base image for acceptance containers** (`git.familie-zink.org/zink/codecraft-testbase`, built from `docker/testbase/Dockerfile` by the release script): Node 24, Python 3, gcc/g++/make/cmake, Chromium with Playwright and common tools (git, curl, e2fsprogs, xz, zsh, sudo, jq, …). It is the runner's default image (`RUNNER_DEFAULT_IMAGE`), so setups that installed these again and again start faster; plain `node:24-bookworm` is the fallback if it cannot be pulled. Projects with their own `image` or `dockerfile` are unchanged.
|
||||||
|
- The runner also logs the apt packages an environment's setup installed (`apt installed: …`), to see what the base image still lacks.
|
||||||
|
|
||||||
|
## [v202611-00076] – 2026-11-20
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Test runner: the cache is now visible.** The runner logs for every environment how long it took until the app answered, whether the seed was a hit or a miss, and how long `install` took (e.g. `test env abc (git-…-penguin31) ready after 42 s; cache on; seed 07be…: hit; install took 3 s`).
|
||||||
|
|
||||||
|
## [v202611-00075] – 2026-11-20
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Factory: the "preparing" lamp** (checkout, test environment) now has a colour that differs from the theme's accent colour in every theme – the lamp of a running chat keeps the accent. Set per theme with the new variable `--prep`.
|
||||||
|
- **Factory overlay:** the chat's menu button is hidden in the overlay (it could only close the overlay).
|
||||||
|
|
||||||
|
## [v202611-00074] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Test runner: cache between acceptance runs.** Every project gets a cache volume (`cc-cache-<project>`) in the runner. Tool caches are shared automatically: npm and Yarn, pip, Go modules and build cache, the Cargo registry and the Cargo target directory (so the second build of a Rust project is incremental). `.factory/setup.json` can add `"cache": {"dirs": [...]}` for directories that persist (downloads – inputs only) and `"cache": {"seed": {"paths": [...], "key": [...]}}` for expensive *results* of `install`, such as a built disk image: the seed is stored after a successful install under a key made from the image, the install command, the seed paths and the contents of the `key` files, and copied into fresh containers only while the key matches – a run never sees changes of an earlier run, and a change of the listed sources builds it anew (the three newest seeds are kept). `"cache": false` turns everything off; `DELETE /v1/cache/<project>` on the runner forgets a project's cache.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Factory: merge and close on the issue card.** A finished issue shows a *Merge* button on its card once the acceptance has passed (the pull request is open); after the merge the card shows *Close*. Before that neither button is shown. The server enforces the order: a pull request is merged only when the acceptance passed, an issue is closed only when its pull request is merged (a merge done on the forge itself counts). The issue also gets its version and tag right after a merge instead of at the next poll.
|
||||||
|
|
||||||
|
## [v202611-00072] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: "preparing" lamp.** An issue card whose phase has been started but whose chat does not exist yet – checkout and, for acceptance, installing and starting the app in its throw-away container – shows a blinking blue lamp with the elapsed time instead of staying silent. (Active chats keep their accent-coloured lamp.)
|
||||||
|
|
||||||
|
## [v202611-00071] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Drafts in every chat.** What you have typed but not sent is kept: in the web UI and in the terminal client's server chats on the server (so you can continue on another device – it is picked up when you open or return to the chat, as long as you have no unsent edits of your own), in the terminal client's local chats in a file. Sending clears it.
|
||||||
|
- **Factory: chats open in an overlay on the desktop** (`#/factory/s/<id>`), closed with one click, Esc (outside text fields) or the back button, with a button to open the chat as a full page. Every issue card has an *open chat* button for the newest phase chat that still exists. On small screens chats still open as pages.
|
||||||
|
|
||||||
|
- **Factory main switch** at the top of the overview (web and PWA): green = running, yellow = stopping, red = stopped. Stopping is *soft*: no new review, build or acceptance starts, agents that are running finish their phase – the switch stays yellow until the last one is done, then turns red. Starting takes up work again at once. The state is kept across restarts; the board still updates while the factory is stopped. The colours come from the theme (new variables `--power-on`, `--power-warn`, `--power-off`, set in all 32 theme files).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The factory overview uses the full width of the window.
|
||||||
|
|
||||||
|
## [v202611-00070] – 2026-11-20
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Factory backlog:** the column is twice as wide and card titles stay on one line (the full title is in the tooltip).
|
||||||
|
|
||||||
|
## [v202611-00069] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: backlog column.** All open issues of the configured repositories that are not in the factory yet appear in a new column on the far left. Each card has a *Queue* button (and the column *Queue all*, with a confirmation): the issue gets the factory label on the forge and the factory takes it up straight away. Issues whose author may not file factory issues are shown but cannot be queued. The list is read from the forge (cached for a minute) and follows the project dropdown.
|
||||||
|
- **Factory: cards are tinted by status** – a faint background and border colour per state (review, question, approved, build, acceptance, failed, done), taken from the theme's own colours.
|
||||||
|
|
||||||
|
## [v202611-00068] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Test runner: `"isolated": false` in `.factory/setup.json`** for apps that cannot run in a container (a native window, a library) – acceptance starts them itself, as before. `ready_seconds` sets how long the runner waits for the port. Free text after the `url` (e.g. `http://localhost:8080 (trunk serve)`) no longer confuses the port detection.
|
||||||
|
|
||||||
|
## [v202611-00067] – 2026-11-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: acceptance runs in throw-away containers.** A new optional service, `testrunner` (`codecraft testrunner`, enabled with `COMPOSE_PROFILES=runner`), owns the Docker socket – the CodeCraft container does not. For every acceptance run it creates a private network, starts the app from `.factory/setup.json` in a fresh container (image, `install`, `start`, `port`, `env`; optionally built from a `dockerfile`) plus helper `services` such as a database, forwards the port to `localhost` for the agent, writes the app's log to `.factory/app.log` and removes everything afterwards. Sources are copied in, never mounted; capabilities are dropped, memory/CPU/process limits apply, and leftovers are swept at startup and after 90 minutes. Without the runner nothing changes: the agent starts the app itself.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Compose files: new optional `testrunner` service and `CODECRAFT_RUNNER_URL` / `RUNNER_TOKEN` in `.env.example`.
|
||||||
|
|
||||||
|
## [v202611-00066] – 2026-11-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Terminal client: steer the server.** `/projects` lists your chats on the server and opens one in the terminal – the agent keeps running on the server; you read along, send messages, answer permissions and questions, interrupt and compact. `/factory` shows the factory board and lets you merge pull requests, close, restart or remove issues and open the chat of any run; `/factory check` polls for new issues. `/local` returns to the local chat.
|
||||||
|
|
||||||
|
## [v202611-00065] – 2026-11-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Terminal client for Linux riscv64** – built with every release alongside x86_64 and aarch64; `install.sh` and `codecraft update` pick it up (`/cli/download/linux-riscv64`).
|
||||||
|
|
||||||
|
## [v202611-00064] – 2026-11-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: Telegram message when an issue needs you** – a question from the review (with the questions) or a failure (build blocked, build/acceptance failed, rework limit reached) is sent to the paired Telegram chat, in the language of your web UI, with a link to the issue. Nothing is sent without a paired bot. (v202611-00063 was tagged but never built; this ships with the next release.)
|
||||||
|
- **Telegram notification settings** (Settings → Telegram): a switch for the factory alerts and a **night mode** (default 22:00–06:00, adjustable, server time) in which nothing is sent on CodeCraft's own initiative – no factory alerts and no approvals/questions from other chats; the chat you are talking to in Telegram keeps answering. Held-back messages are not repeated later.
|
||||||
|
|
||||||
|
## [v202611-00062] – 2026-11-18
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: remove issues from the board** – a "Remove from board" button for issues that are not running, and issues deleted on the forge (404) disappear from the board by themselves at the next poll.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Factory: the "parallel" limit was exceeded** – phases were counted by their run rows, which appear only after the checkout, so one poll could start more phases than allowed (2 allowed, 4 running). They are now counted by issue state, which is set before a phase starts.
|
||||||
|
|
||||||
|
## [v202611-00061] – 2026-11-18
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Factory: project dropdown** instead of one button per project – choose "All projects" or a single one; the choice is remembered.
|
||||||
|
|
||||||
|
## [v202611-00060] – 2026-11-18
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **All uploads are chunked and show progress**: files page, chat attachments, new-session wizard, recreate dialog and backup restore upload in 8 MB chunks (no more reverse-proxy limits) with a progress panel – one bar per file and one for the total.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: recreate mode** ("Recreate software" next to "New project"): upload a program or give a source URL; an analyst chat (craft agent, deep mode, "recreate" skill) unpacks, decompiles and documents the original exhaustively, audits itself against a coverage list and writes a clean-room `spec.md` with milestones. Analysis, originals and notes stay in the private draft folder; the new repository gets only the specification, and the milestones are cut into issues afterwards.
|
||||||
|
|
||||||
|
## [v202611-00059] – 2026-11-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Collapsible chat list** on wide screens: the menu button in the title bar folds the chat list away (remembered), so chat menus are no longer hidden behind it on small monitors.
|
||||||
|
|
||||||
|
## [v202611-00058] – 2026-11-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **README and screenshots** brought up to date (code factory, skills, new interface); skills labels no longer say "1 files".
|
||||||
|
|
||||||
|
## [v202611-00057] – 2026-11-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: skills per phase.** In the repository settings, each phase (review, build, acceptance) can have
|
||||||
|
skills switched on; the chat of that phase follows them in every turn.
|
||||||
|
|
||||||
|
## [v202611-00056] – 2026-11-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Skills you manage yourself.** *Settings → Skills*: create skills (a folder with `SKILL.md` and further
|
||||||
|
files) in an editor, or import them from a GitHub repository or folder – every folder with a `SKILL.md` is
|
||||||
|
offered, with a filter and multi-select. They are stored per user.
|
||||||
|
- **Skills per chat.** Switch skills on for a chat (menu ⋯ → *Skills for this chat*): their full instructions
|
||||||
|
are part of every turn. All other skills cost no context: up to 12 skills are listed by name in the prompt, a
|
||||||
|
larger library is not listed at all – the agent finds a skill with `skill(query=…)` and reads its further
|
||||||
|
files with `skill(name, file)`.
|
||||||
|
|
||||||
|
## [v202611-00055] – 2026-11-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **New project from a Git repository:** the wizard no longer clones into the factory area by default
|
||||||
|
("target folder already exists" when the factory had checked out the same repository); your workspace is
|
||||||
|
preselected, and the factory area is labelled as such in the folder list.
|
||||||
|
|
||||||
|
## [v202611-00053] – 2026-11-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Factory versioning.** The current version is read from the tags on the forge, not from the checkout
|
||||||
|
(which kept tags that were deleted there and so counted from a stale version).
|
||||||
|
|
||||||
|
## [v202611-00054] – 2026-11-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **README:** new "Code factory" section explaining phases, scope, planning chats, versions and releases.
|
||||||
|
|
||||||
|
## [v202611-00052] – 2026-11-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Factory versioning.** Open issues of the forge were never seen (Gitea sends `"pull_request": null`), so every
|
||||||
|
deliverable counted as the last of its milestone and raised the minor version. Now only the last open issue of a
|
||||||
|
milestone raises the minor version; all others raise the patch version.
|
||||||
|
|
||||||
|
## [v202611-00051] – 2026-11-16
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: close finished issues.** A finished issue has a "Close issue" button: you write a comment, it is
|
||||||
|
posted on the issue on the forge, the issue is closed there, and only then it leaves the "Done" column.
|
||||||
|
Issues that are closed on the forge by other means (or by the version pass after the merge) leave "Done" too.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The "Done" column is now the rightmost column of the factory board.
|
||||||
|
|
||||||
|
## [v202611-00050] – 2026-11-16
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- The factory's planning chats (spec chat, "Plan a feature", "Cut a milestone") no longer run the review loop
|
||||||
|
of the agent mode (the "refine" rounds of build mode), which checked their answers as if they were code.
|
||||||
|
|
||||||
|
## [v202611-00049] – 2026-11-16
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory versions and tags.** Every merged factory issue (merged through the factory or on the forge)
|
||||||
|
gets a version: the patch number goes up with each issue (0.1.0 → 0.1.1); the issue that completes a
|
||||||
|
milestone (the last open `M1.x` issue) raises the minor number and restarts the patch (0.0.7 → 0.1.0).
|
||||||
|
The factory commits a `VERSION` file on the default branch, tags the commit `vX.Y.Z`, closes the issue
|
||||||
|
and notes the version in it. The version shows on the repository tile. Versioning starts with the next
|
||||||
|
merged issue; issues that were done before are not counted.
|
||||||
|
- **Factory release (0.x → 1.0.0 and on).** The new "Release" button makes a release you choose the
|
||||||
|
version of: `VERSION`, tag, the Docker image for amd64 and arm64 (buildx, pushed to the registry of the
|
||||||
|
image name), the source zip and further files, and the release on the forge (Gitea and GitHub attach the
|
||||||
|
files; GitLab gets the release without attachments). How to build is described in
|
||||||
|
`.factory/release.json` in the repository (`image`, `platforms`, `dockerfile`, `context`,
|
||||||
|
`build_args`, `commands`, `files`, `name`); without it only tag, release and source zip are made. The
|
||||||
|
dialog shows the recipe first, because its commands run on the server outside the sandbox.
|
||||||
|
- The image now contains the buildx plugin.
|
||||||
|
- **The factory's checkout of the default branch is pulled** (fast-forward) after every fetch, and right after
|
||||||
|
a merge is detected and the version commit is pushed – before, the review read the files of the first clone.
|
||||||
|
Local changes or a diverged branch are left alone with a warning.
|
||||||
|
- **Settings for repetitions** per repository: *Rework rounds* (how often a failed acceptance sends the
|
||||||
|
issue back to the build, default 2, 0 = never) and *Tries* per phase (how often a phase is repeated after
|
||||||
|
a technical failure such as a timeout, default 2).
|
||||||
|
|
||||||
|
## [v202611-00048] – 2026-11-16
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- The factory page showed a blank page since v202611-00047 (the new pull request panel declared its state
|
||||||
|
after an early return, which breaks React's hook order). The hooks now sit above the early returns.
|
||||||
|
|
||||||
|
## [v202611-00047] – 2026-11-16
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory: show and approve pull requests.** Selecting an issue shows its open pull request (state,
|
||||||
|
conflicts, files, +/− lines, link) with "Approve and merge" (merge commit, squash or rebase). Merging only
|
||||||
|
happens on your click after a confirmation; the factory itself still never merges.
|
||||||
|
- **Factory: plan with a model and file the issues.** "Plan a feature" starts a chat that works out a new
|
||||||
|
feature with you; "Cut a milestone" lets a model cut a milestone of the spec into numbered deliverables
|
||||||
|
("M2.1 – …"). The chat reads the repository and ends with an issue list; a dialog lets you tick and edit
|
||||||
|
the issues, which are then created on the forge with `Spec:` and `Scope:` lines and the prerequisites.
|
||||||
|
They get the factory label only if you ask for it, so you can start them one after the other.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- An accepted rework build now gets a new pull request when the earlier one was merged or closed already;
|
||||||
|
before, the commits of the rework rounds stayed on the branch without any pull request.
|
||||||
|
|
||||||
|
## [v202611-00046] – 2026-11-16
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Factory: the pull request is opened by the acceptance**, not by the build. A build only pushes its
|
||||||
|
branch `factory/issue-<n>`; once the acceptance passes, the pull request is created with the build
|
||||||
|
report and the result table (an existing one is kept).
|
||||||
|
- The factory has its own icon (a factory instead of a toolbox).
|
||||||
|
- All factory chats (spec chats, review, build, acceptance) are collected in one sidebar folder
|
||||||
|
"Factory"; existing ones are moved there on start.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Factory acceptance: scenarios outside the scope of the issue (stored scenarios that cover a whole
|
||||||
|
multi-milestone spec) get the result `out_of_scope` and no longer fail the issue. The acceptance
|
||||||
|
receives the build report to tell what the build claims to cover, and an acceptance in which no
|
||||||
|
scenario of the scope could be observed working does not pass.
|
||||||
|
|
||||||
|
## [v202611-00045] – 2026-11-16
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Factory acceptance: when the built branch has no `.factory/setup.json` (it was added to the default
|
||||||
|
branch later), the one from the default branch is used.
|
||||||
|
- Factory acceptance judged things outside the issue (e.g. later milestones of a large spec) and failed
|
||||||
|
the issue for them. Now only the listed scenarios count: the verdict follows the scenario results
|
||||||
|
(one failed scenario fails, unverified or out-of-scope gaps do not), and the prompts of review, build
|
||||||
|
and acceptance restrict the work to the issue's scope. An issue can name it with a `Scope: <name>`
|
||||||
|
line (e.g. `Scope: M1`); without one the review picks the first milestone that is not built yet.
|
||||||
|
|
||||||
|
## [v202611-00044] – 2026-11-16
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- The factory spec chat now also writes `setup.json` (how to install and start the app). Creating the
|
||||||
|
project files it as `.factory/setup.json` in the repository, where the acceptance phase reads it; the
|
||||||
|
create dialog warns when it is missing.
|
||||||
|
|
||||||
|
## [v202611-00043] – 2026-11-16
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Factory acceptance phase**: a finished build is checked by a different model. It starts the built
|
||||||
|
branch (as `.factory/setup.json` describes: `install`, `start`, `url`), goes through the acceptance
|
||||||
|
scenarios from the review – kept away from the builder – and uses the browser tool where it can.
|
||||||
|
Every scenario ends as pass, fail or *unverified*; unverified ones are reported openly and never
|
||||||
|
count as passed. One failed scenario sends the issue back to the build with the findings (at most
|
||||||
|
2 rework rounds, then `failed`); otherwise the issue is `done` and the pull request waits for you
|
||||||
|
to merge – the factory never merges.
|
||||||
|
- **Restart an issue** in the factory page (select an issue → "Restart at": review, build or
|
||||||
|
acceptance). Works for failed, rejected, done and waiting issues; restarting at review forgets the
|
||||||
|
stored scenarios, and restarts reset the retry counters.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Factory runs interrupted by a server restart continue where they were (builds in a rework round
|
||||||
|
resume as rework).
|
||||||
|
|
||||||
## [v202611-00042] – 2026-11-16
|
## [v202611-00042] – 2026-11-16
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ members = ["core", "server", "cli"]
|
|||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = 3
|
opt-level = 3
|
||||||
|
# Symbols and line tables stay in the binary, so a hot thread can be resolved with eu-stack / addr2line
|
||||||
|
# on the running server (the file grows by a few tens of MB).
|
||||||
|
strip = "none"
|
||||||
|
debug = "line-tables-only"
|
||||||
|
|
||||||
# The command line client is small and self-contained.
|
# The command line client is small and self-contained.
|
||||||
[profile.release.package.codecraft-cli]
|
[profile.release.package.codecraft-cli]
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ RUN touch core/src/lib.rs server/src/main.rs \
|
|||||||
&& cargo zigbuild --release -p codecraft --target "$(cat /target).2.36" \
|
&& cargo zigbuild --release -p codecraft --target "$(cat /target).2.36" \
|
||||||
&& cp "target/$(cat /target)/release/codecraft" /codecraft
|
&& cp "target/$(cat /target)/release/codecraft" /codecraft
|
||||||
|
|
||||||
# --- terminal client (static Linux binaries for x86_64 and aarch64) -----------
|
# --- terminal client (static Linux binaries for x86_64, aarch64 and riscv64) -----------
|
||||||
# Served by the server for download (/cli/install.sh, codecraft update).
|
# Served by the server for download (/cli/install.sh, codecraft update).
|
||||||
FROM toolchain AS cli
|
FROM toolchain AS cli
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
@@ -62,10 +62,12 @@ COPY server/resources ./server/resources
|
|||||||
COPY cli ./cli
|
COPY cli ./cli
|
||||||
ARG CODECRAFT_VERSION=""
|
ARG CODECRAFT_VERSION=""
|
||||||
ENV CODECRAFT_VERSION=${CODECRAFT_VERSION}
|
ENV CODECRAFT_VERSION=${CODECRAFT_VERSION}
|
||||||
|
RUN rustup target add riscv64gc-unknown-linux-musl
|
||||||
RUN mkdir -p server/src && echo 'fn main(){}' > server/src/main.rs \
|
RUN mkdir -p server/src && echo 'fn main(){}' > server/src/main.rs \
|
||||||
&& cargo zigbuild --release -p codecraft-cli --target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl \
|
&& cargo zigbuild --release -p codecraft-cli --target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl --target riscv64gc-unknown-linux-musl \
|
||||||
&& mkdir -p /out && cp target/x86_64-unknown-linux-musl/release/codecraft /out/codecraft-linux-x86_64 \
|
&& mkdir -p /out && cp target/x86_64-unknown-linux-musl/release/codecraft /out/codecraft-linux-x86_64 \
|
||||||
&& cp target/aarch64-unknown-linux-musl/release/codecraft /out/codecraft-linux-aarch64
|
&& cp target/aarch64-unknown-linux-musl/release/codecraft /out/codecraft-linux-aarch64 \
|
||||||
|
&& cp target/riscv64gc-unknown-linux-musl/release/codecraft /out/codecraft-linux-riscv64
|
||||||
|
|
||||||
# --- Docker CLI (static client; the daemon is the host's via the mounted socket) --
|
# --- Docker CLI (static client; the daemon is the host's via the mounted socket) --
|
||||||
FROM toolchain AS dockercli
|
FROM toolchain AS dockercli
|
||||||
@@ -74,6 +76,10 @@ ARG DOCKER_VERSION=29.9.3
|
|||||||
RUN case "$TARGETARCH" in amd64) arch=x86_64 ;; arm64) arch=aarch64 ;; *) echo "unsupported $TARGETARCH" >&2; exit 1 ;; esac \
|
RUN case "$TARGETARCH" in amd64) arch=x86_64 ;; arm64) arch=aarch64 ;; *) echo "unsupported $TARGETARCH" >&2; exit 1 ;; esac \
|
||||||
&& curl -fsSL "https://download.docker.com/linux/static/stable/$arch/docker-$DOCKER_VERSION.tgz" | tar -xz -C /tmp docker/docker \
|
&& curl -fsSL "https://download.docker.com/linux/static/stable/$arch/docker-$DOCKER_VERSION.tgz" | tar -xz -C /tmp docker/docker \
|
||||||
&& install -m 0755 /tmp/docker/docker /docker
|
&& install -m 0755 /tmp/docker/docker /docker
|
||||||
|
# buildx plugin: the factory builds multi-arch release images with it (own builder on the host daemon).
|
||||||
|
ARG BUILDX_VERSION=v0.19.3
|
||||||
|
RUN curl -fsSL -o /docker-buildx "https://github.com/docker/buildx/releases/download/${BUILDX_VERSION}/buildx-${BUILDX_VERSION}.linux-${TARGETARCH}" \
|
||||||
|
&& chmod 0755 /docker-buildx
|
||||||
|
|
||||||
# --- runtime ------------------------------------------------------------------
|
# --- runtime ------------------------------------------------------------------
|
||||||
# Node is included so agents can work on JS projects and run npx-based MCP servers.
|
# Node is included so agents can work on JS projects and run npx-based MCP servers.
|
||||||
@@ -95,6 +101,7 @@ COPY --from=web /web/dist /app/web
|
|||||||
COPY --from=cli /out /app/cli
|
COPY --from=cli /out /app/cli
|
||||||
# Used with a mounted /var/run/docker.sock (see docs/MOVING.md, --docker-sock).
|
# Used with a mounted /var/run/docker.sock (see docs/MOVING.md, --docker-sock).
|
||||||
COPY --from=dockercli /docker /usr/local/bin/docker
|
COPY --from=dockercli /docker /usr/local/bin/docker
|
||||||
|
COPY --from=dockercli /docker-buildx /usr/local/lib/docker/cli-plugins/docker-buildx
|
||||||
COPY server/ghidra /app/ghidra
|
COPY server/ghidra /app/ghidra
|
||||||
# git for agent shells: commits get the co-author trailer of the model (server.commit_trailer).
|
# git for agent shells: commits get the co-author trailer of the model (server.commit_trailer).
|
||||||
COPY --chmod=755 docker/git-coauthor /usr/local/lib/codecraft/bin/git
|
COPY --chmod=755 docker/git-coauthor /usr/local/lib/codecraft/bin/git
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img alt="Version v202611-00042" src="https://img.shields.io/badge/version-v202611--00042-d69e2e?style=flat-square">
|
<img alt="Version v202611-00082" src="https://img.shields.io/badge/version-v202611--00082-d69e2e?style=flat-square">
|
||||||
<img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-689d6a?style=flat-square">
|
<img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-689d6a?style=flat-square">
|
||||||
<img alt="Rust backend" src="https://img.shields.io/badge/backend-Rust-b7410e?style=flat-square&logo=rust">
|
<img alt="Rust backend" src="https://img.shields.io/badge/backend-Rust-b7410e?style=flat-square&logo=rust">
|
||||||
<img alt="React PWA" src="https://img.shields.io/badge/frontend-React%20PWA-2d81ff?style=flat-square&logo=react">
|
<img alt="React PWA" src="https://img.shields.io/badge/frontend-React%20PWA-2d81ff?style=flat-square&logo=react">
|
||||||
@@ -25,6 +25,7 @@
|
|||||||
<a href="#models">Models</a> ·
|
<a href="#models">Models</a> ·
|
||||||
<a href="#terminal-client">Terminal client</a> ·
|
<a href="#terminal-client">Terminal client</a> ·
|
||||||
<a href="#automations">Automations</a> ·
|
<a href="#automations">Automations</a> ·
|
||||||
|
<a href="#code-factory">Code factory</a> ·
|
||||||
<a href="#integrations">Integrations</a> ·
|
<a href="#integrations">Integrations</a> ·
|
||||||
<a href="#users-and-security">Users</a> ·
|
<a href="#users-and-security">Users</a> ·
|
||||||
<a href="#statistics">Statistics</a> ·
|
<a href="#statistics">Statistics</a> ·
|
||||||
@@ -36,7 +37,7 @@
|
|||||||
<br>
|
<br>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="docs/images/chat.png" alt="A CodeCraft session in the Gruvbox dark theme: a diff of the fix, the task list, and a permission card asking before the test suite runs; the sidebar shows pinned chats, a folder and the archive" width="100%">
|
<img src="docs/images/chat.png" alt="A CodeCraft session in the Gruvbox dark theme: the agent's task list and a permission card with the diff of a one-line fix; the sidebar shows a pinned chat, a folder and today's chats, and the chip in the top bar shows an active skill" width="100%">
|
||||||
<br>
|
<br>
|
||||||
<sub>A session: the agent works through its task list, shows diffs, and asks before anything outside the rules.</sub>
|
<sub>A session: the agent works through its task list, shows diffs, and asks before anything outside the rules.</sub>
|
||||||
</p>
|
</p>
|
||||||
@@ -88,6 +89,15 @@ tokens and everything else are set in the UI and stored in the configuration fil
|
|||||||
Releases are named `vYYYYMM-NNNNN` (a counter per month). Pin one with
|
Releases are named `vYYYYMM-NNNNN` (a counter per month). Pin one with
|
||||||
`CODECRAFT_VERSION=v202611-00001` in `.env`. Admins see a notice when a new release is out.
|
`CODECRAFT_VERSION=v202611-00001` in `.env`. Admins see a notice when a new release is out.
|
||||||
|
|
||||||
|
**Terminal client:** with the server running, install `codecraft` on any Linux machine (x86_64, aarch64 or
|
||||||
|
riscv64) and sign in – it uses your server's models, skills and MCP tools and can steer its chats and the
|
||||||
|
[factory](#code-factory) (see [Terminal client](#terminal-client)):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -fsSL https://<your-codecraft-server>/cli/install.sh | sh
|
||||||
|
codecraft login # server URL, user name, password
|
||||||
|
```
|
||||||
|
|
||||||
**From source:** `git clone https://git.familie-zink.org/zink/codecraft.git && cd codecraft`,
|
**From source:** `git clone https://git.familie-zink.org/zink/codecraft.git && cd codecraft`,
|
||||||
`cp .env.example .env`, then `docker compose up -d --build`.
|
`cp .env.example .env`, then `docker compose up -d --build`.
|
||||||
|
|
||||||
@@ -129,7 +139,7 @@ opens the command palette, and prompt templates with placeholders save typing.
|
|||||||
<table>
|
<table>
|
||||||
<tr>
|
<tr>
|
||||||
<td width="40%" valign="top">
|
<td width="40%" valign="top">
|
||||||
<img src="docs/images/mobile.png" alt="CodeCraft on a phone in a light theme: the agent asks where coupon codes should be stored and offers three options plus free text" width="100%"><br>
|
<img src="docs/images/mobile.png" alt="CodeCraft on a phone in a dark theme: the task list and a permission card with the diff, with Allow once, Always allow and Reject buttons" width="100%"><br>
|
||||||
<sub><b>Mobile:</b> answer questions and approve changes from your phone. Share links and text from other apps into a chat.</sub>
|
<sub><b>Mobile:</b> answer questions and approve changes from your phone. Share links and text from other apps into a chat.</sub>
|
||||||
</td>
|
</td>
|
||||||
<td width="60%" valign="top">
|
<td width="60%" valign="top">
|
||||||
@@ -153,6 +163,19 @@ slash commands in `.claude/commands` and skills in `.claude/skills` are picked u
|
|||||||
The agent keeps notes about a project in `.codecraft/memory.md`; your personal memory applies to
|
The agent keeps notes about a project in `.codecraft/memory.md`; your personal memory applies to
|
||||||
every project.
|
every project.
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/images/skills.png" alt="Settings, Skills tab: the user's own skills with description and file count, buttons for a new skill and the import from GitHub" width="100%">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
**Skills** are packaged instructions for a kind of task: a folder with a `SKILL.md` (name, description,
|
||||||
|
instructions) and further files. Create them in *Settings → Skills* with a small editor, or import them
|
||||||
|
from a GitHub repository or folder (every folder with a `SKILL.md` is offered; filter and select several).
|
||||||
|
They are stored per user and work next to the skills of your projects and the built-in ones. To keep the
|
||||||
|
context small, you switch skills on **per chat** (menu ⋯ → *Skills for this chat*): only those are part of
|
||||||
|
every turn. All others cost nothing – up to 12 are listed by name, a larger library is not listed at all and
|
||||||
|
the agent finds a skill by keyword and loads it, with its further files, when it needs it. In the
|
||||||
|
[code factory](#code-factory) each phase can have its own skills.
|
||||||
|
|
||||||
## Models
|
## Models
|
||||||
|
|
||||||
Every provider is an endpoint with a list of models. Each model can have a context size,
|
Every provider is an endpoint with a list of models. Each model can have a context size,
|
||||||
@@ -191,19 +214,28 @@ Anthropic, OpenAI, Gemini, OpenRouter, opencode or a local model server (Ollama,
|
|||||||
llama.cpp, vLLM – detected automatically); both can be mixed.
|
llama.cpp, vLLM – detected automatically); both can be mixed.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
curl -fsSL https://<your-codecraft-server>/cli/install.sh | sh # Linux x86_64 / aarch64
|
curl -fsSL https://<your-codecraft-server>/cli/install.sh | sh # Linux x86_64 / aarch64 / riscv64
|
||||||
codecraft login # server URL, user name, password → creates an API token
|
codecraft login # server URL, user name, password → creates an API token
|
||||||
codecraft # start in the current folder; /help lists the commands
|
codecraft # start in the current folder; /help lists the commands
|
||||||
```
|
```
|
||||||
|
|
||||||
The Docker image ships static binaries for Linux x86_64 and aarch64; the server offers them
|
Signed in to a server, the terminal also steers the server itself:
|
||||||
|
|
||||||
|
- `/projects` lists your chats on the server; open one and follow it – the agent keeps running **on the
|
||||||
|
server**, in the server's folder – and answer its permission requests and questions, send messages, interrupt
|
||||||
|
it (<kbd>Esc</kbd>) and `/compact` it. `/local` returns to a local chat. The view refreshes every second or two.
|
||||||
|
- `/factory` shows the factory board (issues by phase with their latest run, totals and cost) and offers per
|
||||||
|
issue: open the chat of a run, merge the pull request (merge, squash or rebase), close the issue, restart it at
|
||||||
|
the review, build or acceptance, or remove it from the board. `/factory check` looks for new issues right away.
|
||||||
|
|
||||||
|
The Docker image ships static binaries for Linux x86_64, aarch64 and riscv64; the server offers them
|
||||||
for download (*Settings → Account*) and `codecraft update` fetches new versions from it. Other
|
for download (*Settings → Account*) and `codecraft update` fetches new versions from it. Other
|
||||||
platforms: `cargo install --locked --git https://git.familie-zink.org/zink/codecraft codecraft-cli`.
|
platforms: `cargo install --locked --git https://git.familie-zink.org/zink/codecraft codecraft-cli`.
|
||||||
|
|
||||||
## Automations
|
## Automations
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="docs/images/automations.png" alt="Creating an automation from a template: schedule chips, cron expression, mode, permission mode, model and the task for the agent" width="100%">
|
<img src="docs/images/automations.png" alt="The automation editor: schedule chips with the next runs, mode, approval mode, model, time limit and the instructions file next to an assistant chat" width="100%">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
An automation is an agent that starts on a schedule. Its instructions are a Markdown file
|
An automation is an agent that starts on a schedule. Its instructions are a Markdown file
|
||||||
@@ -219,6 +251,156 @@ read and continue it.
|
|||||||
**Webhooks** start an automation from outside, e.g. on every push: the request is checked with a
|
**Webhooks** start an automation from outside, e.g. on every push: the request is checked with a
|
||||||
shared secret or a Gitea/GitHub HMAC signature, and its JSON payload is handed to the agent.
|
shared secret or a Gitea/GitHub HMAC signature, and its JSON payload is handed to the agent.
|
||||||
|
|
||||||
|
## Code factory
|
||||||
|
|
||||||
|
The factory turns issues on your Git forge (Gitea, GitHub or GitLab) into reviewed, built, accepted and
|
||||||
|
merged changes – with agents doing the work and you deciding at the points that matter. It is
|
||||||
|
the **Factory** page in the sidebar; all chats it creates live in the sidebar folder *Factory*.
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/images/factory.png" alt="The factory board: columns for review, questions, approved, build, acceptance, failed and done with issue cards, the repository tile with its version, and buttons to plan a feature, cut a milestone and start a release" width="100%">
|
||||||
|
<br>
|
||||||
|
<sub>The factory page: every issue sits in the column of its phase; the repository shows its current version.</sub>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
```
|
||||||
|
issue + label "factory"
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
review ──► question (the agent asks in the issue; you answer, it continues)
|
||||||
|
│ └──► rejected (not buildable as written)
|
||||||
|
▼
|
||||||
|
approved ──► building ──► qa (acceptance) ──► done ──► PR merged ──► version + tag ──► closed
|
||||||
|
▲ │
|
||||||
|
└── rework ◄──┘ (up to N rounds, then failed)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Phases.** Each phase is a normal CodeCraft chat in the sandbox, so you can open and read it.
|
||||||
|
The agent's answer ends with a JSON result that the factory parses; everything else is done by
|
||||||
|
the server.
|
||||||
|
|
||||||
|
1. **Review.** An agent reads the issue and the repository and decides: *approved*, *question*
|
||||||
|
(it comments in the issue and waits for your reply) or *rejected*. It also writes acceptance
|
||||||
|
scenarios. The scenarios are stored in the factory database and are **never shown to the
|
||||||
|
builder**, so the build cannot be tuned to the test.
|
||||||
|
2. **Build.** The builder works in its own git worktree on the branch `factory/issue-<n>`.
|
||||||
|
The server – not the agent – commits, pushes (never forced) and restores the spec file.
|
||||||
|
3. **Acceptance.** A different agent checks the pushed branch in a clean checkout against the
|
||||||
|
scenarios, using the repository's `.factory/setup.json` to build and start the app. Each
|
||||||
|
scenario ends as `pass`, `fail`, `unverified` or `out_of_scope`; the verdict comes from these
|
||||||
|
results, not from the model's opinion, and a run without any pass or fail counts as failed.
|
||||||
|
On *pass* the factory opens the pull request (if none is open) and comments a result table
|
||||||
|
in the issue. On *fail* the issue goes back to the build with the findings (*rework*).
|
||||||
|
4. **Done, merge, version.** You review the pull request in the factory (diff, description) and
|
||||||
|
merge it there – on the page or with the *Merge* button of the issue card, which appears once
|
||||||
|
the acceptance has passed (closing an issue by hand is possible only after its merge). The factory then pulls the merge, gives the issue its version, commits
|
||||||
|
`VERSION`, pushes an annotated tag, comments on the issue and closes it.
|
||||||
|
|
||||||
|
Issue text is treated as data, never as instructions for the factory itself.
|
||||||
|
|
||||||
|
**Scope.** An issue body can contain `Spec: <file>` and `Scope: <deliverable>` lines. Review,
|
||||||
|
build and acceptance then restrict themselves to that deliverable, so a big specification is
|
||||||
|
built in small steps instead of one huge run. Without a `Scope:` line the review picks the
|
||||||
|
first unbuilt milestone of the spec. `Prerequisite:` lines name what must be merged first.
|
||||||
|
|
||||||
|
**Planning with a model.** Three chats help you create issues, without the usual review loop:
|
||||||
|
|
||||||
|
- **Spec chat** (*New project*): works out a specification with you and creates the repository
|
||||||
|
with `docs/specs/<name>.md`, the factory setup and the first issues.
|
||||||
|
- **Plan a feature**: you describe a feature or a bug; the model asks questions and ends with a
|
||||||
|
list of issues (title, description, scope, prerequisites).
|
||||||
|
- **Cut a milestone**: the model splits a milestone of the spec into numbered deliverables
|
||||||
|
(`M2.1 – …`).
|
||||||
|
|
||||||
|
*Create issues* shows the proposal for editing and files the issues on the forge. They get the
|
||||||
|
`factory` label only if you tick *Start right away*; by default you set the label yourself,
|
||||||
|
one after the other, because later issues build on the merged earlier ones.
|
||||||
|
|
||||||
|
**Versions and releases.** Every issue that is merged raises the version of the repository
|
||||||
|
(starting from the highest `vX.Y.Z` tag): a deliverable of a milestone raises the **patch**
|
||||||
|
number (0.0.1, 0.0.2, …); the **last** open deliverable of a milestone (`M<k>.<n>`) raises the
|
||||||
|
**minor** number and resets the patch (M1 complete → 0.1.0). Issues without a milestone
|
||||||
|
(bugs, features) raise the patch number. The factory writes the `VERSION` file, pushes the tag
|
||||||
|
`vX.Y.Z` and closes the issue. The **Release** button turns the current version into a
|
||||||
|
release, e.g. 0.x → 1.0.0: it builds what the repository's `.factory/release.json` describes
|
||||||
|
(Docker image for amd64 and arm64 pushed to your registry, a source zip, extra files by glob,
|
||||||
|
shell commands), tags it and creates the release on the forge with notes from the git log and
|
||||||
|
the files attached (Gitea and GitHub).
|
||||||
|
|
||||||
|
**Settings per repository** (*Factory → Repositories*, *New repository*): forge connection and token, label
|
||||||
|
(default `factory`), parallel runs, allowed issue authors (default: the token's owner), and per
|
||||||
|
phase the model, agent (CodeCraft or Claude Code), permission mode, timeout, tries on
|
||||||
|
technical failures, the skills that are switched on for it, plus the number of rework rounds (default 2). Failed or rejected issues
|
||||||
|
can be restarted from the board, finished ones are closed with a comment.
|
||||||
|
|
||||||
|
**Main switch.** The switch at the top of the factory page starts and stops the whole factory.
|
||||||
|
*Stop* is soft: no new review, build or acceptance starts, running agents finish their phase.
|
||||||
|
The switch is green while the factory runs, yellow while it is stopping (agents still working)
|
||||||
|
and red once the last agent is done. The state survives restarts.
|
||||||
|
|
||||||
|
**Backlog.** The first column of the board lists every open issue of the configured
|
||||||
|
repositories that is not in the factory yet. *Queue* gives an issue the factory label on the
|
||||||
|
forge (so it enters the review at once); *Queue all* does it for the whole list. Issues of authors
|
||||||
|
who are not allowed to file factory issues are shown but cannot be queued. Cards are tinted by
|
||||||
|
status.
|
||||||
|
|
||||||
|
**Files in the repository** (all optional, kept in `.factory/`):
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `setup.json` | How acceptance installs and starts the app: `install`, `start`, `url` – and, with the test runner, `image`, `dockerfile`, `port`, `env`, `services` |
|
||||||
|
| `release.json` | Recipe for releases: image, platforms, Dockerfile, build args, commands, files |
|
||||||
|
|
||||||
|
Repositories are cloned into a separate factory area, not into your workspace, and agents never see the forge API token.
|
||||||
|
|
||||||
|
**Throw-away test containers (optional).** By default the acceptance agent starts the app
|
||||||
|
inside the CodeCraft container. With the **test runner** each acceptance run gets its own
|
||||||
|
container and network instead: set `COMPOSE_PROFILES=runner`, `CODECRAFT_RUNNER_URL=http://testrunner:8788`,
|
||||||
|
`RUNNER_TOKEN` (random, ≥ 16 characters) and `DOCKER_GID` in `.env` (see `.env.example`). The
|
||||||
|
`testrunner` service – the same image started as `codecraft testrunner` – is the only one that
|
||||||
|
touches the Docker socket. It copies the checked-out branch into a fresh container, runs
|
||||||
|
`install` and `start` from `.factory/setup.json`, waits until the port answers, and forwards it
|
||||||
|
to `localhost` for the agent; the app's log is in `.factory/app.log`. Afterwards container,
|
||||||
|
helper services and network are removed (leftovers are swept at startup and after 90 minutes).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"image": "node:22-bookworm",
|
||||||
|
"install": "npm ci",
|
||||||
|
"start": "npm start",
|
||||||
|
"url": "http://localhost:8080",
|
||||||
|
"env": { "DATABASE_URL": "postgres://app:app@db/app" },
|
||||||
|
"services": { "db": { "image": "postgres:16", "env": { "POSTGRES_USER": "app", "POSTGRES_PASSWORD": "app", "POSTGRES_DB": "app" } } }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Between runs of one project the runner keeps a cache volume: npm/Yarn, pip, Go and Cargo caches
|
||||||
|
(including the Cargo target directory) are shared automatically. For more, add to `setup.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"cache": {
|
||||||
|
"dirs": ["build/downloads"],
|
||||||
|
"seed": { "paths": ["data/ubuntu.ext4"], "key": ["guest", "lib", "scripts", "package-lock.json"] }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`dirs` persist and are shared by all runs (use them for downloads, not for results). A `seed`
|
||||||
|
holds expensive *results* of `install`: it is stored after a successful install under a key made
|
||||||
|
from the image, the install command, the seed paths and the contents of the `key` files or
|
||||||
|
directories, and copied into a fresh container only while that key matches – so a run never
|
||||||
|
inherits changes from an earlier one, and editing a listed source rebuilds it. `"cache": false`
|
||||||
|
disables caching; `DELETE /v1/cache/<project>` on the runner clears one project.
|
||||||
|
|
||||||
|
`image` defaults to `RUNNER_DEFAULT_IMAGE`, by default the shared base image
|
||||||
|
`codecraft-testbase` (Node 24, Python 3, gcc/cmake, Chromium with Playwright and common tools; see
|
||||||
|
`docker/testbase/Dockerfile`; plain Node 24 is the fallback when it cannot be pulled). The runner logs
|
||||||
|
per environment the start time, the seed hit/miss and the apt packages the setup installed.
|
||||||
|
The image can be changed per project with `"image"`; `"dockerfile": "path"` builds the image from the
|
||||||
|
repository instead; helper services are reachable by their name. Containers run without extra
|
||||||
|
capabilities, with memory/CPU/process limits (`RUNNER_MEMORY`, `RUNNER_CPUS`), and cannot see the
|
||||||
|
host. Without the runner, or without a `setup.json`, nothing changes. Note that the runner holds
|
||||||
|
the Docker socket (root-equivalent on the host): keep its port unpublished and the token secret.
|
||||||
|
|
||||||
## Integrations
|
## Integrations
|
||||||
|
|
||||||
- **Telegram:** connect your own bot (*Settings → Account → Telegram*) and use CodeCraft from
|
- **Telegram:** connect your own bot (*Settings → Account → Telegram*) and use CodeCraft from
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
use crate::agent::{Env, Reply, UiEvent};
|
use crate::agent::{Env, Reply, UiEvent};
|
||||||
use crate::editor::Editor;
|
use crate::editor::Editor;
|
||||||
use crate::i18n::t;
|
use crate::i18n::t;
|
||||||
|
use crate::remote::{self, Remote, Snapshot};
|
||||||
use crate::session::LocalSession;
|
use crate::session::LocalSession;
|
||||||
use crate::theme::{self, Theme};
|
use crate::theme::{self, Theme};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
@@ -14,7 +15,7 @@ use ratatui::Frame;
|
|||||||
use ratatui::layout::{Constraint, Layout, Rect};
|
use ratatui::layout::{Constraint, Layout, Rect};
|
||||||
use ratatui::style::{Modifier, Style};
|
use ratatui::style::{Modifier, Style};
|
||||||
use ratatui::text::{Line, Span};
|
use ratatui::text::{Line, Span};
|
||||||
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
|
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -61,6 +62,11 @@ enum PickKind {
|
|||||||
Permission,
|
Permission,
|
||||||
Effort,
|
Effort,
|
||||||
Lang,
|
Lang,
|
||||||
|
/// Chats of the server.
|
||||||
|
Remote,
|
||||||
|
/// Issues of the factory board / the actions for one issue.
|
||||||
|
FactoryIssue,
|
||||||
|
FactoryAction,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Picker {
|
struct Picker {
|
||||||
@@ -109,6 +115,10 @@ pub struct App {
|
|||||||
busy_since: Instant,
|
busy_since: Instant,
|
||||||
cancel: Option<CancellationToken>,
|
cancel: Option<CancellationToken>,
|
||||||
queue: VecDeque<String>,
|
queue: VecDeque<String>,
|
||||||
|
/// The messages of a followed server chat that wait for its agent (from the server's queue).
|
||||||
|
remote_queue: Vec<String>,
|
||||||
|
/// The running turn is interrupted so that the queued messages are sent at once.
|
||||||
|
forcing: bool,
|
||||||
dialog: Dialog,
|
dialog: Dialog,
|
||||||
session: LocalSession,
|
session: LocalSession,
|
||||||
effort: Option<String>,
|
effort: Option<String>,
|
||||||
@@ -129,6 +139,41 @@ pub struct App {
|
|||||||
/// Running setup action (login / provider test): Ok(message) or error.
|
/// Running setup action (login / provider test): Ok(message) or error.
|
||||||
pending_setup: Option<oneshot::Receiver<Result<String>>>,
|
pending_setup: Option<oneshot::Receiver<Result<String>>>,
|
||||||
pending_env: Option<oneshot::Receiver<Result<Env>>>,
|
pending_env: Option<oneshot::Receiver<Result<Env>>>,
|
||||||
|
/// A chat of the server that this terminal follows (instead of the local session).
|
||||||
|
remote: Option<Remote>,
|
||||||
|
pending_snapshot: Option<oneshot::Receiver<Result<Snapshot>>>,
|
||||||
|
pending_open: Option<oneshot::Receiver<Result<Remote>>>,
|
||||||
|
pending_pick: Option<oneshot::Receiver<Result<(PickKind, String, Vec<(String, String, String)>)>>>,
|
||||||
|
pending_note: Option<oneshot::Receiver<Result<String>>>,
|
||||||
|
/// The factory issue ("repo#number") whose actions are open.
|
||||||
|
factory_key: String,
|
||||||
|
/// Unsent input is kept per chat: on the server for server chats (so another device can continue it),
|
||||||
|
/// in a local file for local chats.
|
||||||
|
draft: DraftSync,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct DraftSync {
|
||||||
|
/// "remote:<id>" or "local:<id>" of the chat the draft belongs to.
|
||||||
|
key: String,
|
||||||
|
/// What the editor held at the last look, and since when.
|
||||||
|
seen: String,
|
||||||
|
changed: Instant,
|
||||||
|
/// What is stored (or was last stored) for this chat.
|
||||||
|
synced: String,
|
||||||
|
loaded: bool,
|
||||||
|
pull: Option<oneshot::Receiver<Result<String>>>,
|
||||||
|
last_pull: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DraftSync {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self { key: String::new(), seen: String::new(), changed: Instant::now(), synced: String::new(), loaded: false, pull: None, last_pull: Instant::now() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_draft_path(id: &str) -> std::path::PathBuf {
|
||||||
|
let safe: String = id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();
|
||||||
|
crate::conf::data_dir().join("drafts").join(format!("{safe}.txt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
const SPINNER: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
const SPINNER: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||||
@@ -170,6 +215,28 @@ fn wrap(text: &str, width: usize) -> Vec<String> {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Break text into rows of at most `width` display columns exactly where they fill up (nothing is trimmed, so
|
||||||
|
/// typed spaces stay visible); newlines start a new row.
|
||||||
|
fn hard_wrap(text: &str, width: usize) -> Vec<String> {
|
||||||
|
let width = width.max(1);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for raw in text.split('\n') {
|
||||||
|
let mut line = String::new();
|
||||||
|
let mut w = 0;
|
||||||
|
for ch in raw.chars() {
|
||||||
|
let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
|
||||||
|
if w + cw > width && !line.is_empty() {
|
||||||
|
out.push(std::mem::take(&mut line));
|
||||||
|
w = 0;
|
||||||
|
}
|
||||||
|
line.push(ch);
|
||||||
|
w += cw;
|
||||||
|
}
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Inline markdown: `code` and **bold**.
|
/// Inline markdown: `code` and **bold**.
|
||||||
fn inline(text: &str, th: &Theme, base: Style) -> Vec<Span<'static>> {
|
fn inline(text: &str, th: &Theme, base: Style) -> Vec<Span<'static>> {
|
||||||
let mut spans = Vec::new();
|
let mut spans = Vec::new();
|
||||||
@@ -299,9 +366,12 @@ impl App {
|
|||||||
busy_since: Instant::now(),
|
busy_since: Instant::now(),
|
||||||
cancel: None,
|
cancel: None,
|
||||||
queue: VecDeque::new(),
|
queue: VecDeque::new(),
|
||||||
|
remote_queue: Vec::new(),
|
||||||
|
forcing: false,
|
||||||
dialog: Dialog::None,
|
dialog: Dialog::None,
|
||||||
todos: session.todos.clone(),
|
todos: session.todos.clone(),
|
||||||
context: session.context_tokens,
|
context: session.context_tokens,
|
||||||
|
draft: DraftSync::new(),
|
||||||
session,
|
session,
|
||||||
effort: None,
|
effort: None,
|
||||||
images: vec![],
|
images: vec![],
|
||||||
@@ -317,6 +387,12 @@ impl App {
|
|||||||
pending_detect: None,
|
pending_detect: None,
|
||||||
pending_setup: None,
|
pending_setup: None,
|
||||||
pending_env: None,
|
pending_env: None,
|
||||||
|
remote: None,
|
||||||
|
pending_snapshot: None,
|
||||||
|
pending_open: None,
|
||||||
|
pending_pick: None,
|
||||||
|
pending_note: None,
|
||||||
|
factory_key: String::new(),
|
||||||
};
|
};
|
||||||
app.rebuild_items();
|
app.rebuild_items();
|
||||||
app
|
app
|
||||||
@@ -360,7 +436,14 @@ impl App {
|
|||||||
self.busy_since = Instant::now();
|
self.busy_since = Instant::now();
|
||||||
} else {
|
} else {
|
||||||
self.cancel = None;
|
self.cancel = None;
|
||||||
if let Some(next) = self.queue.pop_front() {
|
if self.forcing {
|
||||||
|
// Interrupted on purpose: everything that waited goes out as one message.
|
||||||
|
self.forcing = false;
|
||||||
|
let all: Vec<String> = self.queue.drain(..).collect();
|
||||||
|
if !all.is_empty() {
|
||||||
|
self.send(all.join("\n\n"));
|
||||||
|
}
|
||||||
|
} else if let Some(next) = self.queue.pop_front() {
|
||||||
self.send(next);
|
self.send(next);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -440,12 +523,20 @@ impl App {
|
|||||||
let text = self.editor.take();
|
let text = self.editor.take();
|
||||||
let trimmed = text.trim().to_string();
|
let trimmed = text.trim().to_string();
|
||||||
if trimmed.is_empty() && self.images.is_empty() {
|
if trimmed.is_empty() && self.images.is_empty() {
|
||||||
|
// A further Enter on the empty field delivers the waiting messages at once.
|
||||||
|
if self.busy && self.has_queue() {
|
||||||
|
self.force_queue();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if trimmed.starts_with('/') && self.slash(&trimmed) {
|
if trimmed.starts_with('/') && self.slash(&trimmed) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let text = self.expand_command(&trimmed).unwrap_or(trimmed);
|
let text = self.expand_command(&trimmed).unwrap_or(trimmed);
|
||||||
|
if self.remote.is_some() {
|
||||||
|
self.send_remote(text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if self.busy {
|
if self.busy {
|
||||||
self.queue.push_back(text);
|
self.queue.push_back(text);
|
||||||
self.status = format!("{} ({})", t("queued"), self.queue.len());
|
self.status = format!("{} ({})", t("queued"), self.queue.len());
|
||||||
@@ -454,6 +545,27 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn has_queue(&self) -> bool {
|
||||||
|
if self.remote.is_some() { !self.remote_queue.is_empty() } else { !self.queue.is_empty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Interrupt the running step and deliver the queued messages now (the model reads them at once).
|
||||||
|
fn force_queue(&mut self) {
|
||||||
|
if let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) {
|
||||||
|
let id = r.id.clone();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::force_queue(&server, &id).await.map(|_| String::new()));
|
||||||
|
});
|
||||||
|
self.pending_note = Some(rx);
|
||||||
|
self.status = t("forcing").into();
|
||||||
|
} else if let Some(c) = &self.cancel {
|
||||||
|
self.forcing = true;
|
||||||
|
c.cancel();
|
||||||
|
self.status = t("forcing").into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Custom commands (server, project, built-in): "/name args" -> prompt.
|
/// Custom commands (server, project, built-in): "/name args" -> prompt.
|
||||||
fn expand_command(&mut self, text: &str) -> Option<String> {
|
fn expand_command(&mut self, text: &str) -> Option<String> {
|
||||||
let rest = text.strip_prefix('/')?;
|
let rest = text.strip_prefix('/')?;
|
||||||
@@ -527,6 +639,9 @@ impl App {
|
|||||||
("setup", "add model providers or sign in to a server"),
|
("setup", "add model providers or sign in to a server"),
|
||||||
("memory", "show the project memory"),
|
("memory", "show the project memory"),
|
||||||
("jobs", "automations on the server"),
|
("jobs", "automations on the server"),
|
||||||
|
("projects", "chats on the server: open and steer them"),
|
||||||
|
("factory", "software factory of the server: board and actions"),
|
||||||
|
("local", "back to a local chat"),
|
||||||
("quit", "exit"),
|
("quit", "exit"),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -545,6 +660,21 @@ impl App {
|
|||||||
}
|
}
|
||||||
self.dialog = Dialog::Text { title: t("help").into(), body };
|
self.dialog = Dialog::Text { title: t("help").into(), body };
|
||||||
}
|
}
|
||||||
|
"projects" | "server" => self.fetch_pick(PickKind::Remote),
|
||||||
|
"factory" if arg == "check" => {
|
||||||
|
if let Some(server) = self.env.server.clone() {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::factory_poll(&server).await);
|
||||||
|
});
|
||||||
|
self.pending_note = Some(rx);
|
||||||
|
} else {
|
||||||
|
self.items.push(Item::Error("not signed in to a server".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"factory" => self.fetch_pick(PickKind::FactoryIssue),
|
||||||
|
"local" => self.leave_remote(),
|
||||||
|
"model" | "mode" | "permissions" | "effort" if self.remote.is_some() => self.items.push(Item::Info("this chat runs on the server – change this in the web interface (/local returns to a local chat)".into())),
|
||||||
"model" => self.open_picker(PickKind::Model),
|
"model" => self.open_picker(PickKind::Model),
|
||||||
"mode" => {
|
"mode" => {
|
||||||
if arg.is_empty() {
|
if arg.is_empty() {
|
||||||
@@ -558,7 +688,18 @@ impl App {
|
|||||||
"theme" => self.open_picker(PickKind::Theme),
|
"theme" => self.open_picker(PickKind::Theme),
|
||||||
"lang" => self.open_picker(PickKind::Lang),
|
"lang" => self.open_picker(PickKind::Lang),
|
||||||
"resume" | "sessions" => self.open_picker(PickKind::Session),
|
"resume" | "sessions" => self.open_picker(PickKind::Session),
|
||||||
|
"compact" if self.remote.is_some() => {
|
||||||
|
if let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) {
|
||||||
|
let id = r.id.clone();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::compact(&server, &id).await.map(|_| "compacting on the server…".to_string()));
|
||||||
|
});
|
||||||
|
self.pending_note = Some(rx);
|
||||||
|
}
|
||||||
|
}
|
||||||
"new" | "clear" => {
|
"new" | "clear" => {
|
||||||
|
self.remote = None;
|
||||||
let _ = self.cmd.send(Cmd::New);
|
let _ = self.cmd.send(Cmd::New);
|
||||||
self.session = LocalSession::new(&self.session.cwd, &self.session.model, &self.session.mode, &self.session.permission_mode);
|
self.session = LocalSession::new(&self.session.cwd, &self.session.model, &self.session.mode, &self.session.permission_mode);
|
||||||
self.items.clear();
|
self.items.clear();
|
||||||
@@ -638,6 +779,7 @@ impl App {
|
|||||||
PickKind::Effort => ("Effort".into(), ["low", "medium", "high", "max"].iter().map(|e| (e.to_string(), e.to_string(), "next message only".into())).collect()),
|
PickKind::Effort => ("Effort".into(), ["low", "medium", "high", "max"].iter().map(|e| (e.to_string(), e.to_string(), "next message only".into())).collect()),
|
||||||
PickKind::Theme => (t("choose_theme").into(), theme::names().into_iter().flat_map(|n| ["auto", "dark", "light"].map(|m| (format!("{n}:{m}"), format!("{n} ({m})"), String::new()))).collect()),
|
PickKind::Theme => (t("choose_theme").into(), theme::names().into_iter().flat_map(|n| ["auto", "dark", "light"].map(|m| (format!("{n}:{m}"), format!("{n} ({m})"), String::new()))).collect()),
|
||||||
PickKind::Lang => ("Language".into(), vec![("en".into(), "English".into(), String::new()), ("de".into(), "Deutsch".into(), String::new())]),
|
PickKind::Lang => ("Language".into(), vec![("en".into(), "English".into(), String::new()), ("de".into(), "Deutsch".into(), String::new())]),
|
||||||
|
PickKind::Remote | PickKind::FactoryIssue | PickKind::FactoryAction => return,
|
||||||
PickKind::Session => (
|
PickKind::Session => (
|
||||||
t("choose_session").into(),
|
t("choose_session").into(),
|
||||||
crate::session::list(None)
|
crate::session::list(None)
|
||||||
@@ -682,6 +824,12 @@ impl App {
|
|||||||
cfg.lang = Some(key);
|
cfg.lang = Some(key);
|
||||||
let _ = cfg.save();
|
let _ = cfg.save();
|
||||||
}
|
}
|
||||||
|
PickKind::Remote => self.open_remote(&key),
|
||||||
|
PickKind::FactoryIssue => {
|
||||||
|
self.factory_key = key.clone();
|
||||||
|
self.fetch_actions(&key);
|
||||||
|
}
|
||||||
|
PickKind::FactoryAction => self.factory_action(&key),
|
||||||
PickKind::Session => {
|
PickKind::Session => {
|
||||||
if let Ok(s) = LocalSession::load(&key) {
|
if let Ok(s) = LocalSession::load(&key) {
|
||||||
self.session = s.clone();
|
self.session = s.clone();
|
||||||
@@ -694,6 +842,252 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- server: remote chats and the factory ----------------------------------------------
|
||||||
|
|
||||||
|
fn abort_current(&mut self) {
|
||||||
|
if let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) {
|
||||||
|
let id = r.id.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = remote::abort(&server, &id).await;
|
||||||
|
});
|
||||||
|
} else if let Some(c) = &self.cancel {
|
||||||
|
c.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch the entries of a server picker in the background; the picker opens when they arrive.
|
||||||
|
fn fetch_pick(&mut self, kind: PickKind) {
|
||||||
|
let Some(server) = self.env.server.clone() else {
|
||||||
|
self.items.push(Item::Error("not signed in to a server – run: codecraft login".into()));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.status = "loading…".into();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let res = match kind {
|
||||||
|
PickKind::Remote => remote::sessions(&server).await.map(|items| (kind, "Chats on the server".to_string(), items)),
|
||||||
|
_ => remote::factory_board(&server).await.map(|(summary, items)| (kind, summary, items)),
|
||||||
|
};
|
||||||
|
let _ = tx.send(res);
|
||||||
|
});
|
||||||
|
self.pending_pick = Some(rx);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fetch_actions(&mut self, key: &str) {
|
||||||
|
let Some(server) = self.env.server.clone() else { return };
|
||||||
|
let key = key.to_string();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::factory_actions(&server, &key).await.map(|(title, acts)| (PickKind::FactoryAction, title, acts)));
|
||||||
|
});
|
||||||
|
self.pending_pick = Some(rx);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn factory_action(&mut self, action: &str) {
|
||||||
|
if let Some(id) = action.strip_prefix("chat:") {
|
||||||
|
self.open_remote(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(server) = self.env.server.clone() else { return };
|
||||||
|
let (key, action) = (self.factory_key.clone(), action.to_string());
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::factory_do(&server, &key, &action).await);
|
||||||
|
});
|
||||||
|
self.pending_note = Some(rx);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_remote(&mut self, id: &str) {
|
||||||
|
let Some(server) = self.env.server.clone() else { return };
|
||||||
|
let id = id.to_string();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::open(&server, &id).await);
|
||||||
|
});
|
||||||
|
self.pending_open = Some(rx);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leave_remote(&mut self) {
|
||||||
|
if self.remote.take().is_some() {
|
||||||
|
self.remote_queue.clear();
|
||||||
|
self.items.clear();
|
||||||
|
self.todos = Value::Null;
|
||||||
|
self.busy = false;
|
||||||
|
self.rebuild_items();
|
||||||
|
self.status = "local chat".into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_remote(&mut self, text: String) {
|
||||||
|
let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) else { return };
|
||||||
|
let id = r.id.clone();
|
||||||
|
if self.busy {
|
||||||
|
self.remote_queue.push(text.clone());
|
||||||
|
self.status = format!("{} ({})", t("queued"), self.remote_queue.len());
|
||||||
|
}
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::prompt(&server, &id, &text).await.map(|_| String::new()));
|
||||||
|
});
|
||||||
|
self.pending_note = Some(rx);
|
||||||
|
self.busy = true;
|
||||||
|
self.busy_since = Instant::now();
|
||||||
|
self.scroll = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Items of messages (shared by the local and the remote view).
|
||||||
|
fn items_of(messages: &[codecraft_core::types::Message], open: &std::collections::HashSet<String>) -> Vec<Item> {
|
||||||
|
let mut items = Vec::new();
|
||||||
|
for m in messages {
|
||||||
|
for p in &m.parts {
|
||||||
|
match (&m.role, p) {
|
||||||
|
(Role::User, Part::Text { text }) => items.push(Item::User(text.clone(), 0)),
|
||||||
|
(Role::User, Part::Summary { .. }) => items.push(Item::Info("— conversation compacted —".into())),
|
||||||
|
(_, Part::Text { text }) => items.push(Item::Assistant(text.clone())),
|
||||||
|
(_, Part::Reasoning { text, .. }) if !text.trim().is_empty() => items.push(Item::Thinking(text.clone(), false)),
|
||||||
|
(_, Part::ToolCall { id, name, input, .. }) => items.push(Item::Tool { id: id.clone(), name: name.clone(), title: tool_title(name, input), state: ToolState::Running, output: String::new(), diff: None, open: open.contains(id) }),
|
||||||
|
(_, Part::ToolResult { call_id, content, is_error, meta, .. }) => {
|
||||||
|
if let Some(Item::Tool { state, output, diff, .. }) = items.iter_mut().rev().find(|i| matches!(i, Item::Tool { id, .. } if id == call_id)) {
|
||||||
|
*state = if *is_error { ToolState::Err } else { ToolState::Ok };
|
||||||
|
*output = content.clone();
|
||||||
|
*diff = meta.as_ref().and_then(|m| m["diff"].as_str().map(String::from));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll the followed server chat every ~1.5 s and take up the results of background requests.
|
||||||
|
fn poll_remote(&mut self) {
|
||||||
|
if let Some(rx) = &mut self.pending_pick {
|
||||||
|
if let Ok(res) = rx.try_recv() {
|
||||||
|
self.pending_pick = None;
|
||||||
|
self.status.clear();
|
||||||
|
match res {
|
||||||
|
Ok((kind, title, items)) if items.is_empty() => {
|
||||||
|
let _ = kind;
|
||||||
|
self.items.push(Item::Info(format!("{title}: nothing to show")));
|
||||||
|
}
|
||||||
|
Ok((kind, title, items)) => self.dialog = Dialog::Picker(Picker { kind, title, items, filter: String::new(), sel: 0 }),
|
||||||
|
Err(e) => self.items.push(Item::Error(format!("{e:#}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rx) = &mut self.pending_note {
|
||||||
|
if let Ok(res) = rx.try_recv() {
|
||||||
|
self.pending_note = None;
|
||||||
|
match res {
|
||||||
|
Ok(msg) if !msg.is_empty() => self.items.push(Item::Info(msg)),
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => self.items.push(Item::Error(format!("{e:#}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rx) = &mut self.pending_open {
|
||||||
|
if let Ok(res) = rx.try_recv() {
|
||||||
|
self.pending_open = None;
|
||||||
|
match res {
|
||||||
|
Ok(r) => {
|
||||||
|
self.items.clear();
|
||||||
|
self.items.push(Item::Info(format!("server chat: {} · {} · {} · {} – /local returns", r.title, r.agent, r.model, r.cwd)));
|
||||||
|
self.todos = Value::Null;
|
||||||
|
self.busy = false;
|
||||||
|
self.dialog = Dialog::None;
|
||||||
|
self.remote = Some(r);
|
||||||
|
self.remote_queue.clear();
|
||||||
|
self.pending_snapshot = None;
|
||||||
|
}
|
||||||
|
Err(e) => self.items.push(Item::Error(format!("{e:#}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(server) = self.env.server.clone() else { return };
|
||||||
|
let Some(r) = &mut self.remote else { return };
|
||||||
|
if let Some(rx) = &mut self.pending_snapshot {
|
||||||
|
if let Ok(res) = rx.try_recv() {
|
||||||
|
self.pending_snapshot = None;
|
||||||
|
match res {
|
||||||
|
Ok(snap) => {
|
||||||
|
let open: std::collections::HashSet<String> = self.items.iter().filter_map(|i| if let Item::Tool { id, open: true, .. } = i { Some(id.clone()) } else { None }).collect();
|
||||||
|
let was_busy = self.busy;
|
||||||
|
let at_end = self.scroll == 0;
|
||||||
|
let mut items = Self::items_of(&snap.messages, &open);
|
||||||
|
// Tool calls without a result are still running only while the chat is busy.
|
||||||
|
if !snap.busy {
|
||||||
|
for i in items.iter_mut() {
|
||||||
|
if let Item::Tool { state, .. } = i {
|
||||||
|
if matches!(state, ToolState::Running) {
|
||||||
|
*state = ToolState::Err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let head = self.items.first().filter(|i| matches!(i, Item::Info(s) if s.starts_with("server chat:"))).map(|i| if let Item::Info(s) = i { s.clone() } else { String::new() });
|
||||||
|
self.items = head.map(Item::Info).into_iter().chain(items).collect();
|
||||||
|
self.busy = snap.busy;
|
||||||
|
self.remote_queue = snap.queue.clone();
|
||||||
|
if snap.busy && !was_busy {
|
||||||
|
self.busy_since = Instant::now();
|
||||||
|
}
|
||||||
|
self.todos = snap.todos.clone();
|
||||||
|
if !snap.title.is_empty() {
|
||||||
|
r.title = snap.title.clone();
|
||||||
|
}
|
||||||
|
if at_end {
|
||||||
|
self.scroll = 0;
|
||||||
|
}
|
||||||
|
// Requests that wait for an answer (permissions and questions of this chat).
|
||||||
|
if matches!(self.dialog, Dialog::None) {
|
||||||
|
if let Some(ev) = snap.pending.iter().find(|e| e["id"].as_str().is_some_and(|id| !r.answered.contains(id))) {
|
||||||
|
let id = ev["id"].as_str().unwrap_or("").to_string();
|
||||||
|
r.answered.insert(id.clone());
|
||||||
|
if ev["type"] == "permission_request" {
|
||||||
|
let (tx, rx) = oneshot::channel::<Reply>();
|
||||||
|
let srv = server.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Ok(reply) = rx.await {
|
||||||
|
let (kind, msg) = match reply {
|
||||||
|
Reply::Once => ("once", None),
|
||||||
|
Reply::Always => ("always", None),
|
||||||
|
Reply::Reject(m) => ("reject", m),
|
||||||
|
};
|
||||||
|
let _ = remote::reply_permission(&srv, &id, kind, msg).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.dialog = Dialog::Permission { tool: ev["tool"].as_str().unwrap_or("").into(), title: ev["title"].as_str().unwrap_or("").into(), diff: ev["diff"].as_str().map(String::from), input: ev["input"].clone(), reply: Some(tx), feedback: None };
|
||||||
|
} else if ev["type"] == "question_request" {
|
||||||
|
let questions: Vec<Question> = serde_json::from_value(ev["questions"].clone()).unwrap_or_default();
|
||||||
|
if !questions.is_empty() {
|
||||||
|
let (tx, rx) = oneshot::channel::<Option<serde_json::Map<String, Value>>>();
|
||||||
|
let srv = server.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Ok(answers) = rx.await {
|
||||||
|
let _ = remote::answer_question(&srv, &id, answers).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.dialog = Dialog::Question { questions, idx: 0, sel: 0, custom: String::new(), answers: Default::default(), reply: Some(tx) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => self.status = format!("server: {e:#}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if r.last_poll.elapsed() >= Duration::from_millis(1500) {
|
||||||
|
r.last_poll = Instant::now();
|
||||||
|
let id = r.id.clone();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::snapshot(&server, &id).await);
|
||||||
|
});
|
||||||
|
self.pending_snapshot = Some(rx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- setup wizard ---------------------------------------------------------------
|
// --- setup wizard ---------------------------------------------------------------
|
||||||
|
|
||||||
fn open_setup(&mut self) {
|
fn open_setup(&mut self) {
|
||||||
@@ -771,9 +1165,7 @@ impl App {
|
|||||||
match (k.code, ctrl) {
|
match (k.code, ctrl) {
|
||||||
(KeyCode::Char('c'), true) => {
|
(KeyCode::Char('c'), true) => {
|
||||||
if self.busy {
|
if self.busy {
|
||||||
if let Some(c) = &self.cancel {
|
self.abort_current();
|
||||||
c.cancel();
|
|
||||||
}
|
|
||||||
self.items.push(Item::Info(t("aborted").into()));
|
self.items.push(Item::Info(t("aborted").into()));
|
||||||
} else if !self.editor.is_empty() {
|
} else if !self.editor.is_empty() {
|
||||||
self.editor.clear();
|
self.editor.clear();
|
||||||
@@ -787,9 +1179,7 @@ impl App {
|
|||||||
(KeyCode::Char('d'), true) if self.editor.is_empty() => self.quit = true,
|
(KeyCode::Char('d'), true) if self.editor.is_empty() => self.quit = true,
|
||||||
(KeyCode::Esc, _) => {
|
(KeyCode::Esc, _) => {
|
||||||
if self.busy {
|
if self.busy {
|
||||||
if let Some(c) = &self.cancel {
|
self.abort_current();
|
||||||
c.cancel();
|
|
||||||
}
|
|
||||||
self.queue.clear();
|
self.queue.clear();
|
||||||
self.items.push(Item::Info(t("aborted").into()));
|
self.items.push(Item::Info(t("aborted").into()));
|
||||||
}
|
}
|
||||||
@@ -1146,7 +1536,94 @@ impl App {
|
|||||||
self.status = "loading models…".into();
|
self.status = "loading models…".into();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keep the unsent input of the current chat: load it when the chat changes, save it shortly after typing.
|
||||||
|
fn poll_draft(&mut self) {
|
||||||
|
let remote_id = self.remote.as_ref().map(|r| r.id.clone());
|
||||||
|
let key = match &remote_id {
|
||||||
|
Some(id) => format!("remote:{id}"),
|
||||||
|
None => format!("local:{}", self.session.id),
|
||||||
|
};
|
||||||
|
if self.draft.key != key {
|
||||||
|
self.draft = DraftSync::new();
|
||||||
|
self.draft.key = key.clone();
|
||||||
|
self.draft.seen = self.editor.text();
|
||||||
|
match &remote_id {
|
||||||
|
Some(id) => self.draft_pull(id.clone()),
|
||||||
|
None => {
|
||||||
|
let text = std::fs::read_to_string(local_draft_path(&self.session.id)).unwrap_or_default();
|
||||||
|
if self.editor.is_empty() && !text.is_empty() {
|
||||||
|
self.editor.set(&text);
|
||||||
|
self.draft.seen = text.clone();
|
||||||
|
}
|
||||||
|
self.draft.synced = if self.editor.is_empty() { String::new() } else { self.draft.seen.clone() };
|
||||||
|
self.draft.loaded = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rx) = &mut self.draft.pull {
|
||||||
|
if let Ok(res) = rx.try_recv() {
|
||||||
|
self.draft.pull = None;
|
||||||
|
if let Ok(text) = res {
|
||||||
|
// First load: only into an empty field. Later: only when nothing was typed here since the last sync.
|
||||||
|
let untouched = if self.draft.loaded { self.editor.text() == self.draft.synced } else { self.editor.is_empty() };
|
||||||
|
if untouched && text != self.editor.text() {
|
||||||
|
self.editor.set(&text);
|
||||||
|
self.draft.seen = text.clone();
|
||||||
|
self.draft.synced = text;
|
||||||
|
} else if !self.draft.loaded {
|
||||||
|
self.draft.synced = if untouched { text } else { String::new() };
|
||||||
|
}
|
||||||
|
self.draft.loaded = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let cur = self.editor.text();
|
||||||
|
if cur != self.draft.seen {
|
||||||
|
self.draft.seen = cur;
|
||||||
|
self.draft.changed = Instant::now();
|
||||||
|
}
|
||||||
|
if self.draft.loaded && self.draft.seen != self.draft.synced && self.draft.changed.elapsed() >= Duration::from_millis(700) {
|
||||||
|
let text = self.draft.seen.clone();
|
||||||
|
self.draft.synced = text.clone();
|
||||||
|
match (&remote_id, self.env.server.clone()) {
|
||||||
|
(Some(id), Some(server)) => {
|
||||||
|
let id = id.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = remote::draft_put(&server, &id, &text).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(None, _) => {
|
||||||
|
let path = local_draft_path(&self.session.id);
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
} else if let Some(dir) = path.parent() {
|
||||||
|
let _ = std::fs::create_dir_all(dir);
|
||||||
|
let _ = std::fs::write(&path, &text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Pick up what was typed on another device while this field has no unsent edits.
|
||||||
|
if let (Some(id), true) = (&remote_id, self.draft.loaded && self.draft.pull.is_none() && self.draft.last_pull.elapsed() >= Duration::from_secs(10) && self.editor.text() == self.draft.synced) {
|
||||||
|
self.draft.last_pull = Instant::now();
|
||||||
|
self.draft_pull(id.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draft_pull(&mut self, id: String) {
|
||||||
|
let Some(server) = self.env.server.clone() else { return };
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tx.send(remote::draft_get(&server, &id).await);
|
||||||
|
});
|
||||||
|
self.draft.pull = Some(rx);
|
||||||
|
self.draft.last_pull = Instant::now();
|
||||||
|
}
|
||||||
|
|
||||||
fn poll_pending(&mut self) {
|
fn poll_pending(&mut self) {
|
||||||
|
self.poll_draft();
|
||||||
|
self.poll_remote();
|
||||||
if let Some(rx) = &mut self.pending_detect {
|
if let Some(rx) = &mut self.pending_detect {
|
||||||
if let Ok(found) = rx.try_recv() {
|
if let Ok(found) = rx.try_recv() {
|
||||||
self.pending_detect = None;
|
self.pending_detect = None;
|
||||||
@@ -1290,10 +1767,37 @@ impl App {
|
|||||||
let th = theme::get();
|
let th = theme::get();
|
||||||
let area = f.area();
|
let area = f.area();
|
||||||
f.render_widget(Block::default().style(Style::default().bg(th.bg0).fg(th.fg1)), area);
|
f.render_widget(Block::default().style(Style::default().bg(th.bg0).fg(th.fg1)), area);
|
||||||
let input_h = (self.editor.lines.len() as u16).clamp(1, 8) + 2;
|
// The input wraps at the width of the field (one column stays free for the cursor).
|
||||||
|
let wrap_w = (area.width.saturating_sub(3) as usize).max(1);
|
||||||
|
let layout = self.editor.layout(wrap_w);
|
||||||
|
let input_h = (layout.len() as u16).clamp(1, 8) + 2;
|
||||||
|
// Messages that wait for the agent are shown above the input.
|
||||||
|
let queued: Vec<String> = if self.remote.is_some() { self.remote_queue.clone() } else { self.queue.iter().cloned().collect() };
|
||||||
|
let mut queue_lines: Vec<Line> = Vec::new();
|
||||||
|
if !queued.is_empty() {
|
||||||
|
let w = (area.width as usize).saturating_sub(6).max(10);
|
||||||
|
let mut more = 0;
|
||||||
|
for (n, msg) in queued.iter().enumerate() {
|
||||||
|
let rows = wrap(msg, w);
|
||||||
|
if queue_lines.len() + rows.len() > 5 {
|
||||||
|
more = queued.len() - n;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for (r, row) in rows.into_iter().enumerate() {
|
||||||
|
queue_lines.push(Line::from(vec![Span::styled(if r == 0 { " ↳ " } else { " " }, Style::default().fg(th.accent2)), Span::styled(row, Style::default().fg(th.fg2))]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if more > 0 {
|
||||||
|
queue_lines.push(Line::from(Span::styled(format!(" … +{more}"), Style::default().fg(th.muted))));
|
||||||
|
}
|
||||||
|
if self.busy {
|
||||||
|
queue_lines.push(Line::from(Span::styled(format!(" {}", t("force_hint")), Style::default().fg(th.muted))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let queue_h = queue_lines.len() as u16;
|
||||||
let todo_items: Vec<&Value> = self.todos.as_array().map(|a| a.iter().collect()).unwrap_or_default();
|
let todo_items: Vec<&Value> = self.todos.as_array().map(|a| a.iter().collect()).unwrap_or_default();
|
||||||
let todo_h = if todo_items.iter().any(|t| t["status"] != "completed") { (todo_items.len() as u16).min(6) } else { 0 };
|
let todo_h = if todo_items.iter().any(|t| t["status"] != "completed") { (todo_items.len() as u16).min(6) } else { 0 };
|
||||||
let [head, hist, todos, act, input, status] = Layout::vertical([Constraint::Length(1), Constraint::Min(3), Constraint::Length(todo_h), Constraint::Length(1), Constraint::Length(input_h), Constraint::Length(1)]).areas(area);
|
let [head, hist, todos, act, queue_area, input, status] = Layout::vertical([Constraint::Length(1), Constraint::Min(3), Constraint::Length(todo_h), Constraint::Length(1), Constraint::Length(queue_h), Constraint::Length(input_h), Constraint::Length(1)]).areas(area);
|
||||||
|
|
||||||
// Header.
|
// Header.
|
||||||
let cwd = self.session.cwd.replace(&crate::conf::home().display().to_string(), "~");
|
let cwd = self.session.cwd.replace(&crate::conf::home().display().to_string(), "~");
|
||||||
@@ -1359,12 +1863,15 @@ impl App {
|
|||||||
Span::styled(format!(" {} ", SPINNER[self.tick % SPINNER.len()]), Style::default().fg(th.accent2)),
|
Span::styled(format!(" {} ", SPINNER[self.tick % SPINNER.len()]), Style::default().fg(th.accent2)),
|
||||||
Span::styled(format!("{}…", t("working")), Style::default().fg(th.accent2)),
|
Span::styled(format!("{}…", t("working")), Style::default().fg(th.accent2)),
|
||||||
Span::styled(format!(" ({secs}s · ~{} tokens) · {}", self.step_chars / 4, t("interrupt")), Style::default().fg(th.muted)),
|
Span::styled(format!(" ({secs}s · ~{} tokens) · {}", self.step_chars / 4, t("interrupt")), Style::default().fg(th.muted)),
|
||||||
Span::styled(if self.queue.is_empty() { String::new() } else { format!(" · {} {}", self.queue.len(), t("queued")) }, Style::default().fg(th.muted)),
|
Span::styled({ let n = if self.remote.is_some() { self.remote_queue.len() } else { self.queue.len() }; if n == 0 { String::new() } else { format!(" · {} {}", n, t("queued")) } }, Style::default().fg(th.muted)),
|
||||||
])
|
])
|
||||||
} else {
|
} else {
|
||||||
Line::from(Span::styled(format!(" {}", self.status), Style::default().fg(th.muted)))
|
Line::from(Span::styled(format!(" {}", self.status), Style::default().fg(th.muted)))
|
||||||
};
|
};
|
||||||
f.render_widget(Paragraph::new(activity), act);
|
f.render_widget(Paragraph::new(activity), act);
|
||||||
|
if queue_h > 0 {
|
||||||
|
f.render_widget(Paragraph::new(queue_lines), queue_area);
|
||||||
|
}
|
||||||
|
|
||||||
// Input.
|
// Input.
|
||||||
let mode_col = match self.session.mode.as_str() {
|
let mode_col = match self.session.mode.as_str() {
|
||||||
@@ -1383,22 +1890,26 @@ impl App {
|
|||||||
let inner = block.inner(input);
|
let inner = block.inner(input);
|
||||||
f.render_widget(block, input);
|
f.render_widget(block, input);
|
||||||
let visible = inner.height as usize;
|
let visible = inner.height as usize;
|
||||||
let first = self.editor.row.saturating_sub(visible.saturating_sub(1));
|
let (crow, ccol) = self.editor.cursor_in(&layout);
|
||||||
let text: Vec<Line> = if self.editor.is_empty() {
|
let first = crow.saturating_sub(visible.saturating_sub(1));
|
||||||
vec![Line::from(Span::styled(if self.busy { t("busy_placeholder") } else { t("placeholder") }, Style::default().fg(th.muted)))]
|
if self.editor.is_empty() {
|
||||||
|
let hint = Line::from(Span::styled(if self.busy { t("busy_placeholder") } else { t("placeholder") }, Style::default().fg(th.muted)));
|
||||||
|
f.render_widget(Paragraph::new(hint).wrap(Wrap { trim: false }), inner);
|
||||||
} else {
|
} else {
|
||||||
self.editor.lines[first..].iter().take(visible).map(|l| Line::from(Span::styled(l.clone(), Style::default().fg(th.fg0)))).collect()
|
let text: Vec<Line> = layout[first..].iter().take(visible).map(|r| Line::from(Span::styled(self.editor.row_text(*r), Style::default().fg(th.fg0)))).collect();
|
||||||
};
|
f.render_widget(Paragraph::new(text), inner);
|
||||||
let scroll_x = self.editor.cursor_x().saturating_sub(inner.width.saturating_sub(1) as usize) as u16;
|
}
|
||||||
f.render_widget(Paragraph::new(text).scroll((0, scroll_x)), inner);
|
|
||||||
if matches!(self.dialog, Dialog::None) {
|
if matches!(self.dialog, Dialog::None) {
|
||||||
f.set_cursor_position((inner.x + self.editor.cursor_x() as u16 - scroll_x, inner.y + (self.editor.row - first) as u16));
|
f.set_cursor_position((inner.x + (ccol as u16).min(inner.width.saturating_sub(1)), inner.y + (crow - first) as u16));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status line.
|
// Status line.
|
||||||
let ctx_pct = self.env.catalog.find(&self.session.model).and_then(|m| m.config.context).filter(|c| *c > 0).map(|c| format!("{} {}%", t("context"), self.context * 100 / c)).unwrap_or_default();
|
let ctx_pct = self.env.catalog.find(&self.session.model).and_then(|m| m.config.context).filter(|c| *c > 0).map(|c| format!("{} {}%", t("context"), self.context * 100 / c)).unwrap_or_default();
|
||||||
let cost = if self.session.cost > 0.0 { format!(" · {:.3} {}", self.session.cost, self.env.catalog.currency) } else { String::new() };
|
let cost = if self.session.cost > 0.0 { format!(" · {:.3} {}", self.session.cost, self.env.catalog.currency) } else { String::new() };
|
||||||
let left = format!(" {} · {} ", self.model_label(), self.session.permission_mode);
|
let left = match &self.remote {
|
||||||
|
Some(r) => format!(" server · {} · {} ", r.model, r.agent),
|
||||||
|
None => format!(" {} · {} ", self.model_label(), self.session.permission_mode),
|
||||||
|
};
|
||||||
let right = format!("{ctx_pct}{cost} · Shift+Tab {} · /help ", t("mode"));
|
let right = format!("{ctx_pct}{cost} · Shift+Tab {} · /help ", t("mode"));
|
||||||
let pad = (area.width as usize).saturating_sub(left.chars().count() + right.chars().count());
|
let pad = (area.width as usize).saturating_sub(left.chars().count() + right.chars().count());
|
||||||
f.render_widget(Paragraph::new(Line::from(vec![Span::styled(left, Style::default().fg(th.fg3)), Span::raw(" ".repeat(pad)), Span::styled(right, Style::default().fg(th.muted))])).style(Style::default().bg(th.bg1)), status);
|
f.render_widget(Paragraph::new(Line::from(vec![Span::styled(left, Style::default().fg(th.fg3)), Span::raw(" ".repeat(pad)), Span::styled(right, Style::default().fg(th.muted))])).style(Style::default().bg(th.bg1)), status);
|
||||||
@@ -1469,14 +1980,39 @@ impl App {
|
|||||||
}
|
}
|
||||||
Dialog::Question { questions, idx, sel, custom, .. } => {
|
Dialog::Question { questions, idx, sel, custom, .. } => {
|
||||||
let q = &questions[*idx];
|
let q = &questions[*idx];
|
||||||
let mut lines = vec![Line::from(Span::styled(q.question.clone(), Style::default().fg(th.fg0).add_modifier(Modifier::BOLD))), Line::default()];
|
// Everything wraps at the width of the box (it is 90 columns wide, less on small terminals).
|
||||||
|
let w = (90.min(area.width.saturating_sub(4)) as usize).saturating_sub(2).max(10);
|
||||||
|
let mut lines: Vec<Line> = wrap(&q.question, w).into_iter().map(|l| Line::from(Span::styled(l, Style::default().fg(th.fg0).add_modifier(Modifier::BOLD)))).collect();
|
||||||
|
lines.push(Line::default());
|
||||||
for (i, o) in q.options.iter().enumerate() {
|
for (i, o) in q.options.iter().enumerate() {
|
||||||
let st = if i == *sel && custom.is_empty() { Style::default().fg(th.on_accent).bg(th.accent) } else { Style::default().fg(th.fg1) };
|
let on = i == *sel && custom.is_empty();
|
||||||
lines.push(Line::from(vec![Span::styled(format!(" {}. {} ", i + 1, o.label), st), Span::styled(format!(" {}", o.description), Style::default().fg(th.muted))]));
|
let prefix = format!(" {}. {} ", i + 1, o.label);
|
||||||
|
let full = if o.description.is_empty() { prefix.clone() } else { format!("{prefix} {}", o.description) };
|
||||||
|
for (r, row) in wrap(&full, w.saturating_sub(4)).into_iter().enumerate() {
|
||||||
|
let row = if r == 0 { row } else { format!(" {row}") };
|
||||||
|
if on {
|
||||||
|
lines.push(Line::from(Span::styled(row, Style::default().fg(th.on_accent).bg(th.accent))));
|
||||||
|
} else if r == 0 {
|
||||||
|
let cut = row.char_indices().nth(prefix.chars().count()).map(|(b, _)| b).unwrap_or(row.len());
|
||||||
|
lines.push(Line::from(vec![Span::styled(row[..cut].to_string(), Style::default().fg(th.fg1)), Span::styled(row[cut..].to_string(), Style::default().fg(th.muted))]));
|
||||||
|
} else {
|
||||||
|
lines.push(Line::from(Span::styled(row, Style::default().fg(th.muted))));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
lines.push(Line::default());
|
lines.push(Line::default());
|
||||||
lines.push(Line::from(Span::styled(format!("> {custom}_"), Style::default().fg(th.fg0))));
|
// The own answer: wrapped as typed; only its last rows are shown when it gets long.
|
||||||
lines.push(Line::from(Span::styled(t("question_keys"), Style::default().fg(th.muted))));
|
let typed = hard_wrap(&format!("> {custom}_"), w);
|
||||||
|
let skip = typed.len().saturating_sub(6);
|
||||||
|
if skip > 0 {
|
||||||
|
lines.push(Line::from(Span::styled(" …", Style::default().fg(th.muted))));
|
||||||
|
}
|
||||||
|
for row in typed.into_iter().skip(skip) {
|
||||||
|
lines.push(Line::from(Span::styled(row, Style::default().fg(th.fg0))));
|
||||||
|
}
|
||||||
|
for row in wrap(t("question_keys"), w) {
|
||||||
|
lines.push(Line::from(Span::styled(row, Style::default().fg(th.muted))));
|
||||||
|
}
|
||||||
let title = format!("{} {}/{}", t("question"), idx + 1, questions.len());
|
let title = format!("{} {}/{}", t("question"), idx + 1, questions.len());
|
||||||
let inner = boxed(f, &title, 90, lines.len() as u16 + 2, th.blue);
|
let inner = boxed(f, &title, 90, lines.len() as u16 + 2, th.blue);
|
||||||
f.render_widget(Paragraph::new(lines), inner);
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
@@ -1631,3 +2167,89 @@ impl App {
|
|||||||
self.status = s;
|
self.status = s;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod wrap_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hard_wrap_keeps_every_character() {
|
||||||
|
let rows = hard_wrap("abc def ghi", 5);
|
||||||
|
assert_eq!(rows.join(""), "abc def ghi");
|
||||||
|
assert!(rows.iter().all(|r| UnicodeWidthStr::width(r.as_str()) <= 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hard_wrap_counts_wide_characters() {
|
||||||
|
let rows = hard_wrap("日本語日本語", 4);
|
||||||
|
assert_eq!(rows, vec!["日本", "語日", "本語"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod render_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::agent::Env;
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::TestBackend;
|
||||||
|
|
||||||
|
fn app() -> App {
|
||||||
|
let cfg: crate::conf::Config = serde_json::from_str("{}").expect("empty config");
|
||||||
|
let env = Env {
|
||||||
|
cfg,
|
||||||
|
server: None,
|
||||||
|
server_cfg: None,
|
||||||
|
catalog: Default::default(),
|
||||||
|
modes: crate::agent::builtin_modes(),
|
||||||
|
permissions: Default::default(),
|
||||||
|
base_prompt: String::new(),
|
||||||
|
auto_prompt: String::new(),
|
||||||
|
remote_tools: Vec::new(),
|
||||||
|
server_skills: Vec::new(),
|
||||||
|
memory: String::new(),
|
||||||
|
};
|
||||||
|
let session = LocalSession { id: "t".into(), title: String::new(), cwd: "/tmp".into(), model: String::new(), mode: "build".into(), permission_mode: "default".into(), created_at: 0, updated_at: 0, messages: Vec::new(), usage: Default::default(), cost: 0.0, todos: Value::Null, context_tokens: 0 };
|
||||||
|
let (tx, _rx) = mpsc::unbounded_channel();
|
||||||
|
App::new(Arc::new(env), session, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn screen(app: &mut App, w: u16, h: u16) -> String {
|
||||||
|
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
|
||||||
|
term.draw(|f| app.draw(f)).unwrap();
|
||||||
|
let buf = term.backend().buffer().clone();
|
||||||
|
(0..h).map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>()).collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn queued_messages_show_above_the_input_and_wrap() {
|
||||||
|
let mut a = app();
|
||||||
|
a.busy = true;
|
||||||
|
a.queue.push_back("Das ist eine lange wartende Nachricht, die ueber mehrere Zeilen umbrechen muss weil sie so lang ist".into());
|
||||||
|
a.queue.push_back("zweite".into());
|
||||||
|
let s = screen(&mut a, 50, 20);
|
||||||
|
assert!(s.contains("↳ Das ist eine lange"), "{s}");
|
||||||
|
assert!(s.contains("↳ zweite"), "{s}");
|
||||||
|
assert!(s.contains("sofort zustellen") || s.contains("deliver now"), "{s}");
|
||||||
|
let q = s.lines().position(|l| l.contains("↳ Das")).unwrap();
|
||||||
|
let input = s.lines().position(|l| l.contains('╭') && l.contains("build")).unwrap();
|
||||||
|
assert!(q < input, "the queue is above the input\n{s}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn long_question_and_options_wrap_instead_of_being_cut() {
|
||||||
|
let mut a = app();
|
||||||
|
let (tx, _rx) = oneshot::channel();
|
||||||
|
a.dialog = Dialog::Question {
|
||||||
|
questions: vec![Question { question: "Soll der Builder das Limit auf sechs Mebibyte anheben oder lieber einzelne Grammatiken weglassen, obwohl die Spec das verbietet?".into(), header: String::new(), options: vec![codecraft_core::types::QuestionOption { label: "Limit anheben".into(), description: "Das Archiv bleibt vollstaendig und waechst auf knapp fuenf Mebibyte an".into() }], multi_select: false }],
|
||||||
|
idx: 0,
|
||||||
|
sel: 0,
|
||||||
|
custom: "eine sehr lange eigene Antwort die in dem Feld nicht mehr in eine Zeile passt und deshalb umbrechen muss".into(),
|
||||||
|
answers: Default::default(),
|
||||||
|
reply: Some(tx),
|
||||||
|
};
|
||||||
|
let s = screen(&mut a, 60, 30);
|
||||||
|
for part in ["Mebibyte anheben", "weglassen", "knapp", "Antwort", "umbrechen muss"] {
|
||||||
|
assert!(s.contains(part), "missing {part}\n{s}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
//! Multi-line input field with history.
|
//! Multi-line input field with history.
|
||||||
|
|
||||||
use unicode_width::UnicodeWidthStr;
|
use unicode_width::UnicodeWidthChar;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Editor {
|
pub struct Editor {
|
||||||
@@ -211,9 +211,103 @@ impl Editor {
|
|||||||
self.col = start + with.chars().count();
|
self.col = start + with.chars().count();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cursor position in display columns (for the terminal cursor).
|
/// The text as it is shown at `width` columns: every logical line is broken into rows, preferably after a
|
||||||
pub fn cursor_x(&self) -> usize {
|
/// space, otherwise inside a long word. Each row is (line index, first char, end char).
|
||||||
let line = &self.lines[self.row];
|
pub fn layout(&self, width: usize) -> Vec<(usize, usize, usize)> {
|
||||||
UnicodeWidthStr::width(&line[..byte_idx(line, self.col)])
|
let width = width.max(1);
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for (i, line) in self.lines.iter().enumerate() {
|
||||||
|
let chars: Vec<char> = line.chars().collect();
|
||||||
|
if chars.is_empty() {
|
||||||
|
rows.push((i, 0, 0));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut start = 0;
|
||||||
|
while start < chars.len() {
|
||||||
|
let mut w = 0;
|
||||||
|
let mut end = start;
|
||||||
|
let mut last_space = None;
|
||||||
|
while end < chars.len() {
|
||||||
|
let cw = UnicodeWidthChar::width(chars[end]).unwrap_or(0);
|
||||||
|
if w + cw > width && end > start {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
w += cw;
|
||||||
|
end += 1;
|
||||||
|
if chars[end - 1] == ' ' {
|
||||||
|
last_space = Some(end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if end < chars.len() {
|
||||||
|
if let Some(sp) = last_space.filter(|sp| *sp > start) {
|
||||||
|
end = sp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.push((i, start, end));
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text of one row of `layout`.
|
||||||
|
pub fn row_text(&self, (line, a, b): (usize, usize, usize)) -> String {
|
||||||
|
self.lines[line].chars().skip(a).take(b - a).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cursor in the wrapped view: (row index in `layout`, display column).
|
||||||
|
pub fn cursor_in(&self, layout: &[(usize, usize, usize)]) -> (usize, usize) {
|
||||||
|
for (n, &(line, a, b)) in layout.iter().enumerate() {
|
||||||
|
let last = layout.get(n + 1).is_none_or(|next| next.0 != line);
|
||||||
|
if line == self.row && self.col >= a && (self.col < b || (last && self.col <= b)) {
|
||||||
|
let w: usize = self.lines[line].chars().skip(a).take(self.col - a).map(|c| UnicodeWidthChar::width(c).unwrap_or(0)).sum();
|
||||||
|
return (n, w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(layout.len().saturating_sub(1), 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn editor(text: &str) -> Editor {
|
||||||
|
let mut e = Editor { lines: vec![String::new()], ..Default::default() };
|
||||||
|
e.set(text);
|
||||||
|
e
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn long_line_wraps_at_spaces() {
|
||||||
|
let e = editor("aaa bbb ccc ddd");
|
||||||
|
let rows: Vec<String> = e.layout(8).into_iter().map(|r| e.row_text(r)).collect();
|
||||||
|
assert_eq!(rows, vec!["aaa bbb ", "ccc ddd"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn long_word_breaks_inside() {
|
||||||
|
let e = editor("abcdefghij");
|
||||||
|
let rows: Vec<String> = e.layout(4).into_iter().map(|r| e.row_text(r)).collect();
|
||||||
|
assert_eq!(rows, vec!["abcd", "efgh", "ij"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_lines_keep_a_row_and_nothing_is_lost() {
|
||||||
|
let e = editor("one\n\ntwo words here");
|
||||||
|
let l = e.layout(6);
|
||||||
|
let joined: String = l.iter().map(|r| e.row_text(*r)).collect::<Vec<_>>().join("|");
|
||||||
|
assert_eq!(joined, "one||two |words |here");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cursor_follows_the_wrap() {
|
||||||
|
let mut e = editor("aaa bbb ccc ddd");
|
||||||
|
let l = e.layout(8);
|
||||||
|
assert_eq!(e.cursor_in(&l), (1, 7)); // end of the text, second row
|
||||||
|
e.col = 8; // before "ccc"
|
||||||
|
assert_eq!(e.cursor_in(&l), (1, 0));
|
||||||
|
e.col = 3;
|
||||||
|
assert_eq!(e.cursor_in(&l), (0, 3));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,7 @@ pub fn system_lang() -> String {
|
|||||||
|
|
||||||
/// (key, English, German)
|
/// (key, English, German)
|
||||||
const TEXTS: &[(&str, &str, &str)] = &[
|
const TEXTS: &[(&str, &str, &str)] = &[
|
||||||
("placeholder", "Message… (/ commands, @ files, Shift+Enter new line)", "Nachricht… (/ Befehle, @ Dateien, Shift+Enter neue Zeile)"),
|
("placeholder", "Message… (/ commands, @ files, Shift+Enter or Ctrl+J new line)", "Nachricht… (/ Befehle, @ Dateien, Shift+Enter oder Strg+J neue Zeile)"),
|
||||||
("busy_placeholder", "Message is queued and sent after this turn…", "Nachricht wird nach diesem Schritt gesendet…"),
|
("busy_placeholder", "Message is queued and sent after this turn…", "Nachricht wird nach diesem Schritt gesendet…"),
|
||||||
("permission", "Permission required", "Freigabe erforderlich"),
|
("permission", "Permission required", "Freigabe erforderlich"),
|
||||||
("perm_keys", "[y] allow once [a] always in this session [n] reject [f] reject with feedback", "[y] einmal erlauben [a] immer in dieser Session [n] ablehnen [f] ablehnen mit Hinweis"),
|
("perm_keys", "[y] allow once [a] always in this session [n] reject [f] reject with feedback", "[y] einmal erlauben [a] immer in dieser Session [n] ablehnen [f] ablehnen mit Hinweis"),
|
||||||
@@ -36,6 +36,8 @@ const TEXTS: &[(&str, &str, &str)] = &[
|
|||||||
("choose_theme", "Choose a theme", "Theme wählen"),
|
("choose_theme", "Choose a theme", "Theme wählen"),
|
||||||
("filter", "type to filter", "tippen zum Filtern"),
|
("filter", "type to filter", "tippen zum Filtern"),
|
||||||
("queued", "queued", "in der Warteschlange"),
|
("queued", "queued", "in der Warteschlange"),
|
||||||
|
("force_hint", "Enter on the empty field: deliver now (interrupts the running step)", "Enter im leeren Feld: sofort zustellen (unterbricht den laufenden Schritt)"),
|
||||||
|
("forcing", "interrupting – the queued message is sent now", "unterbreche – die Nachricht wird jetzt gesendet"),
|
||||||
("welcome", "Welcome to CodeCraft", "Willkommen bei CodeCraft"),
|
("welcome", "Welcome to CodeCraft", "Willkommen bei CodeCraft"),
|
||||||
("setup_title", "Set up CodeCraft", "CodeCraft einrichten"),
|
("setup_title", "Set up CodeCraft", "CodeCraft einrichten"),
|
||||||
("setup_intro", "Where should the models come from? You can add more later with /setup.", "Woher sollen die Modelle kommen? Weitere kannst du später mit /setup hinzufügen."),
|
("setup_intro", "Where should the models come from? You can add more later with /setup.", "Woher sollen die Modelle kommen? Weitere kannst du später mit /setup hinzufügen."),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ mod conf;
|
|||||||
mod editor;
|
mod editor;
|
||||||
mod i18n;
|
mod i18n;
|
||||||
mod models;
|
mod models;
|
||||||
|
mod remote;
|
||||||
mod server;
|
mod server;
|
||||||
mod session;
|
mod session;
|
||||||
mod stats;
|
mod stats;
|
||||||
|
|||||||
@@ -0,0 +1,304 @@
|
|||||||
|
//! Remote control of the server: chats that run on the CodeCraft server (`/projects`) and the
|
||||||
|
//! software factory board (`/factory`). Everything goes through the server's REST API with the
|
||||||
|
//! login's token; the chat view polls every second or two instead of holding a socket open.
|
||||||
|
|
||||||
|
use crate::server::Server;
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use codecraft_core::types::Message;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
/// How many messages of a remote chat are loaded (its end; older ones stay on the server).
|
||||||
|
const WINDOW: usize = 300;
|
||||||
|
|
||||||
|
/// A chat of the server that this terminal follows.
|
||||||
|
pub struct Remote {
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub cwd: String,
|
||||||
|
pub agent: String,
|
||||||
|
pub model: String,
|
||||||
|
pub last_poll: Instant,
|
||||||
|
/// Requests already answered here (the server confirms them with the next poll).
|
||||||
|
pub answered: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State of a remote chat at one moment.
|
||||||
|
pub struct Snapshot {
|
||||||
|
pub messages: Vec<Message>,
|
||||||
|
pub busy: bool,
|
||||||
|
pub title: String,
|
||||||
|
pub todos: Value,
|
||||||
|
/// Open permission and question requests of this chat (and its subagents).
|
||||||
|
pub pending: Vec<Value>,
|
||||||
|
/// Messages waiting for the agent (text of each).
|
||||||
|
pub queue: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn short(s: &str, n: usize) -> String {
|
||||||
|
let t: String = s.chars().take(n).collect();
|
||||||
|
if s.chars().count() > n { format!("{t}…") } else { t }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ago(ms: i64) -> String {
|
||||||
|
let d = (chrono::Utc::now().timestamp_millis() - ms).max(0) / 1000;
|
||||||
|
match d {
|
||||||
|
0..=89 => "now".into(),
|
||||||
|
90..=5399 => format!("{} min ago", d / 60),
|
||||||
|
5400..=129_599 => format!("{} h ago", d / 3600),
|
||||||
|
_ => format!("{} d ago", d / 86_400),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user's chats on the server as picker entries: (id, title, description). Busy chats first.
|
||||||
|
pub async fn sessions(server: &Server) -> Result<Vec<(String, String, String)>> {
|
||||||
|
let v = server.get("/sessions").await?;
|
||||||
|
let mut list: Vec<Value> = v.as_array().cloned().unwrap_or_default().into_iter().filter(|s| s["parent_id"].is_null() && s["archived"] != true).collect();
|
||||||
|
list.sort_by_key(|s| (!s["busy"].as_bool().unwrap_or(false), std::cmp::Reverse(s["updated_at"].as_i64().unwrap_or(0))));
|
||||||
|
Ok(list
|
||||||
|
.into_iter()
|
||||||
|
.take(200)
|
||||||
|
.map(|s| {
|
||||||
|
let title = s["title"].as_str().filter(|t| !t.is_empty()).unwrap_or("(untitled)").to_string();
|
||||||
|
let folder = s["folder"].as_str().filter(|f| !f.is_empty()).map(|f| format!("[{f}] ")).unwrap_or_default();
|
||||||
|
let cwd = s["cwd"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("").to_string();
|
||||||
|
let state = if s["busy"].as_bool().unwrap_or(false) { "working · " } else { "" };
|
||||||
|
(s["id"].as_str().unwrap_or("").to_string(), format!("{folder}{title}"), format!("{state}{cwd} · {} · {}", s["agent"].as_str().unwrap_or(""), ago(s["updated_at"].as_i64().unwrap_or(0))))
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load a chat: its end, whether it is working, its task list and what waits for an answer.
|
||||||
|
pub async fn snapshot(server: &Server, id: &str) -> Result<Snapshot> {
|
||||||
|
let path = format!("/sessions/{id}?limit={WINDOW}");
|
||||||
|
let (s, pending) = tokio::join!(server.get(&path), server.get("/pending"));
|
||||||
|
let s = s?;
|
||||||
|
let messages: Vec<Message> = serde_json::from_value(s["messages"].clone()).unwrap_or_default();
|
||||||
|
let pending = pending
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| p.as_array().cloned())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|e| e["session_id"].as_str() == Some(id) || e["root_session_id"].as_str() == Some(id))
|
||||||
|
.collect();
|
||||||
|
let queue = s["queue"]
|
||||||
|
.as_array()
|
||||||
|
.map(|a| {
|
||||||
|
a.iter()
|
||||||
|
.filter(|i| i["source"].as_str() != Some("background"))
|
||||||
|
.map(|i| i["parts"].as_array().map(|p| p.iter().filter_map(|x| x["text"].as_str()).collect::<Vec<_>>().join(" ")).unwrap_or_default())
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
Ok(Snapshot { messages, busy: s["busy"].as_bool().unwrap_or(false), title: s["session"]["title"].as_str().unwrap_or("").to_string(), todos: s["session"]["todos"].clone(), pending, queue })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn open(server: &Server, id: &str) -> Result<Remote> {
|
||||||
|
let s = server.get(&format!("/sessions/{id}?limit=1")).await?;
|
||||||
|
let s = &s["session"];
|
||||||
|
if s["id"].as_str().is_none() {
|
||||||
|
bail!("unknown chat");
|
||||||
|
}
|
||||||
|
Ok(Remote {
|
||||||
|
id: id.to_string(),
|
||||||
|
title: s["title"].as_str().unwrap_or("").to_string(),
|
||||||
|
cwd: s["cwd"].as_str().unwrap_or("").to_string(),
|
||||||
|
agent: s["agent"].as_str().unwrap_or("").to_string(),
|
||||||
|
model: s["model"].as_str().unwrap_or("").to_string(),
|
||||||
|
last_poll: Instant::now(),
|
||||||
|
answered: HashSet::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn prompt(server: &Server, id: &str, text: &str) -> Result<()> {
|
||||||
|
server.post(&format!("/sessions/{id}/prompt"), json!({"text": text})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unsent message of a server chat (typed in the web UI or in another terminal).
|
||||||
|
pub async fn draft_get(server: &Server, id: &str) -> Result<String> {
|
||||||
|
let d = server.get(&format!("/sessions/{id}/composer-draft")).await?;
|
||||||
|
Ok(d["text"].as_str().unwrap_or("").to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn draft_put(server: &Server, id: &str, text: &str) -> Result<()> {
|
||||||
|
server.put(&format!("/sessions/{id}/composer-draft"), json!({"text": text})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn abort(server: &Server, id: &str) -> Result<()> {
|
||||||
|
server.post(&format!("/sessions/{id}/abort"), json!({})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Interrupt the running step and deliver the queued messages at once.
|
||||||
|
pub async fn force_queue(server: &Server, id: &str) -> Result<()> {
|
||||||
|
server.post(&format!("/sessions/{id}/queue/force"), json!({})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn compact(server: &Server, id: &str) -> Result<()> {
|
||||||
|
server.post(&format!("/sessions/{id}/compact"), json!({})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer a permission request. reply: once, always, project, reject.
|
||||||
|
pub async fn reply_permission(server: &Server, id: &str, reply: &str, message: Option<String>) -> Result<()> {
|
||||||
|
server.post(&format!("/permissions/{id}"), json!({"reply": reply, "message": message})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn answer_question(server: &Server, id: &str, answers: Option<serde_json::Map<String, Value>>) -> Result<()> {
|
||||||
|
server.post(&format!("/questions/{id}"), json!({"answers": answers})).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- software factory ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Column of the board for an issue state.
|
||||||
|
pub fn column(state: &str) -> &'static str {
|
||||||
|
match state {
|
||||||
|
"new" | "review" => "Review",
|
||||||
|
"question" => "Question",
|
||||||
|
"approved" => "Approved",
|
||||||
|
"building" | "rework" => "Build",
|
||||||
|
"qa" | "testing" => "Acceptance",
|
||||||
|
"failed" | "rejected" => "Failed",
|
||||||
|
"done" => "Done",
|
||||||
|
"closed" => "Closed",
|
||||||
|
_ => "Other",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn repo_name(url: &str) -> String {
|
||||||
|
url.trim_end_matches(".git").rsplit('/').take(2).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("/")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The board as picker entries (key "repo#number") and a summary line for the title.
|
||||||
|
pub async fn factory_board(server: &Server) -> Result<(String, Vec<(String, String, String)>)> {
|
||||||
|
let v = server.get("/factory/overview").await?;
|
||||||
|
let issues = v["issues"].as_array().cloned().unwrap_or_default();
|
||||||
|
let runs = v["runs"].as_array().cloned().unwrap_or_default();
|
||||||
|
let running = issues.iter().filter(|i| matches!(i["state"].as_str(), Some("review" | "building" | "testing"))).count();
|
||||||
|
let done = issues.iter().filter(|i| i["state"] == "done").count();
|
||||||
|
let cost: f64 = runs.iter().map(|r| r["cost"].as_f64().unwrap_or(0.0)).sum();
|
||||||
|
let summary = format!("Factory · {} issues · {running} running · {done} done · {} runs · ${cost:.2}", issues.iter().filter(|i| i["state"] != "closed").count(), runs.len());
|
||||||
|
let order = ["Question", "Failed", "Build", "Acceptance", "Review", "Approved", "Done"];
|
||||||
|
let mut rows: Vec<(usize, String, String, String)> = issues
|
||||||
|
.iter()
|
||||||
|
.filter(|i| i["state"] != "closed")
|
||||||
|
.map(|i| {
|
||||||
|
let state = i["state"].as_str().unwrap_or("");
|
||||||
|
let col = column(state);
|
||||||
|
let key = format!("{}#{}", i["repo"].as_str().unwrap_or(""), i["number"].as_i64().unwrap_or(0));
|
||||||
|
let latest = runs.iter().find(|r| r["repo"] == i["repo"] && r["issue"] == i["number"]);
|
||||||
|
let run = latest.map(|r| format!(" · {} {}", r["phase"].as_str().unwrap_or(""), if r["ended_at"].is_null() { "running" } else { r["status"].as_str().unwrap_or("") })).unwrap_or_default();
|
||||||
|
let ver = i["version"].as_str().filter(|v| !v.is_empty()).map(|v| format!(" v{v}")).unwrap_or_default();
|
||||||
|
(
|
||||||
|
order.iter().position(|c| *c == col).unwrap_or(order.len()),
|
||||||
|
key,
|
||||||
|
format!("{col:<10} {} #{} {}", repo_name(i["repo"].as_str().unwrap_or("")), i["number"].as_i64().unwrap_or(0), short(i["title"].as_str().unwrap_or(""), 60)),
|
||||||
|
format!("{}{run}{ver}", short(i["note"].as_str().unwrap_or("").replace('\n', " ").as_str(), 80)),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
rows.sort_by_key(|r| r.0);
|
||||||
|
Ok((summary, rows.into_iter().map(|(_, k, l, d)| (k, l, d)).collect()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Split a board key "repo#number".
|
||||||
|
pub fn split_key(key: &str) -> Result<(String, i64)> {
|
||||||
|
let (repo, n) = key.rsplit_once('#').context("invalid issue")?;
|
||||||
|
Ok((repo.to_string(), n.parse()?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What can be done with an issue in this state: (action key, label, description).
|
||||||
|
pub async fn factory_actions(server: &Server, key: &str) -> Result<(String, Vec<(String, String, String)>)> {
|
||||||
|
let (repo, n) = split_key(key)?;
|
||||||
|
let v = server.get("/factory/overview").await?;
|
||||||
|
let issue = v["issues"].as_array().and_then(|a| a.iter().find(|i| i["number"] == n && i["repo"] == repo)).cloned().context("the issue is gone")?;
|
||||||
|
let state = issue["state"].as_str().unwrap_or("").to_string();
|
||||||
|
let busy = matches!(state.as_str(), "review" | "building" | "testing");
|
||||||
|
let title = format!("{} #{n} – {} [{}]", repo_name(&repo), short(issue["title"].as_str().unwrap_or(""), 50), column(&state));
|
||||||
|
let mut acts: Vec<(String, String, String)> = Vec::new();
|
||||||
|
// The chats of its runs.
|
||||||
|
for r in v["runs"].as_array().into_iter().flatten().filter(|r| r["issue"] == n && (r["repo"] == repo)).take(6) {
|
||||||
|
acts.push((format!("chat:{}", r["session_id"].as_str().unwrap_or("")), format!("Open the {} chat", r["phase"].as_str().unwrap_or("")), format!("{} · {}", r["model"].as_str().unwrap_or(""), if r["ended_at"].is_null() { "running".to_string() } else { r["status"].as_str().unwrap_or("").to_string() })));
|
||||||
|
}
|
||||||
|
if state == "done" {
|
||||||
|
if let Ok(p) = server.get(&format!("/factory/issues/pr?repo={}&number={n}", urlenc(&repo))).await {
|
||||||
|
if let Some(pr) = p["pr"].as_object() {
|
||||||
|
if pr.get("state").and_then(|s| s.as_str()) == Some("open") {
|
||||||
|
let num = pr.get("number").and_then(|x| x.as_i64()).unwrap_or(0);
|
||||||
|
for (m, d) in [("merge", "merge commit"), ("squash", "squash into one commit"), ("rebase", "rebase onto the base branch")] {
|
||||||
|
acts.push((format!("merge:{num}:{m}"), format!("Merge pull request #{num} ({m})"), d.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acts.push(("close".into(), "Close the issue".into(), "comments and closes it on the forge".into()));
|
||||||
|
}
|
||||||
|
if !busy {
|
||||||
|
for (to, label) in [("new", "Restart at the review"), ("approved", "Restart at the build"), ("qa", "Restart at the acceptance")] {
|
||||||
|
acts.push((format!("restart:{to}"), label.into(), String::new()));
|
||||||
|
}
|
||||||
|
acts.push(("remove".into(), "Remove from the board".into(), "the issue on the forge stays as it is".into()));
|
||||||
|
}
|
||||||
|
Ok((title, acts))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn urlenc(s: &str) -> String {
|
||||||
|
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run an action chosen in `factory_actions` (everything except opening a chat). Returns a message.
|
||||||
|
pub async fn factory_do(server: &Server, key: &str, action: &str) -> Result<String> {
|
||||||
|
let (repo, number) = split_key(key)?;
|
||||||
|
let (verb, arg) = action.split_once(':').unwrap_or((action, ""));
|
||||||
|
match verb {
|
||||||
|
"restart" => {
|
||||||
|
server.post("/factory/issues/restart", json!({"repo": repo, "number": number, "to": arg})).await?;
|
||||||
|
Ok(format!("#{number} restarted"))
|
||||||
|
}
|
||||||
|
"remove" => {
|
||||||
|
server.post("/factory/issues/remove", json!({"repo": repo, "number": number})).await?;
|
||||||
|
Ok(format!("#{number} removed from the board"))
|
||||||
|
}
|
||||||
|
"close" => {
|
||||||
|
server.post("/factory/issues/close", json!({"repo": repo, "number": number, "comment": "Closed from the terminal."})).await?;
|
||||||
|
Ok(format!("#{number} closed"))
|
||||||
|
}
|
||||||
|
"merge" => {
|
||||||
|
let (pr, method) = arg.split_once(':').context("invalid merge")?;
|
||||||
|
server.post("/factory/issues/pr/merge", json!({"repo": repo, "number": number, "pr": pr.parse::<i64>()?, "method": method})).await?;
|
||||||
|
Ok(format!("pull request #{pr} merged ({method})"))
|
||||||
|
}
|
||||||
|
_ => bail!("unknown action"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn factory_poll(server: &Server) -> Result<String> {
|
||||||
|
let v = server.post("/factory/poll", json!({})).await?;
|
||||||
|
let errs = v["errors"].as_array().map(|a| a.len()).unwrap_or(0);
|
||||||
|
Ok(if errs == 0 { "checked for new issues".into() } else { format!("checked – {errs} repository error(s)") })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn board_columns_and_keys() {
|
||||||
|
assert_eq!(column("rework"), "Build");
|
||||||
|
assert_eq!(column("testing"), "Acceptance");
|
||||||
|
assert_eq!(column("rejected"), "Failed");
|
||||||
|
assert_eq!(repo_name("https://git.example.org/acme/demo-shop.git"), "acme/demo-shop");
|
||||||
|
let (repo, n) = split_key("https://git.example.org/acme/demo-shop.git#12").unwrap();
|
||||||
|
assert_eq!((repo.as_str(), n), ("https://git.example.org/acme/demo-shop.git", 12));
|
||||||
|
assert!(split_key("nonsense").is_err());
|
||||||
|
assert_eq!(urlenc("https://a/b c"), "https%3A%2F%2Fa%2Fb%20c");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn relative_times() {
|
||||||
|
let now = chrono::Utc::now().timestamp_millis();
|
||||||
|
assert_eq!(ago(now), "now");
|
||||||
|
assert_eq!(ago(now - 10 * 60_000), "10 min ago");
|
||||||
|
assert_eq!(ago(now - 5 * 3_600_000), "5 h ago");
|
||||||
|
assert_eq!(ago(now - 3 * 86_400_000), "3 d ago");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -74,6 +74,11 @@ impl Server {
|
|||||||
Ok(check(resp).await?.json().await?)
|
Ok(check(resp).await?.json().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn put(&self, path: &str, body: Value) -> Result<Value> {
|
||||||
|
let resp = self.http.put(format!("{}/api{path}", self.url)).bearer_auth(&self.token).json(&body).send().await.with_context(|| format!("cannot reach {}", self.url))?;
|
||||||
|
Ok(check(resp).await?.json().await?)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn post(&self, path: &str, body: Value) -> Result<Value> {
|
pub async fn post(&self, path: &str, body: Value) -> Result<Value> {
|
||||||
let resp = self.http.post(format!("{}/api{path}", self.url)).bearer_auth(&self.token).json(&body).send().await.with_context(|| format!("cannot reach {}", self.url))?;
|
let resp = self.http.post(format!("{}/api{path}", self.url)).bearer_auth(&self.token).json(&body).send().await.with_context(|| format!("cannot reach {}", self.url))?;
|
||||||
Ok(check(resp).await?.json().await?)
|
Ok(check(resp).await?.json().await?)
|
||||||
|
|||||||
@@ -196,6 +196,9 @@ pub struct Session {
|
|||||||
/// Icon of the chat (a name from `SESSION_ICONS`), shown in the list and the top bar.
|
/// Icon of the chat (a name from `SESSION_ICONS`), shown in the list and the top bar.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub icon: Option<String>,
|
pub icon: Option<String>,
|
||||||
|
/// Skills the user switched on for this chat: their instructions are part of every turn.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub skills: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Names of the colour tags: the client draws them with the colours of the active theme.
|
/// Names of the colour tags: the client draws them with the colours of the active theme.
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ services:
|
|||||||
# Pin a version (e.g. :v202611-00001) or follow :latest.
|
# Pin a version (e.g. :v202611-00001) or follow :latest.
|
||||||
image: git.familie-zink.org/zink/codecraft:${CODECRAFT_VERSION:-latest}
|
image: git.familie-zink.org/zink/codecraft:${CODECRAFT_VERSION:-latest}
|
||||||
container_name: codecraft
|
container_name: codecraft
|
||||||
|
# PID 1 reaps the children the agents leave behind (chromium, bwrap, npm …) instead of keeping them as zombies.
|
||||||
|
init: true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
# Same UID/GID as the owner of your project files.
|
# Same UID/GID as the owner of your project files.
|
||||||
user: "${UID:-1000}:${GID:-1000}"
|
user: "${UID:-1000}:${GID:-1000}"
|
||||||
@@ -36,6 +38,10 @@ services:
|
|||||||
- ${WORKSPACE:-./workspace}:/workspace
|
- ${WORKSPACE:-./workspace}:/workspace
|
||||||
# Separate area for the software factory (clones of the watched repositories).
|
# Separate area for the software factory (clones of the watched repositories).
|
||||||
- ${FACTORY_DIR:-./factory}:/factory
|
- ${FACTORY_DIR:-./factory}:/factory
|
||||||
|
environment:
|
||||||
|
# The test runner below (empty = acceptance runs start the app inside this container).
|
||||||
|
CODECRAFT_RUNNER_URL: ${CODECRAFT_RUNNER_URL:-}
|
||||||
|
CODECRAFT_RUNNER_TOKEN: ${RUNNER_TOKEN:-}
|
||||||
# Reach self-hosted models (Ollama, vLLM, ...) on the host.
|
# Reach self-hosted models (Ollama, vLLM, ...) on the host.
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
@@ -51,6 +57,40 @@ services:
|
|||||||
- apparmor=unconfined
|
- apparmor=unconfined
|
||||||
- systempaths=unconfined
|
- systempaths=unconfined
|
||||||
|
|
||||||
|
# Optional: throw-away containers for the factory's acceptance runs. Enable with
|
||||||
|
# COMPOSE_PROFILES=runner RUNNER_TOKEN=<random string> CODECRAFT_RUNNER_URL=http://testrunner:8788
|
||||||
|
# in .env. The factory then starts each app under test in its own container and
|
||||||
|
# network (plus helper services such as a database) and removes it afterwards.
|
||||||
|
# This service owns the Docker socket – the CodeCraft container does not.
|
||||||
|
testrunner:
|
||||||
|
profiles: ["runner"]
|
||||||
|
image: git.familie-zink.org/zink/codecraft:${CODECRAFT_VERSION:-latest}
|
||||||
|
command: ["testrunner"]
|
||||||
|
container_name: codecraft-testrunner
|
||||||
|
init: true
|
||||||
|
restart: unless-stopped
|
||||||
|
user: "${UID:-1000}:${GID:-1000}"
|
||||||
|
# Group that owns /var/run/docker.sock on the host: stat -c %g /var/run/docker.sock
|
||||||
|
group_add:
|
||||||
|
- "${DOCKER_GID:-999}"
|
||||||
|
environment:
|
||||||
|
RUNNER_TOKEN: ${RUNNER_TOKEN:-}
|
||||||
|
RUNNER_FACTORY_DIR: /factory
|
||||||
|
RUNNER_MEMORY: ${RUNNER_MEMORY:-2g}
|
||||||
|
RUNNER_CPUS: ${RUNNER_CPUS:-2}
|
||||||
|
RUNNER_DEFAULT_IMAGE: ${RUNNER_DEFAULT_IMAGE:-git.familie-zink.org/zink/codecraft-testbase:latest}
|
||||||
|
HOME: /tmp
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
# Read-only: the sources are copied into the containers, never mounted.
|
||||||
|
- ${FACTORY_DIR:-./factory}:/factory:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
codecraft-data:
|
codecraft-data:
|
||||||
name: codecraft-data
|
name: codecraft-data
|
||||||
@@ -14,6 +14,8 @@ services:
|
|||||||
GIT_COMMIT: ${GIT_COMMIT:-}
|
GIT_COMMIT: ${GIT_COMMIT:-}
|
||||||
image: codecraft:latest
|
image: codecraft:latest
|
||||||
container_name: codecraft
|
container_name: codecraft
|
||||||
|
# PID 1 reaps the children the agents leave behind (chromium, bwrap, npm …) instead of keeping them as zombies.
|
||||||
|
init: true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
# Same UID/GID as the owner of your project files.
|
# Same UID/GID as the owner of your project files.
|
||||||
user: "${UID:-1000}:${GID:-1000}"
|
user: "${UID:-1000}:${GID:-1000}"
|
||||||
@@ -32,6 +34,10 @@ services:
|
|||||||
- ${WORKSPACE:-./workspace}:/workspace
|
- ${WORKSPACE:-./workspace}:/workspace
|
||||||
# Separate area for the software factory (clones of the watched repositories).
|
# Separate area for the software factory (clones of the watched repositories).
|
||||||
- ${FACTORY_DIR:-./factory}:/factory
|
- ${FACTORY_DIR:-./factory}:/factory
|
||||||
|
environment:
|
||||||
|
# The test runner below (empty = acceptance runs start the app inside this container).
|
||||||
|
CODECRAFT_RUNNER_URL: ${CODECRAFT_RUNNER_URL:-}
|
||||||
|
CODECRAFT_RUNNER_TOKEN: ${RUNNER_TOKEN:-}
|
||||||
# Reach self-hosted models (Ollama, vLLM, ...) on the host.
|
# Reach self-hosted models (Ollama, vLLM, ...) on the host.
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
@@ -47,6 +53,40 @@ services:
|
|||||||
- apparmor=unconfined
|
- apparmor=unconfined
|
||||||
- systempaths=unconfined
|
- systempaths=unconfined
|
||||||
|
|
||||||
|
# Optional: throw-away containers for the factory's acceptance runs. Enable with
|
||||||
|
# COMPOSE_PROFILES=runner RUNNER_TOKEN=<random string> CODECRAFT_RUNNER_URL=http://testrunner:8788
|
||||||
|
# in .env. The factory then starts each app under test in its own container and
|
||||||
|
# network (plus helper services such as a database) and removes it afterwards.
|
||||||
|
# This service owns the Docker socket – the CodeCraft container does not.
|
||||||
|
testrunner:
|
||||||
|
profiles: ["runner"]
|
||||||
|
image: codecraft:latest
|
||||||
|
command: ["testrunner"]
|
||||||
|
container_name: codecraft-testrunner
|
||||||
|
init: true
|
||||||
|
restart: unless-stopped
|
||||||
|
user: "${UID:-1000}:${GID:-1000}"
|
||||||
|
# Group that owns /var/run/docker.sock on the host: stat -c %g /var/run/docker.sock
|
||||||
|
group_add:
|
||||||
|
- "${DOCKER_GID:-999}"
|
||||||
|
environment:
|
||||||
|
RUNNER_TOKEN: ${RUNNER_TOKEN:-}
|
||||||
|
RUNNER_FACTORY_DIR: /factory
|
||||||
|
RUNNER_MEMORY: ${RUNNER_MEMORY:-2g}
|
||||||
|
RUNNER_CPUS: ${RUNNER_CPUS:-2}
|
||||||
|
RUNNER_DEFAULT_IMAGE: ${RUNNER_DEFAULT_IMAGE:-git.familie-zink.org/zink/codecraft-testbase:latest}
|
||||||
|
HOME: /tmp
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
# Read-only: the sources are copied into the containers, never mounted.
|
||||||
|
- ${FACTORY_DIR:-./factory}:/factory:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
codecraft-data:
|
codecraft-data:
|
||||||
name: codecraft-data
|
name: codecraft-data
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Base image of the factory's throw-away acceptance containers (used when .factory/setup.json names no image).
|
||||||
|
# Node 24, Python 3, a C/C++ toolchain, the Chromium that Playwright needs, and the small tools
|
||||||
|
# that acceptance setups installed again and again (see the runner log "apt installed: ...").
|
||||||
|
FROM node:24-bookworm
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive PIP_BREAK_SYSTEM_PACKAGES=1 PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
build-essential cmake pkg-config git curl wget ca-certificates unzip xz-utils zip \
|
||||||
|
e2fsprogs util-linux zsh sudo nano procps iproute2 netcat-openbsd jq sqlite3 \
|
||||||
|
python3 python3-pip python3-venv \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& npm install -g playwright \
|
||||||
|
&& playwright install --with-deps chromium \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* /root/.npm \
|
||||||
|
&& chmod -R a+rX /ms-playwright
|
||||||
|
Before Width: | Height: | Size: 118 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
Before Width: | Height: | Size: 172 KiB After Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 123 KiB |
|
After Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 177 KiB After Width: | Height: | Size: 203 KiB |
@@ -94,6 +94,10 @@ if (( image )); then
|
|||||||
run docker buildx build --builder "$BUILDER" --platform "$PLATFORMS" \
|
run docker buildx build --builder "$BUILDER" --platform "$PLATFORMS" \
|
||||||
--build-arg GIT_COMMIT="$(git rev-parse --short HEAD)" --build-arg CODECRAFT_VERSION="$version" \
|
--build-arg GIT_COMMIT="$(git rev-parse --short HEAD)" --build-arg CODECRAFT_VERSION="$version" \
|
||||||
"${tags[@]}" --push .
|
"${tags[@]}" --push .
|
||||||
|
# Base image of the factory's acceptance containers (cached layers: cheap unless the Dockerfile changed).
|
||||||
|
step "Building and pushing ${REGISTRY}-testbase for $PLATFORMS"
|
||||||
|
run docker buildx build --builder "$BUILDER" --platform "$PLATFORMS" \
|
||||||
|
-t "${REGISTRY}-testbase:latest" -t "${REGISTRY}-testbase:$tag" --push docker/testbase
|
||||||
fi
|
fi
|
||||||
|
|
||||||
step "Creating the Gitea release $tag"
|
step "Creating the Gitea release $tag"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ arch=$(uname -m)
|
|||||||
case "$arch" in
|
case "$arch" in
|
||||||
x86_64|amd64) arch=x86_64 ;;
|
x86_64|amd64) arch=x86_64 ;;
|
||||||
aarch64|arm64) arch=aarch64 ;;
|
aarch64|arm64) arch=aarch64 ;;
|
||||||
|
riscv64) arch=riscv64 ;;
|
||||||
*) echo "codecraft: unsupported architecture $arch" >&2; exit 1 ;;
|
*) echo "codecraft: unsupported architecture $arch" >&2; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
case "$os" in
|
case "$os" in
|
||||||
|
|||||||
@@ -72,6 +72,10 @@ pub fn router(app: AppState) -> Router {
|
|||||||
.route("/agents/tools", get(agent_tools))
|
.route("/agents/tools", get(agent_tools))
|
||||||
.route("/agents/{name}", delete(delete_agent))
|
.route("/agents/{name}", delete(delete_agent))
|
||||||
.route("/commands", get(commands))
|
.route("/commands", get(commands))
|
||||||
|
.route("/skills", get(crate::skills_api::list))
|
||||||
|
.route("/skills/github/scan", post(crate::skills_api::scan))
|
||||||
|
.route("/skills/github/import", post(crate::skills_api::import))
|
||||||
|
.route("/skills/{name}", get(crate::skills_api::get).put(crate::skills_api::put).delete(crate::skills_api::delete))
|
||||||
.route("/transcribe", post(transcribe))
|
.route("/transcribe", post(transcribe))
|
||||||
.route("/sessions", get(list_sessions).post(create_session))
|
.route("/sessions", get(list_sessions).post(create_session))
|
||||||
.route("/sessions/search", get(search_sessions))
|
.route("/sessions/search", get(search_sessions))
|
||||||
@@ -92,6 +96,7 @@ pub fn router(app: AppState) -> Router {
|
|||||||
.route("/sessions/{id}/compact", post(compact))
|
.route("/sessions/{id}/compact", post(compact))
|
||||||
.route("/sessions/{id}/rewind", post(rewind))
|
.route("/sessions/{id}/rewind", post(rewind))
|
||||||
.route("/sessions/{id}/job-draft", post(job_draft))
|
.route("/sessions/{id}/job-draft", post(job_draft))
|
||||||
|
.route("/sessions/{id}/composer-draft", get(get_composer_draft).put(put_composer_draft))
|
||||||
.route("/projects/overview", get(project_overview))
|
.route("/projects/overview", get(project_overview))
|
||||||
.route("/sessions/{id}/project-defaults", get(get_project_defaults).put(put_project_defaults).delete(delete_project_defaults))
|
.route("/sessions/{id}/project-defaults", get(get_project_defaults).put(put_project_defaults).delete(delete_project_defaults))
|
||||||
.route("/sessions/{id}/check", get(get_check).put(put_check))
|
.route("/sessions/{id}/check", get(get_check).put(put_check))
|
||||||
@@ -108,6 +113,7 @@ pub fn router(app: AppState) -> Router {
|
|||||||
.route("/sessions/{id}/shares", get(get_shares).put(put_shares))
|
.route("/sessions/{id}/shares", get(get_shares).put(put_shares))
|
||||||
.route("/sessions/{id}/queue", get(get_queue))
|
.route("/sessions/{id}/queue", get(get_queue))
|
||||||
.route("/sessions/{id}/queue/flush", post(flush_queue))
|
.route("/sessions/{id}/queue/flush", post(flush_queue))
|
||||||
|
.route("/sessions/{id}/queue/force", post(force_queue))
|
||||||
.route("/sessions/{id}/queue/{item}", delete(delete_queue_item))
|
.route("/sessions/{id}/queue/{item}", delete(delete_queue_item))
|
||||||
.route("/permissions/{id}", post(reply_permission))
|
.route("/permissions/{id}", post(reply_permission))
|
||||||
.route("/permissions/{id}/explain", post(explain_permission))
|
.route("/permissions/{id}/explain", post(explain_permission))
|
||||||
@@ -146,6 +152,8 @@ pub fn router(app: AppState) -> Router {
|
|||||||
.route("/backups", get(list_backups).post(run_backup))
|
.route("/backups", get(list_backups).post(run_backup))
|
||||||
.route("/backups/{name}", get(download_backup))
|
.route("/backups/{name}", get(download_backup))
|
||||||
.route("/backups/{name}/restore", post(restore_stored_backup))
|
.route("/backups/{name}/restore", post(restore_stored_backup))
|
||||||
|
.route("/backups/upload", put(upload_backup_chunk))
|
||||||
|
.route("/backups/restore-uploaded", post(restore_chunked_backup))
|
||||||
.route("/backups/restore", post(restore_uploaded_backup).layer(axum::extract::DefaultBodyLimit::max(4 * 1024 * 1024 * 1024)))
|
.route("/backups/restore", post(restore_uploaded_backup).layer(axum::extract::DefaultBodyLimit::max(4 * 1024 * 1024 * 1024)))
|
||||||
.route("/health", get(health))
|
.route("/health", get(health))
|
||||||
.route("/tools", get(crate::reverse::status))
|
.route("/tools", get(crate::reverse::status))
|
||||||
@@ -162,7 +170,20 @@ pub fn router(app: AppState) -> Router {
|
|||||||
.route("/account/factory", get(get_factory).put(put_factory))
|
.route("/account/factory", get(get_factory).put(put_factory))
|
||||||
.route("/account/factory/test", post(test_factory))
|
.route("/account/factory/test", post(test_factory))
|
||||||
.route("/factory/overview", get(factory_overview))
|
.route("/factory/overview", get(factory_overview))
|
||||||
|
.route("/factory/backlog", get(factory_backlog))
|
||||||
|
.route("/factory/power", post(factory_power))
|
||||||
|
.route("/factory/backlog/enqueue", post(factory_enqueue))
|
||||||
.route("/factory/poll", post(factory_poll))
|
.route("/factory/poll", post(factory_poll))
|
||||||
|
.route("/factory/issues/restart", post(factory_restart))
|
||||||
|
.route("/factory/issue-chats", post(factory_new_issue_chat))
|
||||||
|
.route("/factory/issue-chats/{id}", get(factory_issue_chat))
|
||||||
|
.route("/factory/issue-chats/{id}/create", post(factory_create_issues))
|
||||||
|
.route("/factory/release/preview", get(factory_release_preview))
|
||||||
|
.route("/factory/release", post(factory_release))
|
||||||
|
.route("/factory/issues/close", post(factory_close_issue))
|
||||||
|
.route("/factory/issues/remove", post(factory_remove_issue))
|
||||||
|
.route("/factory/issues/pr", get(factory_pr))
|
||||||
|
.route("/factory/issues/pr/merge", post(factory_pr_merge))
|
||||||
.route("/account/factory/connection/test", post(test_factory_connection))
|
.route("/account/factory/connection/test", post(test_factory_connection))
|
||||||
.route("/factory/drafts", post(factory_new_draft))
|
.route("/factory/drafts", post(factory_new_draft))
|
||||||
.route("/factory/drafts/{id}", get(factory_draft))
|
.route("/factory/drafts/{id}", get(factory_draft))
|
||||||
@@ -175,6 +196,7 @@ pub fn router(app: AppState) -> Router {
|
|||||||
.route("/account/memory", get(crate::cli_api::get_memory).put(crate::cli_api::put_memory))
|
.route("/account/memory", get(crate::cli_api::get_memory).put(crate::cli_api::put_memory))
|
||||||
.route("/account/modes", get(get_personal_modes).put(put_personal_modes))
|
.route("/account/modes", get(get_personal_modes).put(put_personal_modes))
|
||||||
.route("/account/telegram", get(get_telegram).put(put_telegram).delete(delete_telegram))
|
.route("/account/telegram", get(get_telegram).put(put_telegram).delete(delete_telegram))
|
||||||
|
.route("/account/telegram/prefs", put(put_telegram_prefs))
|
||||||
.route("/templates", get(crate::cli_api::get_templates))
|
.route("/templates", get(crate::cli_api::get_templates))
|
||||||
.route("/templates/{scope}", put(crate::cli_api::put_templates))
|
.route("/templates/{scope}", put(crate::cli_api::put_templates))
|
||||||
.route("/cli/config", get(crate::cli_api::config))
|
.route("/cli/config", get(crate::cli_api::config))
|
||||||
@@ -419,12 +441,52 @@ async fn get_telegram(Extension(user): Extension<User>, State(app): State<AppSta
|
|||||||
"configured": !s.token.is_empty(),
|
"configured": !s.token.is_empty(),
|
||||||
"bot": s.bot,
|
"bot": s.bot,
|
||||||
"paired": s.chat_id.is_some(),
|
"paired": s.chat_id.is_some(),
|
||||||
"pair_code": if s.chat_id.is_none() { s.pair_code } else { String::new() },
|
"pair_code": if s.chat_id.is_none() { s.pair_code.clone() } else { String::new() },
|
||||||
"running": running,
|
"running": running,
|
||||||
"error": error,
|
"error": error,
|
||||||
|
"factory_alerts": !s.factory_alerts_off,
|
||||||
|
"quiet": s.quiet,
|
||||||
|
"quiet_from": if s.quiet_from.is_empty() { "22:00".to_string() } else { s.quiet_from.clone() },
|
||||||
|
"quiet_to": if s.quiet_to.is_empty() { "06:00".to_string() } else { s.quiet_to.clone() },
|
||||||
|
"quiet_now": s.quiet_now(),
|
||||||
|
"server_time": chrono::Local::now().format("%H:%M").to_string(),
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct TelegramPrefs {
|
||||||
|
factory_alerts: Option<bool>,
|
||||||
|
quiet: Option<bool>,
|
||||||
|
quiet_from: Option<String>,
|
||||||
|
quiet_to: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notification preferences: factory alerts on/off and the night mode.
|
||||||
|
async fn put_telegram_prefs(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<TelegramPrefs>) -> ApiResult {
|
||||||
|
let mut s = crate::telegram::load(&app, &user.id);
|
||||||
|
for (v, what) in [(&b.quiet_from, "from"), (&b.quiet_to, "to")] {
|
||||||
|
if let Some(t) = v {
|
||||||
|
if crate::telegram::parse_hhmm(t).is_none() {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, format!("invalid time ({what}) – use HH:MM")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(v) = b.factory_alerts {
|
||||||
|
s.factory_alerts_off = !v;
|
||||||
|
}
|
||||||
|
if let Some(v) = b.quiet {
|
||||||
|
s.quiet = v;
|
||||||
|
}
|
||||||
|
if let Some(v) = b.quiet_from {
|
||||||
|
s.quiet_from = v.trim().to_string();
|
||||||
|
}
|
||||||
|
if let Some(v) = b.quiet_to {
|
||||||
|
s.quiet_to = v.trim().to_string();
|
||||||
|
}
|
||||||
|
app.store.set_user_setting(&user.id, "telegram", &s)?;
|
||||||
|
get_telegram(Extension(user), State(app)).await
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct TelegramBody {
|
struct TelegramBody {
|
||||||
token: String,
|
token: String,
|
||||||
@@ -435,7 +497,9 @@ async fn put_telegram(Extension(user): Extension<User>, State(app): State<AppSta
|
|||||||
let token = crate::telegram::extract_token(&b.token)
|
let token = crate::telegram::extract_token(&b.token)
|
||||||
.ok_or_else(|| ApiError(StatusCode::BAD_REQUEST, "that is not a bot token – it looks like 123456789:AAH… (paste only the token from @BotFather)".into()))?;
|
.ok_or_else(|| ApiError(StatusCode::BAD_REQUEST, "that is not a bot token – it looks like 123456789:AAH… (paste only the token from @BotFather)".into()))?;
|
||||||
let bot = crate::telegram::check_token(&token).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("token rejected by Telegram: {e:#}")))?;
|
let bot = crate::telegram::check_token(&token).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("token rejected by Telegram: {e:#}")))?;
|
||||||
let s = crate::telegram::Settings { token, bot, pair_code: crate::telegram::new_pair_code(), ..Default::default() };
|
let old = crate::telegram::load(&app, &user.id);
|
||||||
|
// Notification preferences survive a new bot.
|
||||||
|
let s = crate::telegram::Settings { token, bot, pair_code: crate::telegram::new_pair_code(), factory_alerts_off: old.factory_alerts_off, quiet: old.quiet, quiet_from: old.quiet_from, quiet_to: old.quiet_to, ..Default::default() };
|
||||||
app.store.set_user_setting(&user.id, "telegram", &s)?;
|
app.store.set_user_setting(&user.id, "telegram", &s)?;
|
||||||
crate::telegram::restart(&app, &user.id);
|
crate::telegram::restart(&app, &user.id);
|
||||||
app.audit(Some(&user), "telegram.connect", &s.bot, "");
|
app.audit(Some(&user), "telegram.connect", &s.bot, "");
|
||||||
@@ -523,7 +587,7 @@ async fn commands(Extension(user): Extension<User>, State(app): State<AppState>,
|
|||||||
let (root, cwd) = scope(&app, &user, q.cwd);
|
let (root, cwd) = scope(&app, &user, q.cwd);
|
||||||
Json(json!({
|
Json(json!({
|
||||||
"commands": prompts::commands(&app, &root, &cwd),
|
"commands": prompts::commands(&app, &root, &cwd),
|
||||||
"skills": prompts::skills(&app, &root, &cwd),
|
"skills": prompts::skills(&app, &root, &cwd, Some(&user.id)),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -667,6 +731,7 @@ async fn create_session(Extension(user): Extension<User>, State(app): State<AppS
|
|||||||
summary: String::new(),
|
summary: String::new(),
|
||||||
color: dstr("color").filter(|c| codecraft_core::types::SESSION_COLORS.contains(&c.as_str())),
|
color: dstr("color").filter(|c| codecraft_core::types::SESSION_COLORS.contains(&c.as_str())),
|
||||||
icon: dstr("icon").filter(|c| codecraft_core::types::SESSION_ICONS.contains(&c.as_str())),
|
icon: dstr("icon").filter(|c| codecraft_core::types::SESSION_ICONS.contains(&c.as_str())),
|
||||||
|
skills: Vec::new(),
|
||||||
};
|
};
|
||||||
let s = app.save_session(s)?;
|
let s = app.save_session(s)?;
|
||||||
Ok(Json(json!(s)))
|
Ok(Json(json!(s)))
|
||||||
@@ -964,6 +1029,8 @@ struct UpdateSession {
|
|||||||
color: Option<String>,
|
color: Option<String>,
|
||||||
/// Icon ("" removes it).
|
/// Icon ("" removes it).
|
||||||
icon: Option<String>,
|
icon: Option<String>,
|
||||||
|
/// Skills switched on for this chat (names).
|
||||||
|
skills: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update_session(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>, Json(body): Json<UpdateSession>) -> ApiResult {
|
async fn update_session(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>, Json(body): Json<UpdateSession>) -> ApiResult {
|
||||||
@@ -1027,6 +1094,15 @@ async fn update_session(Extension(user): Extension<User>, State(app): State<AppS
|
|||||||
if let Some(i) = body.icon {
|
if let Some(i) = body.icon {
|
||||||
s.icon = (!i.is_empty()).then_some(i);
|
s.icon = (!i.is_empty()).then_some(i);
|
||||||
}
|
}
|
||||||
|
if let Some(list) = body.skills {
|
||||||
|
let mut seen = Vec::new();
|
||||||
|
for n in list.into_iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty() && n.len() <= 64) {
|
||||||
|
if !seen.contains(&n) && seen.len() < 20 {
|
||||||
|
seen.push(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.skills = seen;
|
||||||
|
}
|
||||||
})?;
|
})?;
|
||||||
Ok(Json(json!(s)))
|
Ok(Json(json!(s)))
|
||||||
}
|
}
|
||||||
@@ -1284,6 +1360,12 @@ async fn flush_queue(Extension(user): Extension<User>, State(app): State<AppStat
|
|||||||
Ok(Json(json!({"started": runner::flush_queue(app.clone(), &id)?})))
|
Ok(Json(json!({"started": runner::flush_queue(app.clone(), &id)?})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Interrupt the running step and deliver the queued messages at once.
|
||||||
|
async fn force_queue(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
|
||||||
|
writable(&app, &user, &id)?;
|
||||||
|
Ok(Json(json!({"forced": runner::force_queue(app.clone(), &id)?})))
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn do_compact(app: AppState, id: String) {
|
pub(crate) async fn do_compact(app: AppState, id: String) {
|
||||||
let cancel = tokio_util::sync::CancellationToken::new();
|
let cancel = tokio_util::sync::CancellationToken::new();
|
||||||
app.with_runtime(&id, |r| r.cancel = Some(cancel.clone()));
|
app.with_runtime(&id, |r| r.cancel = Some(cancel.clone()));
|
||||||
@@ -1587,6 +1669,27 @@ async fn reply_permission(Extension(user): Extension<User>, State(app): State<Ap
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Instructions for an automation drafted from this chat (small model); the client creates the job.
|
/// Instructions for an automation drafted from this chat (small model); the client creates the job.
|
||||||
|
/// The unsent message of this chat (typed on any device).
|
||||||
|
async fn get_composer_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
|
||||||
|
writable(&app, &user, &id)?;
|
||||||
|
let d = app.store.chat_draft(&id, &user.id)?;
|
||||||
|
Ok(Json(json!({"text": d.as_ref().map(|x| x.0.as_str()).unwrap_or(""), "updated_at": d.map(|x| x.1).unwrap_or(0)})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ComposerDraft {
|
||||||
|
text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn put_composer_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>, Json(b): Json<ComposerDraft>) -> ApiResult {
|
||||||
|
writable(&app, &user, &id)?;
|
||||||
|
if b.text.len() > 200_000 {
|
||||||
|
return Err(ApiError(StatusCode::PAYLOAD_TOO_LARGE, "the draft is too long".into()));
|
||||||
|
}
|
||||||
|
let at = app.store.chat_draft_set(&id, &user.id, &b.text)?;
|
||||||
|
Ok(Json(json!({"updated_at": at})))
|
||||||
|
}
|
||||||
|
|
||||||
async fn job_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
|
async fn job_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
|
||||||
let s = writable(&app, &user, &id)?;
|
let s = writable(&app, &user, &id)?;
|
||||||
let (name, prompt) = runner::draft_job(&app, &s).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
let (name, prompt) = runner::draft_job(&app, &s).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||||
@@ -1821,8 +1924,13 @@ async fn list_roots(Extension(user): Extension<User>, State(app): State<AppState
|
|||||||
.user_roots(Some(&user.id))
|
.user_roots(Some(&user.id))
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|r| {
|
.map(|r| {
|
||||||
let rel = r.strip_prefix(&ws).map(|p| p.display().to_string()).unwrap_or_default();
|
let name = match r.strip_prefix(&ws) {
|
||||||
json!({"path": r, "name": if rel.is_empty() { "/".to_string() } else { rel }})
|
Ok(p) if p.as_os_str().is_empty() => "/".to_string(),
|
||||||
|
Ok(p) => p.display().to_string(),
|
||||||
|
// Outside the workspace (e.g. the factory area): show where it is, not "workspace".
|
||||||
|
Err(_) => format!("{} (factory)", r.file_name().and_then(|n| n.to_str()).unwrap_or("")).replace(" ()", ""),
|
||||||
|
};
|
||||||
|
json!({"path": r, "name": name})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
Json(json!(roots))
|
Json(json!(roots))
|
||||||
@@ -1934,6 +2042,43 @@ async fn restore_uploaded_backup(Extension(user): Extension<User>, State(app): S
|
|||||||
restore_and_restart(&app, &user, body.to_vec(), &format!("upload ({} bytes)", body.len())).await
|
restore_and_restart(&app, &user, body.to_vec(), &format!("upload ({} bytes)", body.len())).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ChunkQuery {
|
||||||
|
offset: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_upload_path(app: &App) -> std::path::PathBuf {
|
||||||
|
app.config().data_dir().join("restore-upload.tmp")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One chunk of a backup to restore (offset 0 starts anew); `restore-uploaded` applies the whole file.
|
||||||
|
async fn upload_backup_chunk(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<ChunkQuery>, body: axum::body::Bytes) -> ApiResult {
|
||||||
|
require_admin(&user)?;
|
||||||
|
use tokio::io::AsyncWriteExt;
|
||||||
|
let p = restore_upload_path(&app);
|
||||||
|
if q.offset == 0 {
|
||||||
|
tokio::fs::write(&p, &body).await?;
|
||||||
|
} else {
|
||||||
|
let current = tokio::fs::metadata(&p).await.map(|m| m.len()).unwrap_or(0);
|
||||||
|
if current != q.offset {
|
||||||
|
return Err(ApiError(StatusCode::CONFLICT, format!("chunk offset {} does not match the uploaded size {current}", q.offset)));
|
||||||
|
}
|
||||||
|
let mut f = tokio::fs::OpenOptions::new().append(true).open(&p).await?;
|
||||||
|
f.write_all(&body).await?;
|
||||||
|
f.flush().await?;
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"ok": true, "size": q.offset + body.len() as u64})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn restore_chunked_backup(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||||
|
require_admin(&user)?;
|
||||||
|
let p = restore_upload_path(&app);
|
||||||
|
let bytes = tokio::fs::read(&p).await.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "no uploaded backup".into()))?;
|
||||||
|
let _ = tokio::fs::remove_file(&p).await;
|
||||||
|
let source = format!("upload ({} bytes)", bytes.len());
|
||||||
|
restore_and_restart(&app, &user, bytes, &source).await
|
||||||
|
}
|
||||||
|
|
||||||
async fn download_backup(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> Result<Response, ApiError> {
|
async fn download_backup(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> Result<Response, ApiError> {
|
||||||
require_admin(&user)?;
|
require_admin(&user)?;
|
||||||
if !crate::backup::list(&app).iter().any(|b| b.name == name) {
|
if !crate::backup::list(&app).iter().any(|b| b.name == name) {
|
||||||
@@ -2422,7 +2567,7 @@ async fn job_assistant(Extension(user): Extension<User>, State(app): State<AppSt
|
|||||||
telegram_quiet: true,
|
telegram_quiet: true,
|
||||||
summary: String::new(),
|
summary: String::new(),
|
||||||
color: None,
|
color: None,
|
||||||
icon: None,
|
icon: None, skills: Vec::new(),
|
||||||
};
|
};
|
||||||
let s = app.save_session(s)?;
|
let s = app.save_session(s)?;
|
||||||
st.assistant_session = Some(s.id.clone());
|
st.assistant_session = Some(s.id.clone());
|
||||||
@@ -2631,15 +2776,130 @@ async fn test_factory(Extension(user): Extension<User>, State(app): State<AppSta
|
|||||||
/// Everything the factory page shows: repositories, issues with state, runs with tokens/cost.
|
/// Everything the factory page shows: repositories, issues with state, runs with tokens/cost.
|
||||||
async fn factory_overview(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
async fn factory_overview(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||||
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
let repos: Vec<Value> = s.repos.iter().map(|r| json!({"url": r.url, "enabled": r.enabled, "label": r.label, "max_parallel": r.max_parallel, "kind": s.resolve(r).kind, "has_token": !s.resolve(r).token.is_empty(), "models": {"review": r.review.model, "build": r.build.model, "qa": r.qa.model}, "running": app.store.factory_running(&r.url).unwrap_or(0)})).collect();
|
let repos: Vec<Value> = s.repos.iter().map(|r| json!({"url": r.url, "enabled": r.enabled, "label": r.label, "max_parallel": r.max_parallel, "kind": s.resolve(r).kind, "has_token": !s.resolve(r).token.is_empty(), "models": {"review": r.review.model, "build": r.build.model, "qa": r.qa.model}, "running": app.store.factory_running(&r.url).unwrap_or(0), "version": app.store.factory_version(&r.url).ok().flatten()})).collect();
|
||||||
Ok(Json(json!({
|
Ok(Json(json!({
|
||||||
"area": app.factory_dir().is_some(),
|
"area": app.factory_dir().is_some(),
|
||||||
"repos": repos,
|
"repos": repos,
|
||||||
"issues": app.store.factory_issues(&user.id)?,
|
"issues": app.store.factory_issues(&user.id)?,
|
||||||
|
"power": factory_power_json(&app, &user),
|
||||||
"runs": app.store.factory_runs(&user.id, None, None, 300)?,
|
"runs": app.store.factory_runs(&user.id, None, None, 300)?,
|
||||||
|
"releases": app.store.factory_releases(&user.id, 10)?,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn factory_power_json(app: &App, user: &User) -> Value {
|
||||||
|
let on = app.store.user_setting::<crate::factory::Power>(&user.id, "factory_power").unwrap_or_default().on;
|
||||||
|
let active = app.store.factory_active(&user.id).unwrap_or(0);
|
||||||
|
json!({"on": on, "active": active, "state": crate::factory::power_state(on, active)})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct PowerBody {
|
||||||
|
on: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The master switch: stop = no new agent starts (running ones finish), start = take up work again right away.
|
||||||
|
async fn factory_power(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<PowerBody>) -> ApiResult {
|
||||||
|
app.store.set_user_setting(&user.id, "factory_power", &crate::factory::Power { on: b.on })?;
|
||||||
|
app.audit(Some(&user), if b.on { "factory.start" } else { "factory.stop" }, "", &crate::auth::client_ip(&headers));
|
||||||
|
if b.on {
|
||||||
|
let (app2, user2) = (app.clone(), user.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let s: crate::factory::FactorySettings = app2.store.user_setting(&user2.id, "factory").unwrap_or_default();
|
||||||
|
for cfg in s.repos.iter().filter(|r| r.enabled).map(|r| s.resolve(r)).filter(|r| !r.token.is_empty()) {
|
||||||
|
let _ = crate::factory::poll_repo(&app2, &user2, &cfg).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Json(factory_power_json(&app, &user)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open issues per repository as the forge lists them; cached for a minute so that the board can ask often.
|
||||||
|
static BACKLOG_CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, Vec<Value>)>>> = std::sync::OnceLock::new();
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct BacklogQuery {
|
||||||
|
#[serde(default)]
|
||||||
|
refresh: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The backlog: open issues of the configured repositories that are not in the factory yet.
|
||||||
|
async fn factory_backlog(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<BacklogQuery>) -> ApiResult {
|
||||||
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
|
let cache = BACKLOG_CACHE.get_or_init(Default::default);
|
||||||
|
let tracked_all = app.store.factory_issues(&user.id)?;
|
||||||
|
let (mut issues, mut errors) = (Vec::new(), Vec::new());
|
||||||
|
for cfg in s.repos.iter().filter(|r| r.enabled).map(|r| s.resolve(r)).filter(|r| !r.token.is_empty()) {
|
||||||
|
let key = format!("{}|{}", user.id, cfg.url);
|
||||||
|
let cached = cache.lock().unwrap().get(&key).filter(|(t, _)| !q.refresh && t.elapsed().as_secs() < 60).map(|(_, v)| v.clone());
|
||||||
|
let result = async {
|
||||||
|
let g = crate::factory::Forge::new(&cfg)?;
|
||||||
|
let open = match cached {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
let v = g.open_issues().await?;
|
||||||
|
cache.lock().unwrap().insert(key.clone(), (std::time::Instant::now(), v.clone()));
|
||||||
|
v
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let allowed = crate::factory::allowed_authors(&g, &cfg).await?;
|
||||||
|
let tracked: Vec<i64> = tracked_all.iter().filter(|r| r["repo"].as_str() == Some(cfg.url.as_str())).map(|r| r["number"].as_i64().unwrap_or(0)).collect();
|
||||||
|
anyhow::Ok(crate::factory::backlog_of(&cfg, &open, &tracked, &allowed))
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(v) => issues.extend(v),
|
||||||
|
Err(e) => errors.push(format!("{}: {e:#}", cfg.url)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"issues": issues, "errors": errors})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Enqueue {
|
||||||
|
repo: String,
|
||||||
|
numbers: Vec<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put backlog issues into the process: give them the factory label, the next poll picks them up.
|
||||||
|
async fn factory_enqueue(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<Enqueue>) -> ApiResult {
|
||||||
|
let cfg = factory_repo_cfg(&app, &user, &b.repo)?;
|
||||||
|
if b.numbers.is_empty() || b.numbers.len() > 100 {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "1 to 100 issues".into()));
|
||||||
|
}
|
||||||
|
let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"));
|
||||||
|
let g = crate::factory::Forge::new(&cfg).map_err(bad)?;
|
||||||
|
let allowed = crate::factory::allowed_authors(&g, &cfg).await.map_err(bad)?;
|
||||||
|
let open = g.open_issues().await.map_err(bad)?;
|
||||||
|
g.ensure_labels().await.map_err(bad)?;
|
||||||
|
let (mut queued, mut errors) = (Vec::new(), Vec::new());
|
||||||
|
for n in b.numbers {
|
||||||
|
let Some(issue) = open.iter().find(|i| crate::factory::issue_no(i) == n) else {
|
||||||
|
errors.push(json!({"number": n, "error": "not an open issue of this repository"}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let author = issue["user"]["login"].as_str().unwrap_or("");
|
||||||
|
if !allowed.iter().any(|a| a.eq_ignore_ascii_case(author)) {
|
||||||
|
errors.push(json!({"number": n, "error": format!("the author {author} is not allowed to file factory issues (see the repository settings)")}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match g.add_label(n as u64, &cfg.label).await {
|
||||||
|
Ok(()) => queued.push(n),
|
||||||
|
Err(e) => errors.push(json!({"number": n, "error": format!("{e:#}")})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BACKLOG_CACHE.get_or_init(Default::default).lock().unwrap().remove(&format!("{}|{}", user.id, cfg.url));
|
||||||
|
app.audit(Some(&user), "factory.backlog.enqueue", &format!("{} {:?}", b.repo, queued), &crate::auth::client_ip(&headers));
|
||||||
|
// Take the issues up right away instead of waiting for the next poll.
|
||||||
|
if !queued.is_empty() {
|
||||||
|
let (app2, user2) = (app.clone(), user.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = crate::factory::poll_repo(&app2, &user2, &cfg).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"queued": queued, "errors": errors})))
|
||||||
|
}
|
||||||
|
|
||||||
/// Look for new issues right now instead of waiting for the next poll.
|
/// Look for new issues right now instead of waiting for the next poll.
|
||||||
async fn factory_poll(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
async fn factory_poll(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||||
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
@@ -2652,6 +2912,249 @@ async fn factory_poll(Extension(user): Extension<User>, State(app): State<AppSta
|
|||||||
Ok(Json(json!({"errors": errors})))
|
Ok(Json(json!({"errors": errors})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ReleaseQuery {
|
||||||
|
repo: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current version, suggested next major version and the release recipe (.factory/release.json).
|
||||||
|
async fn factory_release_preview(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<ReleaseQuery>) -> ApiResult {
|
||||||
|
let cfg = factory_repo_cfg(&app, &user, &q.repo)?;
|
||||||
|
let v = crate::factory_version::preview(&app, &user, &cfg).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||||
|
Ok(Json(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct StartRelease {
|
||||||
|
repo: String,
|
||||||
|
version: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a release: tag, Docker image, downloads and the release on the forge (runs in the background).
|
||||||
|
async fn factory_release(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<StartRelease>) -> ApiResult {
|
||||||
|
let cfg = factory_repo_cfg(&app, &user, &b.repo)?;
|
||||||
|
let id = crate::factory_version::start_release(&app, &user, &cfg, b.version.trim()).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||||
|
app.audit(Some(&user), "factory.release.start", &format!("{} {}", b.repo, b.version.trim()), &crate::auth::client_ip(&headers));
|
||||||
|
Ok(Json(json!({"id": id})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct NewIssueChat {
|
||||||
|
repo: String,
|
||||||
|
/// "feature" or "slice"
|
||||||
|
mode: String,
|
||||||
|
#[serde(default)]
|
||||||
|
topic: String,
|
||||||
|
#[serde(default)]
|
||||||
|
model: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn factory_repo_cfg(app: &AppState, user: &User, repo: &str) -> Result<crate::factory::RepoCfg, ApiError> {
|
||||||
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
|
s.repos.iter().find(|r| r.url == repo).map(|r| s.resolve(r)).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "the repository is not configured".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a chat that works out a feature or cuts a milestone into issues.
|
||||||
|
async fn factory_new_issue_chat(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<NewIssueChat>) -> ApiResult {
|
||||||
|
if !["feature", "slice"].contains(&b.mode.as_str()) {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "unknown mode".into()));
|
||||||
|
}
|
||||||
|
let cfg = factory_repo_cfg(&app, &user, &b.repo)?;
|
||||||
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
|
let model = b.model.filter(|m| !m.is_empty()).unwrap_or(s.defaults.spec_model.clone());
|
||||||
|
let session = crate::factory::start_issue_chat(&app, &user, &cfg, &model, &b.mode, &b.topic).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||||
|
Ok(Json(json!(session)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn issue_chat_session(app: &AppState, user: &User, id: &str) -> Result<(String, std::path::PathBuf), ApiError> {
|
||||||
|
let session = app.session(id).map_err(|_| ApiError(StatusCode::NOT_FOUND, "unknown chat".into()))?;
|
||||||
|
let dir = crate::factory::issue_chat_of(app, user, &session).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "not an issue chat".into()))?;
|
||||||
|
let repo = std::fs::read_to_string(dir.join("repo.txt")).unwrap_or_default().trim().to_string();
|
||||||
|
Ok((repo, dir))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The issue list the model proposed in its last message.
|
||||||
|
async fn factory_issue_chat(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
|
||||||
|
let (repo, _) = issue_chat_session(&app, &user, &id)?;
|
||||||
|
Ok(Json(json!({"repo": repo, "proposal": crate::factory::issue_proposal(&app, &id)})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateIssues {
|
||||||
|
spec: String,
|
||||||
|
issues: Vec<Value>,
|
||||||
|
/// Give the issues the factory label so the workflow starts right away.
|
||||||
|
#[serde(default)]
|
||||||
|
start: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create the (possibly edited) issues of a proposal on the forge.
|
||||||
|
async fn factory_create_issues(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Path(id): Path<String>, Json(b): Json<CreateIssues>) -> ApiResult {
|
||||||
|
let (repo, _) = issue_chat_session(&app, &user, &id)?;
|
||||||
|
let cfg = factory_repo_cfg(&app, &user, &repo)?;
|
||||||
|
if b.issues.is_empty() || b.issues.len() > 100 {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "choose between 1 and 100 issues".into()));
|
||||||
|
}
|
||||||
|
let created = crate::factory::create_issues(&cfg, &b.spec, &b.issues, b.start).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||||
|
app.audit(Some(&user), "factory.issues.create", &format!("{repo} ({} issues)", created.len()), &crate::auth::client_ip(&headers));
|
||||||
|
if b.start {
|
||||||
|
let _ = crate::factory::poll_repo(&app, &user, &cfg).await;
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"created": created})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CloseIssue {
|
||||||
|
repo: String,
|
||||||
|
number: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
comment: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a finished issue: a comment, then the issue on the forge; only then it leaves "done".
|
||||||
|
async fn factory_close_issue(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<CloseIssue>) -> ApiResult {
|
||||||
|
let (g, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?;
|
||||||
|
if row["state"].as_str() != Some("done") {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "only finished issues can be closed here".into()));
|
||||||
|
}
|
||||||
|
let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"));
|
||||||
|
// Closing comes after the merge. A merge done on the forge itself counts too: ask the forge when we do not know yet.
|
||||||
|
if row["merged"].as_bool() != Some(true) {
|
||||||
|
let pr_n: u64 = row["pr_url"].as_str().unwrap_or("").trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0);
|
||||||
|
let merged = pr_n > 0 && g.pr(pr_n).await.map(|p| p["state"].as_str() == Some("merged")).unwrap_or(false);
|
||||||
|
if !merged {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "merge the pull request first".into()));
|
||||||
|
}
|
||||||
|
app.store.factory_issue_set(&b.repo, b.number, &[("merged", json!(1))])?;
|
||||||
|
}
|
||||||
|
let text = if b.comment.trim().is_empty() { "Closed.".to_string() } else { b.comment.trim().to_string() };
|
||||||
|
g.comment(b.number as u64, &format!("{}\n**Closed** by {}: {text}", crate::factory::BOT, user.username)).await.map_err(bad)?;
|
||||||
|
g.close_issue(b.number as u64).await.map_err(bad)?;
|
||||||
|
app.store.factory_issue_set(&b.repo, b.number, &[("state", json!("closed"))])?;
|
||||||
|
app.audit(Some(&user), "factory.issue.close", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers));
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Take an issue off the factory board (the issue on the forge is not touched). Not while a phase runs.
|
||||||
|
async fn factory_remove_issue(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<CloseIssue>) -> ApiResult {
|
||||||
|
let (_, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?;
|
||||||
|
if matches!(row["state"].as_str(), Some("review" | "building" | "testing")) {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "a phase is running – wait for it to end or stop it first".into()));
|
||||||
|
}
|
||||||
|
app.store.factory_issue_delete(&b.repo, b.number)?;
|
||||||
|
app.audit(Some(&user), "factory.issue.remove", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers));
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct PrQuery {
|
||||||
|
repo: String,
|
||||||
|
number: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The issue's forge client and row; the issue must belong to the user.
|
||||||
|
fn factory_issue_forge(app: &AppState, user: &User, repo: &str, number: i64) -> Result<(crate::factory::Forge, Value), ApiError> {
|
||||||
|
let row = app.store.factory_issue(repo, number)?.filter(|r| r["owner_id"].as_str() == Some(user.id.as_str())).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown issue".into()))?;
|
||||||
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
|
let cfg = s.repos.iter().find(|r| r.url == repo).map(|r| s.resolve(r)).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "the repository is not configured".into()))?;
|
||||||
|
let g = crate::factory::Forge::new(&cfg).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||||
|
Ok((g, row))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pull request of an issue: the open one from its branch, else the one on record.
|
||||||
|
async fn factory_pr(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<PrQuery>) -> ApiResult {
|
||||||
|
let (g, row) = factory_issue_forge(&app, &user, &q.repo, q.number)?;
|
||||||
|
let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"));
|
||||||
|
let branch = row["branch"].as_str().unwrap_or("");
|
||||||
|
let mut pr = if branch.is_empty() { None } else { g.find_pr(branch).await.map_err(bad)? };
|
||||||
|
if pr.is_none() {
|
||||||
|
let n: u64 = row["pr_url"].as_str().unwrap_or("").trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0);
|
||||||
|
if n > 0 {
|
||||||
|
pr = g.pr(n).await.ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"pr": pr})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct MergePr {
|
||||||
|
repo: String,
|
||||||
|
number: i64,
|
||||||
|
pr: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
method: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merge the pull request of an issue – only on the user's own click in the factory page.
|
||||||
|
async fn factory_pr_merge(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<MergePr>) -> ApiResult {
|
||||||
|
let (g, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?;
|
||||||
|
// Merging comes after a positive acceptance (the issue is "done").
|
||||||
|
if row["state"].as_str() != Some("done") {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "the pull request can be merged once the acceptance has passed".into()));
|
||||||
|
}
|
||||||
|
let method = if b.method.is_empty() { "merge" } else { b.method.as_str() };
|
||||||
|
if !["merge", "squash", "rebase"].contains(&method) {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "unknown merge method".into()));
|
||||||
|
}
|
||||||
|
let pr = g.pr(b.pr).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||||
|
// Only the pull request of this issue's own branch may be merged from here.
|
||||||
|
if pr["head"].as_str() != row["branch"].as_str() || pr["state"].as_str() != Some("open") {
|
||||||
|
return Err(ApiError(StatusCode::BAD_REQUEST, "this is not the open pull request of the issue".into()));
|
||||||
|
}
|
||||||
|
g.merge_pr(b.pr, method).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||||
|
app.store.factory_issue_set(&b.repo, b.number, &[("pr_url", json!(pr["html_url"].as_str().unwrap_or(""))), ("merged", json!(1))])?;
|
||||||
|
app.audit(Some(&user), "factory.pr.merge", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers));
|
||||||
|
// Give the issue its version and tag right away instead of at the next poll.
|
||||||
|
if let Ok(cfg) = factory_repo_cfg(&app, &user, &b.repo) {
|
||||||
|
let (app2, user2) = (app.clone(), user.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = crate::factory::poll_repo(&app2, &user2, &cfg).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RestartIssue {
|
||||||
|
repo: String,
|
||||||
|
number: i64,
|
||||||
|
/// Where to re-enter the flow: new (review again), approved (build again) or qa (acceptance again).
|
||||||
|
to: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put a finished, failed or rejected issue back into the flow at the chosen stage.
|
||||||
|
async fn factory_restart(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<RestartIssue>) -> ApiResult {
|
||||||
|
let bad = |m: &str| ApiError(StatusCode::BAD_REQUEST, m.to_string());
|
||||||
|
let row = app.store.factory_issue(&b.repo, b.number)?.filter(|r| r["owner_id"].as_str() == Some(user.id.as_str())).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown issue".into()))?;
|
||||||
|
let state = row["state"].as_str().unwrap_or("");
|
||||||
|
if ["review", "building", "testing"].contains(&state) {
|
||||||
|
return Err(bad("a phase is running for this issue – wait until it ends"));
|
||||||
|
}
|
||||||
|
if !["new", "approved", "qa"].contains(&b.to.as_str()) {
|
||||||
|
return Err(bad("unknown target stage"));
|
||||||
|
}
|
||||||
|
if b.to == "qa" && row["branch"].as_str().unwrap_or("").is_empty() {
|
||||||
|
return Err(bad("nothing was built yet – restart at review or build"));
|
||||||
|
}
|
||||||
|
let mut fields: Vec<(&str, Value)> = vec![("state", json!(b.to)), ("attempts", json!(0)), ("note", json!(""))];
|
||||||
|
if b.to != "qa" {
|
||||||
|
fields.push(("rounds", json!(0)));
|
||||||
|
}
|
||||||
|
if b.to == "new" {
|
||||||
|
fields.push(("scenarios", json!("")));
|
||||||
|
// Answers given before count as read; the new review starts from the issue as it is now.
|
||||||
|
}
|
||||||
|
app.store.factory_issue_set(&b.repo, b.number, &fields)?;
|
||||||
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
|
if let Some(cfg) = s.repos.iter().find(|r| r.url == b.repo).map(|r| s.resolve(r)) {
|
||||||
|
if let Ok(g) = crate::factory::Forge::new(&cfg) {
|
||||||
|
let labels = if b.to == "new" { vec![cfg.label.clone()] } else { vec![cfg.label.clone(), format!("factory:{}", b.to)] };
|
||||||
|
let _ = g.set_labels(b.number as u64, &labels).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct ConnTest {
|
struct ConnTest {
|
||||||
id: String,
|
id: String,
|
||||||
@@ -2671,13 +3174,20 @@ async fn test_factory_connection(Extension(user): Extension<User>, State(app): S
|
|||||||
struct NewDraft {
|
struct NewDraft {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
|
/// "recreate": analyse existing software first (clean-room).
|
||||||
|
#[serde(default)]
|
||||||
|
mode: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
source: String,
|
||||||
|
#[serde(default)]
|
||||||
|
notes: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start a chat in which the user writes a spec with a model.
|
/// Start a chat in which the user writes a spec with a model.
|
||||||
async fn factory_new_draft(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<NewDraft>) -> ApiResult {
|
async fn factory_new_draft(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<NewDraft>) -> ApiResult {
|
||||||
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
let model = b.model.filter(|m| !m.is_empty()).unwrap_or(s.defaults.spec_model.clone());
|
let model = b.model.filter(|m| !m.is_empty()).unwrap_or(s.defaults.spec_model.clone());
|
||||||
let session = crate::factory::start_spec_chat(&app, &user, &model).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
let session = crate::factory::start_spec_chat(&app, &user, &model, (b.mode.as_deref() == Some("recreate")).then_some((b.source.as_str(), b.notes.as_str()))).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||||
Ok(Json(json!(session)))
|
Ok(Json(json!(session)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2693,7 +3203,8 @@ async fn factory_draft(Extension(user): Extension<User>, State(app): State<AppSt
|
|||||||
let spec = std::fs::read_to_string(dir.join("spec.md")).unwrap_or_default();
|
let spec = std::fs::read_to_string(dir.join("spec.md")).unwrap_or_default();
|
||||||
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
let conns: Vec<Value> = s.connections.iter().map(|c| json!({"id": c.id, "name": c.name, "kind": c.kind, "owner": c.owner})).collect();
|
let conns: Vec<Value> = s.connections.iter().map(|c| json!({"id": c.id, "name": c.name, "kind": c.kind, "owner": c.owner})).collect();
|
||||||
Ok(Json(json!({"spec": spec, "proposal": crate::factory::proposal(&app, &id), "connections": conns})))
|
let setup = std::fs::read_to_string(dir.join("setup.json")).ok().filter(|t| crate::factory::valid_setup(t));
|
||||||
|
Ok(Json(json!({"spec": spec, "setup": setup, "proposal": crate::factory::proposal(&app, &id), "connections": conns, "recreate": dir.join("recreate.txt").exists()})))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -2712,7 +3223,8 @@ async fn factory_create_project(Extension(user): Extension<User>, State(app): St
|
|||||||
let (_, dir) = draft_session(&app, &user, &id)?;
|
let (_, dir) = draft_session(&app, &user, &id)?;
|
||||||
let spec = std::fs::read_to_string(dir.join("spec.md")).unwrap_or_default();
|
let spec = std::fs::read_to_string(dir.join("spec.md")).unwrap_or_default();
|
||||||
let mut s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
let mut s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||||
let res = crate::factory::create_project(&app, &user, &mut s, &spec, &b.connection, &b.name, &b.slug, &b.description, &b.owner).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
let setup = std::fs::read_to_string(dir.join("setup.json")).unwrap_or_default();
|
||||||
|
let res = crate::factory::create_project(&app, &user, &mut s, &spec, &setup, &b.connection, &b.name, &b.slug, &b.description, &b.owner, !dir.join("recreate.txt").exists()).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||||
app.store.set_user_setting(&user.id, "factory", &s)?;
|
app.store.set_user_setting(&user.id, "factory", &s)?;
|
||||||
app.audit(Some(&user), "factory.project.create", res["repo"].as_str().unwrap_or(""), &crate::auth::client_ip(&headers));
|
app.audit(Some(&user), "factory.project.create", res["repo"].as_str().unwrap_or(""), &crate::auth::client_ip(&headers));
|
||||||
Ok(Json(res))
|
Ok(Json(res))
|
||||||
|
|||||||
@@ -45,6 +45,9 @@ pub struct Runtime {
|
|||||||
pub step: Option<Value>,
|
pub step: Option<Value>,
|
||||||
/// Reasoning effort chosen for the current turn (overrides the model's default).
|
/// Reasoning effort chosen for the current turn (overrides the model's default).
|
||||||
pub effort: Option<String>,
|
pub effort: Option<String>,
|
||||||
|
/// The user interrupted the turn to deliver the queued messages at once: they start the next turn
|
||||||
|
/// even though the run was cancelled.
|
||||||
|
pub force_queue: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct App {
|
pub struct App {
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ pub async fn config(Extension(user): Extension<User>, State(app): State<AppState
|
|||||||
.filter(|c| c.description.len() < 400)
|
.filter(|c| c.description.len() < 400)
|
||||||
.map(|c| json!({"name": c.name, "description": c.description, "body": c.body, "agent": c.agent}))
|
.map(|c| json!({"name": c.name, "description": c.description, "body": c.body, "agent": c.agent}))
|
||||||
.collect();
|
.collect();
|
||||||
let skills: Vec<Value> = crate::prompts::skills(&app, &root, &root).into_iter().map(|s| json!({"name": s.name, "description": s.description})).collect();
|
let skills: Vec<Value> = crate::prompts::skills(&app, &root, &root, Some(&user.id)).into_iter().map(|s| json!({"name": s.name, "description": s.description})).collect();
|
||||||
let (direct, deferred) = app.mcp.tools(&cfg, Some(&user));
|
let (direct, deferred) = app.mcp.tools(&cfg, Some(&user));
|
||||||
let mut mcp_tools: Vec<ToolDef> = direct.iter().map(|t| t.def()).collect();
|
let mut mcp_tools: Vec<ToolDef> = direct.iter().map(|t| t.def()).collect();
|
||||||
if !deferred.is_empty() {
|
if !deferred.is_empty() {
|
||||||
@@ -69,7 +69,7 @@ pub async fn config(Extension(user): Extension<User>, State(app): State<AppState
|
|||||||
/// A server skill with its supporting text files (templates).
|
/// A server skill with its supporting text files (templates).
|
||||||
pub async fn skill(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
|
pub async fn skill(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
|
||||||
let root = app.user_roots(Some(&user.id)).into_iter().next().unwrap_or_else(|| app.workspace());
|
let root = app.user_roots(Some(&user.id)).into_iter().next().unwrap_or_else(|| app.workspace());
|
||||||
let sk = crate::prompts::skills(&app, &root, &root).into_iter().find(|s| s.name == name).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "skill not found".into()))?;
|
let sk = crate::prompts::skills(&app, &root, &root, Some(&user.id)).into_iter().find(|s| s.name == name).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "skill not found".into()))?;
|
||||||
let dir = sk.path.parent().map(PathBuf::from).unwrap_or_default();
|
let dir = sk.path.parent().map(PathBuf::from).unwrap_or_default();
|
||||||
let content = std::fs::read_to_string(&sk.path)?;
|
let content = std::fs::read_to_string(&sk.path)?;
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
|
|||||||
@@ -0,0 +1,619 @@
|
|||||||
|
//! Versions, tags and releases of factory repositories.
|
||||||
|
//!
|
||||||
|
//! Every merged factory issue gets a version (`MAJOR.MINOR.PATCH`): the patch number goes up with each
|
||||||
|
//! issue, the minor number when the issue completes a milestone (`M1.3` was the last open `M1.x`
|
||||||
|
//! issue); the patch restarts at 0. A version is a commit with a `VERSION` file on the default branch
|
||||||
|
//! plus the tag `vX.Y.Z` on it. Major versions are only made by a manual release, which also builds
|
||||||
|
//! the Docker image and the downloads described in `.factory/release.json`.
|
||||||
|
|
||||||
|
use crate::app::App;
|
||||||
|
use crate::factory::{Forge, RepoCfg, bot_comment, checkout, git, issue_no, notify};
|
||||||
|
use crate::store::User;
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub type Ver = (u64, u64, u64);
|
||||||
|
|
||||||
|
pub fn parse_version(s: &str) -> Option<Ver> {
|
||||||
|
let mut it = s.trim().trim_start_matches('v').split('.');
|
||||||
|
let v = (it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?.parse().ok()?);
|
||||||
|
it.next().is_none().then_some(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fmt(v: Ver) -> String {
|
||||||
|
format!("{}.{}.{}", v.0, v.1, v.2)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Milestone of an issue title: `M1.3 – x` → (1, Some(3)), `M1 – x` → (1, None).
|
||||||
|
pub fn milestone_of(title: &str) -> Option<(u64, Option<u64>)> {
|
||||||
|
let t = title.trim();
|
||||||
|
let rest = t.strip_prefix('M').or_else(|| t.strip_prefix('m'))?;
|
||||||
|
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
|
||||||
|
let k: u64 = digits.parse().ok()?;
|
||||||
|
let after = &rest[digits.len()..];
|
||||||
|
if let Some(a) = after.strip_prefix('.') {
|
||||||
|
let d: String = a.chars().take_while(|c| c.is_ascii_digit()).collect();
|
||||||
|
if !d.is_empty() {
|
||||||
|
return Some((k, Some(d.parse().ok()?)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match after.chars().next() {
|
||||||
|
None | Some(' ') | Some('–') | Some('-') | Some(':') => Some((k, None)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Clone, Copy)]
|
||||||
|
pub enum Bump {
|
||||||
|
Patch,
|
||||||
|
Minor,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How an issue raises the version, given the titles of the *other* open issues of the repository.
|
||||||
|
pub fn bump_for(title: &str, other_open: &[String]) -> Bump {
|
||||||
|
match milestone_of(title) {
|
||||||
|
Some((_, None)) => Bump::Minor,
|
||||||
|
Some((k, Some(_))) => {
|
||||||
|
if other_open.iter().any(|t| matches!(milestone_of(t), Some((k2, Some(_))) if k2 == k)) {
|
||||||
|
Bump::Patch
|
||||||
|
} else {
|
||||||
|
Bump::Minor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => Bump::Patch,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next_version(cur: Ver, b: Bump) -> Ver {
|
||||||
|
match b {
|
||||||
|
Bump::Patch => (cur.0, cur.1, cur.2 + 1),
|
||||||
|
Bump::Minor => (cur.0, cur.1 + 1, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- git helpers ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Highest `vX.Y.Z` tag of the remote (0.0.0 when there is none).
|
||||||
|
async fn tags_version(cfg: &RepoCfg, dir: &Path) -> Ver {
|
||||||
|
// The remote is the truth: a local checkout keeps tags that were deleted on the forge.
|
||||||
|
let remote = git(cfg, dir, &["ls-remote", "--tags", "--refs", "origin", "v[0-9]*"]).await;
|
||||||
|
let names: Vec<String> = match remote {
|
||||||
|
Ok(out) => out.lines().filter_map(|l| l.split("refs/tags/").nth(1)).map(str::to_string).collect(),
|
||||||
|
Err(_) => {
|
||||||
|
let _ = git(cfg, dir, &["fetch", "--tags", "--force", "origin"]).await;
|
||||||
|
git(cfg, dir, &["tag", "-l", "v[0-9]*"]).await.unwrap_or_default().lines().map(str::to_string).collect()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
names.iter().filter_map(|t| parse_version(t)).max().unwrap_or((0, 0, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `git pull --ff-only` of the default branch in the main checkout, so everything that was merged
|
||||||
|
/// (also by others) is on disk for the reviews. Does nothing harmful: with local changes or a
|
||||||
|
/// diverged branch it reports an error and leaves the checkout alone.
|
||||||
|
pub async fn sync_default(cfg: &RepoCfg, dir: &Path) -> Result<()> {
|
||||||
|
let base = base_branch(cfg, dir).await;
|
||||||
|
let current = git(cfg, dir, &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap_or_default();
|
||||||
|
if current != base {
|
||||||
|
if !git(cfg, dir, &["status", "--porcelain"]).await.unwrap_or_default().is_empty() {
|
||||||
|
bail!("the checkout has local changes and is on '{current}', not on {base}");
|
||||||
|
}
|
||||||
|
git(cfg, dir, &["checkout", "-q", &base]).await?;
|
||||||
|
}
|
||||||
|
git(cfg, dir, &["merge", "--ff-only", "-q", &format!("origin/{base}")]).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn base_branch(cfg: &RepoCfg, repo: &Path) -> String {
|
||||||
|
git(cfg, repo, &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]).await.ok().and_then(|s| s.strip_prefix("origin/").map(String::from)).unwrap_or_else(|| "main".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A throw-away detached worktree of the default branch below `<owner>/<sub>/<name>`.
|
||||||
|
async fn fresh_worktree(cfg: &RepoCfg, repo: &Path, sub: &str, name: &str, base: &str) -> Result<PathBuf> {
|
||||||
|
let work = repo.parent().context("no parent folder")?.join(sub).join(name);
|
||||||
|
std::fs::create_dir_all(work.parent().unwrap())?;
|
||||||
|
if work.exists() {
|
||||||
|
let _ = git(cfg, repo, &["worktree", "remove", "--force", &work.display().to_string()]).await;
|
||||||
|
let _ = std::fs::remove_dir_all(&work);
|
||||||
|
}
|
||||||
|
let _ = git(cfg, repo, &["worktree", "prune"]).await;
|
||||||
|
git(cfg, repo, &["worktree", "add", "--detach", &work.display().to_string(), &format!("origin/{base}")]).await?;
|
||||||
|
Ok(work)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn drop_worktree(cfg: &RepoCfg, repo: &Path, work: &Path) {
|
||||||
|
let _ = git(cfg, repo, &["worktree", "remove", "--force", &work.display().to_string()]).await;
|
||||||
|
let _ = std::fs::remove_dir_all(work);
|
||||||
|
}
|
||||||
|
|
||||||
|
const IDENT: [&str; 4] = ["-c", "user.name=CodeCraft Factory", "-c", "user.email=factory@codecraft.invalid"];
|
||||||
|
|
||||||
|
/// Write `VERSION` and commit it locally (nothing is pushed yet).
|
||||||
|
async fn commit_version(cfg: &RepoCfg, work: &Path, ver: &str, msg: &str) -> Result<()> {
|
||||||
|
std::fs::write(work.join("VERSION"), format!("{ver}\n"))?;
|
||||||
|
git(cfg, work, &["add", "VERSION"]).await?;
|
||||||
|
if !git(cfg, work, &["diff", "--cached", "--name-only"]).await?.is_empty() {
|
||||||
|
let mut args = IDENT.to_vec();
|
||||||
|
args.extend(["commit", "-m", msg]);
|
||||||
|
git(cfg, work, &args).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tag the commit and push default branch and tag. Returns a warning when the branch could not be
|
||||||
|
/// pushed (e.g. protected): then the tag goes onto the commit already on the branch.
|
||||||
|
async fn publish_version(cfg: &RepoCfg, work: &Path, base: &str, ver: &str, msg: &str) -> Result<String> {
|
||||||
|
let mut warn = String::new();
|
||||||
|
let target = format!("HEAD:refs/heads/{base}");
|
||||||
|
let mut pushed = git(cfg, work, &["push", "origin", &target]).await;
|
||||||
|
if pushed.is_err() {
|
||||||
|
// The branch moved meanwhile: put the version commit on top and try once more.
|
||||||
|
let _ = git(cfg, work, &["fetch", "origin"]).await;
|
||||||
|
let upstream = format!("origin/{base}");
|
||||||
|
let mut args = IDENT.to_vec();
|
||||||
|
args.extend(["rebase", &upstream]);
|
||||||
|
if git(cfg, work, &args).await.is_ok() {
|
||||||
|
pushed = git(cfg, work, &["push", "origin", &target]).await;
|
||||||
|
} else {
|
||||||
|
let _ = git(cfg, work, &["rebase", "--abort"]).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Err(e) = pushed {
|
||||||
|
warn = format!("the VERSION commit could not be pushed to {base} ({e:#}); the tag points to the branch head instead");
|
||||||
|
git(cfg, work, &["reset", "--hard", &format!("origin/{base}")]).await?;
|
||||||
|
}
|
||||||
|
let tag = format!("v{ver}");
|
||||||
|
let mut args = IDENT.to_vec();
|
||||||
|
args.extend(["tag", "-a", "-f", &tag, "-m", msg]);
|
||||||
|
git(cfg, work, &args).await?;
|
||||||
|
git(cfg, work, &["push", "origin", &format!("refs/tags/{tag}")]).await?;
|
||||||
|
Ok(warn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- version of merged issues -----------------------------------------------------------------
|
||||||
|
|
||||||
|
static BUSY: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
|
||||||
|
|
||||||
|
/// Keeps two passes (poller and manual poll) from versioning the same repository at once.
|
||||||
|
struct Busy(String);
|
||||||
|
|
||||||
|
fn busy(repo: &str) -> Option<Busy> {
|
||||||
|
let set = BUSY.get_or_init(Default::default);
|
||||||
|
set.lock().unwrap().insert(repo.to_string()).then(|| Busy(repo.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Busy {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(set) = BUSY.get() {
|
||||||
|
set.lock().unwrap().remove(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pr_number(url: &str) -> u64 {
|
||||||
|
url.trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Give every merged, accepted issue its version. The first pass over a repository only
|
||||||
|
/// sets the baseline: issues that were done before are not versioned.
|
||||||
|
pub async fn version_pass(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()> {
|
||||||
|
let Some(_guard) = busy(&cfg.url) else { return Ok(()) };
|
||||||
|
let rows: Vec<Value> = app.store.factory_issues(&user.id)?.into_iter().filter(|r| r["repo"].as_str() == Some(cfg.url.as_str())).collect();
|
||||||
|
let pending = |r: &&Value| matches!(r["state"].as_str(), Some("done") | Some("closed")) && r["version"].as_str() == Some("") && !r["pr_url"].as_str().unwrap_or("").is_empty();
|
||||||
|
if app.store.factory_version(&cfg.url)?.is_none() {
|
||||||
|
let dir = checkout(app, user, cfg).await?;
|
||||||
|
let cur = tags_version(cfg, &dir).await;
|
||||||
|
for r in rows.iter().filter(|r| matches!(r["state"].as_str(), Some("done") | Some("closed")) && r["version"].as_str() == Some("")) {
|
||||||
|
app.store.factory_issue_set(&cfg.url, issue_no(r), &[("version", json!("-"))])?;
|
||||||
|
}
|
||||||
|
app.store.factory_version_set(&cfg.url, &fmt(cur))?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut todo: Vec<&Value> = rows.iter().filter(pending).collect();
|
||||||
|
if todo.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
todo.sort_by_key(|r| issue_no(r));
|
||||||
|
let g = Forge::new(cfg)?;
|
||||||
|
for r in todo {
|
||||||
|
let n = issue_no(r);
|
||||||
|
let pr_n = pr_number(r["pr_url"].as_str().unwrap_or(""));
|
||||||
|
if pr_n == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let pr = match g.pr(pr_n).await {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("factory {}#{n}: pull request: {e:#}", cfg.url);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if pr["state"].as_str() != Some("merged") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Remember it at once: if the version step below fails, the issue can still be closed by hand.
|
||||||
|
let _ = app.store.factory_issue_set(&cfg.url, n, &[("merged", json!(1))]);
|
||||||
|
let title = r["title"].as_str().unwrap_or("").to_string();
|
||||||
|
let others: Vec<String> = g.open_issue_titles().await?.into_iter().filter(|(num, _)| *num != n).map(|(_, t)| t).collect();
|
||||||
|
let dir = checkout(app, user, cfg).await?;
|
||||||
|
let cur = tags_version(cfg, &dir).await;
|
||||||
|
let bump = bump_for(&title, &others);
|
||||||
|
let new = fmt(next_version(cur, bump));
|
||||||
|
let base = base_branch(cfg, &dir).await;
|
||||||
|
let (_, _, name) = cfg.parts()?;
|
||||||
|
let work = fresh_worktree(cfg, &dir, "_release", &format!("{name}-version"), &base).await?;
|
||||||
|
let msg = format!("Release v{new}: {title} (#{n})");
|
||||||
|
let published = async {
|
||||||
|
commit_version(cfg, &work, &new, &msg).await?;
|
||||||
|
publish_version(cfg, &work, &base, &new, &msg).await
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
drop_worktree(cfg, &dir, &work).await;
|
||||||
|
let warn = match published {
|
||||||
|
Ok(w) => w,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("factory {}#{n}: version {new}: {e:#}", cfg.url);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let _ = checkout(app, user, cfg).await; // pulls the merge and the VERSION commit
|
||||||
|
app.store.factory_issue_set(&cfg.url, n, &[("version", json!(new.clone())), ("state", json!("closed"))])?;
|
||||||
|
app.store.factory_version_set(&cfg.url, &new)?;
|
||||||
|
let _ = g.close_issue(n as u64).await;
|
||||||
|
let why = if bump == Bump::Minor && milestone_of(&title).is_some() { " – the milestone is complete" } else { "" };
|
||||||
|
let extra = if warn.is_empty() { String::new() } else { format!("\n\nNote: {warn}.") };
|
||||||
|
bot_comment(&g, n as u64, &format!("**Version v{new}**{why}. The change is merged; tag `v{new}` and `VERSION` are on the default branch.{extra}")).await;
|
||||||
|
notify(app, user, &format!("Factory #{n}"), &format!("v{new}{why}"), n).await;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- manual release ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// `.factory/release.json`: how to build the downloads of a release.
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
pub struct ReleaseSpec {
|
||||||
|
/// Docker image name without tag, e.g. registry.example.org/team/app (empty = no image).
|
||||||
|
#[serde(default)]
|
||||||
|
pub image: String,
|
||||||
|
#[serde(default = "default_platforms")]
|
||||||
|
pub platforms: String,
|
||||||
|
#[serde(default = "default_dockerfile")]
|
||||||
|
pub dockerfile: String,
|
||||||
|
#[serde(default = "default_context")]
|
||||||
|
pub context: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub build_args: HashMap<String, String>,
|
||||||
|
/// Shell commands run in the release checkout before the image is built (e.g. to make zips).
|
||||||
|
#[serde(default)]
|
||||||
|
pub commands: Vec<String>,
|
||||||
|
/// Files (globs relative to the checkout) attached to the release; the source zip is always attached.
|
||||||
|
#[serde(default)]
|
||||||
|
pub files: Vec<String>,
|
||||||
|
/// Name used for the source zip (default: the repository name).
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_platforms() -> String {
|
||||||
|
"linux/amd64,linux/arm64".into()
|
||||||
|
}
|
||||||
|
fn default_dockerfile() -> String {
|
||||||
|
"Dockerfile".into()
|
||||||
|
}
|
||||||
|
fn default_context() -> String {
|
||||||
|
".".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a command with a timeout; returns the last lines of its output.
|
||||||
|
async fn run(cmd: &mut tokio::process::Command, timeout: Duration, stdin: Option<&str>) -> Result<String> {
|
||||||
|
use tokio::io::AsyncWriteExt;
|
||||||
|
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).stdin(if stdin.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() }).kill_on_drop(true);
|
||||||
|
let mut child = cmd.spawn().context("could not start the command")?;
|
||||||
|
if let (Some(text), Some(mut si)) = (stdin, child.stdin.take()) {
|
||||||
|
si.write_all(text.as_bytes()).await?;
|
||||||
|
}
|
||||||
|
let out = tokio::time::timeout(timeout, child.wait_with_output()).await.map_err(|_| anyhow::anyhow!("timed out after {} min", timeout.as_secs() / 60))??;
|
||||||
|
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||||
|
let tail: Vec<&str> = text.lines().rev().take(25).collect::<Vec<_>>().into_iter().rev().collect();
|
||||||
|
let tail = tail.join("\n");
|
||||||
|
if !out.status.success() {
|
||||||
|
bail!("{}", tail);
|
||||||
|
}
|
||||||
|
Ok(tail)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clean_env(cmd: &mut tokio::process::Command, extra: &[(&str, &str)]) {
|
||||||
|
cmd.env_clear().env("PATH", std::env::var("PATH").unwrap_or_default()).env("HOME", "/tmp");
|
||||||
|
for (k, v) in extra {
|
||||||
|
cmd.env(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current version, suggested next major version and the release recipe of the default branch.
|
||||||
|
pub async fn preview(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<Value> {
|
||||||
|
let dir = checkout(app, user, cfg).await?;
|
||||||
|
let cur = tags_version(cfg, &dir).await;
|
||||||
|
let base = base_branch(cfg, &dir).await;
|
||||||
|
let spec = git(cfg, &dir, &["show", &format!("origin/{base}:.factory/release.json")]).await.ok();
|
||||||
|
Ok(json!({"current": fmt(cur), "suggested": fmt((cur.0 + 1, 0, 0)), "spec": spec, "running": app.store.factory_release_running(&cfg.url)?}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate and start a release in the background; returns the release id.
|
||||||
|
pub async fn start_release(app: &Arc<App>, user: &User, cfg: &RepoCfg, version: &str) -> Result<String> {
|
||||||
|
let Some(new) = parse_version(version) else { bail!("the version must look like 1.0.0") };
|
||||||
|
if app.store.factory_release_running(&cfg.url)? {
|
||||||
|
bail!("a release of this repository is already running");
|
||||||
|
}
|
||||||
|
let dir = checkout(app, user, cfg).await?;
|
||||||
|
let cur = tags_version(cfg, &dir).await;
|
||||||
|
if new <= cur {
|
||||||
|
bail!("v{} is not newer than the current version v{}", fmt(new), fmt(cur));
|
||||||
|
}
|
||||||
|
let id = crate::types::new_id();
|
||||||
|
app.store.factory_release_add(&id, &user.id, &cfg.url, &fmt(new))?;
|
||||||
|
let (app, user, cfg, rid) = (app.clone(), user.clone(), cfg.clone(), id.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let log = |m: &str| {
|
||||||
|
let _ = app.store.factory_release_log(&rid, m);
|
||||||
|
};
|
||||||
|
match run_release(&app, &user, &cfg, new, &rid, &log).await {
|
||||||
|
Ok(url) => {
|
||||||
|
let _ = app.store.factory_release_end(&rid, "done", &url);
|
||||||
|
notify(&app, &user, "Factory release", &format!("v{} released", fmt(new)), 0).await;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log(&format!("FAILED: {e:#}"));
|
||||||
|
let _ = app.store.factory_release_end(&rid, "failed", "");
|
||||||
|
notify(&app, &user, "Factory release", &format!("v{} failed", fmt(new)), 0).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_release(app: &Arc<App>, user: &User, cfg: &RepoCfg, new: Ver, rid: &str, log: &(dyn Fn(&str) + Sync)) -> Result<String> {
|
||||||
|
let ver = fmt(new);
|
||||||
|
let tag = format!("v{ver}");
|
||||||
|
let dir = checkout(app, user, cfg).await?;
|
||||||
|
let base = base_branch(cfg, &dir).await;
|
||||||
|
let (_, _, name) = cfg.parts()?;
|
||||||
|
let g = Forge::new(cfg)?;
|
||||||
|
log(&format!("release {tag} from {base}"));
|
||||||
|
let work = fresh_worktree(cfg, &dir, "_release", &format!("{name}-release"), &base).await?;
|
||||||
|
let tmp = std::env::temp_dir().join(format!("factory-release-{rid}"));
|
||||||
|
std::fs::create_dir_all(&tmp)?;
|
||||||
|
let result = release_steps(cfg, &g, &work, &tmp, &base, &name, &ver, &tag, rid, log).await;
|
||||||
|
drop_worktree(cfg, &dir, &work).await;
|
||||||
|
let _ = std::fs::remove_dir_all(&tmp);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
async fn release_steps(cfg: &RepoCfg, g: &Forge, work: &Path, tmp: &Path, base: &str, name: &str, ver: &str, tag: &str, rid: &str, log: &(dyn Fn(&str) + Sync)) -> Result<String> {
|
||||||
|
let msg = format!("Release {tag}");
|
||||||
|
commit_version(cfg, work, ver, &msg).await?;
|
||||||
|
let spec: ReleaseSpec = match std::fs::read_to_string(work.join(".factory/release.json")) {
|
||||||
|
Ok(t) => serde_json::from_str(&t).context(".factory/release.json is not valid")?,
|
||||||
|
Err(_) => {
|
||||||
|
log("no .factory/release.json – only the tag, the release and the source zip are made");
|
||||||
|
ReleaseSpec::default()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let hour = Duration::from_secs(3600);
|
||||||
|
for cmd in &spec.commands {
|
||||||
|
log(&format!("$ {cmd}"));
|
||||||
|
let mut c = tokio::process::Command::new("bash");
|
||||||
|
c.arg("-c").arg(cmd).current_dir(work);
|
||||||
|
clean_env(&mut c, &[("VERSION", ver), ("CI", "1")]);
|
||||||
|
log(&run(&mut c, hour, None).await?);
|
||||||
|
}
|
||||||
|
if !spec.image.trim().is_empty() {
|
||||||
|
build_image(cfg, g, &spec, work, tmp, ver, rid, log).await?;
|
||||||
|
}
|
||||||
|
// Publish: branch + tag, then the release with its files.
|
||||||
|
let warn = publish_version(cfg, work, base, ver, &msg).await?;
|
||||||
|
if !warn.is_empty() {
|
||||||
|
log(&format!("note: {warn}"));
|
||||||
|
}
|
||||||
|
log(&format!("tag {tag} pushed"));
|
||||||
|
let prev = git(cfg, work, &["tag", "-l", "v[0-9]*"]).await.unwrap_or_default().lines().filter_map(|t| parse_version(t).map(|v| (v, t.to_string()))).filter(|(v, _)| fmt(*v) != ver && *v < parse_version(ver).unwrap_or((0, 0, 0))).max().map(|(_, t)| t);
|
||||||
|
let range = prev.as_ref().map(|p| format!("{p}..{tag}")).unwrap_or_else(|| tag.to_string());
|
||||||
|
let changes = git(cfg, work, &["log", "--pretty=format:- %s", "--max-count=200", &range]).await.unwrap_or_default();
|
||||||
|
let mut notes = format!("Release {tag}\n\n");
|
||||||
|
if !spec.image.trim().is_empty() {
|
||||||
|
notes.push_str(&format!("Docker image: `{}:{ver}` ({})\n\n", spec.image.trim(), spec.platforms));
|
||||||
|
}
|
||||||
|
notes.push_str(&format!("## Changes\n\n{changes}\n"));
|
||||||
|
let rel = g.create_release(tag, &format!("{name} {tag}"), ¬es).await?;
|
||||||
|
let url = rel["html_url"].as_str().unwrap_or("").to_string();
|
||||||
|
log(&format!("release created {url}"));
|
||||||
|
|
||||||
|
// Downloads: the source zip and the configured files.
|
||||||
|
let zip_name = format!("{}-{ver}-source.zip", Some(spec.name.trim()).filter(|n| !n.is_empty()).unwrap_or(name));
|
||||||
|
let zip = tmp.join(&zip_name);
|
||||||
|
git(cfg, work, &["archive", "--format=zip", &format!("--prefix={name}-{ver}/"), "-o", &zip.display().to_string(), "HEAD"]).await?;
|
||||||
|
let mut files: Vec<(String, PathBuf)> = vec![(zip_name, zip)];
|
||||||
|
if !spec.files.is_empty() {
|
||||||
|
let mut builder = globset::GlobSetBuilder::new();
|
||||||
|
for f in &spec.files {
|
||||||
|
builder.add(globset::Glob::new(f).with_context(|| format!("bad file pattern {f}"))?);
|
||||||
|
}
|
||||||
|
let set = builder.build()?;
|
||||||
|
let mut stack = vec![work.to_path_buf()];
|
||||||
|
while let Some(d) = stack.pop() {
|
||||||
|
for e in std::fs::read_dir(&d)?.flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
let rel_path = p.strip_prefix(work).unwrap_or(&p).to_path_buf();
|
||||||
|
if rel_path.starts_with(".git") || rel_path.starts_with("node_modules") || rel_path.starts_with("target") && !set.is_match(&rel_path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if p.is_dir() {
|
||||||
|
stack.push(p);
|
||||||
|
} else if set.is_match(&rel_path) && files.len() < 60 {
|
||||||
|
files.push((e.file_name().to_string_lossy().to_string(), p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (fname, path) in &files {
|
||||||
|
match g.upload_asset(&rel["id"], fname, path).await {
|
||||||
|
Ok(()) => log(&format!("attached {fname}")),
|
||||||
|
Err(e) => log(&format!("not attached: {e:#}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build and push the multi-arch Docker image with buildx (own builder, own login, both removed afterwards).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
async fn build_image(cfg: &RepoCfg, g: &Forge, spec: &ReleaseSpec, work: &Path, tmp: &Path, ver: &str, rid: &str, log: &(dyn Fn(&str) + Sync)) -> Result<()> {
|
||||||
|
let image = spec.image.trim();
|
||||||
|
let first = image.split('/').next().unwrap_or("");
|
||||||
|
let host = if image.contains('/') && (first.contains('.') || first.contains(':')) { first } else { "docker.io" };
|
||||||
|
let conf = tmp.join("docker");
|
||||||
|
std::fs::create_dir_all(&conf)?;
|
||||||
|
let conf_s = conf.display().to_string();
|
||||||
|
let builder = format!("factory-{}", &rid[..8.min(rid.len())]);
|
||||||
|
let minute = Duration::from_secs(120);
|
||||||
|
let env = [("DOCKER_CONFIG", conf_s.as_str())];
|
||||||
|
|
||||||
|
let mut c = tokio::process::Command::new("docker");
|
||||||
|
c.args(["buildx", "version"]);
|
||||||
|
clean_env(&mut c, &env);
|
||||||
|
run(&mut c, minute, None).await.context("docker buildx is not available in this installation")?;
|
||||||
|
|
||||||
|
let login = g.login().await?;
|
||||||
|
log(&format!("docker login {host}"));
|
||||||
|
let mut c = tokio::process::Command::new("docker");
|
||||||
|
c.args(["login", host, "-u", &login, "--password-stdin"]);
|
||||||
|
clean_env(&mut c, &env);
|
||||||
|
run(&mut c, minute, Some(&cfg.token)).await.context("docker login failed")?;
|
||||||
|
|
||||||
|
let mut c = tokio::process::Command::new("docker");
|
||||||
|
c.args(["buildx", "create", "--name", &builder, "--driver", "docker-container"]);
|
||||||
|
clean_env(&mut c, &env);
|
||||||
|
run(&mut c, minute, None).await.context("could not create the buildx builder")?;
|
||||||
|
|
||||||
|
let mut args: Vec<String> = ["buildx", "build", "--builder", &builder, "--platform", &spec.platforms, "-f", &spec.dockerfile, "-t", &format!("{image}:{ver}"), "-t", &format!("{image}:latest"), "--build-arg", &format!("VERSION={ver}")].iter().map(|s| s.to_string()).collect();
|
||||||
|
for (k, v) in &spec.build_args {
|
||||||
|
args.extend(["--build-arg".to_string(), format!("{k}={v}")]);
|
||||||
|
}
|
||||||
|
args.extend(["--push".to_string(), spec.context.clone()]);
|
||||||
|
log(&format!("docker buildx build {} → {image}:{ver}", spec.platforms));
|
||||||
|
let mut c = tokio::process::Command::new("docker");
|
||||||
|
c.args(&args).current_dir(work);
|
||||||
|
clean_env(&mut c, &env);
|
||||||
|
let built = run(&mut c, Duration::from_secs(3 * 3600), None).await;
|
||||||
|
|
||||||
|
let mut c = tokio::process::Command::new("docker");
|
||||||
|
c.args(["buildx", "rm", "--force", &builder]);
|
||||||
|
clean_env(&mut c, &env);
|
||||||
|
let _ = run(&mut c, minute, None).await;
|
||||||
|
log(&built.context("the image build failed")?);
|
||||||
|
log("image pushed");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_and_formats_versions() {
|
||||||
|
assert_eq!(parse_version("v1.2.3"), Some((1, 2, 3)));
|
||||||
|
assert_eq!(parse_version("0.0.0"), Some((0, 0, 0)));
|
||||||
|
assert_eq!(parse_version("1.2"), None);
|
||||||
|
assert_eq!(parse_version("1.2.3.4"), None);
|
||||||
|
assert_eq!(parse_version("vx.1.2"), None);
|
||||||
|
assert_eq!(fmt((0, 1, 10)), "0.1.10");
|
||||||
|
assert!(parse_version("0.10.0") > parse_version("0.9.9"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_milestones_from_titles() {
|
||||||
|
assert_eq!(milestone_of("M1.3 – Import"), Some((1, Some(3))));
|
||||||
|
assert_eq!(milestone_of("M12.10 - x"), Some((12, Some(10))));
|
||||||
|
assert_eq!(milestone_of("M1 – Foundation"), Some((1, None)));
|
||||||
|
assert_eq!(milestone_of("M0"), Some((0, None)));
|
||||||
|
assert_eq!(milestone_of("Make it faster"), None);
|
||||||
|
assert_eq!(milestone_of("M1abc"), None);
|
||||||
|
assert_eq!(milestone_of("Fix login"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn issues_raise_patch_and_the_last_one_of_a_milestone_the_minor() {
|
||||||
|
let open = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||||
|
// other M1 issues still open: patch
|
||||||
|
assert_eq!(bump_for("M1.3 – Import", &open(&["M1.4 – Debayering", "M2.1 – Mail"])), Bump::Patch);
|
||||||
|
// the last open M1 issue: minor (other milestones do not matter)
|
||||||
|
assert_eq!(bump_for("M1.11 – Log", &open(&["M2.1 – Mail", "Fix typo"])), Bump::Minor);
|
||||||
|
assert_eq!(bump_for("Fix login bug", &open(&["M1.1 – x"])), Bump::Patch);
|
||||||
|
assert_eq!(bump_for("M3 – Mosaics", &open(&[])), Bump::Minor);
|
||||||
|
assert_eq!(next_version((0, 0, 7), Bump::Patch), (0, 0, 8));
|
||||||
|
assert_eq!(next_version((0, 0, 10), Bump::Minor), (0, 1, 0));
|
||||||
|
assert_eq!(next_version((0, 1, 4), Bump::Minor), (0, 2, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn release_spec_has_defaults() {
|
||||||
|
let s: ReleaseSpec = serde_json::from_str(r#"{"image": "r.example/app"}"#).unwrap();
|
||||||
|
assert_eq!((s.platforms.as_str(), s.dockerfile.as_str(), s.context.as_str()), ("linux/amd64,linux/arm64", "Dockerfile", "."));
|
||||||
|
assert!(s.commands.is_empty() && s.files.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sync_default_pulls_what_was_merged() {
|
||||||
|
let run = |dir: &Path, args: &[&str]| {
|
||||||
|
let o = std::process::Command::new("git").args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "init.defaultBranch=main"]).args(args).current_dir(dir).output().unwrap();
|
||||||
|
assert!(o.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&o.stderr));
|
||||||
|
};
|
||||||
|
let root = std::env::temp_dir().join(format!("factory-sync-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
|
run(&root, &["init", "-q", "--bare", "origin.git"]);
|
||||||
|
run(&root, &["clone", "-q", "origin.git", "a"]);
|
||||||
|
std::fs::write(root.join("a/one.txt"), "1").unwrap();
|
||||||
|
run(&root.join("a"), &["add", "."]);
|
||||||
|
run(&root.join("a"), &["commit", "-qm", "one"]);
|
||||||
|
run(&root.join("a"), &["push", "-q", "origin", "HEAD:main"]);
|
||||||
|
run(&root, &["--git-dir=origin.git", "symbolic-ref", "HEAD", "refs/heads/main"]);
|
||||||
|
run(&root, &["clone", "-q", "origin.git", "checkout"]);
|
||||||
|
// somebody merges a second change on the remote
|
||||||
|
std::fs::write(root.join("a/two.txt"), "2").unwrap();
|
||||||
|
run(&root.join("a"), &["add", "."]);
|
||||||
|
run(&root.join("a"), &["commit", "-qm", "two"]);
|
||||||
|
run(&root.join("a"), &["push", "-q", "origin", "HEAD:main"]);
|
||||||
|
let cfg: RepoCfg = serde_json::from_value(json!({"url": "https://g.example/o/r.git", "token": "t"})).unwrap();
|
||||||
|
let dir = root.join("checkout");
|
||||||
|
git(&cfg, &dir, &["fetch", "origin"]).await.unwrap();
|
||||||
|
assert!(!dir.join("two.txt").exists(), "a fetch alone does not update the files");
|
||||||
|
sync_default(&cfg, &dir).await.unwrap();
|
||||||
|
assert!(dir.join("two.txt").exists());
|
||||||
|
// local changes block switching, nothing is damaged
|
||||||
|
std::fs::write(dir.join("one.txt"), "edited").unwrap();
|
||||||
|
sync_default(&cfg, &dir).await.unwrap();
|
||||||
|
assert_eq!(std::fs::read_to_string(dir.join("one.txt")).unwrap(), "edited");
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pr_numbers_come_from_urls() {
|
||||||
|
assert_eq!(pr_number("https://g.example/o/r/pulls/72"), 72);
|
||||||
|
assert_eq!(pr_number("https://g.example/o/r/-/merge_requests/5/"), 5);
|
||||||
|
assert_eq!(pr_number(""), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn busy_guard_blocks_a_second_pass() {
|
||||||
|
let a = busy("https://g.example/o/busy-test");
|
||||||
|
assert!(a.is_some());
|
||||||
|
assert!(busy("https://g.example/o/busy-test").is_none());
|
||||||
|
drop(a);
|
||||||
|
assert!(busy("https://g.example/o/busy-test").is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -335,7 +335,7 @@ pub async fn run_with(app: &Arc<App>, job: &Job, trigger: &str, payload: Option<
|
|||||||
telegram_quiet: true,
|
telegram_quiet: true,
|
||||||
summary: String::new(),
|
summary: String::new(),
|
||||||
color: None,
|
color: None,
|
||||||
icon: None,
|
icon: None, skills: Vec::new(),
|
||||||
};
|
};
|
||||||
let session = app.save_session(session)?;
|
let session = app.save_session(session)?;
|
||||||
app.store.job_started(&job.id, &session.id, now)?;
|
app.store.job_started(&job.id, &session.id, now)?;
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ mod digest;
|
|||||||
mod docs;
|
mod docs;
|
||||||
mod export;
|
mod export;
|
||||||
mod factory;
|
mod factory;
|
||||||
|
mod factory_version;
|
||||||
mod files;
|
mod files;
|
||||||
mod git;
|
mod git;
|
||||||
mod health;
|
mod health;
|
||||||
@@ -34,6 +35,7 @@ mod push;
|
|||||||
mod provider;
|
mod provider;
|
||||||
mod reverse;
|
mod reverse;
|
||||||
mod runner;
|
mod runner;
|
||||||
|
mod skills_api;
|
||||||
mod sandbox;
|
mod sandbox;
|
||||||
mod shells;
|
mod shells;
|
||||||
mod sshkeys;
|
mod sshkeys;
|
||||||
@@ -43,6 +45,7 @@ mod telegram;
|
|||||||
mod terminal;
|
mod terminal;
|
||||||
mod tools;
|
mod tools;
|
||||||
mod types;
|
mod types;
|
||||||
|
mod testrunner;
|
||||||
mod update;
|
mod update;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
@@ -58,6 +61,11 @@ async fn main() -> Result<()> {
|
|||||||
tracing_subscriber::fmt().with_env_filter(filter).init();
|
tracing_subscriber::fmt().with_env_filter(filter).init();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `codecraft testrunner`: the service that runs throw-away test containers for the factory.
|
||||||
|
if std::env::args().nth(1).as_deref() == Some("testrunner") {
|
||||||
|
return testrunner::serve().await;
|
||||||
|
}
|
||||||
|
|
||||||
// In Docker, HOME lives on the data volume; make sure it exists for git/npm.
|
// In Docker, HOME lives on the data volume; make sure it exists for git/npm.
|
||||||
if let Ok(home) = std::env::var("HOME") {
|
if let Ok(home) = std::env::var("HOME") {
|
||||||
let _ = std::fs::create_dir_all(home);
|
let _ = std::fs::create_dir_all(home);
|
||||||
|
|||||||
@@ -211,7 +211,7 @@ mod tests {
|
|||||||
let session = crate::types::Session {
|
let session = crate::types::Session {
|
||||||
id: crate::types::new_id(), title: String::new(), cwd: dir.join("ws").display().to_string(), model: "x/y".into(), agent: "build".into(), permission_mode: "bypass".into(),
|
id: crate::types::new_id(), title: String::new(), cwd: dir.join("ws").display().to_string(), model: "x/y".into(), agent: "build".into(), permission_mode: "bypass".into(),
|
||||||
parent_id: None, owner_id: None, created_at: now, updated_at: now, todos: Value::Null, last_usage: None, clean_room: None, phase: None, worktree: None,
|
parent_id: None, owner_id: None, created_at: now, updated_at: now, todos: Value::Null, last_usage: None, clean_room: None, phase: None, worktree: None,
|
||||||
pinned: false, archived: false, folder: None, instructions: String::new(), telegram_quiet: true, summary: String::new(), color: None, icon: None,
|
pinned: false, archived: false, folder: None, instructions: String::new(), telegram_quiet: true, summary: String::new(), color: None, icon: None, skills: Vec::new(),
|
||||||
};
|
};
|
||||||
let session = app.save_session(session).unwrap();
|
let session = app.save_session(session).unwrap();
|
||||||
let reg = register(&session.id);
|
let reg = register(&session.id);
|
||||||
|
|||||||
@@ -285,11 +285,16 @@ pub fn system_prompt(app: &App, agent: &Agent, root: &Path, cwd: &Path, model: &
|
|||||||
s.push_str(&format!("- {server} ({n} tools, e.g. {})\n", names.join(", ")));
|
s.push_str(&format!("- {server} ({n} tools, e.g. {})\n", names.join(", ")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let skills = skills(app, root, cwd);
|
let skills = skills(app, root, cwd, owner.map(|u| u.id.as_str()));
|
||||||
if !skills.is_empty() {
|
if !skills.is_empty() {
|
||||||
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
|
if skills.len() <= SKILL_LIST_MAX {
|
||||||
for sk in &skills {
|
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
|
||||||
s.push_str(&format!("- {}: {}\n", sk.name, sk.description));
|
for sk in &skills {
|
||||||
|
s.push_str(&format!("- {}: {}\n", sk.name, sk.description.chars().take(160).collect::<String>()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// A large library must not fill the context: only the count; the agent searches on demand.
|
||||||
|
s.push_str(&format!("\n# Skills\n{} skills (packaged instructions for kinds of task) are available but not listed. Find one with the skill tool (query=<keywords>), then load it with name=<skill>.\n", skills.len()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(u) = owner {
|
if let Some(u) = owner {
|
||||||
@@ -381,23 +386,91 @@ pub struct Skill {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub path: PathBuf,
|
pub path: PathBuf,
|
||||||
|
/// Further files of the skill (relative paths, without SKILL.md).
|
||||||
|
pub files: Vec<String>,
|
||||||
|
/// Created by the user in the UI (editable there).
|
||||||
|
pub user: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn skills(app: &App, root: &Path, cwd: &Path) -> Vec<Skill> {
|
/// Where a user's own skills live: `<data>/user-skills/<user id>/<name>/SKILL.md` (+ more files).
|
||||||
|
pub fn user_skills_dir(app: &App, owner_id: &str) -> PathBuf {
|
||||||
|
app.data_dir().join("user-skills").join(owner_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Relative paths of all files below `dir` (depth <= 5, at most 200), without `SKILL.md` at the top.
|
||||||
|
pub fn skill_files(dir: &Path) -> Vec<String> {
|
||||||
|
fn walk(base: &Path, dir: &Path, depth: usize, out: &mut Vec<String>) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||||
|
let mut entries: Vec<_> = entries.flatten().collect();
|
||||||
|
entries.sort_by_key(|e| e.file_name());
|
||||||
|
for e in entries {
|
||||||
|
if out.len() >= 200 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let p = e.path();
|
||||||
|
let Ok(ty) = e.file_type() else { continue };
|
||||||
|
if ty.is_dir() && depth < 5 {
|
||||||
|
walk(base, &p, depth + 1, out);
|
||||||
|
} else if ty.is_file() {
|
||||||
|
if let Ok(rel) = p.strip_prefix(base) {
|
||||||
|
let rel = rel.to_string_lossy().to_string();
|
||||||
|
if rel != "SKILL.md" {
|
||||||
|
out.push(rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
walk(dir, dir, 0, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn skills(app: &App, root: &Path, cwd: &Path, owner_id: Option<&str>) -> Vec<Skill> {
|
||||||
let mut map = BTreeMap::new();
|
let mut map = BTreeMap::new();
|
||||||
for dir in resource_dirs(app, root, cwd, "skills") {
|
let mut dirs: Vec<(PathBuf, bool)> = resource_dirs(app, root, cwd, "skills").into_iter().map(|d| (d, false)).collect();
|
||||||
|
if let Some(id) = owner_id {
|
||||||
|
dirs.push((user_skills_dir(app, id), true));
|
||||||
|
}
|
||||||
|
for (dir, user) in dirs {
|
||||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||||
for e in entries.flatten() {
|
for e in entries.flatten() {
|
||||||
let p = e.path().join("SKILL.md");
|
let p = e.path().join("SKILL.md");
|
||||||
let Ok(text) = std::fs::read_to_string(&p) else { continue };
|
let Ok(text) = std::fs::read_to_string(&p) else { continue };
|
||||||
let (meta, _) = frontmatter(&text);
|
let (meta, _) = frontmatter(&text);
|
||||||
let name = meta.get("name").cloned().unwrap_or_else(|| e.file_name().to_string_lossy().into());
|
let name = meta.get("name").cloned().unwrap_or_else(|| e.file_name().to_string_lossy().into());
|
||||||
map.insert(name.clone(), Skill { name, description: meta.get("description").cloned().unwrap_or_default(), path: p });
|
map.insert(name.clone(), Skill { name, description: meta.get("description").cloned().unwrap_or_default(), files: skill_files(&e.path()), path: p, user });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
map.into_values().collect()
|
map.into_values().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds the skills the user switched on for this chat: their full instructions are part of every turn.
|
||||||
|
pub fn with_active_skills(app: &App, mut system: String, active: &[String], root: &Path, cwd: &Path, owner_id: Option<&str>) -> String {
|
||||||
|
if active.is_empty() {
|
||||||
|
return system;
|
||||||
|
}
|
||||||
|
let all = skills(app, root, cwd, owner_id);
|
||||||
|
let mut block = String::new();
|
||||||
|
for name in active {
|
||||||
|
let Some(sk) = all.iter().find(|s| &s.name == name) else { continue };
|
||||||
|
let Ok(text) = std::fs::read_to_string(&sk.path) else { continue };
|
||||||
|
let (_, body) = frontmatter(&text);
|
||||||
|
let body: String = body.chars().take(40_000).collect();
|
||||||
|
block.push_str(&format!("\n## Skill: {}\n{}\n", sk.name, body.trim()));
|
||||||
|
if !sk.files.is_empty() {
|
||||||
|
block.push_str(&format!("\nFurther files of this skill (read them with the skill tool: name=\"{}\", file=<path>): {}\n", sk.name, sk.files.join(", ")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !block.is_empty() {
|
||||||
|
system.push_str(&format!("\n\n# Active skills\nThe user switched these skills on for this chat. Follow them for every task they cover.\n{block}"));
|
||||||
|
}
|
||||||
|
system
|
||||||
|
}
|
||||||
|
|
||||||
|
/// More skills than this are not listed in the system prompt (the agent searches instead).
|
||||||
|
const SKILL_LIST_MAX: usize = 12;
|
||||||
|
|
||||||
pub struct SkillTool;
|
pub struct SkillTool;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -406,23 +479,60 @@ impl Tool for SkillTool {
|
|||||||
"skill"
|
"skill"
|
||||||
}
|
}
|
||||||
fn description(&self) -> String {
|
fn description(&self) -> String {
|
||||||
"Load a skill (packaged instructions for a kind of task) by name. Follow the returned instructions.".into()
|
"Load a skill (packaged instructions for a kind of task) by name and follow the returned instructions. `query` (keywords) lists matching skills instead; `file` reads one of the skill's further files.".into()
|
||||||
}
|
}
|
||||||
fn schema(&self) -> Value {
|
fn schema(&self) -> Value {
|
||||||
json!({"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]})
|
json!({"type": "object", "properties": {
|
||||||
|
"name": {"type": "string"},
|
||||||
|
"file": {"type": "string", "description": "relative path of a further file of the skill"},
|
||||||
|
"query": {"type": "string", "description": "keywords: lists the matching skills instead of loading one"}
|
||||||
|
}})
|
||||||
}
|
}
|
||||||
fn read_only(&self) -> bool {
|
fn read_only(&self) -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
async fn run(&self, input: Value, ctx: &ToolCtx) -> Result<ToolOutput> {
|
async fn run(&self, input: Value, ctx: &ToolCtx) -> Result<ToolOutput> {
|
||||||
|
let owner = ctx.app.store.get_session(&ctx.session_id).ok().flatten().and_then(|s| s.owner_id).or_else(|| ctx.owner_id.clone());
|
||||||
|
let all = skills(&ctx.app, &ctx.root(), &ctx.cwd, owner.as_deref());
|
||||||
|
if let Some(q) = input.get("query").and_then(|v| v.as_str()).filter(|q| !q.trim().is_empty()) {
|
||||||
|
let words: Vec<String> = q.to_lowercase().split_whitespace().map(str::to_string).collect();
|
||||||
|
let mut hits: Vec<(usize, &Skill)> = all
|
||||||
|
.iter()
|
||||||
|
.map(|s| {
|
||||||
|
let hay = format!("{} {}", s.name, s.description).to_lowercase();
|
||||||
|
(words.iter().filter(|w| hay.contains(w.as_str())).count(), s)
|
||||||
|
})
|
||||||
|
.filter(|(n, _)| *n > 0)
|
||||||
|
.collect();
|
||||||
|
hits.sort_by_key(|(n, s)| (std::cmp::Reverse(*n), s.name.clone()));
|
||||||
|
if hits.is_empty() {
|
||||||
|
return Ok(ToolOutput::text(format!("No skill matches '{q}' ({} skills available).", all.len())));
|
||||||
|
}
|
||||||
|
let lines: Vec<String> = hits.iter().take(15).map(|(_, s)| format!("- {}: {}", s.name, s.description.chars().take(200).collect::<String>())).collect();
|
||||||
|
return Ok(ToolOutput::text(format!("Matching skills (load one with name=<skill>):\n{}", lines.join("\n"))));
|
||||||
|
}
|
||||||
let name = arg_str(&input, "name")?;
|
let name = arg_str(&input, "name")?;
|
||||||
let Some(sk) = skills(&ctx.app, &ctx.root(), &ctx.cwd).into_iter().find(|s| s.name == name) else {
|
let Some(sk) = all.into_iter().find(|s| s.name == name) else {
|
||||||
return Ok(ToolOutput::error(format!("unknown skill '{name}'")));
|
return Ok(ToolOutput::error(format!("unknown skill '{name}'")));
|
||||||
};
|
};
|
||||||
|
let dir = sk.path.parent().unwrap_or(Path::new("."));
|
||||||
|
if let Some(file) = input.get("file").and_then(|v| v.as_str()).filter(|f| !f.trim().is_empty()) {
|
||||||
|
let rel = Path::new(file.trim());
|
||||||
|
if rel.is_absolute() || rel.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
|
||||||
|
return Ok(ToolOutput::error("file must be a relative path inside the skill"));
|
||||||
|
}
|
||||||
|
let Ok(real) = std::fs::canonicalize(dir.join(rel)) else { return Ok(ToolOutput::error(format!("no file '{file}' in skill '{name}'"))) };
|
||||||
|
if !real.starts_with(std::fs::canonicalize(dir)?) || !real.is_file() {
|
||||||
|
return Ok(ToolOutput::error(format!("no file '{file}' in skill '{name}'")));
|
||||||
|
}
|
||||||
|
let mut text = std::fs::read_to_string(&real).unwrap_or_else(|_| "(binary file)".into());
|
||||||
|
text.truncate(text.char_indices().nth(100_000).map(|(i, _)| i).unwrap_or(text.len()));
|
||||||
|
return Ok(ToolOutput::text(text));
|
||||||
|
}
|
||||||
let text = std::fs::read_to_string(&sk.path)?;
|
let text = std::fs::read_to_string(&sk.path)?;
|
||||||
let (_, body) = frontmatter(&text);
|
let (_, body) = frontmatter(&text);
|
||||||
let dir = sk.path.parent().unwrap_or(Path::new("."));
|
let files = if sk.files.is_empty() { String::new() } else { format!("\n\nFurther files (read with name=\"{name}\" and file=<path>): {}", sk.files.join(", ")) };
|
||||||
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}", dir.display())))
|
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}{files}", dir.display())))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -112,7 +112,8 @@ pub fn submit(app: Arc<App>, session_id: String, parts: Vec<Part>, source: &str)
|
|||||||
let leftover = app.with_runtime(&session_id, |r| {
|
let leftover = app.with_runtime(&session_id, |r| {
|
||||||
r.cancel = None;
|
r.cancel = None;
|
||||||
r.effort = None;
|
r.effort = None;
|
||||||
if cancel.is_cancelled() { Vec::new() } else { take_queue(&app, &session_id) }
|
let forced = std::mem::take(&mut r.force_queue);
|
||||||
|
if cancel.is_cancelled() && !forced { Vec::new() } else { take_queue(&app, &session_id) }
|
||||||
});
|
});
|
||||||
app.emit(Event::SessionStatus { session_id: session_id.clone(), busy: false });
|
app.emit(Event::SessionStatus { session_id: session_id.clone(), busy: false });
|
||||||
if leftover.is_empty() && !cancel.is_cancelled() {
|
if leftover.is_empty() && !cancel.is_cancelled() {
|
||||||
@@ -139,6 +140,25 @@ pub fn flush_queue(app: Arc<App>, session_id: &str) -> Result<bool> {
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Deliver the queued messages now: the running step is interrupted and the messages start the next turn
|
||||||
|
/// at once (instead of waiting for the agent's next step). Without a running turn this is `flush_queue`.
|
||||||
|
/// Returns false when nothing is queued.
|
||||||
|
pub fn force_queue(app: Arc<App>, session_id: &str) -> Result<bool> {
|
||||||
|
if app.store.queue_list(session_id).unwrap_or_default().is_empty() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
if !app.is_busy(session_id) {
|
||||||
|
return flush_queue(app, session_id);
|
||||||
|
}
|
||||||
|
app.with_runtime(session_id, |r| {
|
||||||
|
if let Some(c) = &r.cancel {
|
||||||
|
r.force_queue = true;
|
||||||
|
c.cancel();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn abort(app: &App, session_id: &str) {
|
pub fn abort(app: &App, session_id: &str) {
|
||||||
app.with_runtime(session_id, |r| {
|
app.with_runtime(session_id, |r| {
|
||||||
if let Some(c) = &r.cancel {
|
if let Some(c) = &r.cancel {
|
||||||
@@ -293,6 +313,10 @@ pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationTo
|
|||||||
let roots = app.user_roots(session.owner_id.as_deref());
|
let roots = app.user_roots(session.owner_id.as_deref());
|
||||||
let root = app.root_for(session.owner_id.as_deref(), &cwd);
|
let root = app.root_for(session.owner_id.as_deref(), &cwd);
|
||||||
let mut agent = prompts::find_agent_for(&app, &root, &cwd, &session.agent, session.owner_id.as_deref());
|
let mut agent = prompts::find_agent_for(&app, &root, &cwd, &session.agent, session.owner_id.as_deref());
|
||||||
|
// Chats that plan (spec chat, issue chat) write no code: the mode's review of the work does not apply.
|
||||||
|
if crate::factory::is_planning_chat(&app, &session) {
|
||||||
|
agent.refine = None;
|
||||||
|
}
|
||||||
let clean_room = session.clean_room(app.config().craft.clean_room);
|
let clean_room = session.clean_room(app.config().craft.clean_room);
|
||||||
// The craft prompt follows the session's clean room / deep switch.
|
// The craft prompt follows the session's clean room / deep switch.
|
||||||
if agent.name == "craft" && agent.source == "builtin" {
|
if agent.name == "craft" && agent.source == "builtin" {
|
||||||
@@ -331,7 +355,7 @@ pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationTo
|
|||||||
let owner = session.owner_id.as_deref().and_then(|id| app.store.user(id).ok().flatten());
|
let owner = session.owner_id.as_deref().and_then(|id| app.store.user(id).ok().flatten());
|
||||||
let tools = available_tools(&app, &agent, owner.as_ref());
|
let tools = available_tools(&app, &agent, owner.as_ref());
|
||||||
let req = ChatRequest {
|
let req = ChatRequest {
|
||||||
system: prompts::with_chat_instructions(prompts::system_prompt(&app, &agent, &root, &cwd, &model_spec, &session.permission_mode, owner.as_ref()), &session.instructions),
|
system: prompts::with_active_skills(&app, prompts::with_chat_instructions(prompts::system_prompt(&app, &agent, &root, &cwd, &model_spec, &session.permission_mode, owner.as_ref()), &session.instructions), &session.skills, &root, &cwd, session.owner_id.as_deref()),
|
||||||
messages: history,
|
messages: history,
|
||||||
tools: tools.iter().map(|t| t.def()).collect(),
|
tools: tools.iter().map(|t| t.def()).collect(),
|
||||||
max_tokens,
|
max_tokens,
|
||||||
@@ -899,7 +923,7 @@ fn create_child(app: &Arc<App>, ctx: &ToolCtx, agent_name: &str, description: &s
|
|||||||
telegram_quiet: false,
|
telegram_quiet: false,
|
||||||
summary: String::new(),
|
summary: String::new(),
|
||||||
color: None,
|
color: None,
|
||||||
icon: None,
|
icon: None, skills: Vec::new(),
|
||||||
};
|
};
|
||||||
let child = app.save_session(child)?;
|
let child = app.save_session(child)?;
|
||||||
let msg = Message::new(Role::User, vec![Part::Text { text: prompt }]);
|
let msg = Message::new(Role::User, vec![Part::Text { text: prompt }]);
|
||||||
|
|||||||
@@ -0,0 +1,326 @@
|
|||||||
|
//! The user's own skills: a folder per skill with `SKILL.md` and further text files, kept in
|
||||||
|
//! `<data>/user-skills/<user id>/<name>/`; created in the UI or imported from a GitHub repository.
|
||||||
|
|
||||||
|
use crate::api::{ApiError, ApiResult, AppState};
|
||||||
|
use crate::prompts::{frontmatter, skill_files, user_skills_dir};
|
||||||
|
use crate::store::User;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::{Extension, Json};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
const MAX_FILES: usize = 100;
|
||||||
|
const MAX_FILE: usize = 200_000;
|
||||||
|
const MAX_TOTAL: usize = 2_000_000;
|
||||||
|
|
||||||
|
fn bad(m: impl Into<String>) -> ApiError {
|
||||||
|
ApiError(StatusCode::BAD_REQUEST, m.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A skill name is a folder name: lowercase letters, digits, `-` and `_`.
|
||||||
|
pub fn valid_name(n: &str) -> bool {
|
||||||
|
!n.is_empty() && n.len() <= 64 && n.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') && !n.starts_with(['-', '_'])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn any title into a valid skill name.
|
||||||
|
pub fn slug(s: &str) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
for c in s.to_lowercase().chars() {
|
||||||
|
if c.is_ascii_alphanumeric() {
|
||||||
|
out.push(c);
|
||||||
|
} else if !out.ends_with('-') && !out.is_empty() {
|
||||||
|
out.push('-');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.trim_matches('-').chars().take(64).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_rel(p: &str) -> bool {
|
||||||
|
let rel = std::path::Path::new(p);
|
||||||
|
!p.is_empty() && p.len() <= 200 && !rel.is_absolute() && rel.components().all(|c| matches!(c, std::path::Component::Normal(_)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dir_of(app: &AppState, user: &User, name: &str) -> Result<PathBuf, ApiError> {
|
||||||
|
if !valid_name(name) {
|
||||||
|
return Err(bad("invalid skill name (lowercase letters, digits, - and _)"));
|
||||||
|
}
|
||||||
|
Ok(user_skills_dir(app, &user.id).join(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone)]
|
||||||
|
pub struct FileBody {
|
||||||
|
path: String,
|
||||||
|
content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the files of a skill by `files` (must contain `SKILL.md`).
|
||||||
|
fn write_skill(dir: &std::path::Path, files: &[FileBody]) -> Result<(), ApiError> {
|
||||||
|
if !files.iter().any(|f| f.path == "SKILL.md" && !f.content.trim().is_empty()) {
|
||||||
|
return Err(bad("SKILL.md is required"));
|
||||||
|
}
|
||||||
|
if files.len() > MAX_FILES {
|
||||||
|
return Err(bad(format!("at most {MAX_FILES} files")));
|
||||||
|
}
|
||||||
|
let mut total = 0;
|
||||||
|
for f in files {
|
||||||
|
if !valid_rel(&f.path) {
|
||||||
|
return Err(bad(format!("invalid file path '{}'", f.path)));
|
||||||
|
}
|
||||||
|
if f.content.len() > MAX_FILE {
|
||||||
|
return Err(bad(format!("'{}' is too large (max {} KB)", f.path, MAX_FILE / 1000)));
|
||||||
|
}
|
||||||
|
total += f.content.len();
|
||||||
|
}
|
||||||
|
if total > MAX_TOTAL {
|
||||||
|
return Err(bad("the skill is too large (max 2 MB)"));
|
||||||
|
}
|
||||||
|
let tmp = dir.with_extension("saving");
|
||||||
|
let _ = std::fs::remove_dir_all(&tmp);
|
||||||
|
for f in files {
|
||||||
|
let p = tmp.join(&f.path);
|
||||||
|
if let Some(parent) = p.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
std::fs::write(&p, &f.content)?;
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir_all(dir);
|
||||||
|
std::fs::rename(&tmp, dir)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||||
|
let base = user_skills_dir(&app, &user.id);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for e in std::fs::read_dir(&base).into_iter().flatten().flatten() {
|
||||||
|
let Ok(text) = std::fs::read_to_string(e.path().join("SKILL.md")) else { continue };
|
||||||
|
let (meta, _) = frontmatter(&text);
|
||||||
|
out.push(json!({
|
||||||
|
"name": e.file_name().to_string_lossy(),
|
||||||
|
"description": meta.get("description").cloned().unwrap_or_default(),
|
||||||
|
"files": skill_files(&e.path()),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
out.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str()));
|
||||||
|
Ok(Json(json!({"skills": out})))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
|
||||||
|
let dir = dir_of(&app, &user, &name)?;
|
||||||
|
let main = std::fs::read_to_string(dir.join("SKILL.md")).map_err(|_| ApiError(StatusCode::NOT_FOUND, "skill not found".into()))?;
|
||||||
|
let mut files = vec![json!({"path": "SKILL.md", "content": main})];
|
||||||
|
for f in skill_files(&dir) {
|
||||||
|
let content = std::fs::read_to_string(dir.join(&f)).unwrap_or_default();
|
||||||
|
files.push(json!({"path": f, "content": content}));
|
||||||
|
}
|
||||||
|
Ok(Json(json!({"name": name, "files": files})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct PutBody {
|
||||||
|
files: Vec<FileBody>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn put(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>, Json(b): Json<PutBody>) -> ApiResult {
|
||||||
|
let dir = dir_of(&app, &user, &name)?;
|
||||||
|
std::fs::create_dir_all(user_skills_dir(&app, &user.id))?;
|
||||||
|
write_skill(&dir, &b.files)?;
|
||||||
|
app.audit(Some(&user), "skill.save", name, "");
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
|
||||||
|
let dir = dir_of(&app, &user, &name)?;
|
||||||
|
if !dir.join("SKILL.md").exists() {
|
||||||
|
return Err(ApiError(StatusCode::NOT_FOUND, "skill not found".into()));
|
||||||
|
}
|
||||||
|
std::fs::remove_dir_all(&dir)?;
|
||||||
|
app.audit(Some(&user), "skill.delete", name, "");
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- GitHub import -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
struct Source {
|
||||||
|
owner: String,
|
||||||
|
repo: String,
|
||||||
|
branch: Option<String>,
|
||||||
|
sub: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `https://github.com/<owner>/<repo>[/tree|blob/<branch>[/<path>]]`
|
||||||
|
fn parse_github(url: &str) -> Result<Source, ApiError> {
|
||||||
|
let rest = url.trim().strip_prefix("https://github.com/").ok_or_else(|| bad("only https://github.com/… URLs are supported"))?;
|
||||||
|
let rest = rest.split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
|
||||||
|
let mut it = rest.split('/');
|
||||||
|
let (Some(owner), Some(repo)) = (it.next().filter(|s| !s.is_empty()), it.next().map(|r| r.trim_end_matches(".git")).filter(|s| !s.is_empty())) else {
|
||||||
|
return Err(bad("not a repository URL"));
|
||||||
|
};
|
||||||
|
let (mut branch, mut sub) = (None, String::new());
|
||||||
|
if matches!(it.next(), Some("tree") | Some("blob")) {
|
||||||
|
branch = it.next().map(str::to_string);
|
||||||
|
sub = it.collect::<Vec<_>>().join("/");
|
||||||
|
if sub.ends_with("SKILL.md") {
|
||||||
|
sub = sub.trim_end_matches("SKILL.md").trim_end_matches('/').to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ok = |s: &str| s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
|
||||||
|
if !ok(owner) || !ok(repo) {
|
||||||
|
return Err(bad("not a repository URL"));
|
||||||
|
}
|
||||||
|
Ok(Source { owner: owner.into(), repo: repo.into(), branch, sub })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client() -> Result<reqwest::Client, ApiError> {
|
||||||
|
reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).user_agent("codecraft-skill-import").build().map_err(|e| bad(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blobs (path, size) of the repository below `src.sub`, and the resolved branch.
|
||||||
|
async fn tree(c: &reqwest::Client, src: &Source) -> Result<(String, Vec<(String, u64)>), ApiError> {
|
||||||
|
let branch = match &src.branch {
|
||||||
|
Some(b) => b.clone(),
|
||||||
|
None => {
|
||||||
|
let v: Value = c.get(format!("https://api.github.com/repos/{}/{}", src.owner, src.repo)).send().await.map_err(|e| bad(e.to_string()))?.json().await.map_err(|e| bad(e.to_string()))?;
|
||||||
|
v["default_branch"].as_str().ok_or_else(|| bad("repository not found (is it public?)"))?.to_string()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let r = c.get(format!("https://api.github.com/repos/{}/{}/git/trees/{branch}?recursive=1", src.owner, src.repo)).send().await.map_err(|e| bad(e.to_string()))?;
|
||||||
|
if !r.status().is_success() {
|
||||||
|
return Err(bad(format!("GitHub answered {} (repository or branch not found, or rate limit)", r.status())));
|
||||||
|
}
|
||||||
|
let v: Value = r.json().await.map_err(|e| bad(e.to_string()))?;
|
||||||
|
let prefix = if src.sub.is_empty() { String::new() } else { format!("{}/", src.sub) };
|
||||||
|
let blobs = v["tree"]
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|e| e["type"] == "blob")
|
||||||
|
.filter_map(|e| Some((e["path"].as_str()?.to_string(), e["size"].as_u64().unwrap_or(0))))
|
||||||
|
.filter(|(p, _)| prefix.is_empty() || p.starts_with(&prefix))
|
||||||
|
.collect();
|
||||||
|
Ok((branch, blobs))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Folders that contain a `SKILL.md` (path relative to the repository root; "" = the root itself).
|
||||||
|
fn skill_dirs(blobs: &[(String, u64)]) -> Vec<String> {
|
||||||
|
let mut v: Vec<String> = blobs
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(p, _)| if p == "SKILL.md" { Some(String::new()) } else { p.strip_suffix("/SKILL.md").map(str::to_string) })
|
||||||
|
.collect();
|
||||||
|
v.sort();
|
||||||
|
v.truncate(1000);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ScanBody {
|
||||||
|
url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List the skills found at a GitHub URL (nothing is imported).
|
||||||
|
pub async fn scan(Extension(_user): Extension<User>, Json(b): Json<ScanBody>) -> ApiResult {
|
||||||
|
let src = parse_github(&b.url)?;
|
||||||
|
let c = client()?;
|
||||||
|
let (branch, blobs) = tree(&c, &src).await?;
|
||||||
|
let dirs = skill_dirs(&blobs);
|
||||||
|
let list: Vec<Value> = dirs
|
||||||
|
.iter()
|
||||||
|
.map(|d| {
|
||||||
|
let name = d.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or(&src.repo);
|
||||||
|
let n = blobs.iter().filter(|(p, _)| d.is_empty() || p.starts_with(&format!("{d}/"))).count();
|
||||||
|
json!({"path": d, "name": slug(name), "files": n})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(Json(json!({"branch": branch, "skills": list})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ImportBody {
|
||||||
|
url: String,
|
||||||
|
/// Folders (as listed by `scan`).
|
||||||
|
paths: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const BINARY: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "ico", "pdf", "zip", "gz", "tar", "woff", "woff2", "ttf", "otf", "mp4", "mov", "mp3", "wav", "pyc", "so", "bin", "exe"];
|
||||||
|
|
||||||
|
/// Fetch the chosen skills of a GitHub repository and save them as the user's own skills.
|
||||||
|
pub async fn import(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<ImportBody>) -> ApiResult {
|
||||||
|
if b.paths.is_empty() || b.paths.len() > 100 {
|
||||||
|
return Err(bad("choose between 1 and 100 skills"));
|
||||||
|
}
|
||||||
|
let src = parse_github(&b.url)?;
|
||||||
|
let c = client()?;
|
||||||
|
let (branch, blobs) = tree(&c, &src).await?;
|
||||||
|
let known = skill_dirs(&blobs);
|
||||||
|
std::fs::create_dir_all(user_skills_dir(&app, &user.id))?;
|
||||||
|
let (mut saved, mut skipped) = (Vec::new(), Vec::new());
|
||||||
|
for d in &b.paths {
|
||||||
|
if !known.contains(d) {
|
||||||
|
skipped.push(json!({"path": d, "why": "no SKILL.md there"}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let name = slug(d.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or(&src.repo));
|
||||||
|
if !valid_name(&name) {
|
||||||
|
skipped.push(json!({"path": d, "why": "no usable name"}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let prefix = if d.is_empty() { String::new() } else { format!("{d}/") };
|
||||||
|
let mut files = Vec::new();
|
||||||
|
let mut dropped = 0;
|
||||||
|
for (p, size) in blobs.iter().filter(|(p, _)| p.starts_with(&prefix)) {
|
||||||
|
let rel = &p[prefix.len()..];
|
||||||
|
let ext = rel.rsplit('.').next().unwrap_or("").to_lowercase();
|
||||||
|
if rel.is_empty() || !valid_rel(rel) || *size as usize > MAX_FILE || BINARY.contains(&ext.as_str()) || files.len() >= MAX_FILES || rel.starts_with(".git") {
|
||||||
|
dropped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// A skill at the repository root: only Markdown files, not the whole repository.
|
||||||
|
if d.is_empty() && rel != "SKILL.md" && !rel.ends_with(".md") {
|
||||||
|
dropped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let url = format!("https://raw.githubusercontent.com/{}/{}/{branch}/{p}", src.owner, src.repo);
|
||||||
|
let Ok(r) = c.get(&url).send().await else { dropped += 1; continue };
|
||||||
|
if !r.status().is_success() {
|
||||||
|
dropped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match r.text().await {
|
||||||
|
Ok(content) => files.push(FileBody { path: rel.to_string(), content }),
|
||||||
|
Err(_) => dropped += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match write_skill(&user_skills_dir(&app, &user.id).join(&name), &files) {
|
||||||
|
Ok(()) => saved.push(json!({"name": name, "files": files.len(), "dropped": dropped})),
|
||||||
|
Err(e) => skipped.push(json!({"path": d, "why": e.1})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
app.audit(Some(&user), "skill.import", format!("{}/{}: {} skills", src.owner, src.repo, saved.len()), "");
|
||||||
|
Ok(Json(json!({"saved": saved, "skipped": skipped})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn names_and_urls() {
|
||||||
|
assert!(valid_name("frontend-design"));
|
||||||
|
assert!(!valid_name("../x") && !valid_name("Front") && !valid_name(""));
|
||||||
|
assert_eq!(slug("Frontend Design!"), "frontend-design");
|
||||||
|
let s = parse_github("https://github.com/o/r/blob/main/.claude/skills/frontend/SKILL.md").ok().unwrap();
|
||||||
|
assert_eq!((s.owner.as_str(), s.repo.as_str(), s.branch.as_deref(), s.sub.as_str()), ("o", "r", Some("main"), ".claude/skills/frontend"));
|
||||||
|
let s = parse_github("https://github.com/o/r.git").ok().unwrap();
|
||||||
|
assert!(s.branch.is_none() && s.sub.is_empty());
|
||||||
|
assert!(parse_github("https://example.org/o/r").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finds_skill_folders() {
|
||||||
|
let b = |p: &str| (p.to_string(), 10u64);
|
||||||
|
let dirs = skill_dirs(&[b("a/SKILL.md"), b("a/ref.md"), b("x/y/SKILL.md"), b("README.md")]);
|
||||||
|
assert_eq!(dirs, vec!["a".to_string(), "x/y".to_string()]);
|
||||||
|
assert!(valid_rel("ref/a.md") && !valid_rel("../a") && !valid_rel("/etc/passwd"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,7 @@ impl Store {
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS usage_ts ON usage(ts);
|
CREATE INDEX IF NOT EXISTS usage_ts ON usage(ts);
|
||||||
CREATE INDEX IF NOT EXISTS usage_root ON usage(root_session_id);
|
CREATE INDEX IF NOT EXISTS usage_root ON usage(root_session_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS usage_session ON usage(session_id);
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||||
@@ -125,6 +126,13 @@ impl Store {
|
|||||||
last_status TEXT,
|
last_status TEXT,
|
||||||
created_at INTEGER NOT NULL
|
created_at INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_drafts (
|
||||||
|
session_id TEXT NOT NULL,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (session_id, user_id)
|
||||||
|
);
|
||||||
CREATE TABLE IF NOT EXISTS user_settings (
|
CREATE TABLE IF NOT EXISTS user_settings (
|
||||||
user_id TEXT NOT NULL,
|
user_id TEXT NOT NULL,
|
||||||
key TEXT NOT NULL,
|
key TEXT NOT NULL,
|
||||||
@@ -204,6 +212,22 @@ impl Store {
|
|||||||
result TEXT NOT NULL DEFAULT ''
|
result TEXT NOT NULL DEFAULT ''
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS factory_runs_issue ON factory_runs(repo_url, issue);
|
CREATE INDEX IF NOT EXISTS factory_runs_issue ON factory_runs(repo_url, issue);
|
||||||
|
CREATE TABLE IF NOT EXISTS factory_versions (
|
||||||
|
repo_url TEXT PRIMARY KEY,
|
||||||
|
current TEXT NOT NULL DEFAULT '0.0.0',
|
||||||
|
since INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS factory_releases (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
owner_id TEXT NOT NULL,
|
||||||
|
repo_url TEXT NOT NULL,
|
||||||
|
version TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL DEFAULT 'running',
|
||||||
|
log TEXT NOT NULL DEFAULT '',
|
||||||
|
url TEXT NOT NULL DEFAULT '',
|
||||||
|
started_at INTEGER NOT NULL,
|
||||||
|
ended_at INTEGER
|
||||||
|
);
|
||||||
CREATE TABLE IF NOT EXISTS project_defaults (
|
CREATE TABLE IF NOT EXISTS project_defaults (
|
||||||
cwd TEXT PRIMARY KEY,
|
cwd TEXT PRIMARY KEY,
|
||||||
data TEXT NOT NULL
|
data TEXT NOT NULL
|
||||||
@@ -238,6 +262,8 @@ impl Store {
|
|||||||
("jobs", "settings", "ALTER TABLE jobs ADD COLUMN settings TEXT"),
|
("jobs", "settings", "ALTER TABLE jobs ADD COLUMN settings TEXT"),
|
||||||
("images", "blob", "ALTER TABLE images ADD COLUMN blob TEXT"),
|
("images", "blob", "ALTER TABLE images ADD COLUMN blob TEXT"),
|
||||||
("usage", "allowance", "ALTER TABLE usage ADD COLUMN allowance REAL"),
|
("usage", "allowance", "ALTER TABLE usage ADD COLUMN allowance REAL"),
|
||||||
|
("factory_issues", "version", "ALTER TABLE factory_issues ADD COLUMN version TEXT NOT NULL DEFAULT ''"),
|
||||||
|
("factory_issues", "merged", "ALTER TABLE factory_issues ADD COLUMN merged INTEGER NOT NULL DEFAULT 0"),
|
||||||
] {
|
] {
|
||||||
let exists: bool = conn
|
let exists: bool = conn
|
||||||
.prepare(&format!("SELECT 1 FROM pragma_table_info('{table}') WHERE name = ?1"))?
|
.prepare(&format!("SELECT 1 FROM pragma_table_info('{table}') WHERE name = ?1"))?
|
||||||
@@ -1465,8 +1491,8 @@ impl Store {
|
|||||||
pub fn factory_issue(&self, repo: &str, number: i64) -> Result<Option<Value>> {
|
pub fn factory_issue(&self, repo: &str, number: i64) -> Result<Option<Value>> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
Ok(conn
|
Ok(conn
|
||||||
.query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number], |r| {
|
.query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id, version, merged FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number], |r| {
|
||||||
Ok(json!({"repo": repo, "number": number, "title": r.get::<_, String>(0)?, "author": r.get::<_, String>(1)?, "state": r.get::<_, String>(2)?, "attempts": r.get::<_, i64>(3)?, "rounds": r.get::<_, i64>(4)?, "last_comment": r.get::<_, i64>(5)?, "scenarios": r.get::<_, String>(6)?, "branch": r.get::<_, String>(7)?, "pr_url": r.get::<_, String>(8)?, "note": r.get::<_, String>(9)?, "created_at": r.get::<_, i64>(10)?, "updated_at": r.get::<_, i64>(11)?, "owner_id": r.get::<_, String>(12)?}))
|
Ok(json!({"repo": repo, "number": number, "title": r.get::<_, String>(0)?, "author": r.get::<_, String>(1)?, "state": r.get::<_, String>(2)?, "attempts": r.get::<_, i64>(3)?, "rounds": r.get::<_, i64>(4)?, "last_comment": r.get::<_, i64>(5)?, "scenarios": r.get::<_, String>(6)?, "branch": r.get::<_, String>(7)?, "pr_url": r.get::<_, String>(8)?, "note": r.get::<_, String>(9)?, "created_at": r.get::<_, i64>(10)?, "updated_at": r.get::<_, i64>(11)?, "owner_id": r.get::<_, String>(12)?, "version": r.get::<_, String>(13)?, "merged": r.get::<_, i64>(14)? != 0}))
|
||||||
})
|
})
|
||||||
.optional()?)
|
.optional()?)
|
||||||
}
|
}
|
||||||
@@ -1480,9 +1506,15 @@ impl Store {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Remove an issue from the factory board (runs and cost statistics stay).
|
||||||
|
pub fn factory_issue_delete(&self, repo: &str, number: i64) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute("DELETE FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Update the given columns (whitelisted) of an issue.
|
/// Update the given columns (whitelisted) of an issue.
|
||||||
pub fn factory_issue_set(&self, repo: &str, number: i64, fields: &[(&str, Value)]) -> Result<()> {
|
pub fn factory_issue_set(&self, repo: &str, number: i64, fields: &[(&str, Value)]) -> Result<()> {
|
||||||
const COLS: [&str; 10] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author"];
|
const COLS: [&str; 12] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author", "version", "merged"];
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
for (k, v) in fields {
|
for (k, v) in fields {
|
||||||
if !COLS.contains(k) {
|
if !COLS.contains(k) {
|
||||||
@@ -1498,13 +1530,90 @@ impl Store {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Version of a repository, None while versioning has not been started for it.
|
||||||
|
pub fn factory_version(&self, repo: &str) -> Result<Option<String>> {
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT current FROM factory_versions WHERE repo_url = ?1", [repo], |r| r.get(0)).optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn factory_version_set(&self, repo: &str, current: &str) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute(
|
||||||
|
"INSERT INTO factory_versions (repo_url, current, since) VALUES (?1, ?2, ?3) ON CONFLICT(repo_url) DO UPDATE SET current = ?2",
|
||||||
|
params![repo, current, crate::types::now_ms()],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn factory_release_add(&self, id: &str, owner: &str, repo: &str, version: &str) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute(
|
||||||
|
"INSERT INTO factory_releases (id, owner_id, repo_url, version, started_at) VALUES (?1,?2,?3,?4,?5)",
|
||||||
|
params![id, owner, repo, version, crate::types::now_ms()],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append a line to the log of a release (the log is capped).
|
||||||
|
pub fn factory_release_log(&self, id: &str, line: &str) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute(
|
||||||
|
"UPDATE factory_releases SET log = substr(log || ?2 || char(10), -30000) WHERE id = ?1",
|
||||||
|
params![id, line],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn factory_release_end(&self, id: &str, state: &str, url: &str) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute("UPDATE factory_releases SET state = ?2, url = ?3, ended_at = ?4 WHERE id = ?1", params![id, state, url, crate::types::now_ms()])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn factory_release_running(&self, repo: &str) -> Result<bool> {
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_releases WHERE repo_url = ?1 AND state = 'running'", [repo], |r| r.get::<_, i64>(0))? > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn factory_releases(&self, owner: &str, limit: i64) -> Result<Vec<Value>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let mut st = conn.prepare("SELECT id, repo_url, version, state, log, url, started_at, ended_at FROM factory_releases WHERE owner_id = ?1 ORDER BY started_at DESC LIMIT ?2")?;
|
||||||
|
let rows = st.query_map(params![owner, limit], |r| {
|
||||||
|
Ok(json!({"id": r.get::<_, String>(0)?, "repo": r.get::<_, String>(1)?, "version": r.get::<_, String>(2)?, "state": r.get::<_, String>(3)?, "log": r.get::<_, String>(4)?, "url": r.get::<_, String>(5)?, "started_at": r.get::<_, i64>(6)?, "ended_at": r.get::<_, Option<i64>>(7)?}))
|
||||||
|
})?;
|
||||||
|
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unsent message of a chat, kept on the server so that it can be continued on another device.
|
||||||
|
pub fn chat_draft(&self, session: &str, user: &str) -> Result<Option<(String, i64)>> {
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT text, updated_at FROM chat_drafts WHERE session_id = ?1 AND user_id = ?2", params![session, user], |r| Ok((r.get(0)?, r.get(1)?))).optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store the unsent message (an empty text deletes it).
|
||||||
|
pub fn chat_draft_set(&self, session: &str, user: &str, text: &str) -> Result<i64> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let now = crate::types::now_ms();
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
conn.execute("DELETE FROM chat_drafts WHERE session_id = ?1 AND user_id = ?2", params![session, user])?;
|
||||||
|
} else {
|
||||||
|
conn.execute("INSERT INTO chat_drafts (session_id, user_id, text, updated_at) VALUES (?1,?2,?3,?4) ON CONFLICT(session_id, user_id) DO UPDATE SET text = ?3, updated_at = ?4", params![session, user, text, now])?;
|
||||||
|
}
|
||||||
|
Ok(now)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn factory_issues(&self, owner: &str) -> Result<Vec<Value>> {
|
pub fn factory_issues(&self, owner: &str) -> Result<Vec<Value>> {
|
||||||
let nums: Vec<(String, i64)> = {
|
let nums: Vec<(String, i64)> = {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
let mut st = conn.prepare("SELECT repo_url, number FROM factory_issues WHERE owner_id = ?1 ORDER BY updated_at DESC")?;
|
let mut st = conn.prepare("SELECT repo_url, number FROM factory_issues WHERE owner_id = ?1 ORDER BY updated_at DESC")?;
|
||||||
st.query_map([owner], |r| Ok((r.get(0)?, r.get(1)?)))?.filter_map(|r| r.ok()).collect()
|
st.query_map([owner], |r| Ok((r.get(0)?, r.get(1)?)))?.filter_map(|r| r.ok()).collect()
|
||||||
};
|
};
|
||||||
Ok(nums.into_iter().filter_map(|(r, n)| self.factory_issue(&r, n).ok().flatten()).collect())
|
let mut rows: Vec<Value> = nums.into_iter().filter_map(|(r, n)| self.factory_issue(&r, n).ok().flatten()).collect();
|
||||||
|
// The newest phase chat that still exists, for the "open chat" button of the card.
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
if let Ok(mut chat) = conn.prepare("SELECT r.session_id, r.phase FROM factory_runs r WHERE r.repo_url = ?1 AND r.issue = ?2 AND EXISTS (SELECT 1 FROM sessions s WHERE s.id = r.session_id) ORDER BY r.started_at DESC LIMIT 1") {
|
||||||
|
for row in rows.iter_mut() {
|
||||||
|
let (repo, n) = (row["repo"].as_str().unwrap_or("").to_string(), row["number"].as_i64().unwrap_or(0));
|
||||||
|
if let Ok((sid, phase)) = chat.query_row(params![repo, n], |x| Ok((x.get::<_, String>(0)?, x.get::<_, String>(1)?))) {
|
||||||
|
row["chat_session"] = json!(sid);
|
||||||
|
row["chat_phase"] = json!(phase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn factory_run_add(&self, id: &str, owner: &str, repo: &str, issue: i64, phase: &str, round: i64, session: &str, model: &str) -> Result<()> {
|
pub fn factory_run_add(&self, id: &str, owner: &str, repo: &str, issue: i64, phase: &str, round: i64, session: &str, model: &str) -> Result<()> {
|
||||||
@@ -1521,7 +1630,14 @@ impl Store {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn factory_running(&self, repo: &str) -> Result<i64> {
|
pub fn factory_running(&self, repo: &str) -> Result<i64> {
|
||||||
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_runs WHERE repo_url = ?1 AND status = 'running'", [repo], |r| r.get(0))?)
|
// Counted by issue state, not by run rows: the state is set before the phase is spawned, the run row
|
||||||
|
// only once its checkout is done – counting runs let a single poll start more phases than allowed.
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_issues WHERE repo_url = ?1 AND state IN ('review', 'building', 'testing')", [repo], |r| r.get(0))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Phases of this user that are running right now (any repository).
|
||||||
|
pub fn factory_active(&self, owner: &str) -> Result<i64> {
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_issues WHERE owner_id = ?1 AND state IN ('review', 'building', 'testing')", [owner], |r| r.get(0))?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs with token and cost totals (joined from the usage table).
|
/// Runs with token and cost totals (joined from the usage table).
|
||||||
@@ -1546,8 +1662,14 @@ impl Store {
|
|||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
let n = conn.execute("UPDATE factory_runs SET status = 'interrupted', ended_at = ?1 WHERE status = 'running'", [crate::types::now_ms()])?;
|
let n = conn.execute("UPDATE factory_runs SET status = 'interrupted', ended_at = ?1 WHERE status = 'running'", [crate::types::now_ms()])?;
|
||||||
conn.execute("UPDATE factory_issues SET state = 'new' WHERE state = 'review'", [])?;
|
conn.execute("UPDATE factory_issues SET state = 'new' WHERE state = 'review'", [])?;
|
||||||
conn.execute("UPDATE factory_issues SET state = 'approved' WHERE state = 'building'", [])?;
|
conn.execute("UPDATE factory_issues SET state = CASE WHEN rounds > 0 THEN 'rework' ELSE 'approved' END WHERE state = 'building'", [])?;
|
||||||
conn.execute("UPDATE factory_issues SET state = 'built' WHERE state = 'qa'", [])?;
|
conn.execute("UPDATE factory_issues SET state = 'qa' WHERE state = 'testing'", [])?;
|
||||||
|
conn.execute("UPDATE factory_releases SET state = 'failed', ended_at = ?1, log = log || char(10) || 'interrupted by a restart' WHERE state = 'running'", [crate::types::now_ms()])?;
|
||||||
|
// All factory chats live in one sidebar folder (older ones are moved there once).
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE sessions SET data = json_set(data, '$.folder', 'Factory') WHERE (json_extract(data, '$.folder') IS NULL OR json_extract(data, '$.folder') = '') AND (id IN (SELECT session_id FROM factory_runs) OR json_extract(data, '$.cwd') LIKE '%/_drafts/%')",
|
||||||
|
[],
|
||||||
|
)?;
|
||||||
Ok(n)
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1943,3 +2065,28 @@ mod link_tests {
|
|||||||
std::fs::remove_dir_all(&dir).unwrap();
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod draft_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drafts_are_kept_per_chat_and_user_and_cleared_when_empty() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("cc-drafts-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let store = Store::open(&dir.join("t.db")).unwrap();
|
||||||
|
assert!(store.chat_draft("s1", "u1").unwrap().is_none());
|
||||||
|
store.chat_draft_set("s1", "u1", "half a message").unwrap();
|
||||||
|
store.chat_draft_set("s1", "u2", "someone else").unwrap();
|
||||||
|
store.chat_draft_set("s2", "u1", "other chat").unwrap();
|
||||||
|
assert_eq!(store.chat_draft("s1", "u1").unwrap().unwrap().0, "half a message");
|
||||||
|
store.chat_draft_set("s1", "u1", "continued on another device").unwrap();
|
||||||
|
assert_eq!(store.chat_draft("s1", "u1").unwrap().unwrap().0, "continued on another device");
|
||||||
|
assert_eq!(store.chat_draft("s1", "u2").unwrap().unwrap().0, "someone else");
|
||||||
|
// Sending clears it.
|
||||||
|
store.chat_draft_set("s1", "u1", " \n").unwrap();
|
||||||
|
assert!(store.chat_draft("s1", "u1").unwrap().is_none());
|
||||||
|
assert_eq!(store.chat_draft("s2", "u1").unwrap().unwrap().0, "other chat");
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,48 @@ pub struct Settings {
|
|||||||
/// Reasoning effort for the next messages (/effort).
|
/// Reasoning effort for the next messages (/effort).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub effort: Option<String>,
|
pub effort: Option<String>,
|
||||||
|
/// No factory alerts (question / failed) on Telegram. Inverted so that the default is "on".
|
||||||
|
#[serde(default)]
|
||||||
|
pub factory_alerts_off: bool,
|
||||||
|
/// Night mode: no unsolicited messages between `quiet_from` and `quiet_to` (server time).
|
||||||
|
#[serde(default)]
|
||||||
|
pub quiet: bool,
|
||||||
|
/// "HH:MM"; empty = 22:00.
|
||||||
|
#[serde(default)]
|
||||||
|
pub quiet_from: String,
|
||||||
|
/// "HH:MM"; empty = 06:00.
|
||||||
|
#[serde(default)]
|
||||||
|
pub quiet_to: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Minutes since midnight of an "HH:MM" string.
|
||||||
|
pub fn parse_hhmm(s: &str) -> Option<u32> {
|
||||||
|
let (h, m) = s.trim().split_once(':')?;
|
||||||
|
let (h, m): (u32, u32) = (h.parse().ok()?, m.parse().ok()?);
|
||||||
|
(h < 24 && m < 60).then_some(h * 60 + m)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Is `now` (minutes since midnight) inside the quiet window? The window may span midnight.
|
||||||
|
pub fn in_quiet_window(from: u32, to: u32, now: u32) -> bool {
|
||||||
|
match from.cmp(&to) {
|
||||||
|
std::cmp::Ordering::Equal => false,
|
||||||
|
std::cmp::Ordering::Less => now >= from && now < to,
|
||||||
|
std::cmp::Ordering::Greater => now >= from || now < to,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Settings {
|
||||||
|
/// Night mode is on and it is night now.
|
||||||
|
pub fn quiet_now(&self) -> bool {
|
||||||
|
use chrono::Timelike;
|
||||||
|
if !self.quiet {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let from = parse_hhmm(if self.quiet_from.is_empty() { "22:00" } else { &self.quiet_from }).unwrap_or(22 * 60);
|
||||||
|
let to = parse_hhmm(if self.quiet_to.is_empty() { "06:00" } else { &self.quiet_to }).unwrap_or(6 * 60);
|
||||||
|
let t = chrono::Local::now();
|
||||||
|
in_quiet_window(from, to, t.hour() * 60 + t.minute())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn api_base() -> String {
|
fn api_base() -> String {
|
||||||
@@ -88,7 +130,7 @@ impl Bot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn call(&self, method: &str, body: Value) -> Result<Value> {
|
async fn call(&self, method: &str, body: Value) -> Result<Value> {
|
||||||
let resp = crate::provider::http_client().post(self.url(method)).timeout(Duration::from_secs(60)).json(&body).send().await.context("telegram request failed")?;
|
let resp = crate::provider::http_client().post(self.url(method)).timeout(Duration::from_secs(60)).json(&body).send().await.map_err(|e| e.without_url()).context("telegram request failed")?;
|
||||||
let status = resp.status();
|
let status = resp.status();
|
||||||
let v: Value = resp.json().await.unwrap_or_else(|_| json!({}));
|
let v: Value = resp.json().await.unwrap_or_else(|_| json!({}));
|
||||||
if v["ok"].as_bool() != Some(true) {
|
if v["ok"].as_bool() != Some(true) {
|
||||||
@@ -132,7 +174,7 @@ impl Bot {
|
|||||||
if let Some(c) = caption {
|
if let Some(c) = caption {
|
||||||
form = form.text("caption", c.chars().take(1000).collect::<String>());
|
form = form.text("caption", c.chars().take(1000).collect::<String>());
|
||||||
}
|
}
|
||||||
let v: Value = crate::provider::http_client().post(self.url("sendPhoto")).timeout(Duration::from_secs(120)).multipart(form).send().await?.json().await?;
|
let v: Value = crate::provider::http_client().post(self.url("sendPhoto")).timeout(Duration::from_secs(120)).multipart(form).send().await.map_err(|e| e.without_url())?.json().await.map_err(|e| e.without_url())?;
|
||||||
if v["ok"].as_bool() != Some(true) {
|
if v["ok"].as_bool() != Some(true) {
|
||||||
bail!("telegram sendPhoto: {}", v["description"].as_str().unwrap_or("error"));
|
bail!("telegram sendPhoto: {}", v["description"].as_str().unwrap_or("error"));
|
||||||
}
|
}
|
||||||
@@ -144,7 +186,7 @@ impl Bot {
|
|||||||
let f = self.call("getFile", json!({"file_id": file_id})).await?;
|
let f = self.call("getFile", json!({"file_id": file_id})).await?;
|
||||||
let path = f["file_path"].as_str().context("telegram file without path")?.to_string();
|
let path = f["file_path"].as_str().context("telegram file without path")?.to_string();
|
||||||
let url = format!("{}/file/bot{}/{path}", api_base(), self.token);
|
let url = format!("{}/file/bot{}/{path}", api_base(), self.token);
|
||||||
let bytes = crate::provider::http_client().get(url).timeout(Duration::from_secs(120)).send().await?.error_for_status()?.bytes().await?;
|
let bytes = crate::provider::http_client().get(url).timeout(Duration::from_secs(120)).send().await.map_err(|e| e.without_url())?.error_for_status().map_err(|e| e.without_url())?.bytes().await.map_err(|e| e.without_url())?;
|
||||||
Ok((bytes.to_vec(), path))
|
Ok((bytes.to_vec(), path))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -260,6 +302,18 @@ fn user(app: &App, user_id: &str) -> Result<User> {
|
|||||||
app.store.user(user_id)?.filter(|u| !u.disabled).ok_or_else(|| anyhow!("account disabled"))
|
app.store.user(user_id)?.filter(|u| !u.disabled).ok_or_else(|| anyhow!("account disabled"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Send a message (HTML-escaped) to the user's paired Telegram chat; silent when there is none.
|
||||||
|
pub async fn notify_user(app: &App, user_id: &str, text: &str) {
|
||||||
|
let s = load(app, user_id);
|
||||||
|
let (true, Some(chat)) = (!s.token.is_empty(), s.chat_id) else { return };
|
||||||
|
if s.factory_alerts_off || s.quiet_now() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Err(e) = (Bot { token: s.token }).send(chat, &esc(text), None).await {
|
||||||
|
tracing::warn!("telegram: notification not sent: {e:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The user reads German (language preference of the web UI).
|
/// The user reads German (language preference of the web UI).
|
||||||
pub fn german(app: &App, user_id: &str) -> bool {
|
pub fn german(app: &App, user_id: &str) -> bool {
|
||||||
let prefs: Value = app.store.user_setting(user_id, "prefs").unwrap_or_default();
|
let prefs: Value = app.store.user_setting(user_id, "prefs").unwrap_or_default();
|
||||||
@@ -543,7 +597,7 @@ async fn new_session(app: &Arc<App>, u: &User, bot: &Bot, chat: i64, arg: &str,
|
|||||||
telegram_quiet: false,
|
telegram_quiet: false,
|
||||||
summary: String::new(),
|
summary: String::new(),
|
||||||
color: None,
|
color: None,
|
||||||
icon: None,
|
icon: None, skills: Vec::new(),
|
||||||
})?;
|
})?;
|
||||||
update(app, &u.id, |st| st.session = Some(s.id.clone()));
|
update(app, &u.id, |st| st.session = Some(s.id.clone()));
|
||||||
bot.send(chat, &format!("{} <b>{}</b> · {} · {}", tr(de, "Neue Sitzung", "New session"), esc(&s.cwd), esc(&s.agent), esc(&s.model)), None).await?;
|
bot.send(chat, &format!("{} <b>{}</b> · {} · {}", tr(de, "Neue Sitzung", "New session"), esc(&s.cwd), esc(&s.agent), esc(&s.model)), None).await?;
|
||||||
@@ -875,6 +929,10 @@ async fn listen(app: Arc<App>) {
|
|||||||
let Some(chat) = st.chat_id else { continue };
|
let Some(chat) = st.chat_id else { continue };
|
||||||
let de = german(&app, &owner);
|
let de = german(&app, &owner);
|
||||||
let is_current = st.session.as_deref() == Some(session_id.as_str());
|
let is_current = st.session.as_deref() == Some(session_id.as_str());
|
||||||
|
// Night mode: only the chat the user is talking to in Telegram still reports.
|
||||||
|
if !is_current && st.quiet_now() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// Chats with "not to Telegram": their approvals and questions stay in the web UI
|
// Chats with "not to Telegram": their approvals and questions stay in the web UI
|
||||||
// (subagents follow their top-level chat; the chat open in Telegram always reports).
|
// (subagents follow their top-level chat; the chat open in Telegram always reports).
|
||||||
if !is_current && matches!(ev, Event::PermissionRequest { .. } | Event::QuestionRequest { .. }) {
|
if !is_current && matches!(ev, Event::PermissionRequest { .. } | Event::QuestionRequest { .. }) {
|
||||||
@@ -1204,3 +1262,30 @@ mod tests {
|
|||||||
assert_eq!(step_line("todo_write", &json!({})), "todo_write");
|
assert_eq!(step_line("todo_write", &json!({})), "todo_write");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod quiet_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quiet_window_spans_midnight() {
|
||||||
|
let (from, to) = (parse_hhmm("22:00").unwrap(), parse_hhmm("06:00").unwrap());
|
||||||
|
assert!(in_quiet_window(from, to, 23 * 60));
|
||||||
|
assert!(in_quiet_window(from, to, 0));
|
||||||
|
assert!(in_quiet_window(from, to, 5 * 60 + 59));
|
||||||
|
assert!(!in_quiet_window(from, to, 6 * 60));
|
||||||
|
assert!(!in_quiet_window(from, to, 12 * 60));
|
||||||
|
assert!(!in_quiet_window(from, to, 21 * 60 + 59));
|
||||||
|
assert!(in_quiet_window(from, to, 22 * 60));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quiet_window_within_a_day_and_degenerate() {
|
||||||
|
assert!(in_quiet_window(13 * 60, 14 * 60, 13 * 60 + 30));
|
||||||
|
assert!(!in_quiet_window(13 * 60, 14 * 60, 15 * 60));
|
||||||
|
assert!(!in_quiet_window(600, 600, 600));
|
||||||
|
assert_eq!(parse_hhmm("7:05"), Some(425));
|
||||||
|
assert_eq!(parse_hhmm("24:00"), None);
|
||||||
|
assert_eq!(parse_hhmm("x"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,794 @@
|
|||||||
|
//! Throw-away test environments for the factory's acceptance runs.
|
||||||
|
//!
|
||||||
|
//! Two halves live here:
|
||||||
|
//!
|
||||||
|
//! * the **service** (`codecraft testrunner`): a small HTTP server that owns the
|
||||||
|
//! Docker socket. For every acceptance run it creates a private network, starts
|
||||||
|
//! the application (and optional helper services such as a database) in fresh
|
||||||
|
//! containers, forwards one port, and removes everything again afterwards.
|
||||||
|
//! It only ever runs a fixed, locked-down `docker` command line: no host mounts,
|
||||||
|
//! no privileged mode, capabilities dropped, memory/CPU/process limits.
|
||||||
|
//! * the **client** used by the factory in the main server: start an environment,
|
||||||
|
//! read its log, stop it, and forward a local port to it so that the agent can
|
||||||
|
//! use `http://localhost:PORT` as usual.
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use axum::extract::{Path as AxPath, Query, State};
|
||||||
|
use axum::http::{HeaderMap, StatusCode};
|
||||||
|
use axum::routing::{delete, get, post};
|
||||||
|
use axum::{Json, Router};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Stdio;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tokio::io::AsyncWriteExt;
|
||||||
|
use tokio::net::{TcpListener, TcpStream};
|
||||||
|
use tokio::process::Command;
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
|
const LABEL: &str = "codecraft.testrunner=1";
|
||||||
|
const CACHE_LABEL: &str = "codecraft.testrunner.cache=1";
|
||||||
|
|
||||||
|
/// What every environment container runs: link the shared directories, restore a matching seed, run
|
||||||
|
/// `install`, store a new seed (only after a successful install, so it is pristine), start the app.
|
||||||
|
const FALLBACK_IMAGE: &str = "node:24-bookworm";
|
||||||
|
|
||||||
|
const ENTRY_SCRIPT: &str = r#"cd /app
|
||||||
|
hit=0
|
||||||
|
if [ -d /cache ]; then
|
||||||
|
for d in $CC_CACHE_DIRS; do mkdir -p "/cache/dirs/$d" "$(dirname "$d")" && rm -rf "$d" && ln -s "/cache/dirs/$d" "$d"; done
|
||||||
|
if [ -d /usr/local/cargo ]; then for d in registry git; do mkdir -p "/cache/cargo/$d"; rm -rf "/usr/local/cargo/$d"; ln -s "/cache/cargo/$d" "/usr/local/cargo/$d"; done; fi
|
||||||
|
if [ -n "$CC_SEED_KEY" ]; then for p in $CC_SEED_PATHS; do if [ -e "/cache/seed/$CC_SEED_KEY/$p" ]; then mkdir -p "$(dirname "$p")" && cp -a "/cache/seed/$CC_SEED_KEY/$p" "$p" && hit=1 && echo "[runner] restored $p from the cache"; fi; done; fi
|
||||||
|
fi
|
||||||
|
if [ -n "$CC_SEED_KEY" ]; then if [ "$hit" = 1 ]; then echo "[runner] seed $CC_SEED_KEY: hit"; else echo "[runner] seed $CC_SEED_KEY: miss"; fi; fi
|
||||||
|
t0=$(date +%s); st=$(date -u '+%Y-%m-%d %H:%M:%S')
|
||||||
|
if [ -n "$CC_INSTALL" ]; then sh -c "$CC_INSTALL" || exit 1; fi
|
||||||
|
echo "[runner] install took $(( $(date +%s) - t0 )) s"
|
||||||
|
pk=$(awk -v s="$st" '$3=="install" && ($1" "$2)>=s {sub(/:.*/,"",$4); print $4}' /var/log/dpkg.log 2>/dev/null | sort -u | head -40 | tr '\n' ' ')
|
||||||
|
if [ -n "$pk" ]; then echo "[runner] apt installed: $pk"; fi
|
||||||
|
if [ -d /cache ] && [ -n "$CC_SEED_KEY" ] && [ ! -d "/cache/seed/$CC_SEED_KEY" ]; then
|
||||||
|
t="/cache/seed/.tmp-$$"; rm -rf "$t"; mkdir -p "$t"; ok=1
|
||||||
|
for p in $CC_SEED_PATHS; do if [ -e "$p" ]; then mkdir -p "$t/$(dirname "$p")" && cp -a "$p" "$t/$p" || ok=0; fi; done
|
||||||
|
if [ "$ok" = 1 ]; then mv "$t" "/cache/seed/$CC_SEED_KEY" && echo "[runner] stored the seed $CC_SEED_KEY"; else rm -rf "$t"; fi
|
||||||
|
ls -1t /cache/seed 2>/dev/null | grep -v '^\.tmp' | tail -n +4 | while read -r o; do rm -rf "/cache/seed/$o"; done
|
||||||
|
fi
|
||||||
|
exec sh -c "$CC_START""#;
|
||||||
|
|
||||||
|
// --- what a repository asks for (.factory/setup.json) ------------------------------------
|
||||||
|
|
||||||
|
/// A helper container next to the application, reachable under its name (e.g. `db`).
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||||
|
pub struct Service {
|
||||||
|
pub image: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub env: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What stays between runs of one project (kept in a Docker volume of the runner).
|
||||||
|
///
|
||||||
|
/// * `dirs`: directories of the sources that persist and are shared by all runs (downloads, caches –
|
||||||
|
/// inputs only: whatever lands there is visible to the next run).
|
||||||
|
/// * `seed`: expensive *results* of `install` (e.g. a built disk image). They are stored after a successful
|
||||||
|
/// `install` under a key made from the image, the install command, the seed paths and the contents of the
|
||||||
|
/// `key` files/directories, and copied into fresh containers whenever that key matches – so a run never
|
||||||
|
/// sees changes of an earlier run, and a change of the listed sources builds the seed anew.
|
||||||
|
///
|
||||||
|
/// Tool caches (npm, yarn, pip, Go, Cargo registry and target directory) are always shared per project
|
||||||
|
/// unless `"cache": false`.
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||||
|
pub struct CacheCfg {
|
||||||
|
#[serde(default)]
|
||||||
|
pub disabled: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub dirs: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub seed_paths: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub seed_key: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request to start an environment.
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||||
|
pub struct StartReq {
|
||||||
|
/// Checked-out source (below the factory area); copied into the container, never mounted.
|
||||||
|
pub work: String,
|
||||||
|
/// Image to run in (default: the runner's default image). Ignored when `dockerfile` is set.
|
||||||
|
#[serde(default)]
|
||||||
|
pub image: String,
|
||||||
|
/// Dockerfile inside the source to build the image from.
|
||||||
|
#[serde(default)]
|
||||||
|
pub dockerfile: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub install: String,
|
||||||
|
pub start: String,
|
||||||
|
pub port: u16,
|
||||||
|
#[serde(default)]
|
||||||
|
pub env: BTreeMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub services: BTreeMap<String, Service>,
|
||||||
|
/// How long to wait until the port answers (seconds, default 300).
|
||||||
|
#[serde(default)]
|
||||||
|
pub ready_secs: u64,
|
||||||
|
/// Stable name of the project: its cache lives in the volume `cc-cache-<cache_id>`. Empty = no cache.
|
||||||
|
#[serde(default)]
|
||||||
|
pub cache_id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub cache: CacheCfg,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Started {
|
||||||
|
pub id: String,
|
||||||
|
/// Port on the runner that forwards to the application.
|
||||||
|
pub port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `.factory/setup.json` into a request (without `work`). `None` when there is nothing to start.
|
||||||
|
pub fn parse_setup(text: &str) -> Option<StartReq> {
|
||||||
|
let v: Value = serde_json::from_str(text).ok()?;
|
||||||
|
// `"isolated": false`: the app cannot run in a container (e.g. a native window); acceptance starts it itself.
|
||||||
|
if v["isolated"].as_bool() == Some(false) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let start = v["start"].as_str()?.trim().to_string();
|
||||||
|
if start.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let url = v["url"].as_str().unwrap_or("");
|
||||||
|
let port = v["port"].as_u64().map(|p| p as u16).or_else(|| port_of(url))?;
|
||||||
|
let strs = |k: &str| -> BTreeMap<String, String> {
|
||||||
|
v[k].as_object().map(|o| o.iter().filter_map(|(a, b)| b.as_str().map(|s| (a.clone(), s.to_string()))).collect()).unwrap_or_default()
|
||||||
|
};
|
||||||
|
let services = v["services"]
|
||||||
|
.as_object()
|
||||||
|
.map(|o| {
|
||||||
|
o.iter()
|
||||||
|
.filter_map(|(name, s)| {
|
||||||
|
let image = s["image"].as_str()?.to_string();
|
||||||
|
let env = s["env"].as_object().map(|e| e.iter().filter_map(|(a, b)| b.as_str().map(|x| (a.clone(), x.to_string()))).collect()).unwrap_or_default();
|
||||||
|
Some((name.clone(), Service { image, env }))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
Some(StartReq {
|
||||||
|
work: String::new(),
|
||||||
|
image: v["image"].as_str().unwrap_or("").trim().to_string(),
|
||||||
|
dockerfile: v["dockerfile"].as_str().unwrap_or("").trim().to_string(),
|
||||||
|
install: v["install"].as_str().unwrap_or("").trim().to_string(),
|
||||||
|
start,
|
||||||
|
port,
|
||||||
|
env: strs("env"),
|
||||||
|
services,
|
||||||
|
ready_secs: v["ready_seconds"].as_u64().unwrap_or(0),
|
||||||
|
cache_id: String::new(),
|
||||||
|
cache: parse_cache(&v["cache"]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_cache(v: &Value) -> CacheCfg {
|
||||||
|
let list = |x: &Value| -> Vec<String> { x.as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(|s| s.trim().trim_end_matches('/').to_string())).filter(|s| !s.is_empty()).collect()).unwrap_or_default() };
|
||||||
|
if v.as_bool() == Some(false) {
|
||||||
|
return CacheCfg { disabled: true, ..Default::default() };
|
||||||
|
}
|
||||||
|
CacheCfg { disabled: false, dirs: list(&v["dirs"]), seed_paths: list(&v["seed"]["paths"]), seed_key: list(&v["seed"]["key"]) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Port of `http://host:1234/path` (80/443 by scheme when missing).
|
||||||
|
pub fn port_of(url: &str) -> Option<u16> {
|
||||||
|
let (scheme, rest) = url.trim().split_once("://")?;
|
||||||
|
// Free text after the URL ("http://localhost:8080 (trunk serve)") is ignored.
|
||||||
|
let host = rest.split(|c: char| c == '/' || c.is_whitespace()).next()?;
|
||||||
|
match host.rsplit_once(':') {
|
||||||
|
Some((_, p)) if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() => p.parse().ok(),
|
||||||
|
_ => Some(if scheme == "https" { 443 } else { 80 }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ident_ok(s: &str, extra: &str) -> bool {
|
||||||
|
!s.is_empty() && s.len() <= 200 && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn image_ok(s: &str) -> bool {
|
||||||
|
ident_ok(s, "._/:@-") && !s.starts_with('-')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A path inside the sources: relative, no `..`, only plain characters (it ends up in a shell loop).
|
||||||
|
fn rel_ok(p: &str) -> bool {
|
||||||
|
ident_ok(p, "._/-") && !p.starts_with('/') && !p.starts_with('-') && !p.split('/').any(|c| c.is_empty() || c == "..") && !p.split('/').any(|c| c == ".git")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Key of a seed: image, install command, seed paths and the contents of the key files (directories: recursively).
|
||||||
|
pub fn seed_key(work: &Path, image: &str, req: &StartReq) -> Option<String> {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let c = &req.cache;
|
||||||
|
if c.disabled || c.seed_paths.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
fn walk(base: &Path, rel: &Path, out: &mut Vec<std::path::PathBuf>) {
|
||||||
|
let full = base.join(rel);
|
||||||
|
if full.is_dir() {
|
||||||
|
let mut kids: Vec<_> = std::fs::read_dir(&full).map(|d| d.filter_map(|e| e.ok()).map(|e| e.file_name()).collect()).unwrap_or_default();
|
||||||
|
kids.sort();
|
||||||
|
for k in kids {
|
||||||
|
if k == ".git" || k == "node_modules" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
walk(base, &rel.join(k), out);
|
||||||
|
}
|
||||||
|
} else if full.is_file() {
|
||||||
|
out.push(rel.to_path_buf());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
for part in [image, &req.install, &c.seed_paths.join("\n"), &req.dockerfile] {
|
||||||
|
h.update(part.as_bytes());
|
||||||
|
h.update([0]);
|
||||||
|
}
|
||||||
|
let mut files = Vec::new();
|
||||||
|
let mut keys = c.seed_key.clone();
|
||||||
|
keys.sort();
|
||||||
|
for k in &keys {
|
||||||
|
h.update(k.as_bytes());
|
||||||
|
h.update([1]);
|
||||||
|
walk(work, Path::new(k), &mut files);
|
||||||
|
}
|
||||||
|
let mut total = 0u64;
|
||||||
|
for f in files {
|
||||||
|
let data = std::fs::read(work.join(&f)).ok()?;
|
||||||
|
total += data.len() as u64;
|
||||||
|
if total > 200 << 20 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
h.update(f.to_string_lossy().as_bytes());
|
||||||
|
h.update([2]);
|
||||||
|
h.update(&data);
|
||||||
|
}
|
||||||
|
let d = h.finalize();
|
||||||
|
Some(d.iter().take(10).map(|b| format!("{b:02x}")).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_ok(m: &BTreeMap<String, String>) -> bool {
|
||||||
|
m.len() <= 64 && m.iter().all(|(k, v)| k.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && ident_ok(k, "_") && v.len() <= 4096 && !v.contains('\0'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check a request against the rules of the runner and return the canonical source directory.
|
||||||
|
fn validate(req: &StartReq, factory_dir: &Path) -> Result<PathBuf> {
|
||||||
|
if req.start.trim().is_empty() || req.start.len() > 4096 || req.install.len() > 4096 {
|
||||||
|
bail!("start/install command missing or too long");
|
||||||
|
}
|
||||||
|
if req.port == 0 {
|
||||||
|
bail!("port missing");
|
||||||
|
}
|
||||||
|
if !req.image.is_empty() && !image_ok(&req.image) {
|
||||||
|
bail!("invalid image name");
|
||||||
|
}
|
||||||
|
if req.services.len() > 8 {
|
||||||
|
bail!("at most 8 services");
|
||||||
|
}
|
||||||
|
for (name, s) in &req.services {
|
||||||
|
if !ident_ok(name, "_-") || !image_ok(&s.image) || !env_ok(&s.env) {
|
||||||
|
bail!("invalid service {name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !env_ok(&req.env) {
|
||||||
|
bail!("invalid environment variable");
|
||||||
|
}
|
||||||
|
if !req.cache_id.is_empty() && !ident_ok(&req.cache_id, "-_.") {
|
||||||
|
bail!("invalid cache id");
|
||||||
|
}
|
||||||
|
let c = &req.cache;
|
||||||
|
if c.dirs.len() > 16 || c.seed_paths.len() > 8 || c.seed_key.len() > 32 || !c.dirs.iter().chain(&c.seed_paths).chain(&c.seed_key).all(|p| rel_ok(p)) {
|
||||||
|
bail!("invalid cache path (relative, letters, digits and ._-/ only)");
|
||||||
|
}
|
||||||
|
if !c.seed_paths.is_empty() && c.seed_key.is_empty() {
|
||||||
|
bail!("cache.seed needs a key (the sources the seed depends on)");
|
||||||
|
}
|
||||||
|
let root = factory_dir.canonicalize().with_context(|| format!("factory area {} is not mounted", factory_dir.display()))?;
|
||||||
|
let work = Path::new(&req.work).canonicalize().context("source directory not found")?;
|
||||||
|
if !work.starts_with(&root) || !work.is_dir() {
|
||||||
|
bail!("the source must be a directory inside the factory area");
|
||||||
|
}
|
||||||
|
if !req.dockerfile.is_empty() {
|
||||||
|
let df = work.join(&req.dockerfile).canonicalize().context("dockerfile not found")?;
|
||||||
|
if !df.starts_with(&work) || !df.is_file() {
|
||||||
|
bail!("the dockerfile must be a file inside the source");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(work)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the service ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
struct Env {
|
||||||
|
containers: Vec<String>,
|
||||||
|
network: String,
|
||||||
|
image: Option<String>,
|
||||||
|
forward: JoinHandle<()>,
|
||||||
|
started: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Runner {
|
||||||
|
token: String,
|
||||||
|
factory_dir: PathBuf,
|
||||||
|
ports: (u16, u16),
|
||||||
|
memory: String,
|
||||||
|
cpus: String,
|
||||||
|
default_image: String,
|
||||||
|
max_age: Duration,
|
||||||
|
/// Own container name (to join the per-run networks); empty when not running in Docker.
|
||||||
|
me: String,
|
||||||
|
envs: Mutex<HashMap<String, Env>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn docker(args: &[&str]) -> Result<String> {
|
||||||
|
let out = Command::new("docker").args(args).stdin(Stdio::null()).output().await.context("cannot run docker")?;
|
||||||
|
if !out.status.success() {
|
||||||
|
bail!("docker {}: {}", args.first().unwrap_or(&""), String::from_utf8_lossy(&out.stderr).trim());
|
||||||
|
}
|
||||||
|
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eq_const(a: &str, b: &str) -> bool {
|
||||||
|
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
type Resp<T> = std::result::Result<T, (StatusCode, String)>;
|
||||||
|
|
||||||
|
fn authed(r: &Runner, h: &HeaderMap) -> Resp<()> {
|
||||||
|
let got = h.get("authorization").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or("");
|
||||||
|
if r.token.is_empty() || !eq_const(got, &r.token) {
|
||||||
|
return Err((StatusCode::UNAUTHORIZED, "bad token".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `codecraft testrunner`: serve until the process is stopped.
|
||||||
|
pub async fn serve() -> Result<()> {
|
||||||
|
let token = std::env::var("RUNNER_TOKEN").unwrap_or_default();
|
||||||
|
if token.len() < 16 {
|
||||||
|
bail!("RUNNER_TOKEN must be set (at least 16 characters)");
|
||||||
|
}
|
||||||
|
let (lo, hi) = std::env::var("RUNNER_PORTS").ok().and_then(|s| s.split_once('-').and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?)))).unwrap_or((9100u16, 9199u16));
|
||||||
|
let runner = Arc::new(Runner {
|
||||||
|
token,
|
||||||
|
factory_dir: PathBuf::from(std::env::var("RUNNER_FACTORY_DIR").unwrap_or_else(|_| "/factory".into())),
|
||||||
|
ports: (lo, hi),
|
||||||
|
memory: std::env::var("RUNNER_MEMORY").unwrap_or_else(|_| "2g".into()),
|
||||||
|
cpus: std::env::var("RUNNER_CPUS").unwrap_or_else(|_| "2".into()),
|
||||||
|
default_image: std::env::var("RUNNER_DEFAULT_IMAGE").unwrap_or_else(|_| "git.familie-zink.org/zink/codecraft-testbase:latest".into()),
|
||||||
|
max_age: Duration::from_secs(60 * std::env::var("RUNNER_MAX_MINUTES").ok().and_then(|s| s.parse().ok()).unwrap_or(90)),
|
||||||
|
me: std::env::var("RUNNER_SELF").or_else(|_| std::env::var("HOSTNAME")).unwrap_or_default(),
|
||||||
|
envs: Mutex::new(HashMap::new()),
|
||||||
|
});
|
||||||
|
let ver = docker(&["version", "--format", "{{.Server.Version}}"]).await.context("the Docker socket is not available to the test runner")?;
|
||||||
|
tracing::info!("test runner: Docker {ver}, ports {lo}-{hi}, default image {}", runner.default_image);
|
||||||
|
sweep_all(&runner).await;
|
||||||
|
let r2 = runner.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||||
|
let old: Vec<String> = r2.envs.lock().unwrap().iter().filter(|(_, e)| e.started.elapsed() > r2.max_age).map(|(k, _)| k.clone()).collect();
|
||||||
|
for id in old {
|
||||||
|
tracing::warn!("test runner: removing {id} (older than the limit)");
|
||||||
|
stop(&r2, &id).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/v1/health", get(health))
|
||||||
|
.route("/v1/envs", post(start_env))
|
||||||
|
.route("/v1/envs/{id}", delete(stop_env))
|
||||||
|
.route("/v1/envs/{id}/log", get(log_env))
|
||||||
|
.route("/v1/cache/{id}", delete(clear_cache))
|
||||||
|
.with_state(runner);
|
||||||
|
let bind = std::env::var("RUNNER_BIND").unwrap_or_else(|_| "0.0.0.0:8788".into());
|
||||||
|
let l = TcpListener::bind(&bind).await?;
|
||||||
|
tracing::info!("test runner listening on {bind}");
|
||||||
|
axum::serve(l, app).with_graceful_shutdown(async { let _ = tokio::signal::ctrl_c().await; }).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove everything this service ever created (after a crash or restart).
|
||||||
|
async fn sweep_all(r: &Runner) {
|
||||||
|
if let Ok(ids) = docker(&["ps", "-aq", "--filter", &format!("label={LABEL}")]).await {
|
||||||
|
for id in ids.split_whitespace() {
|
||||||
|
let _ = docker(&["rm", "-f", "-v", id]).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(nets) = docker(&["network", "ls", "-q", "--filter", &format!("label={LABEL}")]).await {
|
||||||
|
for n in nets.split_whitespace() {
|
||||||
|
if !r.me.is_empty() {
|
||||||
|
let _ = docker(&["network", "disconnect", "-f", n, &r.me]).await;
|
||||||
|
}
|
||||||
|
let _ = docker(&["network", "rm", n]).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health(State(r): State<Arc<Runner>>, h: HeaderMap) -> Resp<Json<Value>> {
|
||||||
|
authed(&r, &h)?;
|
||||||
|
let n = r.envs.lock().unwrap().len();
|
||||||
|
Ok(Json(json!({"ok": true, "environments": n})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn bind_forward(r: &Runner) -> Result<(TcpListener, u16)> {
|
||||||
|
for p in r.ports.0..=r.ports.1 {
|
||||||
|
if let Ok(l) = TcpListener::bind(("0.0.0.0", p)).await {
|
||||||
|
return Ok((l, p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bail!("no free forward port")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start_env(State(r): State<Arc<Runner>>, h: HeaderMap, Json(req): Json<StartReq>) -> Resp<Json<Started>> {
|
||||||
|
authed(&r, &h)?;
|
||||||
|
let work = validate(&req, &r.factory_dir).map_err(|e| (StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||||
|
if r.envs.lock().unwrap().len() >= 16 {
|
||||||
|
return Err((StatusCode::TOO_MANY_REQUESTS, "too many running environments".into()));
|
||||||
|
}
|
||||||
|
let id = uuid::Uuid::new_v4().simple().to_string()[..12].to_string();
|
||||||
|
match create(&r, &id, &req, &work).await {
|
||||||
|
Ok(s) => Ok(Json(s)),
|
||||||
|
Err(e) => {
|
||||||
|
let msg = format!("{e:#}");
|
||||||
|
stop(&r, &id).await;
|
||||||
|
Err((StatusCode::BAD_GATEWAY, msg))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create(r: &Arc<Runner>, id: &str, req: &StartReq, work: &Path) -> Result<Started> {
|
||||||
|
let began = Instant::now();
|
||||||
|
let net = format!("cc-run-{id}");
|
||||||
|
let app = format!("cc-run-{id}");
|
||||||
|
// Register first, so a failure at any step is cleaned up by stop().
|
||||||
|
let forward = tokio::spawn(async {});
|
||||||
|
r.envs.lock().unwrap().insert(id.to_string(), Env { containers: vec![app.clone()], network: net.clone(), image: None, forward, started: Instant::now() });
|
||||||
|
docker(&["network", "create", "--label", LABEL, &net]).await?;
|
||||||
|
for (name, s) in &req.services {
|
||||||
|
let cname = format!("{app}-{name}");
|
||||||
|
let mut a: Vec<String> = ["run", "-d", "--name", &cname, "--network", &net, "--network-alias", name, "--label", LABEL, "--memory", &r.memory, "--pids-limit", "1024", "--security-opt", "no-new-privileges"].map(String::from).to_vec();
|
||||||
|
for (k, v) in &s.env {
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("{k}={v}"));
|
||||||
|
}
|
||||||
|
a.push(s.image.clone());
|
||||||
|
let refs: Vec<&str> = a.iter().map(String::as_str).collect();
|
||||||
|
docker(&refs).await.with_context(|| format!("service {name}"))?;
|
||||||
|
r.envs.lock().unwrap().get_mut(id).unwrap().containers.push(cname);
|
||||||
|
}
|
||||||
|
let image = if req.dockerfile.is_empty() {
|
||||||
|
if req.image.is_empty() { default_image_or_fallback(&r.default_image).await } else { req.image.clone() }
|
||||||
|
} else {
|
||||||
|
let tag = format!("cc-run-{id}");
|
||||||
|
let df = work.join(&req.dockerfile);
|
||||||
|
docker(&["build", "-q", "--label", LABEL, "-t", &tag, "-f", &df.display().to_string(), &work.display().to_string()]).await.context("docker build")?;
|
||||||
|
r.envs.lock().unwrap().get_mut(id).unwrap().image = Some(tag.clone());
|
||||||
|
tag
|
||||||
|
};
|
||||||
|
let mut a: Vec<String> = [
|
||||||
|
"create", "--name", &app, "--network", &net, "--label", LABEL, "--memory", &r.memory, "--cpus", &r.cpus, "--pids-limit", "1024",
|
||||||
|
"--cap-drop", "ALL", "--cap-add", "CHOWN", "--cap-add", "DAC_OVERRIDE", "--cap-add", "FOWNER", "--cap-add", "SETUID", "--cap-add", "SETGID", "--cap-add", "KILL", "--cap-add", "NET_BIND_SERVICE",
|
||||||
|
"--security-opt", "no-new-privileges", "-w", "/app", "-e", "CI=1",
|
||||||
|
]
|
||||||
|
.map(String::from)
|
||||||
|
.to_vec();
|
||||||
|
for (k, v) in &req.env {
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("{k}={v}"));
|
||||||
|
}
|
||||||
|
// Per-project cache volume: tool caches, shared download directories and seeds (see CacheCfg).
|
||||||
|
let cached = !req.cache_id.is_empty() && !req.cache.disabled;
|
||||||
|
if cached {
|
||||||
|
let vol = format!("cc-cache-{}", req.cache_id);
|
||||||
|
docker(&["volume", "create", "--label", CACHE_LABEL, &vol]).await.context("cache volume")?;
|
||||||
|
a.push("-v".into());
|
||||||
|
a.push(format!("{vol}:/cache"));
|
||||||
|
for (k, v) in [
|
||||||
|
("npm_config_cache", "/cache/npm"),
|
||||||
|
("YARN_CACHE_FOLDER", "/cache/yarn"),
|
||||||
|
("PIP_CACHE_DIR", "/cache/pip"),
|
||||||
|
("GOMODCACHE", "/cache/go/mod"),
|
||||||
|
("GOCACHE", "/cache/go/build"),
|
||||||
|
("CARGO_TARGET_DIR", "/cache/target"),
|
||||||
|
("XDG_CACHE_HOME", "/cache/xdg"),
|
||||||
|
] {
|
||||||
|
if !req.env.contains_key(k) {
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("{k}={v}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("CC_CACHE_DIRS={}", req.cache.dirs.join(" ")));
|
||||||
|
if let Some(key) = seed_key(work, &image, req) {
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("CC_SEED_KEY={key}"));
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("CC_SEED_PATHS={}", req.cache.seed_paths.join(" ")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("CC_INSTALL={}", req.install));
|
||||||
|
a.push("-e".into());
|
||||||
|
a.push(format!("CC_START={}", req.start));
|
||||||
|
a.push(image);
|
||||||
|
a.extend(["sh", "-c", ENTRY_SCRIPT].map(String::from));
|
||||||
|
let refs: Vec<&str> = a.iter().map(String::as_str).collect();
|
||||||
|
docker(&refs).await.context("docker create")?;
|
||||||
|
// Copy the sources in (without .git); the container never sees the host directory.
|
||||||
|
let cp = Command::new("sh")
|
||||||
|
.args(["-c", r#"tar -C "$1" --exclude=.git -cf - . | docker cp - "$2":/app"#, "sh", &work.display().to_string(), &app])
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.output()
|
||||||
|
.await?;
|
||||||
|
if !cp.status.success() {
|
||||||
|
bail!("copying the sources failed: {}", String::from_utf8_lossy(&cp.stderr).trim());
|
||||||
|
}
|
||||||
|
docker(&["start", &app]).await?;
|
||||||
|
if !r.me.is_empty() {
|
||||||
|
let _ = docker(&["network", "connect", &net, &r.me]).await;
|
||||||
|
}
|
||||||
|
let ip = docker(&["inspect", "-f", &format!("{{{{(index .NetworkSettings.Networks \"{net}\").IPAddress}}}}"), &app]).await?;
|
||||||
|
if ip.is_empty() {
|
||||||
|
bail!("the container got no address");
|
||||||
|
}
|
||||||
|
// Wait until the application answers; give up early when it has exited.
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(if req.ready_secs == 0 { 300 } else { req.ready_secs.min(1800) });
|
||||||
|
loop {
|
||||||
|
if TcpStream::connect((ip.as_str(), req.port)).await.is_ok() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let running = docker(&["inspect", "-f", "{{.State.Running}}", &app]).await.unwrap_or_default();
|
||||||
|
if running != "true" {
|
||||||
|
bail!("the application exited before it listened on port {}:\n{}", req.port, tail(&logs(&app).await, 40));
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
bail!("the application did not listen on port {} in time:\n{}", req.port, tail(&logs(&app).await, 40));
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||||
|
}
|
||||||
|
// Report what the cache brought: seed hit/miss, install time, total time until the app answered.
|
||||||
|
let facts: Vec<String> = logs(&app).await.lines().filter(|l| l.starts_with("[runner] seed ") || l.starts_with("[runner] install took") || l.starts_with("[runner] apt installed")).map(|l| l.trim_start_matches("[runner] ").to_string()).collect();
|
||||||
|
let took = began.elapsed().as_secs();
|
||||||
|
let cache = if cached { "on" } else { "off" };
|
||||||
|
tracing::info!("test env {id} ({}) ready after {took} s; cache {cache}{}{}", req.cache_id, if facts.is_empty() { "" } else { "; " }, facts.join("; "));
|
||||||
|
let (listener, port) = bind_forward(r).await?;
|
||||||
|
let (target, tport) = (ip, req.port);
|
||||||
|
let fwd = tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((mut inbound, _)) = listener.accept().await else { break };
|
||||||
|
let t = target.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Ok(mut out) = TcpStream::connect((t.as_str(), tport)).await {
|
||||||
|
let _ = tokio::io::copy_bidirectional(&mut inbound, &mut out).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(e) = r.envs.lock().unwrap().get_mut(id) {
|
||||||
|
e.forward.abort();
|
||||||
|
e.forward = fwd;
|
||||||
|
}
|
||||||
|
Ok(Started { id: id.to_string(), port })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shared base image; when it can neither be found nor pulled, fall back to plain Node so runs still work.
|
||||||
|
async fn default_image_or_fallback(img: &str) -> String {
|
||||||
|
if docker(&["image", "inspect", img]).await.is_ok() || docker(&["pull", "-q", img]).await.is_ok() {
|
||||||
|
return img.to_string();
|
||||||
|
}
|
||||||
|
tracing::warn!("test runner: base image {img} is not available, using {FALLBACK_IMAGE}");
|
||||||
|
FALLBACK_IMAGE.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn logs(container: &str) -> String {
|
||||||
|
match Command::new("docker").args(["logs", "--tail", "400", container]).output().await {
|
||||||
|
Ok(o) => format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr)),
|
||||||
|
Err(_) => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tail(s: &str, n: usize) -> String {
|
||||||
|
let lines: Vec<&str> = s.lines().collect();
|
||||||
|
lines[lines.len().saturating_sub(n)..].join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn stop(r: &Runner, id: &str) {
|
||||||
|
let Some(e) = r.envs.lock().unwrap().remove(id) else { return };
|
||||||
|
e.forward.abort();
|
||||||
|
for c in e.containers.iter().rev() {
|
||||||
|
let _ = docker(&["rm", "-f", "-v", c]).await;
|
||||||
|
}
|
||||||
|
if !r.me.is_empty() {
|
||||||
|
let _ = docker(&["network", "disconnect", "-f", &e.network, &r.me]).await;
|
||||||
|
}
|
||||||
|
let _ = docker(&["network", "rm", &e.network]).await;
|
||||||
|
if let Some(i) = e.image {
|
||||||
|
let _ = docker(&["rmi", "-f", &i]).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn stop_env(State(r): State<Arc<Runner>>, h: HeaderMap, AxPath(id): AxPath<String>) -> Resp<Json<Value>> {
|
||||||
|
authed(&r, &h)?;
|
||||||
|
stop(&r, &id).await;
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forget the cache of a project (fails while an environment of it is running).
|
||||||
|
async fn clear_cache(State(r): State<Arc<Runner>>, h: HeaderMap, AxPath(id): AxPath<String>) -> Resp<Json<Value>> {
|
||||||
|
authed(&r, &h)?;
|
||||||
|
if !ident_ok(&id, "-_.") {
|
||||||
|
return Err((StatusCode::BAD_REQUEST, "invalid cache id".into()));
|
||||||
|
}
|
||||||
|
docker(&["volume", "rm", &format!("cc-cache-{id}")]).await.map_err(|e| (StatusCode::CONFLICT, format!("{e:#}")))?;
|
||||||
|
Ok(Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct LogQ {
|
||||||
|
tail: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn log_env(State(r): State<Arc<Runner>>, h: HeaderMap, AxPath(id): AxPath<String>, Query(q): Query<LogQ>) -> Resp<String> {
|
||||||
|
authed(&r, &h)?;
|
||||||
|
let mut out = String::new();
|
||||||
|
let names = r.envs.lock().unwrap().get(&id).map(|e| e.containers.clone()).ok_or((StatusCode::NOT_FOUND, "unknown environment".to_string()))?;
|
||||||
|
for c in names {
|
||||||
|
let l = logs(&c).await;
|
||||||
|
if !l.is_empty() {
|
||||||
|
let label = c.strip_prefix(&format!("cc-run-{id}")).unwrap_or("").trim_start_matches('-');
|
||||||
|
out.push_str(&format!("==> {} <==\n{}\n", if label.is_empty() { "app" } else { label }, tail(&l, q.tail.unwrap_or(200))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the client (in the main server) ---------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Client {
|
||||||
|
url: String,
|
||||||
|
token: String,
|
||||||
|
http: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
/// Configured through `CODECRAFT_RUNNER_URL` (e.g. http://runner:8788) and `CODECRAFT_RUNNER_TOKEN`.
|
||||||
|
pub fn from_env() -> Option<Self> {
|
||||||
|
let url = std::env::var("CODECRAFT_RUNNER_URL").ok()?.trim().trim_end_matches('/').to_string();
|
||||||
|
let token = std::env::var("CODECRAFT_RUNNER_TOKEN").ok()?.trim().to_string();
|
||||||
|
if url.is_empty() || token.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Self { url, token, http: reqwest::Client::builder().timeout(Duration::from_secs(40 * 60)).build().ok()? })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn host(&self) -> String {
|
||||||
|
let rest = self.url.split_once("://").map(|(_, r)| r).unwrap_or(&self.url);
|
||||||
|
rest.split('/').next().unwrap_or("").rsplit_once(':').map(|(h, _)| h).unwrap_or(rest).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn check(r: reqwest::Response) -> Result<reqwest::Response> {
|
||||||
|
if r.status().is_success() {
|
||||||
|
return Ok(r);
|
||||||
|
}
|
||||||
|
let s = r.status();
|
||||||
|
bail!("test runner: {} {}", s, r.text().await.unwrap_or_default().trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start(&self, req: &StartReq) -> Result<Started> {
|
||||||
|
let r = self.http.post(format!("{}/v1/envs", self.url)).bearer_auth(&self.token).json(req).send().await.context("test runner unreachable")?;
|
||||||
|
Ok(Self::check(r).await?.json().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn log(&self, id: &str) -> Result<String> {
|
||||||
|
let r = self.http.get(format!("{}/v1/envs/{id}/log?tail=300", self.url)).bearer_auth(&self.token).send().await?;
|
||||||
|
Ok(Self::check(r).await?.text().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn stop(&self, id: &str) {
|
||||||
|
let _ = self.http.delete(format!("{}/v1/envs/{id}", self.url)).bearer_auth(&self.token).send().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Listen on 127.0.0.1 (the wanted port if it is free, otherwise any) and forward every
|
||||||
|
/// connection to `host:port`. Returns the local port and the task to abort.
|
||||||
|
pub async fn forward_local(want: u16, host: String, port: u16) -> Result<(u16, JoinHandle<()>)> {
|
||||||
|
let l = match TcpListener::bind(("127.0.0.1", want)).await {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(_) => TcpListener::bind(("127.0.0.1", 0)).await?,
|
||||||
|
};
|
||||||
|
let local = l.local_addr()?.port();
|
||||||
|
let h = tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((mut inbound, _)) = l.accept().await else { break };
|
||||||
|
let host = host.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Ok(mut out) = TcpStream::connect((host.as_str(), port)).await {
|
||||||
|
let _ = tokio::io::copy_bidirectional(&mut inbound, &mut out).await;
|
||||||
|
let _ = out.shutdown().await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok((local, h))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn setup_is_parsed() {
|
||||||
|
let r = parse_setup(r#"{"install":"npm ci","start":"npm start","url":"http://localhost:8080/app","image":"node:20","env":{"A":"1"},"services":{"db":{"image":"postgres:16","env":{"POSTGRES_PASSWORD":"x"}}}}"#).unwrap();
|
||||||
|
assert_eq!((r.port, r.image.as_str(), r.install.as_str()), (8080, "node:20", "npm ci"));
|
||||||
|
assert_eq!(r.services["db"].image, "postgres:16");
|
||||||
|
assert!(parse_setup(r#"{"url":"http://localhost:1"}"#).is_none());
|
||||||
|
assert!(parse_setup(r#"{"start":"x"}"#).is_none());
|
||||||
|
assert_eq!(parse_setup(r#"{"start":"x","port":3000}"#).unwrap().port, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ports_of_urls() {
|
||||||
|
assert_eq!(port_of("http://localhost:8080"), Some(8080));
|
||||||
|
assert_eq!(port_of("http://localhost"), Some(80));
|
||||||
|
assert_eq!(port_of("https://x/y"), Some(443));
|
||||||
|
assert_eq!(port_of("nonsense"), None);
|
||||||
|
assert_eq!(port_of("http://localhost:8080 (web build: trunk serve)"), Some(8080));
|
||||||
|
assert!(parse_setup(r#"{"start":"x","port":1,"isolated":false}"#).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn requests_are_checked() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("ccr-{}", std::process::id()));
|
||||||
|
let work = dir.join("a/b");
|
||||||
|
std::fs::create_dir_all(&work).unwrap();
|
||||||
|
let ok = StartReq { work: work.display().to_string(), start: "x".into(), port: 80, ..Default::default() };
|
||||||
|
assert!(validate(&ok, &dir).is_ok());
|
||||||
|
// outside of the factory area, bad image, bad env name, dockerfile escaping the source
|
||||||
|
assert!(validate(&StartReq { work: "/etc".into(), ..ok.clone() }, &dir).is_err());
|
||||||
|
assert!(validate(&StartReq { image: "x;rm".into(), ..ok.clone() }, &dir).is_err());
|
||||||
|
assert!(validate(&StartReq { image: "--privileged".into(), ..ok.clone() }, &dir).is_err());
|
||||||
|
assert!(validate(&StartReq { env: [("A B".to_string(), "1".to_string())].into(), ..ok.clone() }, &dir).is_err());
|
||||||
|
assert!(validate(&StartReq { dockerfile: "../../etc/passwd".into(), ..ok.clone() }, &dir).is_err());
|
||||||
|
assert!(validate(&StartReq { work: format!("{}/../../..", work.display()), ..ok.clone() }, &dir).is_err());
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cache_config_and_seed_key() {
|
||||||
|
let r = parse_setup(r#"{"start":"x","port":1,"cache":{"dirs":["build/downloads/"],"seed":{"paths":["data/ubuntu.ext4"],"key":["guest","package-lock.json"]}}}"#).unwrap();
|
||||||
|
assert_eq!(r.cache.dirs, vec!["build/downloads"]);
|
||||||
|
assert_eq!(r.cache.seed_key, vec!["guest", "package-lock.json"]);
|
||||||
|
assert!(parse_setup(r#"{"start":"x","port":1,"cache":false}"#).unwrap().cache.disabled);
|
||||||
|
assert!(!parse_setup(r#"{"start":"x","port":1}"#).unwrap().cache.disabled);
|
||||||
|
assert!(rel_ok("build/downloads") && !rel_ok("../x") && !rel_ok("/etc") && !rel_ok("a b") && !rel_ok("a/.git/b") && !rel_ok("a//b"));
|
||||||
|
// The key follows the contents of the key files, not of anything else.
|
||||||
|
let dir = std::env::temp_dir().join(format!("ccs-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(dir.join("guest")).unwrap();
|
||||||
|
std::fs::write(dir.join("guest/a.c"), "one").unwrap();
|
||||||
|
std::fs::write(dir.join("other.txt"), "x").unwrap();
|
||||||
|
let mut req = r.clone();
|
||||||
|
req.install = "npm ci".into();
|
||||||
|
let k1 = seed_key(&dir, "node:24", &req).unwrap();
|
||||||
|
std::fs::write(dir.join("other.txt"), "changed").unwrap();
|
||||||
|
assert_eq!(seed_key(&dir, "node:24", &req).unwrap(), k1);
|
||||||
|
std::fs::write(dir.join("guest/a.c"), "two").unwrap();
|
||||||
|
assert_ne!(seed_key(&dir, "node:24", &req).unwrap(), k1);
|
||||||
|
assert_ne!(seed_key(&dir, "node:22", &req).unwrap(), seed_key(&dir, "node:24", &req).unwrap());
|
||||||
|
req.cache.seed_paths.clear();
|
||||||
|
assert!(seed_key(&dir, "node:24", &req).is_none());
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_compare() {
|
||||||
|
assert!(eq_const("abc", "abc"));
|
||||||
|
assert!(!eq_const("abc", "abd"));
|
||||||
|
assert!(!eq_const("abc", "ab"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@
|
|||||||
"@xterm/addon-fit": "^0.11.0",
|
"@xterm/addon-fit": "^0.11.0",
|
||||||
"@xterm/addon-web-links": "^0.12.0",
|
"@xterm/addon-web-links": "^0.12.0",
|
||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
|
"antd": "^6.7.2",
|
||||||
"codemirror": "^6.0.2",
|
"codemirror": "^6.0.2",
|
||||||
"occt-import-js": "^0.0.23",
|
"occt-import-js": "^0.0.23",
|
||||||
"react": "^19.3.1",
|
"react": "^19.3.1",
|
||||||
|
|||||||
@@ -36,6 +36,23 @@ export function App() {
|
|||||||
const [info, setInfo] = useState<Info>();
|
const [info, setInfo] = useState<Info>();
|
||||||
const [error, setError] = useState<string>();
|
const [error, setError] = useState<string>();
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
|
// Wide screens: the chat list can be folded away (remembered); narrow screens use the slide-in drawer.
|
||||||
|
const [folded, setFolded] = useState(() => {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem("codecraft.sidebarFolded") === "1";
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const openMenu = () => {
|
||||||
|
if (window.matchMedia("(max-width: 800px)").matches) return setMenuOpen(true);
|
||||||
|
setFolded((f) => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem("codecraft.sidebarFolded", f ? "0" : "1");
|
||||||
|
} catch {}
|
||||||
|
return !f;
|
||||||
|
});
|
||||||
|
};
|
||||||
const [shared, setShared] = useState(pendingShare);
|
const [shared, setShared] = useState(pendingShare);
|
||||||
const offline = useStore((s) => s.offline);
|
const offline = useStore((s) => s.offline);
|
||||||
useTitleActivity();
|
useTitleActivity();
|
||||||
@@ -98,40 +115,40 @@ export function App() {
|
|||||||
const [section, arg] = route;
|
const [section, arg] = route;
|
||||||
let content;
|
let content;
|
||||||
const chatIds = section === "s" && arg ? arg.split("+").filter(Boolean).slice(0, MAX_PANES) : [];
|
const chatIds = section === "s" && arg ? arg.split("+").filter(Boolean).slice(0, MAX_PANES) : [];
|
||||||
if (chatIds.length === 1) content = <ChatView key={chatIds[0]} sessionId={chatIds[0]} onMenu={() => setMenuOpen(true)} />;
|
if (chatIds.length === 1) content = <ChatView key={chatIds[0]} sessionId={chatIds[0]} onMenu={openMenu} />;
|
||||||
else if (chatIds.length > 1)
|
else if (chatIds.length > 1)
|
||||||
content = (
|
content = (
|
||||||
<div className="split-view">
|
<div className="split-view">
|
||||||
{chatIds.map((id) => (
|
{chatIds.map((id) => (
|
||||||
<div key={id} className="split-pane">
|
<div key={id} className="split-pane">
|
||||||
<ChatView sessionId={id} onMenu={() => setMenuOpen(true)} onClosePane={() => closePane(id)} />
|
<ChatView sessionId={id} onMenu={openMenu} onClosePane={() => closePane(id)} />
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
else if (section === "settings") content = <Settings tab={arg} onMenu={() => setMenuOpen(true)} />;
|
else if (section === "settings") content = <Settings tab={arg} onMenu={openMenu} />;
|
||||||
else if (section === "p" && arg) content = <ProjectPage key={arg} cwd={decodeURIComponent(arg)} onMenu={() => setMenuOpen(true)} />;
|
else if (section === "p" && arg) content = <ProjectPage key={arg} cwd={decodeURIComponent(arg)} onMenu={openMenu} />;
|
||||||
else if (section === "factory") content = <Factory onMenu={() => setMenuOpen(true)} />;
|
else if (section === "factory") content = <Factory onMenu={openMenu} overlayId={arg === "s" ? route[2] : undefined} />;
|
||||||
else if (section === "stats") content = <Stats onMenu={() => setMenuOpen(true)} />;
|
else if (section === "stats") content = <Stats onMenu={openMenu} />;
|
||||||
else if (section === "images") content = <Images onMenu={() => setMenuOpen(true)} />;
|
else if (section === "images") content = <Images onMenu={openMenu} />;
|
||||||
else if (section === "jobs" && arg) content = <JobEditor key={arg} id={arg} onMenu={() => setMenuOpen(true)} />;
|
else if (section === "jobs" && arg) content = <JobEditor key={arg} id={arg} onMenu={openMenu} />;
|
||||||
else if (section === "jobs") content = <Jobs onMenu={() => setMenuOpen(true)} />;
|
else if (section === "jobs") content = <Jobs onMenu={openMenu} />;
|
||||||
else if (section === "terminal")
|
else if (section === "terminal")
|
||||||
content = (
|
content = (
|
||||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||||
<TerminalPage id={arg} onMenu={() => setMenuOpen(true)} />
|
<TerminalPage id={arg} onMenu={openMenu} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
);
|
);
|
||||||
else if (section === "files")
|
else if (section === "files")
|
||||||
content = (
|
content = (
|
||||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||||
<Files onMenu={() => setMenuOpen(true)} />
|
<Files onMenu={openMenu} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
);
|
);
|
||||||
else content = <NewSession onMenu={() => setMenuOpen(true)} onCreated={(id) => navigate(`/s/${id}`)} />;
|
else content = <NewSession onMenu={openMenu} onCreated={(id) => navigate(`/s/${id}`)} />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app">
|
<div className={`app ${folded ? "side-folded" : ""}`}>
|
||||||
{menuOpen && <div className="backdrop" onClick={() => setMenuOpen(false)} />}
|
{menuOpen && <div className="backdrop" onClick={() => setMenuOpen(false)} />}
|
||||||
<Sidebar open={menuOpen} activeIds={chatIds} section={section ?? ""} />
|
<Sidebar open={menuOpen} activeIds={chatIds} section={section ?? ""} />
|
||||||
<main className="main">
|
<main className="main">
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { ServerEvent } from "./types";
|
import type { ServerEvent } from "./types";
|
||||||
|
import { chunkedUpload } from "./uploads";
|
||||||
|
|
||||||
// Authentication uses an HttpOnly session cookie set by /api/auth/login.
|
// Authentication uses an HttpOnly session cookie set by /api/auth/login.
|
||||||
|
|
||||||
@@ -101,27 +102,10 @@ export function connectEvents(handlers: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const CHUNK = 8 * 1024 * 1024;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upload a file in 8 MB chunks (stays below reverse proxy body limits; up to the
|
* Upload a single file in chunks (see uploads.ts). `onProgress` gets the uploaded fraction 0..1.
|
||||||
* server's max_upload_mb). `onProgress` gets the uploaded fraction 0..1.
|
* Without the progress panel – use `uploadBatch` for user-visible uploads.
|
||||||
*/
|
*/
|
||||||
export async function uploadFile(path: string, file: Blob, onProgress?: (fraction: number) => void): Promise<void> {
|
export async function uploadFile(path: string, file: Blob, onProgress?: (fraction: number) => void): Promise<void> {
|
||||||
let offset = 0;
|
await chunkedUpload(`/api/files/upload?path=${encodeURIComponent(path)}`, file, (n) => onProgress?.(file.size ? n / file.size : 1));
|
||||||
do {
|
|
||||||
const chunk = file.slice(offset, offset + CHUNK);
|
|
||||||
const res = await fetch(`/api/files/upload?path=${encodeURIComponent(path)}&offset=${offset}`, { method: "PUT", body: chunk, credentials: "same-origin" });
|
|
||||||
if (!res.ok) {
|
|
||||||
let msg = `HTTP ${res.status}`;
|
|
||||||
try {
|
|
||||||
msg = (await res.json()).error ?? msg;
|
|
||||||
} catch {
|
|
||||||
if (res.status === 413) msg = "too large for the reverse proxy";
|
|
||||||
}
|
|
||||||
throw new Error(msg);
|
|
||||||
}
|
|
||||||
offset += chunk.size;
|
|
||||||
onProgress?.(file.size ? offset / file.size : 1);
|
|
||||||
} while (offset < file.size);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { patch } from "../api";
|
||||||
|
import { toast } from "../dialogs";
|
||||||
|
import { useFetch } from "../hooks";
|
||||||
|
import { useT } from "../i18n";
|
||||||
|
import { Spinner } from "./Activity";
|
||||||
|
import { Icon } from "./Icon";
|
||||||
|
|
||||||
|
interface SkillInfo {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
files: string[];
|
||||||
|
user?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Switch skills on for one chat: their full instructions go into every turn. */
|
||||||
|
export function ChatSkillsDialog({ sessionId, cwd, active, onClose }: { sessionId: string; cwd: string; active: string[]; onClose: () => void }) {
|
||||||
|
const t = useT();
|
||||||
|
const { data } = useFetch<{ skills: SkillInfo[] }>(`/commands?cwd=${encodeURIComponent(cwd)}`);
|
||||||
|
const [picked, setPicked] = useState<string[]>(active);
|
||||||
|
const [filter, setFilter] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const all = data?.skills ?? [];
|
||||||
|
// Chosen skills first, then the rest.
|
||||||
|
const shown = all
|
||||||
|
.filter((s) => !filter.trim() || `${s.name} ${s.description}`.toLowerCase().includes(filter.trim().toLowerCase()))
|
||||||
|
.sort((a, b) => Number(picked.includes(b.name)) - Number(picked.includes(a.name)) || a.name.localeCompare(b.name));
|
||||||
|
const toggle = (n: string) => setPicked((p) => (p.includes(n) ? p.filter((x) => x !== n) : [...p, n]));
|
||||||
|
const save = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await patch(`/sessions/${sessionId}`, { skills: picked });
|
||||||
|
onClose();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onClose={onClose} className="draft-modal" role="dialog" aria-label={t("skills.chatTitle")}>
|
||||||
|
<h3>{t("skills.chatTitle")}</h3>
|
||||||
|
<div className="hint" style={{ marginBottom: 8 }}>
|
||||||
|
{t("skills.chatHint")}
|
||||||
|
</div>
|
||||||
|
{!data ? (
|
||||||
|
<Spinner />
|
||||||
|
) : all.length === 0 ? (
|
||||||
|
<div className="empty">{t("skills.empty")}</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{all.length > 6 && <Input autoFocus style={{ width: "100%" }} placeholder={t("skills.filter")} value={filter} onChange={(e) => setFilter(e.target.value)} />}
|
||||||
|
<div className="issue-list">
|
||||||
|
{shown.map((s) => (
|
||||||
|
<Checkbox key={s.name} className="row" style={{ gap: 8, alignItems: "flex-start", padding: "2px 0" }} checked={picked.includes(s.name)} onChange={() => toggle(s.name)}>
|
||||||
|
<span>
|
||||||
|
<code>{s.name}</code>
|
||||||
|
{s.files.length > 0 && <span className="hint"> · {t("skills.files", { n: s.files.length })}</span>}
|
||||||
|
<div className="hint">{s.description}</div>
|
||||||
|
</span>
|
||||||
|
</Checkbox>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{picked.length > 4 && <div className="notice">{t("skills.manyActive")}</div>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
|
||||||
|
<Button onClick={onClose} disabled={busy}>
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={() => void save()} disabled={busy}>
|
||||||
|
{busy ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { del, get, post, put } from "../api";
|
import { del, get, post, put } from "../api";
|
||||||
import { confirmDialog, toast } from "../dialogs";
|
import { confirmDialog, toast } from "../dialogs";
|
||||||
@@ -132,30 +133,30 @@ export function ChatTabBar({ state }: { state: Tabs }) {
|
|||||||
</button>
|
</button>
|
||||||
{terms.map((x, i) => (
|
{terms.map((x, i) => (
|
||||||
<span key={x.id} className={`chat-tab ${tab === x.id ? "active" : ""} ${x.alive ? "" : "dead"}`}>
|
<span key={x.id} className={`chat-tab ${tab === x.id ? "active" : ""} ${x.alive ? "" : "dead"}`}>
|
||||||
<button role="tab" aria-selected={tab === x.id} className="ghost" onClick={() => setTab(x.id)} title={x.cwd}>
|
<Button type="text" role="tab" aria-selected={tab === x.id} onClick={() => setTab(x.id)} title={x.cwd}>
|
||||||
<Icon name="terminal" /> {t("terminal.tab", { n: i + 1 })}
|
<Icon name="terminal" /> {t("terminal.tab", { n: i + 1 })}
|
||||||
</button>
|
</Button>
|
||||||
<button className="ghost close" onClick={() => void closeTerminal(x, i + 1)} aria-label={t("terminal.close")} title={t("terminal.close")}>
|
<Button type="text" className="close" onClick={() => void closeTerminal(x, i + 1)} aria-label={t("terminal.close")} title={t("terminal.close")}>
|
||||||
<Icon name="close" size={12} />
|
<Icon name="close" size={12} />
|
||||||
</button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
{files.map((f) => (
|
{files.map((f) => (
|
||||||
<span key={f.id} className={`chat-tab ${tab === f.id ? "active" : ""}`}>
|
<span key={f.id} className={`chat-tab ${tab === f.id ? "active" : ""}`}>
|
||||||
<button role="tab" aria-selected={tab === f.id} className="ghost" onClick={() => setTab(f.id)} title={f.dir}>
|
<Button type="text" role="tab" aria-selected={tab === f.id} onClick={() => setTab(f.id)} title={f.dir}>
|
||||||
<Icon name="folder" /> {basename(f.dir)}
|
<Icon name="folder" /> {basename(f.dir)}
|
||||||
</button>
|
</Button>
|
||||||
<button className="ghost close" onClick={() => closeFiles(f.id)} aria-label={t("files.closeTab")} title={t("files.closeTab")}>
|
<Button type="text" className="close" onClick={() => closeFiles(f.id)} aria-label={t("files.closeTab")} title={t("files.closeTab")}>
|
||||||
<Icon name="close" size={12} />
|
<Icon name="close" size={12} />
|
||||||
</button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
<button className="ghost chat-tab-add" onClick={() => void openTerminal()} title={t("terminal.new")} aria-label={t("terminal.new")}>
|
<Button type="text" className="chat-tab-add" onClick={() => void openTerminal()} title={t("terminal.new")} aria-label={t("terminal.new")}>
|
||||||
<Icon name="plus" /> <Icon name="terminal" />
|
<Icon name="plus" /> <Icon name="terminal" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="ghost chat-tab-add" onClick={openFiles} title={t("files.newTab")} aria-label={t("files.newTab")}>
|
<Button type="text" className="chat-tab-add" onClick={openFiles} title={t("files.newTab")} aria-label={t("files.newTab")}>
|
||||||
<Icon name="plus" /> <Icon name="folder" />
|
<Icon name="plus" /> <Icon name="folder" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { DraftBar, isDraftChat } from "./FactoryDraft";
|
import { Button, Input } from "antd";
|
||||||
|
import { DraftBar, IssueBar, isDraftChat, isIssueChat } from "./FactoryDraft";
|
||||||
import { takePrefill } from "../share";
|
import { takePrefill } from "../share";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { FileChip, FileFigure, fileType, imageSize, imageSrc } from "./FileFigure";
|
import { FileChip, FileFigure, fileType, imageSize, imageSrc } from "./FileFigure";
|
||||||
@@ -15,6 +16,7 @@ import { Composer } from "./Composer";
|
|||||||
import { ShareDialog } from "./ShareDialog";
|
import { ShareDialog } from "./ShareDialog";
|
||||||
import { RenameDialog } from "./RenameDialog";
|
import { RenameDialog } from "./RenameDialog";
|
||||||
import { InstructionsDialog } from "./InstructionsDialog";
|
import { InstructionsDialog } from "./InstructionsDialog";
|
||||||
|
import { ChatSkillsDialog } from "./ChatSkills";
|
||||||
import { RegenerateButton } from "./Regenerate";
|
import { RegenerateButton } from "./Regenerate";
|
||||||
import { WorktreeChip } from "./WorktreeChip";
|
import { WorktreeChip } from "./WorktreeChip";
|
||||||
import { QueueList } from "./QueueList";
|
import { QueueList } from "./QueueList";
|
||||||
@@ -200,21 +202,21 @@ function ChatSearch({ sessionId, onPick, onClose }: { sessionId: string; onPick:
|
|||||||
<div className="chat-search" role="search">
|
<div className="chat-search" role="search">
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<Icon name="search" />
|
<Icon name="search" />
|
||||||
<input autoFocus value={q} placeholder={t("chat.searchPlaceholder")} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Escape" && onClose()} aria-label={t("chat.search")} />
|
<Input autoFocus value={q} placeholder={t("chat.searchPlaceholder")} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Escape" && onClose()} aria-label={t("chat.search")} />
|
||||||
<button className="small ghost" onClick={onClose} aria-label={t("common.close")}>
|
<Button type="text" size="small" onClick={onClose} aria-label={t("common.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{hits && (
|
{hits && (
|
||||||
<div className="chat-search-hits">
|
<div className="chat-search-hits">
|
||||||
<div className="hint">{hits.length ? t("chat.searchHits", { n: hits.length }) : t("chat.searchNone")}</div>
|
<div className="hint">{hits.length ? t("chat.searchHits", { n: hits.length }) : t("chat.searchNone")}</div>
|
||||||
{hits.map((h) => (
|
{hits.map((h) => (
|
||||||
<button key={h.id} onClick={() => onPick(h.id)}>
|
<Button key={h.id} onClick={() => onPick(h.id)}>
|
||||||
<span className="who">
|
<span className="who">
|
||||||
{t(h.role === "assistant" ? "chat.agent" : "chat.you")} · {new Date(h.created_at).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" })}
|
{t(h.role === "assistant" ? "chat.agent" : "chat.you")} · {new Date(h.created_at).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" })}
|
||||||
</span>
|
</span>
|
||||||
<span className="snippet">{h.snippet}</span>
|
<span className="snippet">{h.snippet}</span>
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -534,14 +536,65 @@ function OlderLoader({ sessionId, afterSummary, scrollRef }: { sessionId: string
|
|||||||
{loading ? (
|
{loading ? (
|
||||||
<Spinner small />
|
<Spinner small />
|
||||||
) : (
|
) : (
|
||||||
<button className="small ghost" onClick={() => void load()}>
|
<Button type="text" size="small" onClick={() => void load()}>
|
||||||
<Icon name="arrow-up" /> {t(afterSummary ? "chat.showBeforeSummary" : "chat.loadOlder")}
|
<Icon name="arrow-up" /> {t(afterSummary ? "chat.showBeforeSummary" : "chat.loadOlder")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep the unsent message of a chat on the server, so that it survives a reload and can be continued
|
||||||
|
* on another device: it is saved shortly after typing, loaded when the chat opens and again when the
|
||||||
|
* window comes back – as long as this device has no unsaved edits of its own.
|
||||||
|
*/
|
||||||
|
function useDraftSync(sessionId: string, text: string, setText: (s: string) => void, readOnly: boolean) {
|
||||||
|
const synced = useRef<string | null>(null);
|
||||||
|
const current = useRef(text);
|
||||||
|
current.current = text;
|
||||||
|
const pull = (initial: boolean) => {
|
||||||
|
if (readOnly) return;
|
||||||
|
get<{ text: string }>(`/sessions/${sessionId}/composer-draft`)
|
||||||
|
.then((d) => {
|
||||||
|
// Only take over when nothing was typed here since the last sync (on opening: when the field is empty).
|
||||||
|
const untouched = initial ? current.current === "" : current.current === (synced.current ?? "");
|
||||||
|
if (synced.current === null) synced.current = initial && current.current !== "" ? "" : d.text;
|
||||||
|
if (untouched && d.text !== current.current) {
|
||||||
|
synced.current = d.text;
|
||||||
|
setText(d.text);
|
||||||
|
} else if (initial && current.current === "") synced.current = d.text;
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
};
|
||||||
|
useEffect(() => {
|
||||||
|
synced.current = null;
|
||||||
|
pull(true);
|
||||||
|
const again = () => document.visibilityState === "visible" && pull(false);
|
||||||
|
document.addEventListener("visibilitychange", again);
|
||||||
|
window.addEventListener("focus", again);
|
||||||
|
const h = setInterval(again, 10000);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("visibilitychange", again);
|
||||||
|
window.removeEventListener("focus", again);
|
||||||
|
clearInterval(h);
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [sessionId, readOnly]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (readOnly || synced.current === null || text === synced.current) return;
|
||||||
|
const h = setTimeout(() => {
|
||||||
|
const value = text;
|
||||||
|
put(`/sessions/${sessionId}/composer-draft`, { text: value })
|
||||||
|
.then(() => {
|
||||||
|
synced.current = value;
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, 700);
|
||||||
|
return () => clearTimeout(h);
|
||||||
|
}, [text, sessionId, readOnly]);
|
||||||
|
}
|
||||||
|
|
||||||
export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string; onMenu: () => void; onClosePane?: () => void }) {
|
export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string; onMenu: () => void; onClosePane?: () => void }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const session = useStore((s) => s.sessionById[sessionId]);
|
const session = useStore((s) => s.sessionById[sessionId]);
|
||||||
@@ -565,11 +618,13 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
// The Telegram switch in the ⋯ menu only matters with a paired bot.
|
// The Telegram switch in the ⋯ menu only matters with a paired bot.
|
||||||
const telegramPaired = useFetch<{ paired: boolean }>("/account/telegram").data?.paired ?? false;
|
const telegramPaired = useFetch<{ paired: boolean }>("/account/telegram").data?.paired ?? false;
|
||||||
const [editingInstructions, setEditingInstructions] = useState(false);
|
const [editingInstructions, setEditingInstructions] = useState(false);
|
||||||
|
const [pickingSkills, setPickingSkills] = useState(false);
|
||||||
const [showApprovals, setShowApprovals] = useState(false);
|
const [showApprovals, setShowApprovals] = useState(false);
|
||||||
const [planning, setPlanning] = useState(false);
|
const [planning, setPlanning] = useState(false);
|
||||||
const models = useModels();
|
const models = useModels();
|
||||||
const [loadError, setLoadError] = useState<string>();
|
const [loadError, setLoadError] = useState<string>();
|
||||||
const [text, setText] = useState(() => takePrefill(sessionId) ?? "");
|
const [text, setText] = useState(() => takePrefill(sessionId) ?? "");
|
||||||
|
useDraftSync(sessionId, text, setText, readOnly);
|
||||||
const [stats, setStats] = useState<SessionStats>();
|
const [stats, setStats] = useState<SessionStats>();
|
||||||
const [showStats, setShowStats] = useState(false);
|
const [showStats, setShowStats] = useState(false);
|
||||||
const [editingTitle, setEditingTitle] = useState(false);
|
const [editingTitle, setEditingTitle] = useState(false);
|
||||||
@@ -665,6 +720,9 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
return () => ro.disconnect();
|
return () => ro.disconnect();
|
||||||
}, [hasSession, sessionId]);
|
}, [hasSession, sessionId]);
|
||||||
|
|
||||||
|
// Before the early returns: a chat that is deleted while open must render the same hooks.
|
||||||
|
const [rewinding, setRewinding] = useState<Message>();
|
||||||
|
|
||||||
if (loadError) return <div className="empty">{loadError}</div>;
|
if (loadError) return <div className="empty">{loadError}</div>;
|
||||||
if (!session) return <div className="empty">{t("common.loading")}</div>;
|
if (!session) return <div className="empty">{t("common.loading")}</div>;
|
||||||
|
|
||||||
@@ -708,7 +766,6 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const [rewinding, setRewinding] = useState<Message>();
|
|
||||||
const rewind = (m: Message) => setRewinding(m);
|
const rewind = (m: Message) => setRewinding(m);
|
||||||
rewindRef.current = rewind;
|
rewindRef.current = rewind;
|
||||||
const rewindDone = async () => {
|
const rewindDone = async () => {
|
||||||
@@ -780,9 +837,9 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
return (
|
return (
|
||||||
<ChatCtx.Provider value={{ sessionId, canFork: !session.parent_id && !readOnly && !busy, canReply: !readOnly }}>
|
<ChatCtx.Provider value={{ sessionId, canFork: !session.parent_id && !readOnly && !busy, canReply: !readOnly }}>
|
||||||
<div className="topbar" data-color={session.color}>
|
<div className="topbar" data-color={session.color}>
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1 onDoubleClick={() => !readOnly && setEditingTitle(true)} title={readOnly ? undefined : t("chat.renameHint")}>
|
<h1 onDoubleClick={() => !readOnly && setEditingTitle(true)} title={readOnly ? undefined : t("chat.renameHint")}>
|
||||||
{session.parent_id && (
|
{session.parent_id && (
|
||||||
@@ -793,9 +850,9 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
{session.icon && <Icon name={session.icon} className="chat-icon" />}
|
{session.icon && <Icon name={session.icon} className="chat-icon" />}
|
||||||
{session.title || t("session.untitled")}
|
{session.title || t("session.untitled")}
|
||||||
{!readOnly && (
|
{!readOnly && (
|
||||||
<button className="ghost small title-edit" onClick={() => setEditingTitle(true)} title={t("rename.title")} aria-label={t("rename.title")}>
|
<Button type="text" size="small" className="title-edit" onClick={() => setEditingTitle(true)} title={t("rename.title")} aria-label={t("rename.title")}>
|
||||||
<Icon name="edit" />
|
<Icon name="edit" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="path">{session.cwd}</div>
|
<div className="path">{session.cwd}</div>
|
||||||
@@ -823,31 +880,36 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
<Icon name="edit" /> {t("instructions.chip")}
|
<Icon name="edit" /> {t("instructions.chip")}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{!!session.skills?.length && (
|
||||||
|
<button className="chip" style={{ border: "none" }} onClick={() => !readOnly && setPickingSkills(true)} title={session.skills.join(", ")}>
|
||||||
|
<Icon name="scroll" /> {t("skills.chip", { n: session.skills.length })}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{readOnly && <span className="chip">{t("chat.readOnly")}</span>}
|
{readOnly && <span className="chip">{t("chat.readOnly")}</span>}
|
||||||
{!readOnly && (
|
{!readOnly && (
|
||||||
<>
|
<>
|
||||||
{!session.parent_id && (
|
{!session.parent_id && (
|
||||||
<button className="small ghost hide-mobile" onClick={() => setSharing(true)} title={t("share.title")}>
|
<Button type="text" size="small" className="hide-mobile" onClick={() => setSharing(true)} title={t("share.title")}>
|
||||||
<Icon name="share" />
|
<Icon name="share" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost hide-mobile"
|
className="hide-mobile"
|
||||||
onClick={() => void tabs.openTerminal()}
|
onClick={() => void tabs.openTerminal()}
|
||||||
title={t("terminal.here")}
|
title={t("terminal.here")}
|
||||||
>
|
>
|
||||||
<Icon name="terminal" />
|
<Icon name="terminal" />
|
||||||
</button>
|
</Button>
|
||||||
<button className={`small ghost ${searching ? "active" : ""}`} onClick={() => setSearching(!searching)} title={t("chat.search")} aria-label={t("chat.search")}>
|
<Button type="text" size="small" className={searching ? "active" : ""} onClick={() => setSearching(!searching)} title={t("chat.search")} aria-label={t("chat.search")}>
|
||||||
<Icon name="search" />
|
<Icon name="search" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost hide-mobile" onClick={tabs.openFiles} title={t("files.newTab")}>
|
<Button type="text" size="small" className="hide-mobile" onClick={tabs.openFiles} title={t("files.newTab")}>
|
||||||
<Icon name="folder" />
|
<Icon name="folder" />
|
||||||
</button>
|
</Button>
|
||||||
{!session.parent_id && (
|
{!session.parent_id && (
|
||||||
<button className="small ghost hide-mobile" onClick={forkSession} disabled={busy} title={t("chat.fork")}>
|
<Button type="text" size="small" className="hide-mobile" onClick={forkSession} disabled={busy} title={t("chat.fork")}>
|
||||||
<Icon name="fork" />
|
<Icon name="fork" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<details className="menu-pop">
|
<details className="menu-pop">
|
||||||
<summary className="small ghost" title={t("chat.more")} aria-label={t("chat.more")}>
|
<summary className="small ghost" title={t("chat.more")} aria-label={t("chat.more")}>
|
||||||
@@ -886,6 +948,16 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
>
|
>
|
||||||
<Icon name="edit" /> {t("instructions.title")}
|
<Icon name="edit" /> {t("instructions.title")}
|
||||||
</a>
|
</a>
|
||||||
|
<a
|
||||||
|
href="#"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
(e.currentTarget.closest("details") as HTMLDetailsElement).open = false;
|
||||||
|
setPickingSkills(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon name="scroll" /> {t("skills.chatTitle")}
|
||||||
|
</a>
|
||||||
<ColorSwatches value={session.color} onChange={(color) => void update({ color })} />
|
<ColorSwatches value={session.color} onChange={(color) => void update({ color })} />
|
||||||
<IconPicker value={session.icon} color={session.color} onChange={(icon) => void update({ icon })} />
|
<IconPicker value={session.icon} color={session.color} onChange={(icon) => void update({ icon })} />
|
||||||
<a href="#" onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), void planJob())} title={t("job.planHint")}>
|
<a href="#" onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), void planJob())} title={t("job.planHint")}>
|
||||||
@@ -952,18 +1024,18 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
<button className="small ghost hide-mobile" onClick={() => post(`/sessions/${sessionId}/compact`).catch((e) => toast(e.message))} disabled={busy} title={t("command.compact")}>
|
<Button type="text" size="small" className="hide-mobile" onClick={() => post(`/sessions/${sessionId}/compact`).catch((e) => toast(e.message))} disabled={busy} title={t("command.compact")}>
|
||||||
<Icon name="compact" />
|
<Icon name="compact" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost danger hide-mobile" onClick={remove} title={t("chat.delete")}>
|
<Button type="text" danger size="small" className="hide-mobile" onClick={remove} title={t("chat.delete")}>
|
||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{onClosePane && (
|
{onClosePane && (
|
||||||
<button className="small ghost" onClick={onClosePane} title={t("chat.closePane")} aria-label={t("chat.closePane")}>
|
<Button type="text" size="small" onClick={onClosePane} title={t("chat.closePane")} aria-label={t("chat.closePane")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{gallery && (
|
{gallery && (
|
||||||
@@ -1055,42 +1127,43 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
|||||||
{errors?.map((e) => (
|
{errors?.map((e) => (
|
||||||
<div key={e.id} className="error-box" role="alert">
|
<div key={e.id} className="error-box" role="alert">
|
||||||
<span>{e.message}</span>
|
<span>{e.message}</span>
|
||||||
<button className="small ghost" onClick={() => dismissError(sessionId, e.id)} aria-label={t("common.close")}>
|
<Button type="text" size="small" onClick={() => dismissError(sessionId, e.id)} aria-label={t("common.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{session.agent === "plan" && !busy && lastIsAssistant && (
|
{session.agent === "plan" && !busy && lastIsAssistant && (
|
||||||
<div className="row" style={{ justifyContent: "center", margin: "12px 0" }}>
|
<div className="row" style={{ justifyContent: "center", margin: "12px 0" }}>
|
||||||
<button
|
<Button type="primary"
|
||||||
className="primary"
|
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
await update({ agent: "build" });
|
await update({ agent: "build" });
|
||||||
await send(t("plan.implementPrompt"), []);
|
await send(t("plan.implementPrompt"), []);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{t("plan.implement")}
|
{t("plan.implement")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{(!following || scrolled) && (
|
{(!following || scrolled) && (
|
||||||
<div className="jump-latest">
|
<div className="jump-latest">
|
||||||
<button onClick={jumpPrevOwn} title={t("chat.jumpPrevOwn")} aria-label={t("chat.jumpPrevOwn")}>
|
<Button onClick={jumpPrevOwn} title={t("chat.jumpPrevOwn")} aria-label={t("chat.jumpPrevOwn")}>
|
||||||
<Icon name="arrow-up" />
|
<Icon name="arrow-up" />
|
||||||
</button>
|
</Button>
|
||||||
{!following && <button className="primary" onClick={jumpToLatest} title={t("chat.jumpLatest")} aria-label={t("chat.jumpLatest")}>
|
{!following && <Button type="primary" onClick={jumpToLatest} title={t("chat.jumpLatest")} aria-label={t("chat.jumpLatest")}>
|
||||||
<Icon name="arrow-down" />
|
<Icon name="arrow-down" />
|
||||||
</button>}
|
</Button>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{showApprovals && <ProjectPermissions sessionId={sessionId} cwd={session.cwd} onClose={() => setShowApprovals(false)} />}
|
{showApprovals && <ProjectPermissions sessionId={sessionId} cwd={session.cwd} onClose={() => setShowApprovals(false)} />}
|
||||||
|
{pickingSkills && <ChatSkillsDialog sessionId={sessionId} cwd={session.cwd} active={session.skills ?? []} onClose={() => setPickingSkills(false)} />}
|
||||||
{editingInstructions && <InstructionsDialog sessionId={sessionId} value={session.instructions ?? ""} onClose={() => setEditingInstructions(false)} />}
|
{editingInstructions && <InstructionsDialog sessionId={sessionId} value={session.instructions ?? ""} onClose={() => setEditingInstructions(false)} />}
|
||||||
{editingTitle && <RenameDialog sessionId={sessionId} title={session.title} onClose={() => setEditingTitle(false)} />}
|
{editingTitle && <RenameDialog sessionId={sessionId} title={session.title} onClose={() => setEditingTitle(false)} />}
|
||||||
{sharing && <ShareDialog sessionId={sessionId} onClose={() => setSharing(false)} />}
|
{sharing && <ShareDialog sessionId={sessionId} onClose={() => setSharing(false)} />}
|
||||||
{rewinding && <RewindDialog sessionId={sessionId} messageId={rewinding.id} onDone={rewindDone} onClose={() => setRewinding(undefined)} />}
|
{rewinding && <RewindDialog sessionId={sessionId} messageId={rewinding.id} onDone={rewindDone} onClose={() => setRewinding(undefined)} />}
|
||||||
{!readOnly && isDraftChat(session.cwd) && <DraftBar sessionId={sessionId} />}
|
{!readOnly && isDraftChat(session.cwd) && <DraftBar sessionId={sessionId} />}
|
||||||
|
{!readOnly && isIssueChat(session.cwd) && <IssueBar sessionId={sessionId} />}
|
||||||
{!readOnly && <OutboxBar sessionId={sessionId} />}
|
{!readOnly && <OutboxBar sessionId={sessionId} />}
|
||||||
{!readOnly && <QueueList sessionId={sessionId} busy={busy} />}
|
{!readOnly && <QueueList sessionId={sessionId} busy={busy} />}
|
||||||
{readOnly ? (
|
{readOnly ? (
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
|
import { Button, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { TemplatePicker } from "./TemplatePicker";
|
import { TemplatePicker } from "./TemplatePicker";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { formatSize, imageSrc } from "./FileFigure";
|
import { formatSize, imageSrc } from "./FileFigure";
|
||||||
import { uploadFile } from "../api";
|
import { uploadBatch } from "../uploads";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useAgents, useFetch, useModels } from "../hooks";
|
import { useAgents, useFetch, useModels } from "../hooks";
|
||||||
import { useT, type Key } from "../i18n";
|
import { useT, type Key } from "../i18n";
|
||||||
|
import { useStore } from "../store";
|
||||||
|
import { post } from "../api";
|
||||||
import type { ImageData, Session } from "../types";
|
import type { ImageData, Session } from "../types";
|
||||||
import { ModelSelect } from "./ModelSelect";
|
import { ModelSelect } from "./ModelSelect";
|
||||||
import { EffortSelect } from "./Regenerate";
|
import { EffortSelect } from "./Regenerate";
|
||||||
@@ -55,7 +59,7 @@ export function Composer({
|
|||||||
busy: boolean;
|
busy: boolean;
|
||||||
text: string;
|
text: string;
|
||||||
setText: (s: string) => void;
|
setText: (s: string) => void;
|
||||||
onSend: (text: string, images: ImageData[], effort?: string) => void;
|
onSend: (text: string, images: ImageData[], effort?: string) => void | Promise<void>;
|
||||||
onAbort: () => void;
|
onAbort: () => void;
|
||||||
onUpdate: (patch: Partial<Session>) => void;
|
onUpdate: (patch: Partial<Session>) => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -145,11 +149,20 @@ export function Composer({
|
|||||||
return [...mine, ...cmds].slice(0, 12);
|
return [...mine, ...cmds].slice(0, 12);
|
||||||
}, [text, cmdData, snippets, t, mention, mentionHits]);
|
}, [text, cmdData, snippets, t, mention, mentionHits]);
|
||||||
|
|
||||||
const send = () => {
|
// Messages waiting for the agent: a further Enter on the empty field (or Ctrl+Enter with text) delivers them at once.
|
||||||
|
const queued = useStore((s) => (s.queue[session.id] ?? []).length);
|
||||||
|
const force = () => post(`/sessions/${session.id}/queue/force`).catch((e) => toast(e.message));
|
||||||
|
|
||||||
|
const send = (thenForce = false) => {
|
||||||
|
if (!text.trim() && images.length === 0 && files.length === 0 && busy && queued > 0) {
|
||||||
|
void force();
|
||||||
|
return;
|
||||||
|
}
|
||||||
if ((!text.trim() && images.length === 0 && files.length === 0) || uploading > 0) return;
|
if ((!text.trim() && images.length === 0 && files.length === 0) || uploading > 0) return;
|
||||||
// Files are referenced by path; the agent reads them with its tools.
|
// Files are referenced by path; the agent reads them with its tools.
|
||||||
const refs = files.length ? `\n\n${t("composer.attachedFiles")}\n${files.map((f) => `- ${f.path} (${formatSize(f.size)})`).join("\n")}` : "";
|
const refs = files.length ? `\n\n${t("composer.attachedFiles")}\n${files.map((f) => `- ${f.path} (${formatSize(f.size)})`).join("\n")}` : "";
|
||||||
onSend(`${text}${refs}`, images, effort);
|
const sent = onSend(`${text}${refs}`, images, effort);
|
||||||
|
if (thenForce && busy) void Promise.resolve(sent).then(force);
|
||||||
setEffort("");
|
setEffort("");
|
||||||
setImages([]);
|
setImages([]);
|
||||||
setFiles([]);
|
setFiles([]);
|
||||||
@@ -174,11 +187,22 @@ export function Composer({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Ctrl+J inserts a new line (like Shift+Enter, and like Ctrl+J / Shift+Enter in the terminal client).
|
||||||
|
if (e.key.toLowerCase() === "j" && e.ctrlKey && !e.altKey && !e.metaKey && !e.nativeEvent.isComposing) {
|
||||||
|
e.preventDefault();
|
||||||
|
const el = e.currentTarget as HTMLTextAreaElement;
|
||||||
|
const a = el.selectionStart ?? text.length;
|
||||||
|
const b = el.selectionEnd ?? a;
|
||||||
|
setText(`${text.slice(0, a)}\n${text.slice(b)}`);
|
||||||
|
requestAnimationFrame(() => ref.current?.setSelectionRange(a + 1, a + 1));
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Enter sends on desktop; on touch devices Enter inserts a newline.
|
// Enter sends on desktop; on touch devices Enter inserts a newline.
|
||||||
const touch = matchMedia("(pointer: coarse)").matches;
|
const touch = matchMedia("(pointer: coarse)").matches;
|
||||||
if (e.key === "Enter" && !e.shiftKey && !touch && !e.nativeEvent.isComposing) {
|
if (e.key === "Enter" && !e.shiftKey && !touch && !e.nativeEvent.isComposing) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
send();
|
// Ctrl/Cmd+Enter while the agent works: queue the message and interrupt the step so it is read at once.
|
||||||
|
send(e.ctrlKey || e.metaKey);
|
||||||
}
|
}
|
||||||
if (e.key === "Escape" && busy) onAbort();
|
if (e.key === "Escape" && busy) onAbort();
|
||||||
};
|
};
|
||||||
@@ -201,9 +225,8 @@ export function Composer({
|
|||||||
await fetch(`/api/files/create?`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path: `${session.cwd}/.codecraft/uploads`, dir: true }) });
|
await fetch(`/api/files/create?`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path: `${session.cwd}/.codecraft/uploads`, dir: true }) });
|
||||||
// Keep uploads out of git status without touching the project's .gitignore.
|
// Keep uploads out of git status without touching the project's .gitignore.
|
||||||
await fetch(`/api/files/upload?path=${encodeURIComponent(`${session.cwd}/.codecraft/uploads/.gitignore`)}`, { method: "PUT", body: "*\n", credentials: "same-origin" });
|
await fetch(`/api/files/upload?path=${encodeURIComponent(`${session.cwd}/.codecraft/uploads/.gitignore`)}`, { method: "PUT", body: "*\n", credentials: "same-origin" });
|
||||||
await uploadFile(path, f).catch((e) => {
|
const sent = await uploadBatch([{ file: f, path }]);
|
||||||
throw new Error(`${f.name}: ${e.message}`);
|
if (!sent.length) throw new Error(f.name);
|
||||||
});
|
|
||||||
setFiles((cur) => [...cur, { name: f.name, path, size: f.size }]);
|
setFiles((cur) => [...cur, { name: f.name, path, size: f.size }]);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
toast(e.message ?? String(e));
|
toast(e.message ?? String(e));
|
||||||
@@ -275,9 +298,9 @@ export function Composer({
|
|||||||
<div className="att file" key={f.path} title={f.path}>
|
<div className="att file" key={f.path} title={f.path}>
|
||||||
<span><Icon name="file" /> {f.name}</span>
|
<span><Icon name="file" /> {f.name}</span>
|
||||||
<small>{formatSize(f.size)}</small>
|
<small>{formatSize(f.size)}</small>
|
||||||
<button onClick={() => removeFile(f.path)} aria-label={t("common.remove")}>
|
<Button onClick={() => removeFile(f.path)} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{uploading > 0 && (
|
{uploading > 0 && (
|
||||||
@@ -288,9 +311,9 @@ export function Composer({
|
|||||||
{images.map((img, i) => (
|
{images.map((img, i) => (
|
||||||
<div className="att" key={i}>
|
<div className="att" key={i}>
|
||||||
<img src={imageSrc(img)} alt="" />
|
<img src={imageSrc(img)} alt="" />
|
||||||
<button onClick={() => setImages((cur) => cur.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
<Button onClick={() => setImages((cur) => cur.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -331,7 +354,7 @@ export function Composer({
|
|||||||
/>
|
/>
|
||||||
<div className="composer-bar">
|
<div className="composer-bar">
|
||||||
<div className="composer-options">
|
<div className="composer-options">
|
||||||
<select
|
<Select
|
||||||
className="mode-select"
|
className="mode-select"
|
||||||
value={session.agent}
|
value={session.agent}
|
||||||
onChange={(e) => onUpdate({ agent: e.target.value })}
|
onChange={(e) => onUpdate({ agent: e.target.value })}
|
||||||
@@ -344,18 +367,21 @@ export function Composer({
|
|||||||
{a.name}
|
{a.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
{session.agent === "craft" && (
|
{session.agent === "craft" && (
|
||||||
<div className="mode-tabs" role="tablist" aria-label={t("craft.mode")} title={t("craft.modeHint")}>
|
<Segmented
|
||||||
<button className={session.clean_room !== false ? "active" : ""} onClick={() => onUpdate({ clean_room: true })}>
|
size="small"
|
||||||
{t("craft.cleanRoom")}
|
aria-label={t("craft.mode")}
|
||||||
</button>
|
title={t("craft.modeHint")}
|
||||||
<button className={session.clean_room === false ? "active deep" : ""} onClick={() => onUpdate({ clean_room: false })}>
|
value={session.clean_room === false ? "deep" : "clean"}
|
||||||
{t("craft.deep")}
|
onChange={(v) => onUpdate({ clean_room: v === "clean" })}
|
||||||
</button>
|
options={[
|
||||||
</div>
|
{ value: "clean", label: t("craft.cleanRoom") },
|
||||||
|
{ value: "deep", label: t("craft.deep") },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
<select
|
<Select
|
||||||
value={session.permission_mode}
|
value={session.permission_mode}
|
||||||
onChange={(e) => onUpdate({ permission_mode: e.target.value as Session["permission_mode"] })}
|
onChange={(e) => onUpdate({ permission_mode: e.target.value as Session["permission_mode"] })}
|
||||||
title={t("composer.permissionMode")}
|
title={t("composer.permissionMode")}
|
||||||
@@ -364,12 +390,12 @@ export function Composer({
|
|||||||
<option value="default">{t("permissionMode.default")}</option>
|
<option value="default">{t("permissionMode.default")}</option>
|
||||||
<option value="accept_edits">{t("permissionMode.accept_edits")}</option>
|
<option value="accept_edits">{t("permissionMode.accept_edits")}</option>
|
||||||
<option value="bypass">{t("permissionMode.bypass")}</option>
|
<option value="bypass">{t("permissionMode.bypass")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<ModelSelect value={session.model} onChange={(m) => onUpdate({ model: m })} title={t("composer.model")} />
|
<ModelSelect value={session.model} onChange={(m) => onUpdate({ model: m })} title={t("composer.model")} />
|
||||||
{reasoning && <EffortSelect value={effort} onChange={setEffort} compact />}
|
{reasoning && <EffortSelect value={effort} onChange={setEffort} compact />}
|
||||||
<button className="ghost" style={{ padding: "3px 6px" }} onClick={() => setPicker(true)} title={t("templates.title")}>
|
<Button type="text" style={{ padding: "3px 6px" }} onClick={() => setPicker(true)} title={t("templates.title")}>
|
||||||
<Icon name="template" />
|
<Icon name="template" />
|
||||||
</button>
|
</Button>
|
||||||
{picker && (
|
{picker && (
|
||||||
<TemplatePicker
|
<TemplatePicker
|
||||||
onClose={() => setPicker(false)}
|
onClose={() => setPicker(false)}
|
||||||
@@ -380,15 +406,15 @@ export function Composer({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<button
|
<Button
|
||||||
className={`ghost ${preview ? "active" : ""}`}
|
type="text" className={preview ? "active" : ""}
|
||||||
style={{ padding: "3px 6px" }}
|
style={{ padding: "3px 6px" }}
|
||||||
onClick={() => setPreview(!preview)}
|
onClick={() => setPreview(!preview)}
|
||||||
aria-pressed={preview}
|
aria-pressed={preview}
|
||||||
title={t(preview ? "composer.previewEdit" : "composer.preview")}
|
title={t(preview ? "composer.previewEdit" : "composer.preview")}
|
||||||
>
|
>
|
||||||
<Icon name={preview ? "edit" : "eye"} />
|
<Icon name={preview ? "edit" : "eye"} />
|
||||||
</button>
|
</Button>
|
||||||
<VoiceButton onText={(d) => setText(text ? `${text.replace(/\s+$/, "")} ${d}` : d)} onInterim={setInterim} />
|
<VoiceButton onText={(d) => setText(text ? `${text.replace(/\s+$/, "")} ${d}` : d)} onInterim={setInterim} />
|
||||||
<label className="ghost" style={{ cursor: "pointer", padding: "3px 6px" }} title={t("composer.attach")}>
|
<label className="ghost" style={{ cursor: "pointer", padding: "3px 6px" }} title={t("composer.attach")}>
|
||||||
<Icon name="clip" />
|
<Icon name="clip" />
|
||||||
@@ -397,13 +423,13 @@ export function Composer({
|
|||||||
</div>
|
</div>
|
||||||
<div className="composer-actions">
|
<div className="composer-actions">
|
||||||
{busy && (
|
{busy && (
|
||||||
<button className="danger" onClick={onAbort} title="Esc">
|
<Button danger onClick={onAbort} title="Esc">
|
||||||
<Icon name="stop" /> {t("composer.stop")}
|
<Icon name="stop" /> {t("composer.stop")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button className="primary" onClick={send} disabled={uploading > 0 || (!text.trim() && images.length === 0 && files.length === 0)}>
|
<Button type="primary" onClick={() => send()} disabled={uploading > 0 || (!text.trim() && images.length === 0 && files.length === 0)}>
|
||||||
{busy ? t("composer.queue") : t("composer.send")}
|
{busy ? t("composer.queue") : t("composer.send")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get } from "../api";
|
import { get } from "../api";
|
||||||
import { getLang, useT } from "../i18n";
|
import { getLang, useT } from "../i18n";
|
||||||
@@ -132,44 +134,44 @@ export function CronBuilder({ value, onChange }: { value: string; onChange: (cro
|
|||||||
<div className="cron-builder">
|
<div className="cron-builder">
|
||||||
<div className="cron-modes" role="radiogroup" aria-label={t("cron.label")}>
|
<div className="cron-modes" role="radiogroup" aria-label={t("cron.label")}>
|
||||||
{modes.map((m) => (
|
{modes.map((m) => (
|
||||||
<button key={m} type="button" role="radio" aria-checked={s.mode === m} className={`chip-btn ${s.mode === m ? "active" : ""}`} onClick={() => set({ mode: m })}>
|
<Button key={m} role="radio" aria-checked={s.mode === m} size="small" shape="round" type={s.mode === m ? "primary" : "default"} onClick={() => set({ mode: m })}>
|
||||||
{t(`cron.mode.${m}` as const)}
|
{t(`cron.mode.${m}` as const)}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="cron-fields">
|
<div className="cron-fields">
|
||||||
{s.mode === "minutes" && (
|
{s.mode === "minutes" && (
|
||||||
<label>
|
<label>
|
||||||
{t("cron.every")}
|
{t("cron.every")}
|
||||||
<select value={s.every} onChange={(e) => set({ every: Number(e.target.value) })}>
|
<Select value={s.every} onChange={(e) => set({ every: Number(e.target.value) })}>
|
||||||
{MINUTE_STEPS.map((n) => (
|
{MINUTE_STEPS.map((n) => (
|
||||||
<option key={n} value={n}>
|
<option key={n} value={n}>
|
||||||
{n}
|
{n}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
{t("cron.minutes")}
|
{t("cron.minutes")}
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
{s.mode === "hourly" && (
|
{s.mode === "hourly" && (
|
||||||
<label>
|
<label>
|
||||||
{t("cron.atMinute")}
|
{t("cron.atMinute")}
|
||||||
<input type="number" min={0} max={59} value={s.minute} onChange={(e) => set({ minute: Math.min(59, Math.max(0, Number(e.target.value) || 0)) })} />
|
<Input type="number" min={0} max={59} value={s.minute} onChange={(e) => set({ minute: Math.min(59, Math.max(0, Number(e.target.value) || 0)) })} />
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
{s.mode === "weekly" && (
|
{s.mode === "weekly" && (
|
||||||
<div className="cron-days" role="group" aria-label={t("cron.days")}>
|
<div className="cron-days" role="group" aria-label={t("cron.days")}>
|
||||||
{WEEK.map((d) => (
|
{WEEK.map((d) => (
|
||||||
<button
|
<Button
|
||||||
key={d}
|
key={d}
|
||||||
type="button"
|
|
||||||
aria-pressed={s.days.includes(d)}
|
aria-pressed={s.days.includes(d)}
|
||||||
className={`chip-btn ${s.days.includes(d) ? "active" : ""}`}
|
size="small" shape="round" type={s.days.includes(d) ? "primary" : "default"}
|
||||||
title={dayName(d, "long")}
|
title={dayName(d, "long")}
|
||||||
onClick={() => set({ days: s.days.includes(d) ? s.days.filter((x) => x !== d) : [...s.days, d] })}
|
onClick={() => set({ days: s.days.includes(d) ? s.days.filter((x) => x !== d) : [...s.days, d] })}
|
||||||
>
|
>
|
||||||
{dayName(d, "short")}
|
{dayName(d, "short")}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
<button type="button" className="link-btn" onClick={() => set({ days: [1, 2, 3, 4, 5] })}>
|
<button type="button" className="link-btn" onClick={() => set({ days: [1, 2, 3, 4, 5] })}>
|
||||||
{t("cron.workdays")}
|
{t("cron.workdays")}
|
||||||
@@ -179,24 +181,24 @@ export function CronBuilder({ value, onChange }: { value: string; onChange: (cro
|
|||||||
{s.mode === "monthly" && (
|
{s.mode === "monthly" && (
|
||||||
<label>
|
<label>
|
||||||
{t("cron.onDay")}
|
{t("cron.onDay")}
|
||||||
<select value={s.dom} onChange={(e) => set({ dom: Number(e.target.value) })}>
|
<Select value={s.dom} onChange={(e) => set({ dom: Number(e.target.value) })}>
|
||||||
{Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
|
{Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
|
||||||
<option key={d} value={d}>
|
<option key={d} value={d}>
|
||||||
{d}.
|
{d}.
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
{(s.mode === "daily" || s.mode === "weekly" || s.mode === "monthly") && (
|
{(s.mode === "daily" || s.mode === "weekly" || s.mode === "monthly") && (
|
||||||
<label>
|
<label>
|
||||||
{t("cron.at")}
|
{t("cron.at")}
|
||||||
<input type="time" value={s.time} onChange={(e) => e.target.value && set({ time: e.target.value })} />
|
<Input type="time" value={s.time} onChange={(e) => e.target.value && set({ time: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
{s.mode === "custom" && (
|
{s.mode === "custom" && (
|
||||||
<label className="cron-custom">
|
<label className="cron-custom">
|
||||||
<input className="mono" value={s.custom} placeholder="0 3 * * *" spellCheck={false} onChange={(e) => set({ custom: e.target.value })} />
|
<Input className="mono" value={s.custom} placeholder="0 3 * * *" spellCheck={false} onChange={(e) => set({ custom: e.target.value })} />
|
||||||
<small className="hint">{t("cron.customHint")}</small>
|
<small className="hint">{t("cron.customHint")}</small>
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Checkbox } from "antd";
|
||||||
export function Diff({ diff }: { diff: string }) {
|
export function Diff({ diff }: { diff: string }) {
|
||||||
const lines = diff.replace(/\n+$/, "").split("\n");
|
const lines = diff.replace(/\n+$/, "").split("\n");
|
||||||
return (
|
return (
|
||||||
@@ -43,10 +44,9 @@ export function HunkDiff({ diff, selected, onToggle }: { diff: string; selected:
|
|||||||
))}
|
))}
|
||||||
{hunks.map((h, i) => (
|
{hunks.map((h, i) => (
|
||||||
<div key={i} className={`hunk-block ${selected[i] ? "" : "off"}`}>
|
<div key={i} className={`hunk-block ${selected[i] ? "" : "off"}`}>
|
||||||
<label className="hunk-head">
|
<Checkbox className="hunk-head" checked={!!selected[i]} onChange={() => onToggle(i)}>
|
||||||
<input type="checkbox" checked={!!selected[i]} onChange={() => onToggle(i)} />
|
|
||||||
<span>{h[0]}</span>
|
<span>{h[0]}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
{h.slice(1).map((l, j) => (
|
{h.slice(1).map((l, j) => (
|
||||||
<div key={j} className={l.startsWith("+") ? "add" : l.startsWith("-") ? "del" : ""}>
|
<div key={j} className={l.startsWith("+") ? "add" : l.startsWith("-") ? "del" : ""}>
|
||||||
{l || " "}
|
{l || " "}
|
||||||
|
|||||||
@@ -1,11 +1,28 @@
|
|||||||
|
import { Button, Checkbox, Input, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { get, post, put } from "../api";
|
import { get, post, put } from "../api";
|
||||||
import { fmtCompact, fmtCost, fmtRelative, useT } from "../i18n";
|
import { fmtCompact, fmtCost, fmtRelative, useT } from "../i18n";
|
||||||
import { navigate } from "../router";
|
import { navigate } from "../router";
|
||||||
import { confirmDialog, toast } from "../dialogs";
|
import { choiceDialog, confirmDialog, promptDialog, toast } from "../dialogs";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { Spinner } from "./Activity";
|
import { Spinner } from "./Activity";
|
||||||
import { ModelSelect } from "./ModelSelect";
|
import { ModelSelect } from "./ModelSelect";
|
||||||
|
import { RecreateDialog } from "./FactoryDraft";
|
||||||
|
import { ChatOverlay, openFactoryChat } from "./FactoryChat";
|
||||||
|
import { ReleaseDialog, ReleasesPanel, type ReleaseRow } from "./FactoryRelease";
|
||||||
|
|
||||||
|
interface PrInfo {
|
||||||
|
number: number;
|
||||||
|
html_url: string;
|
||||||
|
title: string;
|
||||||
|
state: "open" | "merged" | "closed";
|
||||||
|
mergeable: boolean | null;
|
||||||
|
changed_files: number | null;
|
||||||
|
additions: number | null;
|
||||||
|
deletions: number | null;
|
||||||
|
head: string;
|
||||||
|
}
|
||||||
|
|
||||||
type Phase = "review" | "build" | "qa";
|
type Phase = "review" | "build" | "qa";
|
||||||
const PHASES: Phase[] = ["review", "build", "qa"];
|
const PHASES: Phase[] = ["review", "build", "qa"];
|
||||||
@@ -15,7 +32,9 @@ interface PhaseCfg {
|
|||||||
agent: string;
|
agent: string;
|
||||||
permission_mode: string;
|
permission_mode: string;
|
||||||
timeout_minutes: number;
|
timeout_minutes: number;
|
||||||
|
max_attempts: number;
|
||||||
extra_prompt: string;
|
extra_prompt: string;
|
||||||
|
skills: string[];
|
||||||
}
|
}
|
||||||
interface RepoCfg {
|
interface RepoCfg {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -24,6 +43,7 @@ interface RepoCfg {
|
|||||||
token: string;
|
token: string;
|
||||||
label: string;
|
label: string;
|
||||||
max_parallel: number;
|
max_parallel: number;
|
||||||
|
max_rework: number;
|
||||||
allowed_users: string[];
|
allowed_users: string[];
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
review: PhaseCfg;
|
review: PhaseCfg;
|
||||||
@@ -57,10 +77,25 @@ interface Issue {
|
|||||||
state: string;
|
state: string;
|
||||||
note: string;
|
note: string;
|
||||||
pr_url: string;
|
pr_url: string;
|
||||||
|
branch: string;
|
||||||
rounds: number;
|
rounds: number;
|
||||||
|
/** Newest phase chat that still exists. */
|
||||||
|
/** The pull request is merged (merging comes after a positive acceptance, closing after the merge). */
|
||||||
|
merged?: boolean;
|
||||||
|
chat_session?: string;
|
||||||
|
chat_phase?: Phase;
|
||||||
created_at: number;
|
created_at: number;
|
||||||
updated_at: number;
|
updated_at: number;
|
||||||
}
|
}
|
||||||
|
interface BacklogIssue {
|
||||||
|
repo: string;
|
||||||
|
number: number;
|
||||||
|
title: string;
|
||||||
|
author: string;
|
||||||
|
url: string;
|
||||||
|
allowed: boolean;
|
||||||
|
labels: string[];
|
||||||
|
}
|
||||||
interface Run {
|
interface Run {
|
||||||
id: string;
|
id: string;
|
||||||
repo: string;
|
repo: string;
|
||||||
@@ -85,12 +120,21 @@ interface RepoInfo {
|
|||||||
has_token: boolean;
|
has_token: boolean;
|
||||||
models: Record<Phase, string>;
|
models: Record<Phase, string>;
|
||||||
running: number;
|
running: number;
|
||||||
|
version?: string | null;
|
||||||
|
}
|
||||||
|
interface Power {
|
||||||
|
on: boolean;
|
||||||
|
/** Agents that are working right now. */
|
||||||
|
active: number;
|
||||||
|
state: "running" | "stopping" | "stopped";
|
||||||
}
|
}
|
||||||
interface Overview {
|
interface Overview {
|
||||||
area: boolean;
|
area: boolean;
|
||||||
|
power?: Power;
|
||||||
repos: RepoInfo[];
|
repos: RepoInfo[];
|
||||||
issues: Issue[];
|
issues: Issue[];
|
||||||
runs: Run[];
|
runs: Run[];
|
||||||
|
releases: ReleaseRow[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Board columns: a column collects one or more issue states. */
|
/** Board columns: a column collects one or more issue states. */
|
||||||
@@ -98,10 +142,10 @@ const COLUMNS: { id: string; states: string[] }[] = [
|
|||||||
{ id: "review", states: ["new", "review"] },
|
{ id: "review", states: ["new", "review"] },
|
||||||
{ id: "question", states: ["question"] },
|
{ id: "question", states: ["question"] },
|
||||||
{ id: "approved", states: ["approved"] },
|
{ id: "approved", states: ["approved"] },
|
||||||
{ id: "build", states: ["building", "built"] },
|
{ id: "build", states: ["building", "rework"] },
|
||||||
{ id: "qa", states: ["qa"] },
|
{ id: "qa", states: ["qa", "testing"] },
|
||||||
{ id: "done", states: ["done"] },
|
|
||||||
{ id: "failed", states: ["failed", "rejected"] },
|
{ id: "failed", states: ["failed", "rejected"] },
|
||||||
|
{ id: "done", states: ["done"] },
|
||||||
];
|
];
|
||||||
|
|
||||||
const KIND_NAME: Record<string, string> = { gitea: "Gitea", github: "GitHub", gitlab: "GitLab" };
|
const KIND_NAME: Record<string, string> = { gitea: "Gitea", github: "GitHub", gitlab: "GitLab" };
|
||||||
@@ -118,47 +162,102 @@ function fmtDuration(ms: number) {
|
|||||||
const runMs = (r: Run, now: number) => (r.ended_at ?? now) - r.started_at;
|
const runMs = (r: Run, now: number) => (r.ended_at ?? now) - r.started_at;
|
||||||
|
|
||||||
/** Software factory: spec issues in Gitea are reviewed, built and accepted by agents with a model per phase. */
|
/** Software factory: spec issues in Gitea are reviewed, built and accepted by agents with a model per phase. */
|
||||||
export function Factory({ onMenu }: { onMenu: () => void }) {
|
export function Factory({ onMenu, overlayId }: { onMenu: () => void; overlayId?: string }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const [tab, setTab] = useState<"overview" | "settings">("overview");
|
const [tab, setTab] = useState<"overview" | "settings">("overview");
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{t("factory.title")}</h1>
|
<h1>{t("factory.title")}</h1>
|
||||||
</div>
|
</div>
|
||||||
<div className="segmented">
|
<Segmented
|
||||||
{(["overview", "settings"] as const).map((x) => (
|
value={tab}
|
||||||
<button key={x} className={tab === x ? "active" : ""} onClick={() => setTab(x)}>
|
onChange={(x) => setTab(x)}
|
||||||
{t(`factory.tab.${x}` as any)}
|
options={(["overview", "settings"] as const).map((x) => ({ value: x, label: t(`factory.tab.${x}` as any) }))}
|
||||||
</button>
|
/>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="page">
|
<div className="page">
|
||||||
<div className="page-inner" style={{ maxWidth: 1280 }}>
|
<div className="page-inner" style={{ maxWidth: tab === "overview" ? "none" : 1280 }}>
|
||||||
{tab === "overview" ? <FactoryOverview onSettings={() => setTab("settings")} /> : <FactorySettings />}
|
{tab === "overview" ? <FactoryOverview onSettings={() => setTab("settings")} /> : <FactorySettings />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{overlayId && <ChatOverlay id={overlayId} />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A button inside an issue card (the card itself is a button, so this is a span with the button role). */
|
||||||
|
function CardAction({ children, onClick, title, primary, disabled }: { children: React.ReactNode; onClick: () => void; title?: string; primary?: boolean; disabled?: boolean }) {
|
||||||
|
const run = (e: React.SyntheticEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
if (!disabled) onClick();
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<span role="button" tabIndex={disabled ? -1 : 0} aria-disabled={disabled} className={`factory-card-action ${primary ? "primary" : ""} ${disabled ? "disabled" : ""}`} title={title} onClick={run} onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && run(e)}>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The factory's main switch, coloured by state: green = running, yellow = stopping, red = stopped. */
|
||||||
|
function PowerSwitch({ power, onToggle }: { power: Power; onToggle: (on: boolean) => void }) {
|
||||||
|
const t = useT();
|
||||||
|
const label = power.state === "running" ? t("factory.power.running") : power.state === "stopping" ? t("factory.power.stopping", { n: power.active }) : t("factory.power.stopped");
|
||||||
|
const hint = power.on ? t("factory.power.stopHint") : t("factory.power.startHint");
|
||||||
|
return (
|
||||||
|
<button type="button" role="switch" aria-checked={power.on} className={`factory-power ${power.state}`} onClick={() => onToggle(!power.on)} title={hint}>
|
||||||
|
<span className="factory-power-track">
|
||||||
|
<span className="factory-power-knob" />
|
||||||
|
</span>
|
||||||
|
<span className="factory-power-text">
|
||||||
|
<b>{label}</b>
|
||||||
|
<span className="hint">{hint}</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const [data, setData] = useState<Overview>();
|
const [data, setData] = useState<Overview>();
|
||||||
const [repo, setRepo] = useState<string>("");
|
const [repo, setRepoState] = useState<string>(() => {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem("codecraft.factoryRepo") ?? "";
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const setRepo = (r: string) => {
|
||||||
|
setRepoState(r);
|
||||||
|
try {
|
||||||
|
localStorage.setItem("codecraft.factoryRepo", r);
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
const [sel, setSel] = useState<string>("");
|
const [sel, setSel] = useState<string>("");
|
||||||
const [now, setNow] = useState(Date.now());
|
const [now, setNow] = useState(Date.now());
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [recreate, setRecreate] = useState(false);
|
||||||
|
|
||||||
const reload = () =>
|
const [backlog, setBacklog] = useState<BacklogIssue[]>([]);
|
||||||
get<Overview>("/factory/overview")
|
const [backlogErrors, setBacklogErrors] = useState<string[]>([]);
|
||||||
|
const loadBacklog = (refresh = false) =>
|
||||||
|
get<{ issues: BacklogIssue[]; errors: string[] }>(`/factory/backlog${refresh ? "?refresh=1" : ""}`)
|
||||||
|
.then((r) => {
|
||||||
|
setBacklog(r.issues);
|
||||||
|
setBacklogErrors(r.errors);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
const reload = () => {
|
||||||
|
void loadBacklog();
|
||||||
|
return get<Overview>("/factory/overview")
|
||||||
.then(setData)
|
.then(setData)
|
||||||
.catch((e) => toast(e.message));
|
.catch((e) => toast(e.message));
|
||||||
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void reload();
|
void reload();
|
||||||
const h = setInterval(() => {
|
const h = setInterval(() => {
|
||||||
@@ -168,6 +267,11 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
return () => clearInterval(h);
|
return () => clearInterval(h);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// A remembered project that no longer exists falls back to "all".
|
||||||
|
useEffect(() => {
|
||||||
|
if (data && repo && !data.repos.some((r) => r.url === repo)) setRepo("");
|
||||||
|
}, [data, repo]);
|
||||||
|
|
||||||
const newProject = async () => {
|
const newProject = async () => {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
@@ -179,18 +283,103 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const [releaseRepo, setReleaseRepo] = useState("");
|
||||||
|
const startRelease = async () => {
|
||||||
|
if (!data) return;
|
||||||
|
let target = repo;
|
||||||
|
if (!target) {
|
||||||
|
const repos = data.repos.filter((r) => r.enabled);
|
||||||
|
if (repos.length === 1) target = repos[0].url;
|
||||||
|
else {
|
||||||
|
const pick = await choiceDialog({ message: t("issues.pickRepo"), choices: repos.map((r) => ({ value: r.url, label: repoName(r.url) })) });
|
||||||
|
if (!pick) return;
|
||||||
|
target = pick;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setReleaseRepo(target);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Start a chat that works out a feature or cuts a milestone into issues. */
|
||||||
|
const issueChat = async (mode: "feature" | "slice") => {
|
||||||
|
if (!data) return;
|
||||||
|
let target = repo;
|
||||||
|
if (!target) {
|
||||||
|
const repos = data.repos.filter((r) => r.enabled);
|
||||||
|
if (repos.length === 1) target = repos[0].url;
|
||||||
|
else {
|
||||||
|
const pick = await choiceDialog({ message: t("issues.pickRepo"), choices: repos.map((r) => ({ value: r.url, label: repoName(r.url) })) });
|
||||||
|
if (!pick) return;
|
||||||
|
target = pick;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let topic = "";
|
||||||
|
if (mode === "slice") {
|
||||||
|
const name = await promptDialog({ message: t("issues.sliceWhich"), placeholder: "M2", confirmLabel: t("issues.sliceGo") });
|
||||||
|
if (!name?.trim()) return;
|
||||||
|
topic = name.trim();
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const s = await post<{ id: string }>("/factory/issue-chats", { repo: target, mode, topic });
|
||||||
|
navigate(`/s/${s.id}`);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const issues = useMemo(() => (data?.issues ?? []).filter((i) => !repo || i.repo === repo), [data, repo]);
|
const issues = useMemo(() => (data?.issues ?? []).filter((i) => !repo || i.repo === repo), [data, repo]);
|
||||||
|
const backlogShown = useMemo(() => backlog.filter((i) => !repo || i.repo === repo), [backlog, repo]);
|
||||||
|
/** Put backlog issues into the process (they get the factory label on the forge). */
|
||||||
|
const enqueue = async (items: BacklogIssue[]) => {
|
||||||
|
if (items.length === 0) return;
|
||||||
|
if (items.length > 1 && !(await confirmDialog({ message: t("factory.backlog.allConfirm", { n: items.length }), confirmLabel: t("factory.backlog.queueAll") }))) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
for (const r of [...new Set(items.map((i) => i.repo))]) {
|
||||||
|
const res = await post<{ queued: number[]; errors: { number: number; error: string }[] }>("/factory/backlog/enqueue", { repo: r, numbers: items.filter((i) => i.repo === r).map((i) => i.number) });
|
||||||
|
for (const e of res.errors) toast(`#${e.number}: ${e.error}`);
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
}
|
||||||
|
setBusy(false);
|
||||||
|
await loadBacklog(true);
|
||||||
|
await reload();
|
||||||
|
};
|
||||||
const runs = useMemo(() => (data?.runs ?? []).filter((r) => !repo || r.repo === repo), [data, repo]);
|
const runs = useMemo(() => (data?.runs ?? []).filter((r) => !repo || r.repo === repo), [data, repo]);
|
||||||
|
const selected = issues.find((i) => `${i.repo}#${i.number}` === sel);
|
||||||
|
const [pr, setPr] = useState<PrInfo | null>(null);
|
||||||
|
const [prMethod, setPrMethod] = useState("merge");
|
||||||
|
const selKey = selected ? `${selected.repo}#${selected.number}` : "";
|
||||||
|
const loadPr = async () => {
|
||||||
|
if (!selected || (!selected.branch && !selected.pr_url)) return setPr(null);
|
||||||
|
try {
|
||||||
|
const r = await get<{ pr: PrInfo | null }>(`/factory/issues/pr?repo=${encodeURIComponent(selected.repo)}&number=${selected.number}`);
|
||||||
|
setPr(r.pr);
|
||||||
|
} catch {
|
||||||
|
setPr(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
useEffect(() => {
|
||||||
|
setPr(null);
|
||||||
|
void loadPr();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [selKey, selected?.state]);
|
||||||
if (!data) return <div className="empty"><Spinner /></div>;
|
if (!data) return <div className="empty"><Spinner /></div>;
|
||||||
if (data.repos.length === 0)
|
if (data.repos.length === 0)
|
||||||
return (
|
return (
|
||||||
<div className="empty">
|
<div className="empty">
|
||||||
|
{recreate && <RecreateDialog onClose={() => setRecreate(false)} />}
|
||||||
<p>{t("factory.empty")}</p>
|
<p>{t("factory.empty")}</p>
|
||||||
<div className="row" style={{ gap: 8, justifyContent: "center" }}>
|
<div className="row" style={{ gap: 8, justifyContent: "center" }}>
|
||||||
<button className="primary" onClick={newProject} disabled={busy}>
|
<Button type="primary" onClick={newProject} disabled={busy}>
|
||||||
<Icon name="plus" /> {t("factory.newProject")}
|
<Icon name="plus" /> {t("factory.newProject")}
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={onSettings}>{t("factory.tab.settings")}</button>
|
<Button onClick={() => setRecreate(true)} disabled={busy}>
|
||||||
|
<Icon name="search" /> {t("recreate.button")}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={onSettings}>{t("factory.tab.settings")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -201,7 +390,6 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
const done = issues.filter((i) => i.state === "done").length;
|
const done = issues.filter((i) => i.state === "done").length;
|
||||||
const failed = issues.filter((i) => ["failed", "rejected"].includes(i.state)).length;
|
const failed = issues.filter((i) => ["failed", "rejected"].includes(i.state)).length;
|
||||||
const runsOf = (i: Issue) => data.runs.filter((r) => r.repo === i.repo && r.issue === i.number);
|
const runsOf = (i: Issue) => data.runs.filter((r) => r.repo === i.repo && r.issue === i.number);
|
||||||
const selected = issues.find((i) => `${i.repo}#${i.number}` === sel);
|
|
||||||
const shown = selected ? runsOf(selected) : runs.slice(0, 12);
|
const shown = selected ? runsOf(selected) : runs.slice(0, 12);
|
||||||
|
|
||||||
const poll = async () => {
|
const poll = async () => {
|
||||||
@@ -217,9 +405,85 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const restart = async (to: "new" | "approved" | "qa") => {
|
||||||
|
if (!selected) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await post("/factory/issues/restart", { repo: selected.repo, number: selected.number, to });
|
||||||
|
toast(t("factory.restarted"));
|
||||||
|
await reload();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const prNo = (i: Issue) => Number(i.pr_url.replace(/\/$/, "").split("/").pop()) || 0;
|
||||||
|
/** Merge the pull request of an issue; only offered once the acceptance has passed. */
|
||||||
|
const mergeIssue = async (i: Issue, n = prNo(i)) => {
|
||||||
|
if (!n || i.state !== "done") return;
|
||||||
|
if (!(await confirmDialog({ message: t("factory.mergeConfirm", { n, method: t(`factory.merge.${prMethod}` as any) }) }))) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await post("/factory/issues/pr/merge", { repo: i.repo, number: i.number, pr: n, method: prMethod });
|
||||||
|
toast(t("factory.merged"));
|
||||||
|
await loadPr();
|
||||||
|
await reload();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const mergePr = () => (selected && pr ? mergeIssue(selected, pr.number) : Promise.resolve());
|
||||||
|
const removeIssue = async () => {
|
||||||
|
if (!selected) return;
|
||||||
|
if (!(await confirmDialog({ message: t("factory.removeConfirm", { n: selected.number }), confirmLabel: t("factory.remove"), danger: true }))) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await post("/factory/issues/remove", { repo: selected.repo, number: selected.number });
|
||||||
|
setSel("");
|
||||||
|
await reload();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
/** Close an issue; only offered once its pull request is merged. */
|
||||||
|
const closeIssueOf = async (i: Issue) => {
|
||||||
|
if (i.state !== "done" || !i.merged) return;
|
||||||
|
const comment = await promptDialog({ title: t("factory.closeTitle"), message: t("factory.closeMsg", { n: i.number }), defaultValue: t("factory.closeDefault"), confirmLabel: t("factory.close") });
|
||||||
|
if (comment === null) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await post("/factory/issues/close", { repo: i.repo, number: i.number, comment });
|
||||||
|
toast(t("factory.closed"), "success");
|
||||||
|
if (selected && selected.number === i.number && selected.repo === i.repo) setSel("");
|
||||||
|
await reload();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const closeIssue = () => (selected ? closeIssueOf(selected) : Promise.resolve());
|
||||||
|
const phaseRunning = !!selected && ["review", "building", "testing"].includes(selected.state);
|
||||||
|
/** Master switch: a soft stop – no new agent starts, running ones finish their phase. */
|
||||||
|
const setPower = async (on: boolean) => {
|
||||||
|
try {
|
||||||
|
const power = await post<Power>("/factory/power", { on });
|
||||||
|
setData((d) => (d ? { ...d, power } : d));
|
||||||
|
void reload();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{!data.area && <div className="notice err">{t("factory.noArea")}</div>}
|
{!data.area && <div className="notice err">{t("factory.noArea")}</div>}
|
||||||
|
{data.power && <PowerSwitch power={data.power} onToggle={(on) => void setPower(on)} />}
|
||||||
<div className="kpis">
|
<div className="kpis">
|
||||||
<div className="kpi">
|
<div className="kpi">
|
||||||
<div className="k-label">{t("factory.kpi.running")}</div>
|
<div className="k-label">{t("factory.kpi.running")}</div>
|
||||||
@@ -251,34 +515,79 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="factory-repos">
|
<div className="factory-repos">
|
||||||
<button className={`factory-repo ${repo === "" ? "active" : ""}`} onClick={() => setRepo("")}>
|
<Select className="factory-repo-select" value={repo} onChange={(e) => setRepo(e.target.value)} aria-label={t("factory.project")}>
|
||||||
<b>{t("factory.allRepos")}</b>
|
<option value="">
|
||||||
<span className="hint">{t("factory.kpi.issues", { n: data.issues.length })}</span>
|
{t("factory.allRepos")} ({data.issues.length})
|
||||||
</button>
|
</option>
|
||||||
{data.repos.map((r) => {
|
{data.repos.map((r) => (
|
||||||
const mine = data.issues.filter((i) => i.repo === r.url);
|
<option key={r.url} value={r.url}>
|
||||||
|
{repoName(r.url)}
|
||||||
|
{r.version ? ` · v${r.version}` : ""} ({data.issues.filter((i) => i.repo === r.url).length}){r.enabled ? "" : " – off"}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
{(() => {
|
||||||
|
const r = data.repos.find((x) => x.url === repo);
|
||||||
|
if (!r) return null;
|
||||||
return (
|
return (
|
||||||
<button key={r.url} className={`factory-repo ${repo === r.url ? "active" : ""} ${r.enabled ? "" : "off"}`} onClick={() => setRepo(r.url)}>
|
<span className="factory-repo-info">
|
||||||
<b>{repoName(r.url)}</b>
|
|
||||||
<span className="chip">{KIND_NAME[r.kind] ?? r.kind}</span>
|
<span className="chip">{KIND_NAME[r.kind] ?? r.kind}</span>
|
||||||
|
{r.version && <span className="chip ok mono">v{r.version}</span>}
|
||||||
<span className="hint">
|
<span className="hint">
|
||||||
{r.running > 0 && <span className="factory-pulse" />}
|
{r.running > 0 && <span className="factory-pulse" />}
|
||||||
{t("factory.repoLine", { n: mine.length, run: r.running })}
|
{t("factory.repoLine", { n: data.issues.filter((i) => i.repo === r.url).length, run: r.running })}
|
||||||
</span>
|
</span>
|
||||||
<span className="hint mono">{PHASES.map((p) => r.models[p] || "·").map((m) => m.split("/").pop()).join(" → ")}</span>
|
<span className="hint mono">{PHASES.map((p) => r.models[p] || "·").map((m) => m.split("/").pop()).join(" → ")}</span>
|
||||||
{!r.has_token && <span className="chip warn">{t("factory.noToken")}</span>}
|
{!r.has_token && <span className="chip warn">{t("factory.noToken")}</span>}
|
||||||
</button>
|
</span>
|
||||||
);
|
);
|
||||||
})}
|
})()}
|
||||||
<button className="small primary" onClick={newProject} disabled={busy}>
|
<Button type="primary" size="small" onClick={newProject} disabled={busy}>
|
||||||
<Icon name="plus" /> {t("factory.newProject")}
|
<Icon name="plus" /> {t("factory.newProject")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small" onClick={poll} disabled={busy} title={t("factory.pollNow")}>
|
<Button size="small" onClick={() => setRecreate(true)} disabled={busy} title={t("recreate.hint")}>
|
||||||
|
<Icon name="search" /> {t("recreate.button")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={() => issueChat("feature")} disabled={busy} title={t("issues.featureHint")}>
|
||||||
|
<Icon name="sparkle" /> {t("issues.feature")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={() => issueChat("slice")} disabled={busy} title={t("issues.sliceHint")}>
|
||||||
|
<Icon name="sparkle" /> {t("issues.slice")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={startRelease} disabled={busy} title={t("release.hint")}>
|
||||||
|
<Icon name="download" /> {t("release.button")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={poll} disabled={busy} title={t("factory.pollNow")}>
|
||||||
<Icon name="refresh" /> {t("factory.pollNow")}
|
<Icon name="refresh" /> {t("factory.pollNow")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="factory-board">
|
<div className="factory-board">
|
||||||
|
<div className="factory-col backlog">
|
||||||
|
<h4>
|
||||||
|
{t("factory.col.backlog")} <span className="chip">{backlogShown.length}</span>
|
||||||
|
</h4>
|
||||||
|
{backlogShown.length > 1 && (
|
||||||
|
<Button size="small" onClick={() => void enqueue(backlogShown.filter((i) => i.allowed))} disabled={busy || !backlogShown.some((i) => i.allowed)} title={t("factory.backlog.queueAllHint")}>
|
||||||
|
<Icon name="plus" /> {t("factory.backlog.queueAll")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{backlogShown.map((i) => (
|
||||||
|
<div key={`${i.repo}#${i.number}`} className="factory-card backlog">
|
||||||
|
<span className="hint">
|
||||||
|
{repoName(i.repo)} #{i.number} · {i.author}
|
||||||
|
</span>
|
||||||
|
<a href={i.url || issueUrl(i.repo, i.number)} target="_blank" rel="noreferrer" title={i.title}>
|
||||||
|
<b>{i.title || `#${i.number}`}</b>
|
||||||
|
</a>
|
||||||
|
<Button size="small" onClick={() => void enqueue([i])} disabled={busy || !i.allowed} title={i.allowed ? t("factory.backlog.queueHint") : t("factory.backlog.notAllowed", { user: i.author })}>
|
||||||
|
<Icon name="plus" /> {t("factory.backlog.queue")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{backlogShown.length === 0 && <span className="hint">{t("factory.backlog.empty")}</span>}
|
||||||
|
{backlogErrors.length > 0 && <span className="hint" title={backlogErrors.join("\n")}>{t("factory.backlog.error")}</span>}
|
||||||
|
</div>
|
||||||
{COLUMNS.map((c) => {
|
{COLUMNS.map((c) => {
|
||||||
const cards = issues.filter((i) => c.states.includes(i.state));
|
const cards = issues.filter((i) => c.states.includes(i.state));
|
||||||
return (
|
return (
|
||||||
@@ -290,20 +599,65 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
const rs = runsOf(i);
|
const rs = runsOf(i);
|
||||||
const active = rs.find((r) => !r.ended_at);
|
const active = rs.find((r) => !r.ended_at);
|
||||||
const latest = active ?? rs[0];
|
const latest = active ?? rs[0];
|
||||||
|
// Claimed by a phase but no chat yet: checkout, and – for acceptance – installing and starting the app in its throw-away container.
|
||||||
|
const preparing = !active && ["review", "building", "testing"].includes(i.state);
|
||||||
const tokens = rs.reduce((a, r) => a + r.input_tokens + r.output_tokens, 0);
|
const tokens = rs.reduce((a, r) => a + r.input_tokens + r.output_tokens, 0);
|
||||||
return (
|
return (
|
||||||
<button key={`${i.repo}#${i.number}`} className={`factory-card ${sel === `${i.repo}#${i.number}` ? "active" : ""} ${active ? "running" : ""}`} onClick={() => setSel(sel === `${i.repo}#${i.number}` ? "" : `${i.repo}#${i.number}`)}>
|
<button key={`${i.repo}#${i.number}`} data-state={i.state} className={`factory-card ${sel === `${i.repo}#${i.number}` ? "active" : ""} ${active ? "running" : ""} ${preparing ? "preparing" : ""}`} onClick={() => setSel(sel === `${i.repo}#${i.number}` ? "" : `${i.repo}#${i.number}`)}>
|
||||||
<span className="hint">
|
<span className="factory-card-head">
|
||||||
{repoName(i.repo)} #{i.number}
|
<span className="hint">
|
||||||
|
{repoName(i.repo)} #{i.number}
|
||||||
|
</span>
|
||||||
|
{i.chat_session && (
|
||||||
|
<span
|
||||||
|
role="link"
|
||||||
|
tabIndex={0}
|
||||||
|
className="factory-open"
|
||||||
|
title={`${t("factory.openChat")}: ${t(`factory.phase.${i.chat_phase ?? "review"}` as any)}`}
|
||||||
|
aria-label={t("factory.openChat")}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
openFactoryChat(i.chat_session!);
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" || e.key === " ") {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
openFactoryChat(i.chat_session!);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon name="eye" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
<b>{i.title || `#${i.number}`}</b>
|
<b>{i.title || `#${i.number}`}</b>
|
||||||
{latest && (
|
{preparing && (
|
||||||
|
<span className="hint" title={t("factory.preparing.hint")}>
|
||||||
|
<span className="factory-pulse prep" />
|
||||||
|
{i.state === "testing" ? t("factory.preparing.env") : t("factory.preparing.start")} · {fmtDuration(now - i.updated_at)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{latest && !preparing && (
|
||||||
<span className="hint">
|
<span className="hint">
|
||||||
{active && <span className="factory-pulse" />}
|
{active && <span className="factory-pulse" />}
|
||||||
{t(`factory.phase.${latest.phase}` as any)} · {(latest.model || "").split("/").pop()} · {fmtDuration(runMs(latest, now))}
|
{t(`factory.phase.${latest.phase}` as any)} · {(latest.model || "").split("/").pop()} · {fmtDuration(runMs(latest, now))}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{tokens > 0 && <span className="hint">{fmtCompact(tokens)} {t("factory.tokens")}</span>}
|
{tokens > 0 && <span className="hint">{fmtCompact(tokens)} {t("factory.tokens")}</span>}
|
||||||
|
{i.state === "done" && (i.merged || prNo(i) > 0) && (
|
||||||
|
<span className="factory-card-actions">
|
||||||
|
{!i.merged ? (
|
||||||
|
<CardAction primary disabled={busy} title={t("factory.mergeHint")} onClick={() => void mergeIssue(i)}>
|
||||||
|
<Icon name="fork" /> {t("factory.mergeBtn")}
|
||||||
|
</CardAction>
|
||||||
|
) : (
|
||||||
|
<CardAction disabled={busy} title={t("factory.closeHint")} onClick={() => void closeIssueOf(i)}>
|
||||||
|
<Icon name="check" /> {t("factory.close")}
|
||||||
|
</CardAction>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -312,10 +666,38 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ReleasesPanel releases={(data.releases ?? []).filter((r) => !repo || r.repo === repo)} />
|
||||||
|
{recreate && <RecreateDialog onClose={() => setRecreate(false)} />}
|
||||||
|
{releaseRepo && <ReleaseDialog repo={releaseRepo} onClose={() => setReleaseRepo("")} onStarted={() => void reload()} />}
|
||||||
|
|
||||||
<div className="panel" style={{ marginTop: 16 }}>
|
<div className="panel" style={{ marginTop: 16 }}>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<h3 style={{ margin: 0 }}>{selected ? `${repoName(selected.repo)} #${selected.number} – ${selected.title}` : t("factory.latestRuns")}</h3>
|
<h3 style={{ margin: 0 }}>{selected ? `${repoName(selected.repo)} #${selected.number} – ${selected.title}` : t("factory.latestRuns")}</h3>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
|
{selected && !phaseRunning && (
|
||||||
|
<>
|
||||||
|
<span className="hint">{t("factory.restartAt")}</span>
|
||||||
|
<Button size="small" onClick={() => restart("new")} disabled={busy}>
|
||||||
|
{t("factory.col.review")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={() => restart("approved")} disabled={busy}>
|
||||||
|
{t("factory.col.build")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={() => restart("qa")} disabled={busy || !selected.branch}>
|
||||||
|
{t("factory.col.qa")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{selected && !["review", "building", "testing"].includes(selected.state) && (
|
||||||
|
<Button size="small" onClick={removeIssue} disabled={busy} title={t("factory.removeHint")}>
|
||||||
|
<Icon name="trash" /> {t("factory.remove")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{selected && selected.state === "done" && selected.merged && (
|
||||||
|
<Button size="small" onClick={closeIssue} disabled={busy}>
|
||||||
|
<Icon name="check" /> {t("factory.close")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{selected && (
|
{selected && (
|
||||||
<>
|
<>
|
||||||
<a className="small ghost button-link" href={issueUrl(selected.repo, selected.number)} target="_blank" rel="noreferrer">
|
<a className="small ghost button-link" href={issueUrl(selected.repo, selected.number)} target="_blank" rel="noreferrer">
|
||||||
@@ -330,6 +712,36 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{selected?.note && <div className="hint" style={{ margin: "6px 0" }}>{selected.note}</div>}
|
{selected?.note && <div className="hint" style={{ margin: "6px 0" }}>{selected.note}</div>}
|
||||||
|
{pr && (
|
||||||
|
<div className="factory-pr">
|
||||||
|
<a href={pr.html_url} target="_blank" rel="noreferrer">
|
||||||
|
<Icon name="external" /> #{pr.number} {pr.title}
|
||||||
|
</a>
|
||||||
|
<span className={`chip ${pr.state === "merged" ? "ok" : pr.state === "open" ? "" : "warn"}`}>{t(`factory.pr.${pr.state}` as any)}</span>
|
||||||
|
{pr.state === "open" && pr.mergeable === false && <span className="chip warn">{t("factory.pr.conflict")}</span>}
|
||||||
|
{pr.changed_files != null && (
|
||||||
|
<span className="hint">
|
||||||
|
{t("factory.pr.files", { n: pr.changed_files })}
|
||||||
|
{pr.additions != null && ` · +${pr.additions} −${pr.deletions ?? 0}`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="spacer" />
|
||||||
|
{pr.state === "open" && selected?.state === "done" && (
|
||||||
|
<>
|
||||||
|
<Select value={prMethod} onChange={(e) => setPrMethod(e.target.value)} disabled={busy}>
|
||||||
|
{["merge", "squash", "rebase"].map((m) => (
|
||||||
|
<option key={m} value={m}>
|
||||||
|
{t(`factory.merge.${m}` as any)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
<Button type="primary" size="small" onClick={mergePr} disabled={busy || pr.mergeable === false}>
|
||||||
|
{t("factory.mergeBtn")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{shown.length === 0 && <div className="hint">{t("factory.noRuns")}</div>}
|
{shown.length === 0 && <div className="hint">{t("factory.noRuns")}</div>}
|
||||||
{shown.length > 0 && (
|
{shown.length > 0 && (
|
||||||
<div className="table-wrap">
|
<div className="table-wrap">
|
||||||
@@ -373,9 +785,9 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
</td>
|
</td>
|
||||||
<td>{fmtCost(r.cost, "USD")}</td>
|
<td>{fmtCost(r.cost, "USD")}</td>
|
||||||
<td>
|
<td>
|
||||||
<button className="small" onClick={() => navigate(`/s/${r.session_id}`)}>
|
<Button size="small" onClick={() => openFactoryChat(r.session_id)}>
|
||||||
<Icon name="eye" /> {t("factory.openChat")}
|
<Icon name="eye" /> {t("factory.openChat")}
|
||||||
</button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@@ -388,11 +800,46 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, extra_prompt: "" });
|
const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, max_attempts: 2, extra_prompt: "", skills: [] });
|
||||||
const blankRepo = (connection = "", kind = "gitea"): RepoCfg => ({ url: "", kind, connection, token: "", label: "factory", max_parallel: 1, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() });
|
const blankRepo = (connection = "", kind = "gitea"): RepoCfg => ({ url: "", kind, connection, token: "", label: "factory", max_parallel: 1, max_rework: 2, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() });
|
||||||
const blankConn = (): Connection => ({ id: "", name: "", kind: "gitea", url: "", token: "", owner: "" });
|
const blankConn = (): Connection => ({ id: "", name: "", kind: "gitea", url: "", token: "", owner: "" });
|
||||||
const MODES = ["default", "auto", "accept_edits", "bypass"];
|
const MODES = ["default", "auto", "accept_edits", "bypass"];
|
||||||
|
|
||||||
|
/** Skills switched on for the chat of one phase (the agent follows them in every turn). */
|
||||||
|
function PhaseSkills({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [all, setAll] = useState<{ name: string; description: string }[]>([]);
|
||||||
|
useEffect(() => {
|
||||||
|
get<{ skills: { name: string; description: string }[] }>("/commands")
|
||||||
|
.then((d) => setAll(d.skills))
|
||||||
|
.catch(() => {});
|
||||||
|
}, []);
|
||||||
|
const rest = all.filter((s) => !value.includes(s.name));
|
||||||
|
return (
|
||||||
|
<div className="factory-skills">
|
||||||
|
<span>{t("factory.skills")}</span>
|
||||||
|
<div className="row" style={{ gap: 4, flexWrap: "wrap" }}>
|
||||||
|
{value.map((n) => (
|
||||||
|
<button key={n} type="button" className="chip" style={{ border: "none" }} title={t("factory.skillRemove")} onClick={() => onChange(value.filter((x) => x !== n))}>
|
||||||
|
{n} ×
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{rest.length > 0 && value.length < 10 && (
|
||||||
|
<Select value="" onChange={(e) => e.target.value && onChange([...value, e.target.value])}>
|
||||||
|
<option value="">{t("factory.skillAdd")}</option>
|
||||||
|
{rest.map((s) => (
|
||||||
|
<option key={s.name} value={s.name} title={s.description}>
|
||||||
|
{s.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="hint">{t("factory.skillsHint")}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg; onChange: (patch: Partial<PhaseCfg>) => void }) {
|
function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg; onChange: (patch: Partial<PhaseCfg>) => void }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
return (
|
return (
|
||||||
@@ -404,28 +851,33 @@ function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg;
|
|||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.agent")}</span>
|
<span>{t("factory.agent")}</span>
|
||||||
<select value={value.agent} onChange={(e) => onChange({ agent: e.target.value })}>
|
<Select value={value.agent} onChange={(e) => onChange({ agent: e.target.value })}>
|
||||||
<option value="codecraft">CodeCraft</option>
|
<option value="codecraft">CodeCraft</option>
|
||||||
<option value="claude-code">Claude Code</option>
|
<option value="claude-code">Claude Code</option>
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.mode")}</span>
|
<span>{t("factory.mode")}</span>
|
||||||
<select value={value.permission_mode} onChange={(e) => onChange({ permission_mode: e.target.value })}>
|
<Select value={value.permission_mode} onChange={(e) => onChange({ permission_mode: e.target.value })}>
|
||||||
{MODES.map((m) => (
|
{MODES.map((m) => (
|
||||||
<option key={m} value={m}>
|
<option key={m} value={m}>
|
||||||
{t(`permissionMode.${m}` as any)}
|
{t(`permissionMode.${m}` as any)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.timeout")}</span>
|
<span>{t("factory.timeout")}</span>
|
||||||
<input type="number" min={1} value={value.timeout_minutes} onChange={(e) => onChange({ timeout_minutes: Number(e.target.value) || 60 })} />
|
<Input type="number" min={1} value={value.timeout_minutes} onChange={(e) => onChange({ timeout_minutes: Number(e.target.value) || 60 })} />
|
||||||
</label>
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>{t("factory.attempts")}</span>
|
||||||
|
<Input type="number" min={1} max={10} value={value.max_attempts} title={t("factory.attemptsHint")} onChange={(e) => onChange({ max_attempts: Math.max(1, Number(e.target.value) || 1) })} />
|
||||||
|
</label>
|
||||||
|
<PhaseSkills value={value.skills ?? []} onChange={(skills) => onChange({ skills })} />
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.extraPrompt")}</span>
|
<span>{t("factory.extraPrompt")}</span>
|
||||||
<textarea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
|
<Input.TextArea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -481,8 +933,7 @@ function FactorySettings() {
|
|||||||
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
|
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
|
||||||
<h3 style={{ margin: 0 }}>{c.name || KIND_NAME[c.kind]}</h3>
|
<h3 style={{ margin: 0 }}>{c.name || KIND_NAME[c.kind]}</h3>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
disabled={busy !== undefined}
|
disabled={busy !== undefined}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
act(`c${i}`, async () => {
|
act(`c${i}`, async () => {
|
||||||
@@ -495,9 +946,8 @@ function FactorySettings() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{busy === `c${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.testConn")}
|
{busy === `c${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.testConn")}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
title={t("common.delete")}
|
title={t("common.delete")}
|
||||||
aria-label={t("common.delete")}
|
aria-label={t("common.delete")}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
@@ -505,35 +955,35 @@ function FactorySettings() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="factory-form">
|
<div className="factory-form">
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.connName")}</span>
|
<span>{t("factory.connName")}</span>
|
||||||
<input value={c.name} onChange={(e) => upConn(i, { name: e.target.value })} />
|
<Input value={c.name} onChange={(e) => upConn(i, { name: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.kind")}</span>
|
<span>{t("factory.kind")}</span>
|
||||||
<select value={c.kind} onChange={(e) => upConn(i, { kind: e.target.value as Connection["kind"] })}>
|
<Select value={c.kind} onChange={(e) => upConn(i, { kind: e.target.value as Connection["kind"] })}>
|
||||||
{Object.entries(KIND_NAME).map(([k, n]) => (
|
{Object.entries(KIND_NAME).map(([k, n]) => (
|
||||||
<option key={k} value={k}>
|
<option key={k} value={k}>
|
||||||
{n}
|
{n}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.serviceUrl")}</span>
|
<span>{t("factory.serviceUrl")}</span>
|
||||||
<input value={c.url} placeholder={URL_PLACEHOLDER[c.kind]} onChange={(e) => upConn(i, { url: e.target.value })} />
|
<Input value={c.url} placeholder={URL_PLACEHOLDER[c.kind]} onChange={(e) => upConn(i, { url: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.token")}</span>
|
<span>{t("factory.token")}</span>
|
||||||
<input type="password" autoComplete="new-password" value={c.token} placeholder={t("factory.tokenPlaceholder")} onChange={(e) => upConn(i, { token: e.target.value })} onFocus={(e) => c.token.startsWith("•") && e.currentTarget.select()} />
|
<Input.Password autoComplete="new-password" value={c.token} placeholder={t("factory.tokenPlaceholder")} onChange={(e) => upConn(i, { token: e.target.value })} onFocus={(e) => c.token.startsWith("•") && e.currentTarget.select()} />
|
||||||
<span className="hint">{c.token.startsWith("•") ? t("factory.tokenSet") : t(`factory.tokenHint.${c.kind}` as any)}</span>
|
<span className="hint">{c.token.startsWith("•") ? t("factory.tokenSet") : t(`factory.tokenHint.${c.kind}` as any)}</span>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.defaultOwner")}</span>
|
<span>{t("factory.defaultOwner")}</span>
|
||||||
<input list={`orgs-${c.id}`} value={c.owner} placeholder={t("draft.ownerPlaceholder")} onChange={(e) => upConn(i, { owner: e.target.value })} />
|
<Input list={`orgs-${c.id}`} value={c.owner} placeholder={t("draft.ownerPlaceholder")} onChange={(e) => upConn(i, { owner: e.target.value })} />
|
||||||
<datalist id={`orgs-${c.id}`}>
|
<datalist id={`orgs-${c.id}`}>
|
||||||
{(orgs[c.id] ?? []).map((o) => (
|
{(orgs[c.id] ?? []).map((o) => (
|
||||||
<option key={o} value={o} />
|
<option key={o} value={o} />
|
||||||
@@ -543,9 +993,9 @@ function FactorySettings() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<button onClick={() => setConns([...conns, blankConn()])}>
|
<Button onClick={() => setConns([...conns, blankConn()])}>
|
||||||
<Icon name="plus" /> {t("factory.addConn")}
|
<Icon name="plus" /> {t("factory.addConn")}
|
||||||
</button>
|
</Button>
|
||||||
|
|
||||||
<h3 className="factory-h">{t("factory.defaults")}</h3>
|
<h3 className="factory-h">{t("factory.defaults")}</h3>
|
||||||
<div className="hint" style={{ marginBottom: 8 }}>{t("factory.defaultsHint")}</div>
|
<div className="hint" style={{ marginBottom: 8 }}>{t("factory.defaultsHint")}</div>
|
||||||
@@ -568,12 +1018,10 @@ function FactorySettings() {
|
|||||||
<h3 style={{ margin: 0 }}>{r.url ? repoName(r.url) : t("factory.newRepo")}</h3>
|
<h3 style={{ margin: 0 }}>{r.url ? repoName(r.url) : t("factory.newRepo")}</h3>
|
||||||
<span className="chip">{KIND_NAME[conns.find((c) => c.id === r.connection)?.kind ?? r.kind] ?? r.kind}</span>
|
<span className="chip">{KIND_NAME[conns.find((c) => c.id === r.connection)?.kind ?? r.kind] ?? r.kind}</span>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<label className="switch">
|
<Checkbox className="switch" checked={r.enabled} onChange={(e) => up(i, { enabled: e.target.checked })}>
|
||||||
<input type="checkbox" checked={r.enabled} onChange={(e) => up(i, { enabled: e.target.checked })} />
|
|
||||||
<span>{t(r.enabled ? "jobs.on" : "jobs.off")}</span>
|
<span>{t(r.enabled ? "jobs.on" : "jobs.off")}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
disabled={busy !== undefined}
|
disabled={busy !== undefined}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
act(`t${i}`, async () => {
|
act(`t${i}`, async () => {
|
||||||
@@ -584,9 +1032,8 @@ function FactorySettings() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{busy === `t${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.test")}
|
{busy === `t${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.test")}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
title={t("common.delete")}
|
title={t("common.delete")}
|
||||||
aria-label={t("common.delete")}
|
aria-label={t("common.delete")}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
@@ -594,12 +1041,12 @@ function FactorySettings() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="factory-form">
|
<div className="factory-form">
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.connection")}</span>
|
<span>{t("factory.connection")}</span>
|
||||||
<select
|
<Select
|
||||||
value={r.connection}
|
value={r.connection}
|
||||||
onChange={(e) => up(i, { connection: e.target.value, kind: conns.find((c) => c.id === e.target.value)?.kind ?? r.kind })}
|
onChange={(e) => up(i, { connection: e.target.value, kind: conns.find((c) => c.id === e.target.value)?.kind ?? r.kind })}
|
||||||
>
|
>
|
||||||
@@ -611,40 +1058,44 @@ function FactorySettings() {
|
|||||||
{c.name || KIND_NAME[c.kind]}
|
{c.name || KIND_NAME[c.kind]}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
{!r.connection && (
|
{!r.connection && (
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.kind")}</span>
|
<span>{t("factory.kind")}</span>
|
||||||
<select value={r.kind} onChange={(e) => up(i, { kind: e.target.value })}>
|
<Select value={r.kind} onChange={(e) => up(i, { kind: e.target.value })}>
|
||||||
{Object.entries(KIND_NAME).map(([k, n]) => (
|
{Object.entries(KIND_NAME).map(([k, n]) => (
|
||||||
<option key={k} value={k}>
|
<option key={k} value={k}>
|
||||||
{n}
|
{n}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.url")}</span>
|
<span>{t("factory.url")}</span>
|
||||||
<input value={r.url} placeholder="https://host/owner/repo.git" onChange={(e) => up(i, { url: e.target.value })} />
|
<Input value={r.url} placeholder="https://host/owner/repo.git" onChange={(e) => up(i, { url: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.repoToken")}</span>
|
<span>{t("factory.repoToken")}</span>
|
||||||
<input type="password" autoComplete="new-password" value={r.token} placeholder={t("factory.repoTokenPlaceholder")} onChange={(e) => up(i, { token: e.target.value })} onFocus={(e) => r.token.startsWith("•") && e.currentTarget.select()} />
|
<Input.Password autoComplete="new-password" value={r.token} placeholder={t("factory.repoTokenPlaceholder")} onChange={(e) => up(i, { token: e.target.value })} onFocus={(e) => r.token.startsWith("•") && e.currentTarget.select()} />
|
||||||
<span className="hint">{r.token.startsWith("•") ? t("factory.tokenSet") : t("factory.repoTokenHint")}</span>
|
<span className="hint">{r.token.startsWith("•") ? t("factory.tokenSet") : t("factory.repoTokenHint")}</span>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.label")}</span>
|
<span>{t("factory.label")}</span>
|
||||||
<input value={r.label} onChange={(e) => up(i, { label: e.target.value })} />
|
<Input value={r.label} onChange={(e) => up(i, { label: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.parallel")}</span>
|
<span>{t("factory.parallel")}</span>
|
||||||
<input type="number" min={1} max={4} value={r.max_parallel} onChange={(e) => up(i, { max_parallel: Number(e.target.value) || 1 })} />
|
<Input type="number" min={1} max={4} value={r.max_parallel} onChange={(e) => up(i, { max_parallel: Number(e.target.value) || 1 })} />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>{t("factory.rework")}</span>
|
||||||
|
<Input type="number" min={0} max={10} value={r.max_rework} title={t("factory.reworkHint")} onChange={(e) => up(i, { max_rework: Math.max(0, Number(e.target.value) || 0) })} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("factory.allowed")}</span>
|
<span>{t("factory.allowed")}</span>
|
||||||
<input value={r.allowed_users.join(", ")} placeholder={t("factory.allowedPlaceholder")} onChange={(e) => up(i, { allowed_users: e.target.value.split(",").map((u) => u.trim()).filter(Boolean) })} />
|
<Input value={r.allowed_users.join(", ")} placeholder={t("factory.allowedPlaceholder")} onChange={(e) => up(i, { allowed_users: e.target.value.split(",").map((u) => u.trim()).filter(Boolean) })} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div className="factory-phases">
|
<div className="factory-phases">
|
||||||
@@ -655,11 +1106,10 @@ function FactorySettings() {
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<div className="row" style={{ gap: 8, marginTop: 12 }}>
|
<div className="row" style={{ gap: 8, marginTop: 12 }}>
|
||||||
<button onClick={() => setRepos([...repos, blankRepo(conns.find((c) => c.id)?.id ?? "", conns.find((c) => c.id)?.kind ?? "gitea")])}>
|
<Button onClick={() => setRepos([...repos, blankRepo(conns.find((c) => c.id)?.id ?? "", conns.find((c) => c.id)?.kind ?? "gitea")])}>
|
||||||
<Icon name="plus" /> {t("factory.addRepo")}
|
<Icon name="plus" /> {t("factory.addRepo")}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button type="primary"
|
||||||
className="primary"
|
|
||||||
disabled={busy !== undefined}
|
disabled={busy !== undefined}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
act("save", async () => {
|
act("save", async () => {
|
||||||
@@ -669,7 +1119,7 @@ function FactorySettings() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{busy === "save" ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
{busy === "save" ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { navigate } from "../router";
|
||||||
|
import { useT } from "../i18n";
|
||||||
|
import { ChatView } from "./ChatView";
|
||||||
|
import { Icon } from "./Icon";
|
||||||
|
|
||||||
|
/** Desktop only: chats of the factory open over the board and are closed with one click. */
|
||||||
|
export const isDesktop = () => window.matchMedia("(min-width: 801px)").matches;
|
||||||
|
|
||||||
|
/** Open the chat of a phase: in the overlay on the desktop, as a page on small screens. */
|
||||||
|
export function openFactoryChat(sessionId: string) {
|
||||||
|
navigate(isDesktop() ? `/factory/s/${sessionId}` : `/s/${sessionId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChatOverlay({ id }: { id: string }) {
|
||||||
|
const t = useT();
|
||||||
|
const close = () => navigate("/factory");
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
// Esc closes – unless it is meant for a field, a dialog or the image viewer on top.
|
||||||
|
const el = document.activeElement;
|
||||||
|
const typing = el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement || el instanceof HTMLSelectElement;
|
||||||
|
if (e.key === "Escape" && !typing && !document.querySelector(".ant-modal-wrap, .modal-backdrop, .viewer-overlay")) close();
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<div className="chat-overlay" onMouseDown={(e) => e.target === e.currentTarget && close()}>
|
||||||
|
<div className="chat-overlay-box" role="dialog" aria-modal="true">
|
||||||
|
<div className="chat-overlay-bar">
|
||||||
|
<span className="hint">{t("factory.chatOverlay")}</span>
|
||||||
|
<span className="spacer" />
|
||||||
|
<Button size="small" onClick={() => navigate(`/s/${id}`)} title={t("factory.openFullHint")}>
|
||||||
|
<Icon name="external" /> {t("factory.openFull")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" onClick={close} aria-label={t("common.close")}>
|
||||||
|
<Icon name="close" /> {t("common.close")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="chat-overlay-body">
|
||||||
|
<ChatView key={id} sessionId={id} onMenu={close} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,15 +1,21 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get, post } from "../api";
|
import { get, post } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
import { navigate } from "../router";
|
import { navigate } from "../router";
|
||||||
import { toast } from "../dialogs";
|
import { toast } from "../dialogs";
|
||||||
|
import { uploadBatch } from "../uploads";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { Spinner } from "./Activity";
|
import { Spinner } from "./Activity";
|
||||||
|
|
||||||
interface Draft {
|
interface Draft {
|
||||||
spec: string;
|
spec: string;
|
||||||
|
setup?: string | null;
|
||||||
proposal: { name?: string; slug?: string; description?: string } | null;
|
proposal: { name?: string; slug?: string; description?: string } | null;
|
||||||
connections: { id: string; name: string; kind: string; owner: string }[];
|
connections: { id: string; name: string; kind: string; owner: string }[];
|
||||||
|
recreate?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isDraftChat = (cwd: string) => /\/_drafts\/[^/]+$/.test(cwd);
|
export const isDraftChat = (cwd: string) => /\/_drafts\/[^/]+$/.test(cwd);
|
||||||
@@ -35,9 +41,9 @@ export function DraftBar({ sessionId }: { sessionId: string }) {
|
|||||||
<Icon name="scroll" />
|
<Icon name="scroll" />
|
||||||
<span>{t("draft.hint")}</span>
|
<span>{t("draft.hint")}</span>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button className="small primary" onClick={() => setOpen(true)}>
|
<Button type="primary" size="small" onClick={() => setOpen(true)}>
|
||||||
<Icon name="check" /> {t("draft.create")}
|
<Icon name="check" /> {t("draft.create")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{open && <CreateProjectDialog sessionId={sessionId} onClose={() => setOpen(false)} />}
|
{open && <CreateProjectDialog sessionId={sessionId} onClose={() => setOpen(false)} />}
|
||||||
</>
|
</>
|
||||||
@@ -74,11 +80,9 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
|
|
||||||
if (!draft)
|
if (!draft)
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop">
|
<Modal >
|
||||||
<div className="modal">
|
|
||||||
<Spinner />
|
<Spinner />
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const conn = draft.connections.find((c) => c.id === connection);
|
const conn = draft.connections.find((c) => c.id === connection);
|
||||||
@@ -87,9 +91,9 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
const create = async () => {
|
const create = async () => {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
const r = await post<{ repo: string; issue: number }>(`/factory/drafts/${sessionId}/create`, { connection, name, slug, description, owner });
|
const r = await post<{ repo: string; issue: number | null }>(`/factory/drafts/${sessionId}/create`, { connection, name, slug, description, owner });
|
||||||
await post("/factory/poll", {}).catch(() => undefined);
|
await post("/factory/poll", {}).catch(() => undefined);
|
||||||
toast(t("draft.created", { repo: r.repo, n: r.issue }), "success");
|
toast(r.issue == null ? t("draft.createdRecreate", { repo: r.repo }) : t("draft.created", { repo: r.repo, n: r.issue }), "success");
|
||||||
onClose();
|
onClose();
|
||||||
navigate("/factory");
|
navigate("/factory");
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -99,8 +103,7 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
|
<Modal onClose={busy ? undefined : onClose} className="draft-modal" role="dialog" aria-label={t("draft.create")}>
|
||||||
<div className="modal draft-modal" role="dialog" aria-label={t("draft.create")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("draft.create")}</h3>
|
<h3>{t("draft.create")}</h3>
|
||||||
{draft.connections.length === 0 ? (
|
{draft.connections.length === 0 ? (
|
||||||
<div className="notice err">
|
<div className="notice err">
|
||||||
@@ -112,10 +115,11 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{!draft.spec.trim() && <div className="notice err">{t("draft.noSpec")}</div>}
|
{!draft.spec.trim() && <div className="notice err">{t("draft.noSpec")}</div>}
|
||||||
|
{draft.spec.trim() && !draft.setup && <div className="notice">{t("draft.noSetup")}</div>}
|
||||||
<div className="factory-form">
|
<div className="factory-form">
|
||||||
<label>
|
<label>
|
||||||
<span>{t("draft.name")}</span>
|
<span>{t("draft.name")}</span>
|
||||||
<input
|
<Input
|
||||||
autoFocus
|
autoFocus
|
||||||
value={name}
|
value={name}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
@@ -126,7 +130,7 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("draft.slug")}</span>
|
<span>{t("draft.slug")}</span>
|
||||||
<input
|
<Input
|
||||||
value={slug}
|
value={slug}
|
||||||
className="mono"
|
className="mono"
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
@@ -137,11 +141,11 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
</label>
|
</label>
|
||||||
<label style={{ gridColumn: "1 / -1" }}>
|
<label style={{ gridColumn: "1 / -1" }}>
|
||||||
<span>{t("draft.description")}</span>
|
<span>{t("draft.description")}</span>
|
||||||
<input value={description} onChange={(e) => setDescription(e.target.value)} />
|
<Input value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("draft.connection")}</span>
|
<span>{t("draft.connection")}</span>
|
||||||
<select
|
<Select
|
||||||
value={connection}
|
value={connection}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setConnection(e.target.value);
|
setConnection(e.target.value);
|
||||||
@@ -153,11 +157,11 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
{c.name || c.kind} ({c.kind})
|
{c.name || c.kind} ({c.kind})
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
<span>{t("draft.owner")}</span>
|
<span>{t("draft.owner")}</span>
|
||||||
<input value={owner} placeholder={t("draft.ownerPlaceholder")} onChange={(e) => setOwner(e.target.value)} />
|
<Input value={owner} placeholder={t("draft.ownerPlaceholder")} onChange={(e) => setOwner(e.target.value)} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div className="hint" style={{ margin: "6px 0" }}>
|
<div className="hint" style={{ margin: "6px 0" }}>
|
||||||
@@ -170,14 +174,189 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
|
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
|
||||||
<button onClick={onClose} disabled={busy}>
|
<Button onClick={onClose} disabled={busy}>
|
||||||
{t("common.cancel")}
|
{t("common.cancel")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="primary" onClick={create} disabled={!ready || busy}>
|
<Button type="primary" onClick={create} disabled={!ready || busy}>
|
||||||
{busy ? <Spinner small /> : <Icon name="check" />} {t("draft.createGo")}
|
{busy ? <Spinner small /> : <Icon name="check" />} {t("draft.createGo")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isIssueChat = (cwd: string) => /\/_issues\/[^/]+$/.test(cwd);
|
||||||
|
|
||||||
|
interface ProposedIssue {
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
scope: string;
|
||||||
|
depends: string;
|
||||||
|
}
|
||||||
|
interface IssueProposal {
|
||||||
|
repo: string;
|
||||||
|
proposal: { spec?: string; issues: ProposedIssue[] } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bar above the composer of an issue chat: file the proposed issues on the forge. */
|
||||||
|
export function IssueBar({ sessionId }: { sessionId: string }) {
|
||||||
|
const t = useT();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="draft-bar">
|
||||||
|
<Icon name="scroll" />
|
||||||
|
<span>{t("issues.hint")}</span>
|
||||||
|
<span className="spacer" />
|
||||||
|
<Button type="primary" size="small" onClick={() => setOpen(true)}>
|
||||||
|
<Icon name="check" /> {t("issues.create")}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
{open && <CreateIssuesDialog sessionId={sessionId} onClose={() => setOpen(false)} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CreateIssuesDialog({ sessionId, onClose }: { sessionId: string; onClose: () => void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [data, setData] = useState<IssueProposal>();
|
||||||
|
const [items, setItems] = useState<(ProposedIssue & { on: boolean })[]>([]);
|
||||||
|
const [spec, setSpec] = useState("");
|
||||||
|
const [start, setStart] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
get<IssueProposal>(`/factory/issue-chats/${sessionId}`)
|
||||||
|
.then((d) => {
|
||||||
|
setData(d);
|
||||||
|
setSpec(d.proposal?.spec ?? "");
|
||||||
|
setItems((d.proposal?.issues ?? []).map((i) => ({ title: i.title ?? "", description: i.description ?? "", scope: i.scope ?? "", depends: i.depends ?? "", on: true })));
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
toast(e.message);
|
||||||
|
onClose();
|
||||||
|
});
|
||||||
|
}, [sessionId]);
|
||||||
|
|
||||||
|
if (!data)
|
||||||
|
return (
|
||||||
|
<Modal >
|
||||||
|
<Spinner />
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
|
||||||
|
const chosen = items.filter((i) => i.on && i.title.trim());
|
||||||
|
const set = (k: number, patch: Partial<ProposedIssue & { on: boolean }>) => setItems(items.map((x, j) => (j === k ? { ...x, ...patch } : x)));
|
||||||
|
const create = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await post<{ created: { number: number }[] }>(`/factory/issue-chats/${sessionId}/create`, {
|
||||||
|
spec,
|
||||||
|
start,
|
||||||
|
issues: chosen.map(({ on, ...i }) => i),
|
||||||
|
});
|
||||||
|
toast(t("issues.created", { n: r.created.length }), "success");
|
||||||
|
onClose();
|
||||||
|
navigate("/factory");
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onClose={busy ? undefined : onClose} className="draft-modal" role="dialog" aria-label={t("issues.create")}>
|
||||||
|
<h3>{t("issues.create")}</h3>
|
||||||
|
{!data.proposal ? (
|
||||||
|
<div className="notice err">{t("issues.noProposal")}</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<label className="factory-form" style={{ display: "block" }}>
|
||||||
|
<span>{t("issues.spec")}</span>
|
||||||
|
<Input className="mono" value={spec} onChange={(e) => setSpec(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div className="issue-list">
|
||||||
|
{items.map((i, k) => (
|
||||||
|
<div key={k} className="issue-item">
|
||||||
|
<Checkbox className="row" style={{ gap: 8 }} checked={i.on} onChange={(e) => set(k, { on: e.target.checked })}>
|
||||||
|
<Input style={{ flex: 1 }} value={i.title} onChange={(e) => set(k, { title: e.target.value })} />
|
||||||
|
</Checkbox>
|
||||||
|
<div className="hint">{i.scope}</div>
|
||||||
|
{i.depends && i.depends.toLowerCase() !== "none" && <div className="hint">{t("issues.depends", { d: i.depends })}</div>}
|
||||||
|
<details>
|
||||||
|
<summary>{t("issues.description")}</summary>
|
||||||
|
<Input.TextArea rows={4} value={i.description} onChange={(e) => set(k, { description: e.target.value })} />
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<Checkbox className="row" style={{ gap: 8, marginTop: 8 }} checked={start} onChange={(e) => setStart(e.target.checked)}>
|
||||||
|
<span>{t("issues.start")}</span>
|
||||||
|
</Checkbox>
|
||||||
|
<div className="hint">{t("issues.startHint")}</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
|
||||||
|
<Button onClick={onClose} disabled={busy}>
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={create} disabled={!data.proposal || chosen.length === 0 || !spec.trim() || busy}>
|
||||||
|
{busy ? <Spinner small /> : <Icon name="check" />} {t("issues.createGo", { n: chosen.length })}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Start a recreate draft: the original (upload and/or URL) is analysed in depth, then a clean-room spec is written. */
|
||||||
|
export function RecreateDialog({ onClose }: { onClose: () => void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [source, setSource] = useState("");
|
||||||
|
const [notes, setNotes] = useState("");
|
||||||
|
const [files, setFiles] = useState<File[]>([]);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const start = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const s = await post<{ id: string; cwd: string }>("/factory/drafts", { mode: "recreate", source, notes });
|
||||||
|
const sent = await uploadBatch(files.map((f) => ({ file: f, path: `${s.cwd}/original/${f.name}` })));
|
||||||
|
if (sent.length < files.length) throw new Error(t("recreate.uploadFailed"));
|
||||||
|
await post(`/sessions/${s.id}/prompt`, { text: t("recreate.firstMessage") });
|
||||||
|
onClose();
|
||||||
|
navigate(`/s/${s.id}`);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onClose={busy ? undefined : onClose} className="draft-modal" role="dialog" aria-label={t("recreate.title")}>
|
||||||
|
<h3>{t("recreate.title")}</h3>
|
||||||
|
<div className="hint" style={{ marginBottom: 8 }}>{t("recreate.hint")}</div>
|
||||||
|
<div className="factory-form">
|
||||||
|
<label style={{ gridColumn: "1 / -1" }}>
|
||||||
|
<span>{t("recreate.source")}</span>
|
||||||
|
<Input autoFocus value={source} placeholder="https://…" onChange={(e) => setSource(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<label style={{ gridColumn: "1 / -1" }}>
|
||||||
|
<span>{t("recreate.files")}</span>
|
||||||
|
<input type="file" multiple onChange={(e) => setFiles([...(e.target.files ?? [])])} />
|
||||||
|
</label>
|
||||||
|
<label style={{ gridColumn: "1 / -1" }}>
|
||||||
|
<span>{t("recreate.notes")}</span>
|
||||||
|
<Input.TextArea rows={4} value={notes} placeholder={t("recreate.notesPlaceholder")} onChange={(e) => setNotes(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
|
||||||
|
<Button onClick={onClose} disabled={busy}>
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={start} disabled={busy || (!source.trim() && files.length === 0)}>
|
||||||
|
{busy ? <Spinner small /> : <Icon name="search" />} {t("recreate.go")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { get, post } from "../api";
|
||||||
|
import { fmtRelative, useT } from "../i18n";
|
||||||
|
import { toast } from "../dialogs";
|
||||||
|
import { Icon } from "./Icon";
|
||||||
|
import { Spinner } from "./Activity";
|
||||||
|
|
||||||
|
export interface ReleaseRow {
|
||||||
|
id: string;
|
||||||
|
repo: string;
|
||||||
|
version: string;
|
||||||
|
state: "running" | "done" | "failed";
|
||||||
|
log: string;
|
||||||
|
url: string;
|
||||||
|
started_at: number;
|
||||||
|
ended_at: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Preview {
|
||||||
|
current: string;
|
||||||
|
suggested: string;
|
||||||
|
spec: string | null;
|
||||||
|
running: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const repoName = (url: string) => url.replace(/\.git$/, "").split("/").slice(-2).join("/");
|
||||||
|
|
||||||
|
/** Confirm and start a release: version, the recipe that will run, then tag + image + downloads. */
|
||||||
|
export function ReleaseDialog({ repo, onClose, onStarted }: { repo: string; onClose: () => void; onStarted: () => void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [pv, setPv] = useState<Preview>();
|
||||||
|
const [version, setVersion] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
get<Preview>(`/factory/release/preview?repo=${encodeURIComponent(repo)}`)
|
||||||
|
.then((p) => {
|
||||||
|
setPv(p);
|
||||||
|
setVersion(p.suggested);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
toast(e.message);
|
||||||
|
onClose();
|
||||||
|
});
|
||||||
|
}, [repo]);
|
||||||
|
|
||||||
|
if (!pv)
|
||||||
|
return (
|
||||||
|
<Modal >
|
||||||
|
<Spinner />
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
|
||||||
|
const start = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await post("/factory/release", { repo, version });
|
||||||
|
toast(t("release.started", { v: version }), "success");
|
||||||
|
onStarted();
|
||||||
|
onClose();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e.message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal onClose={busy ? undefined : onClose} className="draft-modal" role="dialog" aria-label={t("release.title")}>
|
||||||
|
<h3>
|
||||||
|
{t("release.title")} – {repoName(repo)}
|
||||||
|
</h3>
|
||||||
|
<div className="hint">{t("release.current", { v: pv.current })}</div>
|
||||||
|
<label className="factory-form" style={{ display: "block", margin: "8px 0" }}>
|
||||||
|
<span>{t("release.version")}</span>
|
||||||
|
<Input className="mono" value={version} onChange={(e) => setVersion(e.target.value.trim().replace(/^v/, ""))} />
|
||||||
|
</label>
|
||||||
|
<div className="notice">{t("release.what")}</div>
|
||||||
|
{pv.spec ? (
|
||||||
|
<details open>
|
||||||
|
<summary>{t("release.recipe")}</summary>
|
||||||
|
<pre className="draft-spec">{pv.spec}</pre>
|
||||||
|
<div className="notice err">{t("release.trust")}</div>
|
||||||
|
</details>
|
||||||
|
) : (
|
||||||
|
<div className="hint">{t("release.noRecipe")}</div>
|
||||||
|
)}
|
||||||
|
{pv.running && <div className="notice err">{t("release.running")}</div>}
|
||||||
|
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
|
||||||
|
<Button onClick={onClose} disabled={busy}>
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={start} disabled={busy || pv.running || !/^\d+\.\d+\.\d+$/.test(version)}>
|
||||||
|
{busy ? <Spinner small /> : <Icon name="check" />} {t("release.go", { v: version })}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The latest releases with their log. */
|
||||||
|
export function ReleasesPanel({ releases }: { releases: ReleaseRow[] }) {
|
||||||
|
const t = useT();
|
||||||
|
if (releases.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<div className="panel" style={{ marginTop: 16 }}>
|
||||||
|
<h3 style={{ margin: "0 0 8px" }}>{t("release.list")}</h3>
|
||||||
|
{releases.map((r) => (
|
||||||
|
<details key={r.id} className="release-row" open={r.state === "running"}>
|
||||||
|
<summary>
|
||||||
|
<b>
|
||||||
|
{repoName(r.repo)} v{r.version}
|
||||||
|
</b>{" "}
|
||||||
|
<span className={`chip ${r.state === "done" ? "ok" : r.state === "running" ? "" : "warn"}`}>
|
||||||
|
{r.state === "running" && <span className="factory-pulse" />}
|
||||||
|
{t(`release.state.${r.state}` as any)}
|
||||||
|
</span>{" "}
|
||||||
|
<span className="hint">{fmtRelative(r.started_at)}</span>
|
||||||
|
{r.url && (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
<a href={r.url} target="_blank" rel="noreferrer" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<Icon name="external" />
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</summary>
|
||||||
|
<pre className="draft-spec">{r.log || "–"}</pre>
|
||||||
|
</details>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Segmented } from "antd";
|
||||||
import { lazy, Suspense, useEffect, useState } from "react";
|
import { lazy, Suspense, useEffect, useState } from "react";
|
||||||
import { get } from "../api";
|
import { get } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -33,13 +34,13 @@ function PdfPreview({ path }: { path: string }) {
|
|||||||
return (
|
return (
|
||||||
<div className="pdf-preview">
|
<div className="pdf-preview">
|
||||||
<div className="row pdf-nav">
|
<div className="row pdf-nav">
|
||||||
<button className="small" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
<Button size="small" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
‹
|
‹
|
||||||
</button>
|
</Button>
|
||||||
<span>{t("preview.page", { n: page, total: pages ?? "…" })}</span>
|
<span>{t("preview.page", { n: page, total: pages ?? "…" })}</span>
|
||||||
<button className="small" disabled={!pages || page >= pages} onClick={() => setPage(page + 1)}>
|
<Button size="small" disabled={!pages || page >= pages} onClick={() => setPage(page + 1)}>
|
||||||
›
|
›
|
||||||
</button>
|
</Button>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<a className="button small" href={`/api/files/raw?${q(path)}`} target="_blank" rel="noreferrer">
|
<a className="button small" href={`/api/files/raw?${q(path)}`} target="_blank" rel="noreferrer">
|
||||||
{t("preview.openBrowser")}
|
{t("preview.openBrowser")}
|
||||||
@@ -74,13 +75,12 @@ function DocPreview({ path }: { path: string }) {
|
|||||||
const s = data.sheets?.[sheet];
|
const s = data.sheets?.[sheet];
|
||||||
return (
|
return (
|
||||||
<div className="pdf-preview">
|
<div className="pdf-preview">
|
||||||
<div className="mode-tabs sheet-tabs">
|
<Segmented
|
||||||
{data.sheets?.map((x, i) => (
|
className="sheet-tabs seg-wrap"
|
||||||
<button key={x.name} className={i === sheet ? "active" : ""} onClick={() => setSheet(i)}>
|
value={sheet}
|
||||||
{x.name}
|
onChange={setSheet}
|
||||||
</button>
|
options={data.sheets?.map((x, i) => ({ value: i, label: x.name })) ?? []}
|
||||||
))}
|
/>
|
||||||
</div>
|
|
||||||
<div className="pane-scroll">
|
<div className="pane-scroll">
|
||||||
{s && (
|
{s && (
|
||||||
<table className="grid sheet">
|
<table className="grid sheet">
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
import { Button, Input, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
|
import { uploadBatch } from "../uploads";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { del, get, post, put } from "../api";
|
import { del, get, post, put } from "../api";
|
||||||
@@ -223,10 +226,7 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
|
|
||||||
const upload = async (files: FileList | File[]) => {
|
const upload = async (files: FileList | File[]) => {
|
||||||
if (!listing) return;
|
if (!listing) return;
|
||||||
for (const f of [...files]) {
|
await uploadBatch([...files].map((f) => ({ file: f, path: `${listing.path}/${f.name}` })));
|
||||||
const res = await fetch(`/api/files/upload?path=${encodeURIComponent(`${listing.path}/${f.name}`)}`, { method: "PUT", body: f, credentials: "same-origin" });
|
|
||||||
if (!res.ok) toast(`${f.name}: HTTP ${res.status}${res.status === 413 ? " – too large for the reverse proxy" : ""}`);
|
|
||||||
}
|
|
||||||
await load(listing.path);
|
await load(listing.path);
|
||||||
void refreshGit();
|
void refreshGit();
|
||||||
};
|
};
|
||||||
@@ -262,39 +262,39 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
>
|
>
|
||||||
<div className="files-toolbar">
|
<div className="files-toolbar">
|
||||||
{roots.length > 1 && (
|
{roots.length > 1 && (
|
||||||
<select value={root?.path ?? ""} onChange={(e) => { const v = e.target.value; void confirmDiscard().then((ok): unknown => ok && load(v)); }} aria-label={t("images.folder")}>
|
<Select value={root?.path ?? ""} onChange={(e) => { const v = e.target.value; void confirmDiscard().then((ok): unknown => ok && load(v)); }} aria-label={t("images.folder")}>
|
||||||
{roots.map((r) => (
|
{roots.map((r) => (
|
||||||
<option key={r.path} value={r.path}>
|
<option key={r.path} value={r.path}>
|
||||||
{r.name}
|
{r.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
)}
|
)}
|
||||||
<input className="files-search" placeholder={t("files.search")} value={search} onChange={(e) => setSearch(e.target.value)} />
|
<Input className="files-search" placeholder={t("files.search")} value={search} onChange={(e) => setSearch(e.target.value)} />
|
||||||
<button className="small" title={t("files.newFile")} onClick={() => newEntry(false)}>
|
<Button size="small" title={t("files.newFile")} onClick={() => newEntry(false)}>
|
||||||
<Icon name="plus" className="tiny" /> <Icon name="file" />
|
<Icon name="plus" className="tiny" /> <Icon name="file" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small" title={t("files.newFolder")} onClick={() => newEntry(true)}>
|
<Button size="small" title={t("files.newFolder")} onClick={() => newEntry(true)}>
|
||||||
<Icon name="plus" className="tiny" /> <Icon name="folder" />
|
<Icon name="plus" className="tiny" /> <Icon name="folder" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small" title={t("files.upload")} onClick={() => uploadRef.current?.click()}>
|
<Button size="small" title={t("files.upload")} onClick={() => uploadRef.current?.click()}>
|
||||||
<Icon name="upload" />
|
<Icon name="upload" />
|
||||||
</button>
|
</Button>
|
||||||
<input ref={uploadRef} type="file" multiple hidden onChange={(e) => e.target.files && upload(e.target.files)} />
|
<input ref={uploadRef} type="file" multiple hidden onChange={(e) => e.target.files && upload(e.target.files)} />
|
||||||
<button className={`small ${hidden ? "active" : ""}`} title={t("files.showHidden")} onClick={() => setHidden(!hidden)}>
|
<Button size="small" className={hidden ? "active" : ""} title={t("files.showHidden")} onClick={() => setHidden(!hidden)}>
|
||||||
.*
|
.*
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="crumbs">
|
<div className="crumbs">
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost crumbs-up"
|
className="crumbs-up"
|
||||||
disabled={!listing?.parent}
|
disabled={!listing?.parent}
|
||||||
onClick={() => listing?.parent && void confirmDiscard().then((ok): unknown => ok && load(listing.parent!))}
|
onClick={() => listing?.parent && void confirmDiscard().then((ok): unknown => ok && load(listing.parent!))}
|
||||||
title={t("files.up")}
|
title={t("files.up")}
|
||||||
aria-label={t("files.up")}
|
aria-label={t("files.up")}
|
||||||
>
|
>
|
||||||
<Icon name="folder-up" />
|
<Icon name="folder-up" />
|
||||||
</button>
|
</Button>
|
||||||
{crumbs.map((c, i) => {
|
{crumbs.map((c, i) => {
|
||||||
const path = i === 0 ? c : `${crumbs[0]}/${crumbs.slice(1, i + 1).join("/")}`;
|
const path = i === 0 ? c : `${crumbs[0]}/${crumbs.slice(1, i + 1).join("/")}`;
|
||||||
return (
|
return (
|
||||||
@@ -343,18 +343,18 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
<summary aria-label={t("files.actions")}><Icon name="more" /></summary>
|
<summary aria-label={t("files.actions")}><Icon name="more" /></summary>
|
||||||
<div className="menu">
|
<div className="menu">
|
||||||
{e.is_dir && (
|
{e.is_dir && (
|
||||||
<button onClick={() => void chatHere(e)}>{t("files.chatHere")}</button>
|
<Button onClick={() => void chatHere(e)}>{t("files.chatHere")}</Button>
|
||||||
)}
|
)}
|
||||||
<button onClick={() => rename(e)}>{t("files.rename")}</button>
|
<Button onClick={() => rename(e)}>{t("files.rename")}</Button>
|
||||||
<button onClick={() => duplicate(e)}>{t("files.duplicate")}</button>
|
<Button onClick={() => duplicate(e)}>{t("files.duplicate")}</Button>
|
||||||
{!e.is_dir && (
|
{!e.is_dir && (
|
||||||
<a className="button" href={rawUrl(e.path, true)}>
|
<a className="button" href={rawUrl(e.path, true)}>
|
||||||
{t("files.download")}
|
{t("files.download")}
|
||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
<button className="danger" onClick={() => remove(e)}>
|
<Button danger onClick={() => remove(e)}>
|
||||||
{t("common.delete")}
|
{t("common.delete")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
</div>
|
</div>
|
||||||
@@ -373,9 +373,9 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
return (
|
return (
|
||||||
<div className="editor-pane">
|
<div className="editor-pane">
|
||||||
<div className="editor-bar">
|
<div className="editor-bar">
|
||||||
<button className="ghost small mobile-only" onClick={() => setMobileEditor(false)}>
|
<Button type="text" size="small" className="mobile-only" onClick={() => setMobileEditor(false)}>
|
||||||
<Icon name="arrow-left" />
|
<Icon name="arrow-left" />
|
||||||
</button>
|
</Button>
|
||||||
<b className="grow">{pane.title}</b>
|
<b className="grow">{pane.title}</b>
|
||||||
</div>
|
</div>
|
||||||
<div className="pane-scroll">{pane.diff ? <Diff diff={pane.diff} /> : <div className="empty">{t("git.noDiff")}</div>}</div>
|
<div className="pane-scroll">{pane.diff ? <Diff diff={pane.diff} /> : <div className="empty">{t("git.noDiff")}</div>}</div>
|
||||||
@@ -389,25 +389,25 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
return (
|
return (
|
||||||
<div className="editor-pane">
|
<div className="editor-pane">
|
||||||
<div className="editor-bar">
|
<div className="editor-bar">
|
||||||
<button className="ghost small mobile-only" onClick={() => void confirmDiscard().then((ok): unknown => ok && setMobileEditor(false))}>
|
<Button type="text" size="small" className="mobile-only" onClick={() => void confirmDiscard().then((ok): unknown => ok && setMobileEditor(false))}>
|
||||||
<Icon name="arrow-left" />
|
<Icon name="arrow-left" />
|
||||||
</button>
|
</Button>
|
||||||
<b className="grow" title={f.path}>
|
<b className="grow" title={f.path}>
|
||||||
{baseName(f.path)}
|
{baseName(f.path)}
|
||||||
{dirty && <span className="dirty"> <Icon name="dot" className="tiny" /></span>}
|
{dirty && <span className="dirty"> <Icon name="dot" className="tiny" /></span>}
|
||||||
</b>
|
</b>
|
||||||
{(isMd || isImage) && !f.preview && (
|
{(isMd || isImage) && !f.preview && (
|
||||||
<button className="small" onClick={() => setPreview(!preview)}>
|
<Button size="small" onClick={() => setPreview(!preview)}>
|
||||||
{preview ? t("files.edit") : t("files.preview")}
|
{preview ? t("files.edit") : t("files.preview")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<a className="button small" href={rawUrl(f.path, true)}>
|
<a className="button small" href={rawUrl(f.path, true)}>
|
||||||
<Icon name="download" />
|
<Icon name="download" />
|
||||||
</a>
|
</a>
|
||||||
{!f.binary && (
|
{!f.binary && (
|
||||||
<button className="small primary" disabled={!dirty} onClick={() => save()}>
|
<Button type="primary" size="small" disabled={!dirty} onClick={() => save()}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{f.preview ? (
|
{f.preview ? (
|
||||||
@@ -441,23 +441,23 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
<>
|
<>
|
||||||
<div className={embed ? "files-embed-bar" : "topbar"}>
|
<div className={embed ? "files-embed-bar" : "topbar"}>
|
||||||
{!embed && (
|
{!embed && (
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
{!embed && <h1>{t("nav.files")}</h1>}
|
{!embed && <h1>{t("nav.files")}</h1>}
|
||||||
<div className="path">{listing?.path}</div>
|
<div className="path">{listing?.path}</div>
|
||||||
</div>
|
</div>
|
||||||
{listing?.repo && (
|
{listing?.repo && (
|
||||||
<div className="mode-tabs" role="tablist">
|
<Segmented
|
||||||
<button className={tab === "files" ? "active" : ""} onClick={() => setTab("files")}>
|
value={tab}
|
||||||
{t("files.tabFiles")}
|
onChange={(v) => setTab(v)}
|
||||||
</button>
|
options={[
|
||||||
<button className={tab === "git" ? "active" : ""} onClick={() => setTab("git")}>
|
{ value: "files" as const, label: t("files.tabFiles") },
|
||||||
Git{git && git.files.length > 0 ? ` (${git.files.length})` : ""}
|
{ value: "git" as const, label: `Git${git && git.files.length > 0 ? ` (${git.files.length})` : ""}` },
|
||||||
</button>
|
]}
|
||||||
</div>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className={`files-layout ${mobileEditor ? "show-editor" : ""}`}>
|
<div className={`files-layout ${mobileEditor ? "show-editor" : ""}`}>
|
||||||
@@ -475,11 +475,10 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
)}
|
)}
|
||||||
{!listing?.repo && listing && (
|
{!listing?.repo && listing && (
|
||||||
<div className="git-init">
|
<div className="git-init">
|
||||||
<button className="small" onClick={() => act(() => post("/git", { path: listing.path, action: "init" }))}>
|
<Button size="small" onClick={() => act(() => post("/git", { path: listing.path, action: "init" }))}>
|
||||||
{t("git.init")}
|
{t("git.init")}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
const url = await promptDialog({ message: t("git.cloneUrl"), placeholder: "https://…/repo.git" });
|
const url = await promptDialog({ message: t("git.cloneUrl"), placeholder: "https://…/repo.git" });
|
||||||
if (!url) return;
|
if (!url) return;
|
||||||
@@ -488,7 +487,7 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{t("git.clone")}
|
{t("git.clone")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Checkbox, Input, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { post } from "../api";
|
import { post } from "../api";
|
||||||
@@ -101,26 +103,26 @@ export function GitPanel({
|
|||||||
return (
|
return (
|
||||||
<div key={`${isStaged}-${f.path}`} className="git-file">
|
<div key={`${isStaged}-${f.path}`} className="git-file">
|
||||||
<span className={`git-mark m-${LABEL[code] ?? code}`}>{LABEL[code] ?? code}</span>
|
<span className={`git-mark m-${LABEL[code] ?? code}`}>{LABEL[code] ?? code}</span>
|
||||||
<button className="ghost git-name" onClick={() => diff(f, isStaged)} title={f.path}>
|
<Button type="text" className="git-name" onClick={() => diff(f, isStaged)} title={f.path}>
|
||||||
{f.path}
|
{f.path}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost" title={t("git.openFile")} onClick={() => openFile(abs(f))}>
|
<Button type="text" size="small" title={t("git.openFile")} onClick={() => openFile(abs(f))}>
|
||||||
<Icon name="external" />
|
<Icon name="external" />
|
||||||
</button>
|
</Button>
|
||||||
{isStaged ? (
|
{isStaged ? (
|
||||||
<button className="small" title={t("git.unstage")} onClick={() => run("unstage", () => call("unstage", { files: [abs(f)] }))}>
|
<Button size="small" title={t("git.unstage")} onClick={() => run("unstage", () => call("unstage", { files: [abs(f)] }))}>
|
||||||
<Icon name="minus" />
|
<Icon name="minus" />
|
||||||
</button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{f.index !== "?" && (
|
{f.index !== "?" && (
|
||||||
<button className="small ghost danger" title={t("git.discard")} onClick={() => void confirmDialog({ message: t("git.discardConfirm", { file: f.path }), danger: true, confirmLabel: t("git.discard") }).then((ok): unknown => ok && run("discard", () => call("discard", { files: [abs(f)] })))}>
|
<Button type="text" danger size="small" title={t("git.discard")} onClick={() => void confirmDialog({ message: t("git.discardConfirm", { file: f.path }), danger: true, confirmLabel: t("git.discard") }).then((ok): unknown => ok && run("discard", () => call("discard", { files: [abs(f)] })))}>
|
||||||
<Icon name="refresh" />
|
<Icon name="refresh" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button className="small" title={t("git.stage")} onClick={() => run("stage", () => call("stage", { files: [abs(f)] }))}>
|
<Button size="small" title={t("git.stage")} onClick={() => run("stage", () => call("stage", { files: [abs(f)] }))}>
|
||||||
+
|
+
|
||||||
</button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -130,7 +132,7 @@ export function GitPanel({
|
|||||||
return (
|
return (
|
||||||
<div className="git-panel">
|
<div className="git-panel">
|
||||||
<div className="git-branch">
|
<div className="git-branch">
|
||||||
<select
|
<Select
|
||||||
value={branches.find((b) => b.current)?.name ?? status.branch ?? ""}
|
value={branches.find((b) => b.current)?.name ?? status.branch ?? ""}
|
||||||
onChange={(e) => run("checkout", () => call("checkout", { branch: e.target.value.replace(/^origin\//, "") }), true)}
|
onChange={(e) => run("checkout", () => call("checkout", { branch: e.target.value.replace(/^origin\//, "") }), true)}
|
||||||
aria-label={t("git.branch")}
|
aria-label={t("git.branch")}
|
||||||
@@ -141,9 +143,8 @@ export function GitPanel({
|
|||||||
{b.name}
|
{b.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
title={t("git.newBranch")}
|
title={t("git.newBranch")}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
const name = await promptDialog({ message: t("git.newBranchName"), placeholder: "feature/…" });
|
const name = await promptDialog({ message: t("git.newBranchName"), placeholder: "feature/…" });
|
||||||
@@ -151,7 +152,7 @@ export function GitPanel({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
+
|
+
|
||||||
</button>
|
</Button>
|
||||||
{status.upstream && (
|
{status.upstream && (
|
||||||
<span className="chip" title={status.upstream}>
|
<span className="chip" title={status.upstream}>
|
||||||
<Icon name="arrow-up" className="tiny" />{status.ahead} <Icon name="arrow-down" className="tiny" />{status.behind}
|
<Icon name="arrow-up" className="tiny" />{status.ahead} <Icon name="arrow-down" className="tiny" />{status.behind}
|
||||||
@@ -159,21 +160,22 @@ export function GitPanel({
|
|||||||
)}
|
)}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{(["fetch", "pull", "push"] as const).map((a) => (
|
{(["fetch", "pull", "push"] as const).map((a) => (
|
||||||
<button key={a} className="small" disabled={!!busy} onClick={() => run(a, () => call(a), true)}>
|
<Button size="small" key={a} disabled={!!busy} onClick={() => run(a, () => call(a), true)}>
|
||||||
{busy === a ? <Spinner small /> : t(`git.${a}`)}
|
{busy === a ? <Spinner small /> : t(`git.${a}`)}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{output && <pre className={`git-output ${output.ok ? "" : "err"}`}>{output.text}</pre>}
|
{output && <pre className={`git-output ${output.ok ? "" : "err"}`}>{output.text}</pre>}
|
||||||
|
|
||||||
<div className="mode-tabs" style={{ margin: "8px 0" }}>
|
<Segmented
|
||||||
<button className={view === "changes" ? "active" : ""} onClick={() => setView("changes")}>
|
style={{ margin: "8px 0", alignSelf: "flex-start" }}
|
||||||
{t("git.changes")} ({status.files.length})
|
value={view}
|
||||||
</button>
|
onChange={(v) => setView(v)}
|
||||||
<button className={view === "history" ? "active" : ""} onClick={() => setView("history")}>
|
options={[
|
||||||
{t("git.history")}
|
{ value: "changes" as const, label: `${t("git.changes")} (${status.files.length})` },
|
||||||
</button>
|
{ value: "history" as const, label: t("git.history") },
|
||||||
</div>
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
{view === "changes" ? (
|
{view === "changes" ? (
|
||||||
<>
|
<>
|
||||||
@@ -181,9 +183,9 @@ export function GitPanel({
|
|||||||
<div className="git-head">
|
<div className="git-head">
|
||||||
{t("git.staged")} ({staged.length})
|
{t("git.staged")} ({staged.length})
|
||||||
{staged.length > 0 && (
|
{staged.length > 0 && (
|
||||||
<button className="small ghost" onClick={() => run("unstage", () => call("unstage", { files: staged.map(abs) }))}>
|
<Button type="text" size="small" onClick={() => run("unstage", () => call("unstage", { files: staged.map(abs) }))}>
|
||||||
{t("git.unstageAll")}
|
{t("git.unstageAll")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{staged.map((f) => fileRow(f, true))}
|
{staged.map((f) => fileRow(f, true))}
|
||||||
@@ -192,30 +194,28 @@ export function GitPanel({
|
|||||||
<div className="git-head">
|
<div className="git-head">
|
||||||
{t("git.unstaged")} ({unstaged.length})
|
{t("git.unstaged")} ({unstaged.length})
|
||||||
{unstaged.length > 0 && (
|
{unstaged.length > 0 && (
|
||||||
<button className="small ghost" onClick={() => run("stage", () => call("stage", { files: unstaged.map(abs) }))}>
|
<Button type="text" size="small" onClick={() => run("stage", () => call("stage", { files: unstaged.map(abs) }))}>
|
||||||
{t("git.stageAll")}
|
{t("git.stageAll")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{unstaged.map((f) => fileRow(f, false))}
|
{unstaged.map((f) => fileRow(f, false))}
|
||||||
{status.files.length === 0 && <div className="empty" style={{ padding: 12 }}>{t("git.clean")}</div>}
|
{status.files.length === 0 && <div className="empty" style={{ padding: 12 }}>{t("git.clean")}</div>}
|
||||||
</div>
|
</div>
|
||||||
<div className="git-commit">
|
<div className="git-commit">
|
||||||
<textarea rows={3} placeholder={t("git.message")} value={message} onChange={(e) => setMessage(e.target.value)} />
|
<Input.TextArea rows={3} placeholder={t("git.message")} value={message} onChange={(e) => setMessage(e.target.value)} />
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<label style={{ fontSize: 12.5 }}>
|
<Checkbox style={{ fontSize: 12.5 }} checked={amend} onChange={(e) => setAmend(e.target.checked)}> {t("git.amend")}
|
||||||
<input type="checkbox" checked={amend} onChange={(e) => setAmend(e.target.checked)} /> {t("git.amend")}
|
</Checkbox>
|
||||||
</label>
|
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button
|
<Button
|
||||||
disabled={!!busy || staged.length === 0}
|
disabled={!!busy || staged.length === 0}
|
||||||
title={t("git.suggestHint")}
|
title={t("git.suggestHint")}
|
||||||
onClick={() => run("suggest", async () => setMessage((await call<{ message: string }>("suggest")).message))}
|
onClick={() => run("suggest", async () => setMessage((await call<{ message: string }>("suggest")).message))}
|
||||||
>
|
>
|
||||||
{busy === "suggest" ? <Spinner small /> : t("git.suggest")}
|
{busy === "suggest" ? <Spinner small /> : t("git.suggest")}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button type="primary"
|
||||||
className="primary"
|
|
||||||
disabled={!!busy || (!amend && (!message.trim() || staged.length === 0))}
|
disabled={!!busy || (!amend && (!message.trim() || staged.length === 0))}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
run(
|
run(
|
||||||
@@ -231,7 +231,7 @@ export function GitPanel({
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{busy === "commit" ? <Spinner small /> : t("git.commit")}
|
{busy === "commit" ? <Spinner small /> : t("git.commit")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -260,6 +260,12 @@ const P: Record<string, ReactNode> = {
|
|||||||
<path d="M4.5 20.5a7.5 7.5 0 0 1 15 0" />
|
<path d="M4.5 20.5a7.5 7.5 0 0 1 15 0" />
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
|
factory: (
|
||||||
|
<>
|
||||||
|
<path d="M3 20V9.5l5 3V9.5l5 3V9.5l5 3V4h3v16Z" />
|
||||||
|
<path d="M7 16h2M12 16h2M17 16h2" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
toolbox: (
|
toolbox: (
|
||||||
<>
|
<>
|
||||||
<rect x="3" y="8" width="18" height="11" rx="2" />
|
<rect x="3" y="8" width="18" height="11" rx="2" />
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
import { toast } from "../dialogs";
|
import { toast } from "../dialogs";
|
||||||
@@ -135,25 +136,25 @@ export function ImageAnnotator({ src, name, onDone, onCancel }: { src: string; n
|
|||||||
/>
|
/>
|
||||||
<div className="annotator-tools" role="toolbar" aria-label={t("viewer.annotate")}>
|
<div className="annotator-tools" role="toolbar" aria-label={t("viewer.annotate")}>
|
||||||
{(["pen", "arrow", "rect"] as Tool[]).map((k) => (
|
{(["pen", "arrow", "rect"] as Tool[]).map((k) => (
|
||||||
<button key={k} className={`small ${tool === k ? "primary" : "ghost"}`} onClick={() => setTool(k)} aria-pressed={tool === k} title={t(`viewer.tool.${k}` as const)}>
|
<Button key={k} size="small" type={tool === k ? "primary" : "text"} onClick={() => setTool(k)} aria-pressed={tool === k} title={t(`viewer.tool.${k}` as const)}>
|
||||||
<Icon name={k === "pen" ? "edit" : k === "arrow" ? "arrow-right" : "box-off"} />
|
<Icon name={k === "pen" ? "edit" : k === "arrow" ? "arrow-right" : "box-off"} />
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
<span className="annotator-colors">
|
<span className="annotator-colors">
|
||||||
{COLORS.map((c) => (
|
{COLORS.map((c) => (
|
||||||
<button key={c} className={`swatch ${c === color ? "on" : ""}`} style={{ background: c }} onClick={() => setColor(c)} aria-label={c} aria-pressed={c === color} />
|
<button key={c} className={`swatch ${c === color ? "on" : ""}`} style={{ background: c }} onClick={() => setColor(c)} aria-label={c} aria-pressed={c === color} />
|
||||||
))}
|
))}
|
||||||
</span>
|
</span>
|
||||||
<button className="small ghost" onClick={() => setShapes((s) => s.slice(0, -1))} disabled={!shapes.length} title={t("viewer.undo")} aria-label={t("viewer.undo")}>
|
<Button type="text" size="small" onClick={() => setShapes((s) => s.slice(0, -1))} disabled={!shapes.length} title={t("viewer.undo")} aria-label={t("viewer.undo")}>
|
||||||
<Icon name="undo" />
|
<Icon name="undo" />
|
||||||
</button>
|
</Button>
|
||||||
<span className="grow" />
|
<span className="grow" />
|
||||||
<button className="small" onClick={onCancel}>
|
<Button size="small" onClick={onCancel}>
|
||||||
{t("common.cancel")}
|
{t("common.cancel")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small primary" onClick={finish} disabled={!ready}>
|
<Button type="primary" size="small" onClick={finish} disabled={!ready}>
|
||||||
<Icon name="clip" /> {t("viewer.attach")}
|
<Icon name="clip" /> {t("viewer.attach")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { ImageAnnotator } from "./ImageAnnotator";
|
import { ImageAnnotator } from "./ImageAnnotator";
|
||||||
@@ -139,12 +140,12 @@ export function ImageViewer() {
|
|||||||
<span className="viewer-name">{cur.alt && !/^(image|SVG)$/i.test(cur.alt) ? cur.alt : ""}</span>
|
<span className="viewer-name">{cur.alt && !/^(image|SVG)$/i.test(cur.alt) ? cur.alt : ""}</span>
|
||||||
{sessionId && (
|
{sessionId && (
|
||||||
<>
|
<>
|
||||||
<button className="small ghost" onClick={() => setMarking(true)} title={t("viewer.annotate")} aria-label={t("viewer.annotate")}>
|
<Button type="text" size="small" onClick={() => setMarking(true)} title={t("viewer.annotate")} aria-label={t("viewer.annotate")}>
|
||||||
<Icon name="edit" />
|
<Icon name="edit" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost" onClick={() => void useInChat()} title={t("viewer.useInChat")} aria-label={t("viewer.useInChat")}>
|
<Button type="text" size="small" onClick={() => void useInChat()} title={t("viewer.useInChat")} aria-label={t("viewer.useInChat")}>
|
||||||
<Icon name="reply" />
|
<Icon name="reply" />
|
||||||
</button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<a className="button small ghost" href={cur.src} target="_blank" rel="noreferrer" title={t("viewer.open")} aria-label={t("viewer.open")}>
|
<a className="button small ghost" href={cur.src} target="_blank" rel="noreferrer" title={t("viewer.open")} aria-label={t("viewer.open")}>
|
||||||
@@ -153,9 +154,9 @@ export function ImageViewer() {
|
|||||||
<a className="button small ghost" href={cur.src} download title={t("viewer.download")} aria-label={t("viewer.download")}>
|
<a className="button small ghost" href={cur.src} download title={t("viewer.download")} aria-label={t("viewer.download")}>
|
||||||
<Icon name="download" />
|
<Icon name="download" />
|
||||||
</a>
|
</a>
|
||||||
<button className="small ghost" onClick={close} aria-label={t("common.close")}>
|
<Button type="text" size="small" onClick={close} aria-label={t("common.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{marking && (
|
{marking && (
|
||||||
<ImageAnnotator
|
<ImageAnnotator
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { del, post } from "../api";
|
import { del, post } from "../api";
|
||||||
@@ -63,9 +65,9 @@ export function Images({ onMenu }: { onMenu: () => void }) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{t("nav.images")}</h1>
|
<h1>{t("nav.images")}</h1>
|
||||||
</div>
|
</div>
|
||||||
@@ -74,7 +76,7 @@ export function Images({ onMenu }: { onMenu: () => void }) {
|
|||||||
<div className="page-inner">
|
<div className="page-inner">
|
||||||
{cfg && !cfg.enabled && <div className="notice">{t("images.disabled")}</div>}
|
{cfg && !cfg.enabled && <div className="notice">{t("images.disabled")}</div>}
|
||||||
<div className="panel">
|
<div className="panel">
|
||||||
<textarea
|
<Input.TextArea
|
||||||
style={{ width: "100%", minHeight: 90 }}
|
style={{ width: "100%", minHeight: 90 }}
|
||||||
placeholder={t("images.promptPlaceholder")}
|
placeholder={t("images.promptPlaceholder")}
|
||||||
value={form.prompt}
|
value={form.prompt}
|
||||||
@@ -82,42 +84,42 @@ export function Images({ onMenu }: { onMenu: () => void }) {
|
|||||||
onKeyDown={(e) => e.key === "Enter" && (e.ctrlKey || e.metaKey) && form.prompt.trim() && generate()}
|
onKeyDown={(e) => e.key === "Enter" && (e.ctrlKey || e.metaKey) && form.prompt.trim() && generate()}
|
||||||
/>
|
/>
|
||||||
<div className="row" style={{ marginTop: 8 }}>
|
<div className="row" style={{ marginTop: 8 }}>
|
||||||
<select value={form.model} onChange={(e) => setForm({ ...form, model: e.target.value })} aria-label={t("images.model")}>
|
<Select value={form.model} onChange={(e) => setForm({ ...form, model: e.target.value })} aria-label={t("images.model")}>
|
||||||
{cfg?.models.map((m) => (
|
{cfg?.models.map((m) => (
|
||||||
<option key={m.id} value={m.id}>
|
<option key={m.id} value={m.id}>
|
||||||
{m.name}
|
{m.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<select value={form.size} onChange={(e) => setForm({ ...form, size: e.target.value })} aria-label={t("images.size")}>
|
<Select value={form.size} onChange={(e) => setForm({ ...form, size: e.target.value })} aria-label={t("images.size")}>
|
||||||
{cfg?.sizes.map((s) => (
|
{cfg?.sizes.map((s) => (
|
||||||
<option key={s} value={s}>
|
<option key={s} value={s}>
|
||||||
{t(`images.size.${s}` as Key)}
|
{t(`images.size.${s}` as Key)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<select value={form.count} onChange={(e) => setForm({ ...form, count: Number(e.target.value) })} aria-label={t("images.count")}>
|
<Select value={form.count} onChange={(e) => setForm({ ...form, count: Number(e.target.value) })} aria-label={t("images.count")}>
|
||||||
{[1, 2, 3, 4].map((n) => (
|
{[1, 2, 3, 4].map((n) => (
|
||||||
<option key={n} value={n}>
|
<option key={n} value={n}>
|
||||||
{t("images.countN", { n })}
|
{t("images.countN", { n })}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
{roots.length > 1 && (
|
{roots.length > 1 && (
|
||||||
<select value={form.root} onChange={(e) => setForm({ ...form, root: e.target.value })} aria-label={t("images.folder")}>
|
<Select value={form.root} onChange={(e) => setForm({ ...form, root: e.target.value })} aria-label={t("images.folder")}>
|
||||||
{roots.map((r) => (
|
{roots.map((r) => (
|
||||||
<option key={r.path} value={r.path}>
|
<option key={r.path} value={r.path}>
|
||||||
{r.name}
|
{r.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
)}
|
)}
|
||||||
<input value={form.folder} onChange={(e) => setForm({ ...form, folder: e.target.value })} title={t("images.folder")} style={{ width: 140 }} />
|
<Input value={form.folder} onChange={(e) => setForm({ ...form, folder: e.target.value })} title={t("images.folder")} style={{ width: 140 }} />
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{price ? <span className="chip">≈ {fmtCost(price * form.count, cfg!.currency)}</span> : null}
|
{price ? <span className="chip">≈ {fmtCost(price * form.count, cfg!.currency)}</span> : null}
|
||||||
<button className="primary" disabled={busy || !form.prompt.trim() || !cfg?.enabled} onClick={generate}>
|
<Button type="primary" disabled={busy || !form.prompt.trim() || !cfg?.enabled} onClick={generate}>
|
||||||
{busy ? <Spinner small /> : null} {busy ? t("images.generating") : t("images.generate")}
|
{busy ? <Spinner small /> : null} {busy ? t("images.generating") : t("images.generate")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{error && <div className="notice err" style={{ marginTop: 8 }}>{error}</div>}
|
{error && <div className="notice err" style={{ marginTop: 8 }}>{error}</div>}
|
||||||
</div>
|
</div>
|
||||||
@@ -144,15 +146,15 @@ export function Images({ onMenu }: { onMenu: () => void }) {
|
|||||||
<a className="button small" href={fileUrl(img.id)} download={img.path.split("/").pop()}>
|
<a className="button small" href={fileUrl(img.id)} download={img.path.split("/").pop()}>
|
||||||
<Icon name="download" />
|
<Icon name="download" />
|
||||||
</a>
|
</a>
|
||||||
<button className="small" title={t("images.reuse")} onClick={() => setForm({ ...form, prompt: img.prompt, model: img.model })}>
|
<Button size="small" title={t("images.reuse")} onClick={() => setForm({ ...form, prompt: img.prompt, model: img.model })}>
|
||||||
<Icon name="refresh" />
|
<Icon name="refresh" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small" title={t("images.copyPath")} onClick={() => navigator.clipboard?.writeText(img.path)}>
|
<Button size="small" title={t("images.copyPath")} onClick={() => navigator.clipboard?.writeText(img.path)}>
|
||||||
<Icon name="copy" />
|
<Icon name="copy" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small danger" title={t("common.delete")} onClick={() => void confirmDialog({ message: t("images.deleteConfirm"), danger: true, confirmLabel: t("common.delete") }).then((ok): unknown => ok && del(`/images/${img.id}`).then(reload))}>
|
<Button danger size="small" title={t("common.delete")} onClick={() => void confirmDialog({ message: t("images.deleteConfirm"), danger: true, confirmLabel: t("common.delete") }).then((ok): unknown => ok && del(`/images/${img.id}`).then(reload))}>
|
||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</figcaption>
|
</figcaption>
|
||||||
</figure>
|
</figure>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { patch } from "../api";
|
import { patch } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -21,13 +23,12 @@ export function InstructionsDialog({ sessionId, value, onClose }: { sessionId: s
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} className="instructions-modal" role="dialog" aria-label={t("instructions.title")}>
|
||||||
<div className="modal instructions-modal" role="dialog" aria-label={t("instructions.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("instructions.title")}</h3>
|
<h3>{t("instructions.title")}</h3>
|
||||||
<div className="hint" style={{ marginBottom: 8 }}>
|
<div className="hint" style={{ marginBottom: 8 }}>
|
||||||
{t("instructions.hint")}
|
{t("instructions.hint")}
|
||||||
</div>
|
</div>
|
||||||
<textarea
|
<Input.TextArea
|
||||||
autoFocus
|
autoFocus
|
||||||
rows={10}
|
rows={10}
|
||||||
style={{ width: "100%" }}
|
style={{ width: "100%" }}
|
||||||
@@ -39,17 +40,16 @@ export function InstructionsDialog({ sessionId, value, onClose }: { sessionId: s
|
|||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
|
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
|
||||||
{value && (
|
{value && (
|
||||||
<button className="danger" onClick={() => void save("")} disabled={busy}>
|
<Button danger onClick={() => void save("")} disabled={busy}>
|
||||||
{t("instructions.clear")}
|
{t("instructions.clear")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
<Button onClick={onClose}>{t("common.cancel")}</Button>
|
||||||
<button className="primary" onClick={() => void save(text)} disabled={busy || text.trim() === value.trim()}>
|
<Button type="primary" onClick={() => void save(text)} disabled={busy || text.trim() === value.trim()}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { post } from "../api";
|
import { post } from "../api";
|
||||||
@@ -98,12 +99,12 @@ export function PermissionCard({ req, currentId }: { req: PermissionRequest; cur
|
|||||||
<Icon name="sparkle" className="tiny" /> {explanation}
|
<Icon name="sparkle" className="tiny" /> {explanation}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<button className="small ghost explain-btn" disabled={explaining} onClick={explain}>
|
<Button type="text" size="small" className="explain-btn" disabled={explaining} onClick={explain}>
|
||||||
<Icon name="sparkle" /> {explaining ? t("permission.explaining") : t("permission.explain")}
|
<Icon name="sparkle" /> {explaining ? t("permission.explaining") : t("permission.explain")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{explainError && <div className="hint">{explainError}</div>}
|
{explainError && <div className="hint">{explainError}</div>}
|
||||||
<input
|
<Input
|
||||||
style={{ width: "100%", marginTop: 8 }}
|
style={{ width: "100%", marginTop: 8 }}
|
||||||
placeholder={t("permission.feedback")}
|
placeholder={t("permission.feedback")}
|
||||||
value={feedback}
|
value={feedback}
|
||||||
@@ -111,20 +112,20 @@ export function PermissionCard({ req, currentId }: { req: PermissionRequest; cur
|
|||||||
onKeyDown={(e) => e.key === "Enter" && reply("reject")}
|
onKeyDown={(e) => e.key === "Enter" && reply("reject")}
|
||||||
/>
|
/>
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
<button className="primary" disabled={busy || (hunkCount > 1 && chosen === 0)} onClick={() => reply("once")} autoFocus>
|
<Button type="primary" disabled={busy || (hunkCount > 1 && chosen === 0)} onClick={() => reply("once")} autoFocus>
|
||||||
{partial ? t("permission.applySelected", { k: chosen, n: hunkCount }) : t("permission.allowOnce")}
|
{partial ? t("permission.applySelected", { k: chosen, n: hunkCount }) : t("permission.allowOnce")}
|
||||||
</button>
|
</Button>
|
||||||
<button disabled={busy || partial} onClick={() => reply("always")}>
|
<Button disabled={busy || partial} onClick={() => reply("always")}>
|
||||||
{alwaysLabel}
|
{alwaysLabel}
|
||||||
</button>
|
</Button>
|
||||||
{!dangerous && (
|
{!dangerous && (
|
||||||
<button disabled={busy || partial} onClick={() => reply("project")} title={t("permission.projectHint")}>
|
<Button disabled={busy || partial} onClick={() => reply("project")} title={t("permission.projectHint")}>
|
||||||
{projectLabel}
|
{projectLabel}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button className="danger" disabled={busy} onClick={() => reply("reject")}>
|
<Button danger disabled={busy} onClick={() => reply("reject")}>
|
||||||
{feedback ? t("permission.rejectWithFeedback") : t("permission.reject")}
|
{feedback ? t("permission.rejectWithFeedback") : t("permission.reject")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -194,7 +195,7 @@ export function QuestionCard({ req, currentId }: { req: QuestionRequest; current
|
|||||||
<Icon name={q.multi_select ? (isSel ? "box-on" : "box-off") : isSel ? "radio-on" : "radio-off"} />
|
<Icon name={q.multi_select ? (isSel ? "box-on" : "box-off") : isSel ? "radio-on" : "radio-off"} />
|
||||||
<div style={{ flex: 1 }}>
|
<div style={{ flex: 1 }}>
|
||||||
{o.label === OTHER ? (
|
{o.label === OTHER ? (
|
||||||
<input
|
<Input
|
||||||
style={{ width: "100%" }}
|
style={{ width: "100%" }}
|
||||||
placeholder={t("question.other")}
|
placeholder={t("question.other")}
|
||||||
value={other[qi] ?? ""}
|
value={other[qi] ?? ""}
|
||||||
@@ -214,7 +215,7 @@ export function QuestionCard({ req, currentId }: { req: QuestionRequest; current
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<textarea
|
<Input.TextArea
|
||||||
style={{ width: "100%", marginTop: 6 }}
|
style={{ width: "100%", marginTop: 6 }}
|
||||||
placeholder={t("question.answer")}
|
placeholder={t("question.answer")}
|
||||||
value={other[qi] ?? ""}
|
value={other[qi] ?? ""}
|
||||||
@@ -224,12 +225,12 @@ export function QuestionCard({ req, currentId }: { req: QuestionRequest; current
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
<button className="primary" disabled={busy || !complete} onClick={() => submit()}>
|
<Button type="primary" disabled={busy || !complete} onClick={() => submit()}>
|
||||||
{t("question.submit")}
|
{t("question.submit")}
|
||||||
</button>
|
</Button>
|
||||||
<button disabled={busy} onClick={() => submit(true)}>
|
<Button disabled={busy} onClick={() => submit(true)}>
|
||||||
{t("question.dismiss")}
|
{t("question.dismiss")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Checkbox, Input, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { ApiError, get, patch, post, put } from "../api";
|
import { ApiError, get, patch, post, put } from "../api";
|
||||||
import { confirmDialog, toast } from "../dialogs";
|
import { confirmDialog, toast } from "../dialogs";
|
||||||
@@ -174,35 +176,42 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost" onClick={back} title={t("jobEditor.back")} aria-label={t("jobEditor.back")}>
|
<Button type="text" size="small" onClick={back} title={t("jobEditor.back")} aria-label={t("jobEditor.back")}>
|
||||||
<Icon name="arrow-left" />
|
<Icon name="arrow-left" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{settings.name || t("nav.jobs")}</h1>
|
<h1>{settings.name || t("nav.jobs")}</h1>
|
||||||
<div className="path mono">{job.path}</div>
|
<div className="path mono">{job.path}</div>
|
||||||
</div>
|
</div>
|
||||||
<label className="switch" title={t(job.enabled ? "jobs.disable" : "jobs.enable")}>
|
<Checkbox className="switch" title={t(job.enabled ? "jobs.disable" : "jobs.enable")} checked={job.enabled} onChange={(e) => void setEnabled(e.target.checked)}>
|
||||||
<input type="checkbox" checked={job.enabled} onChange={(e) => void setEnabled(e.target.checked)} />
|
|
||||||
<span>{t(job.enabled ? "jobs.on" : "jobs.off")}</span>
|
<span>{t(job.enabled ? "jobs.on" : "jobs.off")}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
<button className="small ghost" onClick={runNow} title={t("jobs.runNow")}>
|
<Button type="text" size="small" onClick={runNow} title={t("jobs.runNow")}>
|
||||||
<Icon name="play" /> <span className="hide-mobile">{t("jobs.runNow")}</span>
|
<Icon name="play" /> <span className="hide-mobile">{t("jobs.runNow")}</span>
|
||||||
</button>
|
</Button>
|
||||||
<button className="small primary" disabled={!dirty || saving} onClick={() => void save()}>
|
<Button type="primary" size="small" disabled={!dirty || saving} onClick={() => void save()}>
|
||||||
{saving ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
{saving ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="job-tabs" role="tablist">
|
<div className="job-tabs">
|
||||||
{(["prompt", "settings", "assistant"] as Tab[]).map((x) => (
|
<Segmented<Tab>
|
||||||
<button key={x} role="tab" aria-selected={tab === x} className={tab === x ? "active" : ""} onClick={() => setTab(x)}>
|
block
|
||||||
{t(`jobEditor.tab.${x}` as const)}
|
value={tab}
|
||||||
{x === "prompt" && fileDirty && " •"}
|
onChange={setTab}
|
||||||
{x === "settings" && settingsDirty && " •"}
|
options={(["prompt", "settings", "assistant"] as Tab[]).map((x) => ({
|
||||||
</button>
|
value: x,
|
||||||
))}
|
label: (
|
||||||
|
<>
|
||||||
|
{t(`jobEditor.tab.${x}` as const)}
|
||||||
|
{x === "prompt" && fileDirty && " •"}
|
||||||
|
{x === "settings" && settingsDirty && " •"}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className={`job-editor tab-${tab}`}>
|
<div className={`job-editor tab-${tab}`}>
|
||||||
<div className="job-editor-main">
|
<div className="job-editor-main">
|
||||||
@@ -210,7 +219,7 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
|||||||
<div className="job-editor-row">
|
<div className="job-editor-row">
|
||||||
<label className="field" style={{ flex: 2 }}>
|
<label className="field" style={{ flex: 2 }}>
|
||||||
<span>{t("jobs.tplName")}</span>
|
<span>{t("jobs.tplName")}</span>
|
||||||
<input value={settings.name} onChange={(e) => up({ name: e.target.value })} />
|
<Input value={settings.name} onChange={(e) => up({ name: e.target.value })} />
|
||||||
</label>
|
</label>
|
||||||
<div className="job-editor-status">
|
<div className="job-editor-status">
|
||||||
<span>
|
<span>
|
||||||
@@ -233,19 +242,19 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
|||||||
<div className="job-editor-row">
|
<div className="job-editor-row">
|
||||||
<label className="field">
|
<label className="field">
|
||||||
<span>{t("jobs.tplMode")}</span>
|
<span>{t("jobs.tplMode")}</span>
|
||||||
<select value={settings.agent} onChange={(e) => up({ agent: e.target.value })}>
|
<Select value={settings.agent} onChange={(e) => up({ agent: e.target.value })}>
|
||||||
<option value="build">build</option>
|
<option value="build">build</option>
|
||||||
<option value="plan">plan</option>
|
<option value="plan">plan</option>
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label className="field">
|
<label className="field">
|
||||||
<span>{t("jobs.permissionMode")}</span>
|
<span>{t("jobs.permissionMode")}</span>
|
||||||
<select value={settings.permission_mode} title={t("jobs.permissionModeHint")} onChange={(e) => up({ permission_mode: e.target.value })}>
|
<Select value={settings.permission_mode} title={t("jobs.permissionModeHint")} onChange={(e) => up({ permission_mode: e.target.value })}>
|
||||||
<option value="default">{t("permissionMode.default")}</option>
|
<option value="default">{t("permissionMode.default")}</option>
|
||||||
<option value="auto">{t("permissionMode.auto")}</option>
|
<option value="auto">{t("permissionMode.auto")}</option>
|
||||||
<option value="accept_edits">{t("permissionMode.accept_edits")}</option>
|
<option value="accept_edits">{t("permissionMode.accept_edits")}</option>
|
||||||
<option value="bypass">{t("permissionMode.bypass")}</option>
|
<option value="bypass">{t("permissionMode.bypass")}</option>
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label className="field">
|
<label className="field">
|
||||||
<span>{t("composer.model")}</span>
|
<span>{t("composer.model")}</span>
|
||||||
@@ -253,13 +262,12 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
|||||||
</label>
|
</label>
|
||||||
<label className="field" style={{ maxWidth: 140 }}>
|
<label className="field" style={{ maxWidth: 140 }}>
|
||||||
<span>{t("jobEditor.timeout")}</span>
|
<span>{t("jobEditor.timeout")}</span>
|
||||||
<input type="number" min={1} max={1440} value={settings.timeout_minutes} onChange={(e) => up({ timeout_minutes: Math.max(1, Number(e.target.value) || 60) })} />
|
<Input type="number" min={1} max={1440} value={settings.timeout_minutes} onChange={(e) => up({ timeout_minutes: Math.max(1, Number(e.target.value) || 60) })} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center", marginTop: 6 }}>
|
<Checkbox className="row" style={{ gap: 6, alignItems: "center", marginTop: 6 }} checked={settings.notify} onChange={(e) => up({ notify: e.target.checked })}>
|
||||||
<input type="checkbox" checked={settings.notify} onChange={(e) => up({ notify: e.target.checked })} />
|
|
||||||
{t("jobEditor.notify")}
|
{t("jobEditor.notify")}
|
||||||
</label>
|
</Checkbox>
|
||||||
{settings.permission_mode !== "bypass" && <div className="hint">{t("jobEditor.bypassHint")}</div>}
|
{settings.permission_mode !== "bypass" && <div className="hint">{t("jobEditor.bypassHint")}</div>}
|
||||||
</section>
|
</section>
|
||||||
<section className="job-editor-prompt">
|
<section className="job-editor-prompt">
|
||||||
@@ -270,9 +278,9 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
|||||||
{changedOnDisk && (
|
{changedOnDisk && (
|
||||||
<div className="notice">
|
<div className="notice">
|
||||||
{t("jobEditor.changedOnDisk")}{" "}
|
{t("jobEditor.changedOnDisk")}{" "}
|
||||||
<button className="small" onClick={() => void loadFile(job.path)}>
|
<Button size="small" onClick={() => void loadFile(job.path)}>
|
||||||
{t("jobEditor.reload")}
|
{t("jobEditor.reload")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{job.error && !job.error.includes("empty") && <div className="notice err">{job.error}</div>}
|
{job.error && !job.error.includes("empty") && <div className="notice err">{job.error}</div>}
|
||||||
@@ -292,9 +300,9 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
|||||||
<div className="job-assistant-start">
|
<div className="job-assistant-start">
|
||||||
<Icon name="sparkle" />
|
<Icon name="sparkle" />
|
||||||
<p>{t("jobEditor.assistantIntro")}</p>
|
<p>{t("jobEditor.assistantIntro")}</p>
|
||||||
<button className="primary" onClick={startAssistant}>
|
<Button type="primary" onClick={startAssistant}>
|
||||||
{t("jobEditor.assistantStart")}
|
{t("jobEditor.assistantStart")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</aside>
|
</aside>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { del, get, patch, post } from "../api";
|
import { del, get, patch, post } from "../api";
|
||||||
import { fmtRelative, useT } from "../i18n";
|
import { fmtRelative, useT } from "../i18n";
|
||||||
@@ -56,9 +57,9 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{t("nav.jobs")}</h1>
|
<h1>{t("nav.jobs")}</h1>
|
||||||
</div>
|
</div>
|
||||||
@@ -67,9 +68,9 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
<div className="page-inner" style={{ maxWidth: 980 }}>
|
<div className="page-inner" style={{ maxWidth: 980 }}>
|
||||||
<div className="notice">{t("jobs.intro")}</div>
|
<div className="notice">{t("jobs.intro")}</div>
|
||||||
<div className="row" style={{ margin: "12px 0" }}>
|
<div className="row" style={{ margin: "12px 0" }}>
|
||||||
<button className="primary" onClick={() => setTemplates(true)}>
|
<Button type="primary" onClick={() => setTemplates(true)}>
|
||||||
<Icon name="plus" /> {t("jobs.new")}
|
<Icon name="plus" /> {t("jobs.new")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{templates && <NewJobDialog onClose={() => setTemplates(false)} />}
|
{templates && <NewJobDialog onClose={() => setTemplates(false)} />}
|
||||||
{!jobs && <div className="empty"><Spinner /></div>}
|
{!jobs && <div className="empty"><Spinner /></div>}
|
||||||
@@ -86,10 +87,9 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
</h3>
|
</h3>
|
||||||
<div className="hint mono">{j.path}</div>
|
<div className="hint mono">{j.path}</div>
|
||||||
</div>
|
</div>
|
||||||
<label className="switch" title={t(j.enabled ? "jobs.disable" : "jobs.enable")}>
|
<Checkbox className="switch" title={t(j.enabled ? "jobs.disable" : "jobs.enable")} checked={j.enabled} onChange={(e) => act(j.id, () => patch(`/jobs/${j.id}`, { enabled: e.target.checked }))}>
|
||||||
<input type="checkbox" checked={j.enabled} onChange={(e) => act(j.id, () => patch(`/jobs/${j.id}`, { enabled: e.target.checked }))} />
|
|
||||||
<span>{t(j.enabled ? "jobs.on" : "jobs.off")}</span>
|
<span>{t(j.enabled ? "jobs.on" : "jobs.off")}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
</div>
|
</div>
|
||||||
{j.error ? (
|
{j.error ? (
|
||||||
<div className="notice err">{j.error}</div>
|
<div className="notice err">{j.error}</div>
|
||||||
@@ -126,8 +126,7 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
<span>
|
<span>
|
||||||
<Icon name="external" /> {t("jobs.webhook")}: {j.webhook ? t("jobs.on") : t("jobs.off")}
|
<Icon name="external" /> {t("jobs.webhook")}: {j.webhook ? t("jobs.on") : t("jobs.off")}
|
||||||
</span>
|
</span>
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost"
|
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
act(j.id, async () => {
|
act(j.id, async () => {
|
||||||
const r = await post<{ url?: string; secret?: string }>(`/jobs/${j.id}/webhook`, { enable: !j.webhook });
|
const r = await post<{ url?: string; secret?: string }>(`/jobs/${j.id}/webhook`, { enable: !j.webhook });
|
||||||
@@ -136,10 +135,9 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{j.webhook ? t("jobs.webhookOff") : t("jobs.webhookOn")}
|
{j.webhook ? t("jobs.webhookOff") : t("jobs.webhookOn")}
|
||||||
</button>
|
</Button>
|
||||||
{j.webhook && (
|
{j.webhook && (
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost"
|
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
act(j.id, async () => {
|
act(j.id, async () => {
|
||||||
const r = await post<{ url: string; secret: string }>(`/jobs/${j.id}/webhook`, { enable: true });
|
const r = await post<{ url: string; secret: string }>(`/jobs/${j.id}/webhook`, { enable: true });
|
||||||
@@ -148,7 +146,7 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{t("jobs.webhookRenew")}
|
{t("jobs.webhookRenew")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{hook?.id === j.id && (
|
{hook?.id === j.id && (
|
||||||
@@ -161,24 +159,23 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ gap: 8, marginTop: 10 }}>
|
<div className="row" style={{ gap: 8, marginTop: 10 }}>
|
||||||
<button className="small" disabled={busy === j.id || !!j.error} onClick={() => act(j.id, async () => {
|
<Button size="small" disabled={busy === j.id || !!j.error} onClick={() => act(j.id, async () => {
|
||||||
const r = await post<{ session_id: string }>(`/jobs/${j.id}/run`, {});
|
const r = await post<{ session_id: string }>(`/jobs/${j.id}/run`, {});
|
||||||
navigate(`/s/${r.session_id}`);
|
navigate(`/s/${r.session_id}`);
|
||||||
})}>
|
})}>
|
||||||
{busy === j.id ? <Spinner small /> : <Icon name="play" />} {t("jobs.runNow")}
|
{busy === j.id ? <Spinner small /> : <Icon name="play" />} {t("jobs.runNow")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small" onClick={() => navigate(`/jobs/${j.id}`)}>
|
<Button size="small" onClick={() => navigate(`/jobs/${j.id}`)}>
|
||||||
<Icon name="edit" /> {t("jobs.edit")}
|
<Icon name="edit" /> {t("jobs.edit")}
|
||||||
</button>
|
</Button>
|
||||||
<span className="grow" />
|
<span className="grow" />
|
||||||
<button
|
<Button type="text" danger size="small"
|
||||||
className="small ghost danger"
|
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (await confirmDialog({ message: t("jobs.deleteConfirm", { name: j.spec?.name ?? j.path }), danger: true })) void act(j.id, () => del(`/jobs/${j.id}`));
|
if (await confirmDialog({ message: t("jobs.deleteConfirm", { name: j.spec?.name ?? j.path }), danger: true })) void act(j.id, () => del(`/jobs/${j.id}`));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon name="trash" /> {t("jobs.remove")}
|
<Icon name="trash" /> {t("jobs.remove")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -186,14 +183,14 @@ export function Jobs({ onMenu }: { onMenu: () => void }) {
|
|||||||
<h3>{t("jobs.register")}</h3>
|
<h3>{t("jobs.register")}</h3>
|
||||||
<div className="hint" style={{ marginBottom: 8 }}>{t("jobs.registerHint")}</div>
|
<div className="hint" style={{ marginBottom: 8 }}>{t("jobs.registerHint")}</div>
|
||||||
<div className="row" style={{ gap: 8 }}>
|
<div className="row" style={{ gap: 8 }}>
|
||||||
<input className="mono" style={{ flex: 1, minWidth: 0 }} value={path} placeholder="/workspace/project/.codecraft/jobs/nightly.md" onChange={(e) => setPath(e.target.value)} />
|
<Input className="mono" style={{ flex: 1, minWidth: 0 }} value={path} placeholder="/workspace/project/.codecraft/jobs/nightly.md" onChange={(e) => setPath(e.target.value)} />
|
||||||
<button disabled={!path.trim()} onClick={() => act("new", async () => {
|
<Button disabled={!path.trim()} onClick={() => act("new", async () => {
|
||||||
const j = await post<JobInfo>("/jobs", { path: path.trim() });
|
const j = await post<JobInfo>("/jobs", { path: path.trim() });
|
||||||
setPath("");
|
setPath("");
|
||||||
navigate(`/jobs/${j.id}`);
|
navigate(`/jobs/${j.id}`);
|
||||||
})}>
|
})}>
|
||||||
{t("jobs.registerBtn")}
|
{t("jobs.registerBtn")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { post } from "../api";
|
import { post } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -35,14 +36,14 @@ export function Login({ info, onSuccess }: { info: Info; onSuccess: () => void }
|
|||||||
<img src="/icon.svg" alt="" />
|
<img src="/icon.svg" alt="" />
|
||||||
<h2 style={{ margin: 0 }}>CodeCraft</h2>
|
<h2 style={{ margin: 0 }}>CodeCraft</h2>
|
||||||
<div style={{ color: "var(--fg3)" }}>{setup ? t("login.setupPrompt") : t("login.prompt")}</div>
|
<div style={{ color: "var(--fg3)" }}>{setup ? t("login.setupPrompt") : t("login.prompt")}</div>
|
||||||
{setup && <input autoFocus placeholder={t("login.setupCode")} value={form.code} onChange={set("code")} autoComplete="one-time-code" />}
|
{setup && <Input autoFocus placeholder={t("login.setupCode")} value={form.code} onChange={set("code")} autoComplete="one-time-code" />}
|
||||||
<input autoFocus={!setup} placeholder={t("login.username")} value={form.username} onChange={set("username")} autoComplete="username" autoCapitalize="none" />
|
<Input autoFocus={!setup} placeholder={t("login.username")} value={form.username} onChange={set("username")} autoComplete="username" autoCapitalize="none" />
|
||||||
<input type="password" placeholder={t("login.password")} value={form.password} onChange={set("password")} autoComplete={setup ? "new-password" : "current-password"} />
|
<Input.Password placeholder={t("login.password")} value={form.password} onChange={set("password")} autoComplete={setup ? "new-password" : "current-password"} />
|
||||||
{setup && <input type="password" placeholder={t("login.passwordRepeat")} value={form.password2} onChange={set("password2")} autoComplete="new-password" />}
|
{setup && <Input.Password placeholder={t("login.passwordRepeat")} value={form.password2} onChange={set("password2")} autoComplete="new-password" />}
|
||||||
{error && <div style={{ color: "var(--red)" }}>{error}</div>}
|
{error && <div style={{ color: "var(--red)" }}>{error}</div>}
|
||||||
<button className="primary" type="submit" disabled={busy || !form.username || !form.password}>
|
<Button type="primary" htmlType="submit" disabled={busy || !form.username || !form.password}>
|
||||||
{setup ? t("login.createAdmin") : t("login.submit")}
|
{setup ? t("login.createAdmin") : t("login.submit")}
|
||||||
</button>
|
</Button>
|
||||||
{!setup && info.oidc && (
|
{!setup && info.oidc && (
|
||||||
<>
|
<>
|
||||||
<div style={{ color: "var(--muted)", fontSize: 12 }}>{t("login.or")}</div>
|
<div style={{ color: "var(--muted)", fontSize: 12 }}>{t("login.or")}</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { memo, useState, type ReactNode } from "react";
|
import { memo, useState, type ReactNode } from "react";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
@@ -36,9 +37,9 @@ export function SvgBlock({ code, children }: { code: string; children?: ReactNod
|
|||||||
<FileFigure name="inline.svg" size={new Blob([code]).size} mime="image/svg+xml">
|
<FileFigure name="inline.svg" size={new Blob([code]).size} mime="image/svg+xml">
|
||||||
<img src={url} alt="SVG" />
|
<img src={url} alt="SVG" />
|
||||||
</FileFigure>
|
</FileFigure>
|
||||||
<button className="small ghost" onClick={() => setShowCode(!showCode)}>
|
<Button type="text" size="small" onClick={() => setShowCode(!showCode)}>
|
||||||
<Icon name={showCode ? "chevron-down" : "chevron-right"} /> SVG
|
<Icon name={showCode ? "chevron-down" : "chevron-right"} /> SVG
|
||||||
</button>
|
</Button>
|
||||||
{showCode && children}
|
{showCode && children}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get } from "../api";
|
import { get } from "../api";
|
||||||
import { useT, type Key } from "../i18n";
|
import { useT, type Key } from "../i18n";
|
||||||
@@ -58,22 +60,21 @@ export function MediaGallery({ sessionId, onClose, onJump }: { sessionId: string
|
|||||||
}, [current, shown.length, onClose]);
|
}, [current, shown.length, onClose]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} className="media-gallery" role="dialog" aria-label={t("media.title")}>
|
||||||
<div className="modal media-gallery" role="dialog" aria-label={t("media.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="media-head">
|
<div className="media-head">
|
||||||
<h3>
|
<h3>
|
||||||
<Icon name="image" /> {t("media.title")}
|
<Icon name="image" /> {t("media.title")}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="media-filters" role="radiogroup">
|
<div className="media-filters" role="radiogroup">
|
||||||
{(["all", "image", "video", "audio", "model"] as Filter[]).map((k) => (
|
{(["all", "image", "video", "audio", "model"] as Filter[]).map((k) => (
|
||||||
<button key={k} role="radio" aria-checked={filter === k} className={`chip-btn ${filter === k ? "active" : ""}`} onClick={() => (setFilter(k), setOpen(undefined))} disabled={!!items && count(k) === 0 && k !== "all"}>
|
<Button key={k} role="radio" aria-checked={filter === k} size="small" shape="round" type={filter === k ? "primary" : "default"} onClick={() => (setFilter(k), setOpen(undefined))} disabled={!!items && count(k) === 0 && k !== "all"}>
|
||||||
{t(`media.filter.${k}` as Key)} {items && <small>{count(k)}</small>}
|
{t(`media.filter.${k}` as Key)} {items && <small>{count(k)}</small>}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<button className="small ghost" onClick={onClose} aria-label={t("common.close")}>
|
<Button type="text" size="small" onClick={onClose} aria-label={t("common.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
{!items && !error && (
|
{!items && !error && (
|
||||||
@@ -92,34 +93,34 @@ export function MediaGallery({ sessionId, onClose, onJump }: { sessionId: string
|
|||||||
<div className="media-model">
|
<div className="media-model">
|
||||||
{current.preview ? <img src={current.preview} alt={current.name} /> : <Icon name="cube" />}
|
{current.preview ? <img src={current.preview} alt={current.name} /> : <Icon name="cube" />}
|
||||||
{current.path && (
|
{current.path && (
|
||||||
<button className="primary" onClick={() => open3d(current.path!)}>
|
<Button type="primary" onClick={() => open3d(current.path!)}>
|
||||||
<Icon name="cube" /> {t("tool.open3d")}
|
<Icon name="cube" /> {t("tool.open3d")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="media-bar">
|
<div className="media-bar">
|
||||||
<button className="small ghost" disabled={open === 0} onClick={() => setOpen((o) => (o ?? 1) - 1)} aria-label={t("media.prev")}>
|
<Button type="text" size="small" disabled={open === 0} onClick={() => setOpen((o) => (o ?? 1) - 1)} aria-label={t("media.prev")}>
|
||||||
<Icon name="arrow-left" />
|
<Icon name="arrow-left" />
|
||||||
</button>
|
</Button>
|
||||||
<span className="grow">
|
<span className="grow">
|
||||||
{current.name} · {t(`media.source.${current.source}` as Key)} · {new Date(current.created_at).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" })}
|
{current.name} · {t(`media.source.${current.source}` as Key)} · {new Date(current.created_at).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" })}
|
||||||
</span>
|
</span>
|
||||||
{current.message_id && (
|
{current.message_id && (
|
||||||
<button className="small" onClick={() => onJump(current.message_id!)}>
|
<Button size="small" onClick={() => onJump(current.message_id!)}>
|
||||||
{t("media.showInChat")}
|
{t("media.showInChat")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<a className="small button" href={current.url} target="_blank" rel="noreferrer">
|
<a className="small button" href={current.url} target="_blank" rel="noreferrer">
|
||||||
<Icon name="external" /> {t("media.open")}
|
<Icon name="external" /> {t("media.open")}
|
||||||
</a>
|
</a>
|
||||||
<button className="small ghost" disabled={open === shown.length - 1} onClick={() => setOpen((o) => (o ?? 0) + 1)} aria-label={t("media.next")}>
|
<Button type="text" size="small" disabled={open === shown.length - 1} onClick={() => setOpen((o) => (o ?? 0) + 1)} aria-label={t("media.next")}>
|
||||||
<Icon name="arrow-right" />
|
<Icon name="arrow-right" />
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost" onClick={() => setOpen(undefined)} aria-label={t("media.back")}>
|
<Button type="text" size="small" onClick={() => setOpen(undefined)} aria-label={t("media.back")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -149,7 +150,6 @@ export function MediaGallery({ sessionId, onClose, onJump }: { sessionId: string
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Select } from "../ui/Select";
|
||||||
import { useModels, modelOptions } from "../hooks";
|
import { useModels, modelOptions } from "../hooks";
|
||||||
|
|
||||||
/** Model picker; keeps unknown current values selectable. */
|
/** Model picker; keeps unknown current values selectable. */
|
||||||
@@ -5,7 +6,7 @@ export function ModelSelect({ value, onChange, title, emptyLabel }: { value: str
|
|||||||
const options = modelOptions(useModels());
|
const options = modelOptions(useModels());
|
||||||
const known = options.some((o) => o.value === value);
|
const known = options.some((o) => o.value === value);
|
||||||
return (
|
return (
|
||||||
<select value={value} onChange={(e) => onChange(e.target.value)} title={title}>
|
<Select value={value} onChange={(e) => onChange(e.target.value)} title={title}>
|
||||||
{emptyLabel !== undefined && <option value="">{emptyLabel}</option>}
|
{emptyLabel !== undefined && <option value="">{emptyLabel}</option>}
|
||||||
{!known && value && <option value={value}>{value}</option>}
|
{!known && value && <option value={value}>{value}</option>}
|
||||||
{options.map((o) => (
|
{options.map((o) => (
|
||||||
@@ -13,6 +14,6 @@ export function ModelSelect({ value, onChange, title, emptyLabel }: { value: str
|
|||||||
{o.label}
|
{o.label}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { post } from "../api";
|
import { post } from "../api";
|
||||||
import { getLang, useT } from "../i18n";
|
import { getLang, useT } from "../i18n";
|
||||||
@@ -82,12 +84,11 @@ export function NewJobDialog({ onClose }: { onClose: () => void }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} className="job-tpl" role="dialog" aria-label={t("jobs.new")}>
|
||||||
<div className="modal job-tpl" role="dialog" aria-label={t("jobs.new")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("jobs.new")}</h3>
|
<h3>{t("jobs.new")}</h3>
|
||||||
<label className="field">
|
<label className="field">
|
||||||
<span>{t("jobs.tplName")}</span>
|
<span>{t("jobs.tplName")}</span>
|
||||||
<input autoFocus value={name} placeholder={t("jobs.namePlaceholder")} onChange={(e) => setName(e.target.value)} />
|
<Input autoFocus value={name} placeholder={t("jobs.namePlaceholder")} onChange={(e) => setName(e.target.value)} />
|
||||||
</label>
|
</label>
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<span>{t("jobs.tplProject")}</span>
|
<span>{t("jobs.tplProject")}</span>
|
||||||
@@ -117,12 +118,11 @@ export function NewJobDialog({ onClose }: { onClose: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
||||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
<Button onClick={onClose}>{t("common.cancel")}</Button>
|
||||||
<button className="primary" disabled={busy || !cwd || !name.trim()} onClick={create}>
|
<Button type="primary" disabled={busy || !cwd || !name.trim()} onClick={create}>
|
||||||
{t("jobs.createAndEdit")}
|
{t("jobs.createAndEdit")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
|
import { Button, Checkbox, Input, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||||
import { post, uploadFile } from "../api";
|
import { post } from "../api";
|
||||||
|
import { uploadBatch } from "../uploads";
|
||||||
import { promptDialog, toast } from "../dialogs";
|
import { promptDialog, toast } from "../dialogs";
|
||||||
import { useAgents, useFetch } from "../hooks";
|
import { useAgents, useFetch } from "../hooks";
|
||||||
import { useT, type Key } from "../i18n";
|
import { useT, type Key } from "../i18n";
|
||||||
@@ -193,7 +196,7 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
if (!model && config?.default_model) setModel(config.default_model);
|
if (!model && config?.default_model) setModel(config.default_model);
|
||||||
}, [config, model]);
|
}, [config, model]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!rootPath && roots.length) setRootPath(roots[roots.length - 1].path);
|
if (!rootPath && roots.length) setRootPath(roots[0].path);
|
||||||
}, [roots, rootPath]);
|
}, [roots, rootPath]);
|
||||||
// Old software is analysed in deep mode; websites default to clean room.
|
// Old software is analysed in deep mode; websites default to clean room.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -313,12 +316,14 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
const send = async (list: File[], dir: string) => {
|
const send = async (list: File[], dir: string) => {
|
||||||
if (!list.length) return;
|
if (!list.length) return;
|
||||||
await mkdirs(dir);
|
await mkdirs(dir);
|
||||||
for (const f of list) {
|
const jobs = list.map((f) => {
|
||||||
const name = f.name.replace(/[\\/]/g, "_");
|
const name = f.name.replace(/[\\/]/g, "_");
|
||||||
setCreating(`${t("wizard.uploading")} ${name}`);
|
return { file: f, path: `${cwd}/${dir}/${name}`, name, onProgress: (x: number) => setProgress((p) => ({ ...p, [f.name]: x })) };
|
||||||
await uploadFile(`${cwd}/${dir}/${name}`, f, (x) => setProgress((p) => ({ ...p, [f.name]: x })));
|
});
|
||||||
uploaded.push(`${dir}/${name}`);
|
setCreating(t("wizard.uploading"));
|
||||||
}
|
const sent = await uploadBatch(jobs);
|
||||||
|
if (sent.length < jobs.length) throw new Error(t("recreate.uploadFailed"));
|
||||||
|
for (const j of jobs) uploaded.push(`${dir}/${j.name}`);
|
||||||
};
|
};
|
||||||
// Originals of old software go to original/, everything else to .codecraft/uploads/.
|
// Originals of old software go to original/, everything else to .codecraft/uploads/.
|
||||||
await send(originals, "original");
|
await send(originals, "original");
|
||||||
@@ -350,9 +355,9 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{t("new.title")}</h1>
|
<h1>{t("new.title")}</h1>
|
||||||
</div>
|
</div>
|
||||||
@@ -430,9 +435,9 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
<i style={{ width: `${Math.round(progress[f.name] * 100)}%` }} />
|
<i style={{ width: `${Math.round(progress[f.name] * 100)}%` }} />
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<button className="small ghost" onClick={() => setOriginals((c) => c.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
<Button type="text" size="small" onClick={() => setOriginals((c) => c.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -443,7 +448,7 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
|
|
||||||
<Step n={n++} title={t("wizard.sayWhat")}>
|
<Step n={n++} title={t("wizard.sayWhat")}>
|
||||||
{needsUrl && (
|
{needsUrl && (
|
||||||
<input
|
<Input
|
||||||
className="wiz-url"
|
className="wiz-url"
|
||||||
type="url"
|
type="url"
|
||||||
value={url}
|
value={url}
|
||||||
@@ -459,7 +464,7 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
void addFiles(e.dataTransfer.files);
|
void addFiles(e.dataTransfer.files);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<textarea
|
<Input.TextArea
|
||||||
value={text}
|
value={text}
|
||||||
placeholder={t(task === "craft" ? (`wizard.placeholder.${target}` as Key) : task === "cad" ? "wizard.placeholder.cad" : task === "chat" ? "wizard.placeholder.chat" : "wizard.placeholder.task")}
|
placeholder={t(task === "craft" ? (`wizard.placeholder.${target}` as Key) : task === "cad" ? "wizard.placeholder.cad" : task === "chat" ? "wizard.placeholder.chat" : "wizard.placeholder.task")}
|
||||||
onChange={(e) => setText(e.target.value)}
|
onChange={(e) => setText(e.target.value)}
|
||||||
@@ -481,26 +486,26 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
{images.map((img, i) => (
|
{images.map((img, i) => (
|
||||||
<div className="att" key={`i${i}`}>
|
<div className="att" key={`i${i}`}>
|
||||||
<img src={imageSrc(img)} alt="" />
|
<img src={imageSrc(img)} alt="" />
|
||||||
<button onClick={() => setImages((c) => c.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
<Button onClick={() => setImages((c) => c.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{files.map((f, i) => (
|
{files.map((f, i) => (
|
||||||
<div className="att file" key={`f${i}`}>
|
<div className="att file" key={`f${i}`}>
|
||||||
<span><Icon name="file" /> {f.name}</span>
|
<span><Icon name="file" /> {f.name}</span>
|
||||||
<small>{formatSize(f.size)}</small>
|
<small>{formatSize(f.size)}</small>
|
||||||
<button onClick={() => setFiles((c) => c.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
<Button onClick={() => setFiles((c) => c.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="wiz-input-foot">
|
<div className="wiz-input-foot">
|
||||||
<button type="button" className="ghost small" onClick={() => fileInput.current?.click()} title={t("wizard.attach")}>
|
<Button type="text" size="small" onClick={() => fileInput.current?.click()} title={t("wizard.attach")}>
|
||||||
{ICONS.clip}
|
{ICONS.clip}
|
||||||
</button>
|
</Button>
|
||||||
<span>{target === "software" && task === "craft" ? t("wizard.softwareHint") : t("wizard.enterHint")}</span>
|
<span>{target === "software" && task === "craft" ? t("wizard.softwareHint") : t("wizard.enterHint")}</span>
|
||||||
<input ref={fileInput} type="file" multiple hidden onChange={(e) => e.target.files && void addFiles(e.target.files)} />
|
<input ref={fileInput} type="file" multiple hidden onChange={(e) => e.target.files && void addFiles(e.target.files)} />
|
||||||
</div>
|
</div>
|
||||||
@@ -509,9 +514,9 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
<div className="wiz-ideas">
|
<div className="wiz-ideas">
|
||||||
<span>{t("wizard.ideas")}</span>
|
<span>{t("wizard.ideas")}</span>
|
||||||
{ideas.map((k) => (
|
{ideas.map((k) => (
|
||||||
<button key={k} type="button" className="chip-btn" onClick={() => setText(t(k))}>
|
<Button key={k} size="small" shape="round" onClick={() => setText(t(k))}>
|
||||||
{t(k)}
|
{t(k)}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -533,7 +538,7 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{folderMode === "git" && (
|
{folderMode === "git" && (
|
||||||
<input className="wiz-url" value={repoUrl} placeholder="https://git.example.com/user/repo.git" onChange={(e) => setRepoUrl(e.target.value)} />
|
<Input className="wiz-url" value={repoUrl} placeholder="https://git.example.com/user/repo.git" onChange={(e) => setRepoUrl(e.target.value)} />
|
||||||
)}
|
)}
|
||||||
{folderMode !== "existing" && (
|
{folderMode !== "existing" && (
|
||||||
<div className="wiz-folder">
|
<div className="wiz-folder">
|
||||||
@@ -541,18 +546,18 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
<span className="wiz-folder-text">
|
<span className="wiz-folder-text">
|
||||||
{t(folderMode === "git" ? "wizard.cloneInto" : "wizard.newFolderIn")}{" "}
|
{t(folderMode === "git" ? "wizard.cloneInto" : "wizard.newFolderIn")}{" "}
|
||||||
{roots.length > 1 ? (
|
{roots.length > 1 ? (
|
||||||
<select value={rootPath} onChange={(e) => setRootPath(e.target.value)}>
|
<Select value={rootPath} onChange={(e) => setRootPath(e.target.value)}>
|
||||||
{roots.map((r) => (
|
{roots.map((r) => (
|
||||||
<option key={r.path} value={r.path}>
|
<option key={r.path} value={r.path}>
|
||||||
{r.name === "/" ? "workspace" : r.name}
|
{r.name === "/" ? "workspace" : r.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
) : (
|
) : (
|
||||||
<code>{!roots[0] || roots[0].name === "/" ? "workspace" : roots[0].name}</code>
|
<code>{!roots[0] || roots[0].name === "/" ? "workspace" : roots[0].name}</code>
|
||||||
)}
|
)}
|
||||||
<span>/</span>
|
<span>/</span>
|
||||||
<input
|
<Input
|
||||||
className="wiz-folder-name"
|
className="wiz-folder-name"
|
||||||
value={folderName}
|
value={folderName}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
@@ -565,22 +570,21 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
|||||||
)}
|
)}
|
||||||
{folderMode === "existing" && <FolderPicker path={picked} onPick={setPicked} />}
|
{folderMode === "existing" && <FolderPicker path={picked} onPick={setPicked} />}
|
||||||
{folderMode !== "new" && (
|
{folderMode !== "new" && (
|
||||||
<label className="wiz-check-row">
|
<Checkbox className="wiz-check-row" checked={isolated} onChange={(e) => setIsolated(e.target.checked)}>
|
||||||
<input type="checkbox" checked={isolated} onChange={(e) => setIsolated(e.target.checked)} />
|
|
||||||
<span>
|
<span>
|
||||||
<b>{t("worktree.isolate")}</b>
|
<b>{t("worktree.isolate")}</b>
|
||||||
<span className="hint"> – {t("worktree.isolateHint")}</span>
|
<span className="hint"> – {t("worktree.isolateHint")}</span>
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
<div className="wiz-start-row">
|
<div className="wiz-start-row">
|
||||||
<button className="primary wiz-start" disabled={!canStart} onClick={create}>
|
<Button type="primary" className="wiz-start" disabled={!canStart} onClick={create}>
|
||||||
{ICONS.start}
|
{ICONS.start}
|
||||||
{creating ?? t("wizard.start")}
|
{creating ?? t("wizard.start")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -621,37 +625,37 @@ export function FolderPicker({ path, onPick }: { path: string; onPick: (p: strin
|
|||||||
return (
|
return (
|
||||||
<div className="wiz-picker">
|
<div className="wiz-picker">
|
||||||
{roots.length > 1 && (
|
{roots.length > 1 && (
|
||||||
<div className="mode-tabs" style={{ marginBottom: 8, flexWrap: "wrap" }}>
|
<Segmented
|
||||||
{roots.map((r) => (
|
className="seg-wrap"
|
||||||
<button key={r.path} className={listing?.root === r.path ? "active" : ""} onClick={() => setBrowse(r.path)}>
|
style={{ marginBottom: 8 }}
|
||||||
{r.name}
|
value={listing?.root ?? ""}
|
||||||
</button>
|
onChange={(path) => setBrowse(path)}
|
||||||
))}
|
options={roots.map((r) => ({ value: r.path, label: r.name }))}
|
||||||
</div>
|
/>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ marginBottom: 8 }}>
|
<div className="row" style={{ marginBottom: 8 }}>
|
||||||
<code className="grow" style={{ flex: 1 }}>
|
<code className="grow" style={{ flex: 1 }}>
|
||||||
{rel}
|
{rel}
|
||||||
</code>
|
</code>
|
||||||
{listing?.parent && (
|
{listing?.parent && (
|
||||||
<button className="small" onClick={() => setBrowse(listing.parent!)}>
|
<Button size="small" onClick={() => setBrowse(listing.parent!)}>
|
||||||
<Icon name="arrow-up" /> {t("new.up")}
|
<Icon name="arrow-up" /> {t("new.up")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{listing && (
|
{listing && (
|
||||||
<button className="small" onClick={() => void newFolder()}>
|
<Button size="small" onClick={() => void newFolder()}>
|
||||||
<Icon name="plus" /> {t("files.newFolder")}
|
<Icon name="plus" /> {t("files.newFolder")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="dir-list">
|
<div className="dir-list">
|
||||||
{listing?.dirs.length === 0 && <div className="empty" style={{ padding: 16 }}>{t("new.noSubdirs")}</div>}
|
{listing?.dirs.length === 0 && <div className="empty" style={{ padding: 16 }}>{t("new.noSubdirs")}</div>}
|
||||||
{listing?.dirs.map((d) => (
|
{listing?.dirs.map((d) => (
|
||||||
<button key={d.path} onClick={() => setBrowse(d.path)}>
|
<Button key={d.path} onClick={() => setBrowse(d.path)}>
|
||||||
{ICONS.folder}
|
{ICONS.folder}
|
||||||
<span style={{ flex: 1 }}>{d.name}</span>
|
<span style={{ flex: 1 }}>{d.name}</span>
|
||||||
{d.git && <span className="chip">git</span>}
|
{d.git && <span className="chip">git</span>}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
import { flushOutbox, removeFromOutbox, useOutbox } from "../outbox";
|
import { flushOutbox, removeFromOutbox, useOutbox } from "../outbox";
|
||||||
@@ -22,16 +23,16 @@ export function OutboxBar({ sessionId }: { sessionId: string }) {
|
|||||||
<div className="outbox-head">
|
<div className="outbox-head">
|
||||||
<Icon name="clock" className="tiny" /> {t("outbox.waiting", { n: items.length })}
|
<Icon name="clock" className="tiny" /> {t("outbox.waiting", { n: items.length })}
|
||||||
<span className="grow" />
|
<span className="grow" />
|
||||||
<button className="small" onClick={() => void flushOutbox(sessionId)}>
|
<Button size="small" onClick={() => void flushOutbox(sessionId)}>
|
||||||
{t("outbox.sendNow")}
|
{t("outbox.sendNow")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{items.map((i) => (
|
{items.map((i) => (
|
||||||
<div key={i.id} className="outbox-item">
|
<div key={i.id} className="outbox-item">
|
||||||
<span>{i.text.length > 120 ? `${i.text.slice(0, 120)}…` : i.text}</span>
|
<span>{i.text.length > 120 ? `${i.text.slice(0, 120)}…` : i.text}</span>
|
||||||
<button className="small ghost" onClick={() => removeFromOutbox(i.id)} aria-label={t("outbox.discard")} title={t("outbox.discard")}>
|
<Button type="text" size="small" onClick={() => removeFromOutbox(i.id)} aria-label={t("outbox.discard")} title={t("outbox.discard")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { fmtRelative, useT, type Key } from "../i18n";
|
import { fmtRelative, useT, type Key } from "../i18n";
|
||||||
import { navigate } from "../router";
|
import { navigate } from "../router";
|
||||||
@@ -103,9 +105,8 @@ export function Palette() {
|
|||||||
const close = () => setOpen(false);
|
const close = () => setOpen(false);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop palette-backdrop" onClick={close}>
|
<Modal onClose={close} className="palette" role="dialog" aria-label={t("palette.title")}>
|
||||||
<div className="modal palette" role="dialog" aria-label={t("palette.title")} onClick={(e) => e.stopPropagation()}>
|
<Input
|
||||||
<input
|
|
||||||
autoFocus
|
autoFocus
|
||||||
value={q}
|
value={q}
|
||||||
placeholder={t("palette.placeholder")}
|
placeholder={t("palette.placeholder")}
|
||||||
@@ -142,7 +143,6 @@ export function Palette() {
|
|||||||
<span><kbd>Alt+<Icon name="arrow-up" className="tiny" /></kbd><kbd>Alt+<Icon name="arrow-down" className="tiny" /></kbd> {t("palette.prevNext")}</span>
|
<span><kbd>Alt+<Icon name="arrow-up" className="tiny" /></kbd><kbd>Alt+<Icon name="arrow-down" className="tiny" /></kbd> {t("palette.prevNext")}</span>
|
||||||
<span><kbd>Esc</kbd> {t("palette.close")}</span>
|
<span><kbd>Esc</kbd> {t("palette.close")}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { useFetch } from "../hooks";
|
import { useFetch } from "../hooks";
|
||||||
import { fmtCost, fmtDate, fmtRelative, useT, type Key } from "../i18n";
|
import { fmtCost, fmtDate, fmtRelative, useT, type Key } from "../i18n";
|
||||||
@@ -54,18 +55,18 @@ export function ProjectPage({ cwd, onMenu }: { cwd: string; onMenu: () => void }
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>
|
<h1>
|
||||||
<Icon name="folder" /> {basename(cwd) || "/"}
|
<Icon name="folder" /> {basename(cwd) || "/"}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="path mono">{cwd}</div>
|
<div className="path mono">{cwd}</div>
|
||||||
</div>
|
</div>
|
||||||
<button className="small primary" onClick={newChat}>
|
<Button type="primary" size="small" onClick={newChat}>
|
||||||
<Icon name="plus" /> {t("project.newChat")}
|
<Icon name="plus" /> {t("project.newChat")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="chat-scroll">
|
<div className="chat-scroll">
|
||||||
<div className="chat project-page">
|
<div className="chat project-page">
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { api, get } from "../api";
|
import { api, get } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -23,8 +25,7 @@ export function ProjectPermissions({ sessionId, cwd, onClose }: { sessionId: str
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} role="dialog" aria-label={t("permProject.title")}>
|
||||||
<div className="modal" role="dialog" aria-label={t("permProject.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>
|
<h3>
|
||||||
<Icon name="lock" /> {t("permProject.title")}
|
<Icon name="lock" /> {t("permProject.title")}
|
||||||
</h3>
|
</h3>
|
||||||
@@ -39,17 +40,16 @@ export function ProjectPermissions({ sessionId, cwd, onClose }: { sessionId: str
|
|||||||
{keys.map((k) => (
|
{keys.map((k) => (
|
||||||
<li key={k} className="row" style={{ justifyContent: "space-between" }}>
|
<li key={k} className="row" style={{ justifyContent: "space-between" }}>
|
||||||
<code>{label(k)}</code>
|
<code>{label(k)}</code>
|
||||||
<button className="small danger" onClick={() => void revoke(k)}>
|
<Button danger size="small" onClick={() => void revoke(k)}>
|
||||||
{t("permProject.revoke")}
|
{t("permProject.revoke")}
|
||||||
</button>
|
</Button>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ justifyContent: "flex-end", marginTop: 10 }}>
|
<div className="row" style={{ justifyContent: "flex-end", marginTop: 10 }}>
|
||||||
<button onClick={onClose}>{t("common.close")}</button>
|
<Button onClick={onClose}>{t("common.close")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { del, post } from "../api";
|
import { del, post } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -17,11 +18,12 @@ export function QueueList({ sessionId, busy }: { sessionId: string; busy: boolea
|
|||||||
<div className="queue">
|
<div className="queue">
|
||||||
<div className="queue-head">
|
<div className="queue-head">
|
||||||
<span>{busy ? t("queue.pending", { n: items.length }) : t("queue.stopped", { n: items.length })}</span>
|
<span>{busy ? t("queue.pending", { n: items.length }) : t("queue.stopped", { n: items.length })}</span>
|
||||||
{!busy && (
|
<Button type="primary" size="small"
|
||||||
<button className="small primary" onClick={() => post(`/sessions/${sessionId}/queue/flush`).catch((e) => toast(e.message))}>
|
title={busy ? t("queue.forceHint") : undefined}
|
||||||
{t("queue.sendNow")}
|
onClick={() => post(`/sessions/${sessionId}/queue/force`).catch((e) => toast(e.message))}
|
||||||
</button>
|
>
|
||||||
)}
|
{busy ? t("queue.force") : t("queue.sendNow")}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{items.map((it) => {
|
{items.map((it) => {
|
||||||
const text = it.parts.map((p) => (p.type === "text" ? p.text : "")).join(" ").trim();
|
const text = it.parts.map((p) => (p.type === "text" ? p.text : "")).join(" ").trim();
|
||||||
@@ -34,14 +36,13 @@ export function QueueList({ sessionId, busy }: { sessionId: string; busy: boolea
|
|||||||
<img key={i} src={imageSrc(p.image)} alt="" />
|
<img key={i} src={imageSrc(p.image)} alt="" />
|
||||||
))}
|
))}
|
||||||
{it.source !== "background" && (
|
{it.source !== "background" && (
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost"
|
|
||||||
aria-label={t("queue.remove")}
|
aria-label={t("queue.remove")}
|
||||||
title={t("queue.remove")}
|
title={t("queue.remove")}
|
||||||
onClick={() => del(`/sessions/${sessionId}/queue/${it.id}`).catch((e) => toast(e.message))}
|
onClick={() => del(`/sessions/${sessionId}/queue/${it.id}`).catch((e) => toast(e.message))}
|
||||||
>
|
>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { post } from "../api";
|
import { post } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -11,14 +13,14 @@ export const EFFORTS = ["low", "medium", "high", "max"] as const;
|
|||||||
export function EffortSelect({ value, onChange, compact }: { value: string; onChange: (v: string) => void; compact?: boolean }) {
|
export function EffortSelect({ value, onChange, compact }: { value: string; onChange: (v: string) => void; compact?: boolean }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
return (
|
return (
|
||||||
<select className={compact ? "effort-select" : ""} value={value} onChange={(e) => onChange(e.target.value)} title={t("effort.title")} aria-label={t("effort.title")}>
|
<Select className={compact ? "effort-select" : ""} value={value} onChange={(e) => onChange(e.target.value)} title={t("effort.title")} aria-label={t("effort.title")}>
|
||||||
<option value="">{compact ? t("effort.autoShort") : t("effort.auto")}</option>
|
<option value="">{compact ? t("effort.autoShort") : t("effort.auto")}</option>
|
||||||
{EFFORTS.map((e) => (
|
{EFFORTS.map((e) => (
|
||||||
<option key={e} value={e}>
|
<option key={e} value={e}>
|
||||||
{t(`effort.${e}` as any)}
|
{t(`effort.${e}` as any)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,18 +44,18 @@ export function RegenerateButton({ sessionId, messageId, model }: { sessionId: s
|
|||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className="regen">
|
<div className="regen">
|
||||||
<button className="small ghost" onClick={() => setOpen(!open)} title={t("regen.title")}>
|
<Button type="text" size="small" onClick={() => setOpen(!open)} title={t("regen.title")}>
|
||||||
<Icon name="refresh" /> {t("regen.button")}
|
<Icon name="refresh" /> {t("regen.button")}
|
||||||
</button>
|
</Button>
|
||||||
{open && (
|
{open && (
|
||||||
<div className="regen-panel">
|
<div className="regen-panel">
|
||||||
<div className="hint">{t("regen.hint")}</div>
|
<div className="hint">{t("regen.hint")}</div>
|
||||||
<div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
|
<div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
|
||||||
<ModelSelect value={m} onChange={setM} />
|
<ModelSelect value={m} onChange={setM} />
|
||||||
<EffortSelect value={effort} onChange={setEffort} />
|
<EffortSelect value={effort} onChange={setEffort} />
|
||||||
<button className="small primary" disabled={busy} onClick={go}>
|
<Button type="primary" size="small" disabled={busy} onClick={go}>
|
||||||
<Icon name="refresh" /> {t("regen.go")}
|
<Icon name="refresh" /> {t("regen.go")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { patch, post } from "../api";
|
import { patch, post } from "../api";
|
||||||
import { useFetch } from "../hooks";
|
import { useFetch } from "../hooks";
|
||||||
@@ -41,10 +43,9 @@ export function RenameDialog({ sessionId, title, onClose }: { sessionId: string;
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} role="dialog" aria-label={t("rename.title")}>
|
||||||
<div className="modal" role="dialog" aria-label={t("rename.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("rename.title")}</h3>
|
<h3>{t("rename.title")}</h3>
|
||||||
<input
|
<Input
|
||||||
autoFocus
|
autoFocus
|
||||||
style={{ width: "100%" }}
|
style={{ width: "100%" }}
|
||||||
value={value}
|
value={value}
|
||||||
@@ -55,18 +56,17 @@ export function RenameDialog({ sessionId, title, onClose }: { sessionId: string;
|
|||||||
<div className="rename-gen">
|
<div className="rename-gen">
|
||||||
<span className="hint">{t("rename.generateWith")}</span>
|
<span className="hint">{t("rename.generateWith")}</span>
|
||||||
<ModelSelect value={chosen} onChange={setModel} />
|
<ModelSelect value={chosen} onChange={setModel} />
|
||||||
<button className="small" onClick={generate} disabled={!!busy}>
|
<Button size="small" onClick={generate} disabled={!!busy}>
|
||||||
{busy === "gen" ? <Spinner small /> : <Icon name="sparkle" />} {t("rename.generate")}
|
{busy === "gen" ? <Spinner small /> : <Icon name="sparkle" />} {t("rename.generate")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
||||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
<Button onClick={onClose}>{t("common.cancel")}</Button>
|
||||||
<button className="primary" onClick={save} disabled={!!busy}>
|
<Button type="primary" onClick={save} disabled={!!busy}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Checkbox } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get, post } from "../api";
|
import { get, post } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -23,8 +25,7 @@ export function RewindDialog({ sessionId, messageId, onDone, onClose }: { sessio
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} role="dialog" aria-label={t("chat.rewind")}>
|
||||||
<div className="modal" role="dialog" aria-label={t("chat.rewind")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("chat.rewind")}</h3>
|
<h3>{t("chat.rewind")}</h3>
|
||||||
<p style={{ fontSize: 13, color: "var(--fg3)" }}>{t("rewind.intro")}</p>
|
<p style={{ fontSize: 13, color: "var(--fg3)" }}>{t("rewind.intro")}</p>
|
||||||
{files === undefined ? (
|
{files === undefined ? (
|
||||||
@@ -33,9 +34,8 @@ export function RewindDialog({ sessionId, messageId, onDone, onClose }: { sessio
|
|||||||
<p style={{ fontSize: 13 }}>{t("rewind.noFiles")}</p>
|
<p style={{ fontSize: 13 }}>{t("rewind.noFiles")}</p>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<label className="row" style={{ marginBottom: 6 }}>
|
<Checkbox className="row" style={{ marginBottom: 6 }} checked={restore} onChange={(e) => setRestore(e.target.checked)}> {t("rewind.restore", { n: files.length })}
|
||||||
<input type="checkbox" checked={restore} onChange={(e) => setRestore(e.target.checked)} /> {t("rewind.restore", { n: files.length })}
|
</Checkbox>
|
||||||
</label>
|
|
||||||
<ul className="rewind-files">
|
<ul className="rewind-files">
|
||||||
{files.map((f) => (
|
{files.map((f) => (
|
||||||
<li key={f.path}>
|
<li key={f.path}>
|
||||||
@@ -47,12 +47,11 @@ export function RewindDialog({ sessionId, messageId, onDone, onClose }: { sessio
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ justifyContent: "flex-end", marginTop: 10 }}>
|
<div className="row" style={{ justifyContent: "flex-end", marginTop: 10 }}>
|
||||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
<Button onClick={onClose}>{t("common.cancel")}</Button>
|
||||||
<button className="primary" disabled={busy || files === undefined} onClick={go}>
|
<Button type="primary" disabled={busy || files === undefined} onClick={go}>
|
||||||
{t("rewind.confirm")}
|
{t("rewind.confirm")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Checkbox, Input, Segmented, Tabs } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||||
import { get, patch as apiPatch, post, put } from "../api";
|
import { get, patch as apiPatch, post, put } from "../api";
|
||||||
@@ -18,6 +20,7 @@ import { Folders } from "./settings/Folders";
|
|||||||
import { Users } from "./settings/Users";
|
import { Users } from "./settings/Users";
|
||||||
import { Audit } from "./settings/Audit";
|
import { Audit } from "./settings/Audit";
|
||||||
import { Tools } from "./settings/Tools";
|
import { Tools } from "./settings/Tools";
|
||||||
|
import { Skills } from "./settings/Skills";
|
||||||
import { confirmDialog, promptDialog, toast } from "../dialogs";
|
import { confirmDialog, promptDialog, toast } from "../dialogs";
|
||||||
|
|
||||||
type Json = any;
|
type Json = any;
|
||||||
@@ -64,16 +67,16 @@ function InterfaceSettings() {
|
|||||||
<h3>{t("settings.interface")}</h3>
|
<h3>{t("settings.interface")}</h3>
|
||||||
<div className="form">
|
<div className="form">
|
||||||
<label>{t("settings.language")}</label>
|
<label>{t("settings.language")}</label>
|
||||||
<select value={getLang()} onChange={(e) => setLang(e.target.value)}>
|
<Select value={getLang()} onChange={(e) => setLang(e.target.value)}>
|
||||||
{Object.entries(languages).map(([k, v]) => (
|
{Object.entries(languages).map(([k, v]) => (
|
||||||
<option key={k} value={k}>
|
<option key={k} value={k}>
|
||||||
{v.name}
|
{v.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<label>{t("settings.theme")}</label>
|
<label>{t("settings.theme")}</label>
|
||||||
<div className="stack">
|
<div className="stack">
|
||||||
<select
|
<Select
|
||||||
value={theme}
|
value={theme}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const v = e.target.value as Theme;
|
const v = e.target.value as Theme;
|
||||||
@@ -85,30 +88,23 @@ function InterfaceSettings() {
|
|||||||
{th.name}
|
{th.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<div className="hint">{t("settings.themeSource", { source: themeInfo.source, license: themeInfo.license })}</div>
|
<div className="hint">{t("settings.themeSource", { source: themeInfo.source, license: themeInfo.license })}</div>
|
||||||
</div>
|
</div>
|
||||||
<label>{t("settings.themeMode")}</label>
|
<label>{t("settings.themeMode")}</label>
|
||||||
<div className="segmented">
|
<Segmented
|
||||||
{THEME_MODES.map((m) => (
|
className="theme-mode"
|
||||||
<button
|
value={mode}
|
||||||
key={m}
|
onChange={(m) => applyTheme(theme, m)}
|
||||||
className={`small ${m === mode ? "active" : "ghost"}`}
|
options={THEME_MODES.map((m) => ({ value: m, label: t(m === "auto" ? "settings.themeAuto" : m === "light" ? "settings.themeLight" : "settings.themeDark") }))}
|
||||||
onClick={() => {
|
/>
|
||||||
applyTheme(theme, m);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t(m === "auto" ? "settings.themeAuto" : m === "light" ? "settings.themeLight" : "settings.themeDark")}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<label>{t("settings.reasoningDisplay")}</label>
|
<label>{t("settings.reasoningDisplay")}</label>
|
||||||
<select value={reasoning} onChange={(e) => setReasoningMode(e.target.value as ReasoningMode)}>
|
<Select value={reasoning} onChange={(e) => setReasoningMode(e.target.value as ReasoningMode)}>
|
||||||
<option value="collapsed">{t("settings.reasoningCollapsed")}</option>
|
<option value="collapsed">{t("settings.reasoningCollapsed")}</option>
|
||||||
<option value="hidden">{t("settings.reasoningHidden")}</option>
|
<option value="hidden">{t("settings.reasoningHidden")}</option>
|
||||||
<option value="live">{t("settings.reasoningLive")}</option>
|
<option value="live">{t("settings.reasoningLive")}</option>
|
||||||
<option value="expanded">{t("settings.reasoningExpanded")}</option>
|
<option value="expanded">{t("settings.reasoningExpanded")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<div className="hint">{t("settings.reasoningHint")}</div>
|
<div className="hint">{t("settings.reasoningHint")}</div>
|
||||||
<label>{t("settings.notifications")}</label>
|
<label>{t("settings.notifications")}</label>
|
||||||
<PushControl />
|
<PushControl />
|
||||||
@@ -129,9 +125,9 @@ function InstallControl() {
|
|||||||
if (prompt)
|
if (prompt)
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<button className="small primary" onClick={() => void promptInstall()}>
|
<Button type="primary" size="small" onClick={() => void promptInstall()}>
|
||||||
<Icon name="download" /> {t("install.button")}
|
<Icon name="download" /> {t("install.button")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
return <div className="hint">{t(`install.hint.${platformHint()}` as Key)}</div>;
|
return <div className="hint">{t(`install.hint.${platformHint()}` as Key)}</div>;
|
||||||
@@ -155,33 +151,22 @@ function DigestToggle() {
|
|||||||
if (on === undefined) return null;
|
if (on === undefined) return null;
|
||||||
return (
|
return (
|
||||||
<div className="row" style={{ gap: 8, flexBasis: "100%", alignItems: "center", flexWrap: "wrap" }}>
|
<div className="row" style={{ gap: 8, flexBasis: "100%", alignItems: "center", flexWrap: "wrap" }}>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
<Checkbox className="row" style={{ gap: 6, alignItems: "center" }} checked={on} onChange={(e) => {
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={on}
|
|
||||||
onChange={(e) => {
|
|
||||||
const v = e.target.checked;
|
const v = e.target.checked;
|
||||||
setOn(v);
|
setOn(v);
|
||||||
put("/push/digest", { enabled: v }).catch((err) => (setOn(!v), toast(err.message)));
|
put("/push/digest", { enabled: v }).catch((err) => (setOn(!v), toast(err.message)));
|
||||||
}}
|
}}>
|
||||||
/>
|
|
||||||
{t("settings.digest")}
|
{t("settings.digest")}
|
||||||
</label>
|
</Checkbox>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
<Checkbox className="row" style={{ gap: 6, alignItems: "center" }} checked={weekly} onChange={(e) => {
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={weekly}
|
|
||||||
onChange={(e) => {
|
|
||||||
const v = e.target.checked;
|
const v = e.target.checked;
|
||||||
setWeekly(v);
|
setWeekly(v);
|
||||||
put("/push/digest", { weekly: v }).catch((err) => (setWeekly(!v), toast(err.message)));
|
put("/push/digest", { weekly: v }).catch((err) => (setWeekly(!v), toast(err.message)));
|
||||||
}}
|
}}>
|
||||||
/>
|
|
||||||
{t("settings.weeklyDigest")}
|
{t("settings.weeklyDigest")}
|
||||||
</label>
|
</Checkbox>
|
||||||
{weekly && (
|
{weekly && (
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost"
|
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
post<{ sent: number; errors: string[] }>("/push/digest?weekly=true")
|
post<{ sent: number; errors: string[] }>("/push/digest?weekly=true")
|
||||||
.then((r) => toast(r.sent ? t("settings.pushTestSent") : r.errors.join("; ") || t("settings.pushTestNone"), r.sent ? "success" : "error"))
|
.then((r) => toast(r.sent ? t("settings.pushTestSent") : r.errors.join("; ") || t("settings.pushTestNone"), r.sent ? "success" : "error"))
|
||||||
@@ -189,11 +174,10 @@ function DigestToggle() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{t("settings.digestNow")}
|
{t("settings.digestNow")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{on && (
|
{on && (
|
||||||
<button
|
<Button type="text" size="small"
|
||||||
className="small ghost"
|
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
post<{ sent: number; errors: string[] }>("/push/digest")
|
post<{ sent: number; errors: string[] }>("/push/digest")
|
||||||
.then((r) => toast(r.sent ? t("settings.pushTestSent") : r.errors.join("; ") || t("settings.pushTestNone"), r.sent ? "success" : "error"))
|
.then((r) => toast(r.sent ? t("settings.pushTestSent") : r.errors.join("; ") || t("settings.pushTestNone"), r.sent ? "success" : "error"))
|
||||||
@@ -201,7 +185,7 @@ function DigestToggle() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{t("settings.digestNow")}
|
{t("settings.digestNow")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -241,8 +225,7 @@ function PushControl() {
|
|||||||
{state === "on" ? (
|
{state === "on" ? (
|
||||||
<>
|
<>
|
||||||
<span className="chip">{t("settings.notificationsOn")}</span>
|
<span className="chip">{t("settings.notificationsOn")}</span>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={run(async () => {
|
onClick={run(async () => {
|
||||||
const r = await testPush();
|
const r = await testPush();
|
||||||
@@ -251,16 +234,16 @@ function PushControl() {
|
|||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
{t("settings.pushTest")}
|
{t("settings.pushTest")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost" disabled={busy} onClick={run(async () => (await disablePush(), setState("off")))}>
|
<Button type="text" size="small" disabled={busy} onClick={run(async () => (await disablePush(), setState("off")))}>
|
||||||
{t("settings.pushDisable")}
|
{t("settings.pushDisable")}
|
||||||
</button>
|
</Button>
|
||||||
<DigestToggle />
|
<DigestToggle />
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<button className="small" disabled={busy} onClick={run(async () => (await enablePush(), setState("on")))}>
|
<Button size="small" disabled={busy} onClick={run(async () => (await enablePush(), setState("on")))}>
|
||||||
{t("settings.notificationsEnable")}
|
{t("settings.notificationsEnable")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -337,35 +320,35 @@ function General({ cfg, reload }: { cfg: ConfigResponse; reload: () => void }) {
|
|||||||
<ModelSelect value={form.plan_model} emptyLabel={t("settings.sameAsChat")} onChange={(v) => setForm({ ...form, plan_model: v })} />
|
<ModelSelect value={form.plan_model} emptyLabel={t("settings.sameAsChat")} onChange={(v) => setForm({ ...form, plan_model: v })} />
|
||||||
<div className="hint">{t("settings.planModelHint")}</div>
|
<div className="hint">{t("settings.planModelHint")}</div>
|
||||||
<label>{t("settings.transcribeModel")}</label>
|
<label>{t("settings.transcribeModel")}</label>
|
||||||
<input value={form.transcribe_model} placeholder="openai/whisper-1" onChange={(e) => setForm({ ...form, transcribe_model: e.target.value })} />
|
<Input value={form.transcribe_model} placeholder="openai/whisper-1" onChange={(e) => setForm({ ...form, transcribe_model: e.target.value })} />
|
||||||
<div className="hint">{t("settings.transcribeHint")}</div>
|
<div className="hint">{t("settings.transcribeHint")}</div>
|
||||||
<label>{t("settings.currency")}</label>
|
<label>{t("settings.currency")}</label>
|
||||||
<input value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value.toUpperCase() })} maxLength={3} />
|
<Input value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value.toUpperCase() })} maxLength={3} />
|
||||||
<label>{t("settings.autoCompact")}</label>
|
<label>{t("settings.autoCompact")}</label>
|
||||||
<input type="number" min={0} max={1} step={0.05} value={form.auto_compact_threshold} onChange={(e) => setForm({ ...form, auto_compact_threshold: e.target.value })} />
|
<Input type="number" min={0} max={1} step={0.05} value={form.auto_compact_threshold} onChange={(e) => setForm({ ...form, auto_compact_threshold: e.target.value })} />
|
||||||
<div className="hint">{t("settings.autoCompactHint")}</div>
|
<div className="hint">{t("settings.autoCompactHint")}</div>
|
||||||
<label>{t("settings.commitTrailer")}</label>
|
<label>{t("settings.commitTrailer")}</label>
|
||||||
<input className="mono" value={form.commit_trailer} placeholder={t("settings.commitTrailerOff")} onChange={(e) => setForm({ ...form, commit_trailer: e.target.value })} />
|
<Input className="mono" value={form.commit_trailer} placeholder={t("settings.commitTrailerOff")} onChange={(e) => setForm({ ...form, commit_trailer: e.target.value })} />
|
||||||
<div className="hint">{t("settings.commitTrailerHint")}</div>
|
<div className="hint">{t("settings.commitTrailerHint")}</div>
|
||||||
<label>{t("settings.monthlyBudgetTotal")}</label>
|
<label>{t("settings.monthlyBudgetTotal")}</label>
|
||||||
<input type="number" min={0} value={form.monthly_budget} onChange={(e) => setForm({ ...form, monthly_budget: e.target.value })} />
|
<Input type="number" min={0} value={form.monthly_budget} onChange={(e) => setForm({ ...form, monthly_budget: e.target.value })} />
|
||||||
<div className="hint">{t("settings.monthlyBudgetHint")}</div>
|
<div className="hint">{t("settings.monthlyBudgetHint")}</div>
|
||||||
<label>{t("settings.budgetWarning")}</label>
|
<label>{t("settings.budgetWarning")}</label>
|
||||||
<input type="number" min={0} max={1} step={0.05} value={form.budget_warning} onChange={(e) => setForm({ ...form, budget_warning: e.target.value })} />
|
<Input type="number" min={0} max={1} step={0.05} value={form.budget_warning} onChange={(e) => setForm({ ...form, budget_warning: e.target.value })} />
|
||||||
<label>{t("settings.budgetAction")}</label>
|
<label>{t("settings.budgetAction")}</label>
|
||||||
<select value={form.budget_action} onChange={(e) => setForm({ ...form, budget_action: e.target.value })}>
|
<Select value={form.budget_action} onChange={(e) => setForm({ ...form, budget_action: e.target.value })}>
|
||||||
<option value="warn">{t("settings.budgetWarn")}</option>
|
<option value="warn">{t("settings.budgetWarn")}</option>
|
||||||
<option value="block">{t("settings.budgetBlock")}</option>
|
<option value="block">{t("settings.budgetBlock")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<label>{t("settings.sandbox")}</label>
|
<label>{t("settings.sandbox")}</label>
|
||||||
<select value={form.sandbox_mode} onChange={(e) => setForm({ ...form, sandbox_mode: e.target.value })}>
|
<Select value={form.sandbox_mode} onChange={(e) => setForm({ ...form, sandbox_mode: e.target.value })}>
|
||||||
<option value="auto">{t("settings.sandboxAuto")}</option>
|
<option value="auto">{t("settings.sandboxAuto")}</option>
|
||||||
<option value="always">{t("settings.sandboxAlways")}</option>
|
<option value="always">{t("settings.sandboxAlways")}</option>
|
||||||
<option value="off">{t("settings.sandboxOff")}</option>
|
<option value="off">{t("settings.sandboxOff")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<div className="hint">{t("settings.sandboxHint")}</div>
|
<div className="hint">{t("settings.sandboxHint")}</div>
|
||||||
<label>{t("settings.maxParallelSubagents")}</label>
|
<label>{t("settings.maxParallelSubagents")}</label>
|
||||||
<input type="number" min={0} value={form.max_parallel_subagents} onChange={(e) => setForm({ ...form, max_parallel_subagents: e.target.value })} />
|
<Input type="number" min={0} value={form.max_parallel_subagents} onChange={(e) => setForm({ ...form, max_parallel_subagents: e.target.value })} />
|
||||||
<div className="hint">{t("settings.maxParallelSubagentsHint")}</div>
|
<div className="hint">{t("settings.maxParallelSubagentsHint")}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -373,40 +356,40 @@ function General({ cfg, reload }: { cfg: ConfigResponse; reload: () => void }) {
|
|||||||
<h3>{t("settings.craft")}</h3>
|
<h3>{t("settings.craft")}</h3>
|
||||||
<div className="form">
|
<div className="form">
|
||||||
<label>{t("settings.cleanRoom")}</label>
|
<label>{t("settings.cleanRoom")}</label>
|
||||||
<input type="checkbox" checked={form.clean_room} onChange={(e) => setForm({ ...form, clean_room: e.target.checked })} style={{ justifySelf: "start" }} />
|
<Checkbox checked={form.clean_room} onChange={(e) => setForm({ ...form, clean_room: e.target.checked })} style={{ justifySelf: "start" }} />
|
||||||
<div className="hint">{t("settings.cleanRoomHint")}</div>
|
<div className="hint">{t("settings.cleanRoomHint")}</div>
|
||||||
<label>{t("settings.chromium")}</label>
|
<label>{t("settings.chromium")}</label>
|
||||||
<input value={form.chromium} onChange={(e) => setForm({ ...form, chromium: e.target.value })} />
|
<Input value={form.chromium} onChange={(e) => setForm({ ...form, chromium: e.target.value })} />
|
||||||
<label>{t("settings.widths")}</label>
|
<label>{t("settings.widths")}</label>
|
||||||
<input value={form.widths} onChange={(e) => setForm({ ...form, widths: e.target.value })} />
|
<Input value={form.widths} onChange={(e) => setForm({ ...form, widths: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="panel">
|
<div className="panel">
|
||||||
<h3>{t("settings.images")}</h3>
|
<h3>{t("settings.images")}</h3>
|
||||||
<div className="form">
|
<div className="form">
|
||||||
<label>{t("settings.imagesEnabled")}</label>
|
<label>{t("settings.imagesEnabled")}</label>
|
||||||
<input type="checkbox" checked={form.images_enabled} onChange={(e) => setForm({ ...form, images_enabled: e.target.checked })} style={{ justifySelf: "start" }} />
|
<Checkbox checked={form.images_enabled} onChange={(e) => setForm({ ...form, images_enabled: e.target.checked })} style={{ justifySelf: "start" }} />
|
||||||
<label>{t("settings.imagesKey")}</label>
|
<label>{t("settings.imagesKey")}</label>
|
||||||
<input type="password" value={form.images_key} placeholder={cfg.config.images?.api_key === MASK ? t("settings.apiKeyStored") : "fal.ai API key"} onChange={(e) => setForm({ ...form, images_key: e.target.value })} />
|
<Input.Password value={form.images_key} placeholder={cfg.config.images?.api_key === MASK ? t("settings.apiKeyStored") : "fal.ai API key"} onChange={(e) => setForm({ ...form, images_key: e.target.value })} />
|
||||||
<label>{t("settings.imagesDefault")}</label>
|
<label>{t("settings.imagesDefault")}</label>
|
||||||
<select value={form.images_model} onChange={(e) => setForm({ ...form, images_model: e.target.value })}>
|
<Select value={form.images_model} onChange={(e) => setForm({ ...form, images_model: e.target.value })}>
|
||||||
{(cfg.config.images?.models ?? []).map((m: any) => (
|
{(cfg.config.images?.models ?? []).map((m: any) => (
|
||||||
<option key={m.id} value={m.id}>
|
<option key={m.id} value={m.id}>
|
||||||
{m.name ?? m.id}
|
{m.name ?? m.id}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<label>{t("settings.monthlyBudget")}</label>
|
<label>{t("settings.monthlyBudget")}</label>
|
||||||
<input type="number" min={0} value={form.images_budget} placeholder="–" onChange={(e) => setForm({ ...form, images_budget: e.target.value })} />
|
<Input type="number" min={0} value={form.images_budget} placeholder="–" onChange={(e) => setForm({ ...form, images_budget: e.target.value })} />
|
||||||
<label>{t("settings.imagesDir")}</label>
|
<label>{t("settings.imagesDir")}</label>
|
||||||
<input value={form.images_dir} onChange={(e) => setForm({ ...form, images_dir: e.target.value })} />
|
<Input value={form.images_dir} onChange={(e) => setForm({ ...form, images_dir: e.target.value })} />
|
||||||
<div className="hint">{t("settings.imagesHint")}</div>
|
<div className="hint">{t("settings.imagesHint")}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{view}
|
{view}
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -574,7 +557,7 @@ function ProviderEditor({ name, p, reload, status }: { name: string; p: Json; re
|
|||||||
return (
|
return (
|
||||||
<div className="panel">
|
<div className="panel">
|
||||||
<h3>
|
<h3>
|
||||||
<input type="checkbox" checked={!!form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} title={t("settings.enabled")} />
|
<Checkbox checked={!!form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} title={t("settings.enabled")} />
|
||||||
{name}
|
{name}
|
||||||
<span className="chip">{form.kind}</span>
|
<span className="chip">{form.kind}</span>
|
||||||
<span className="chip">{t("settings.modelCount", { n: models.length || discovered.length })}</span>
|
<span className="chip">{t("settings.modelCount", { n: models.length || discovered.length })}</span>
|
||||||
@@ -588,66 +571,65 @@ function ProviderEditor({ name, p, reload, status }: { name: string; p: Json; re
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button className="small" onClick={() => setOpen(!open)}>
|
<Button size="small" onClick={() => setOpen(!open)}>
|
||||||
{open ? t("common.collapse") : t("common.edit")}
|
{open ? t("common.collapse") : t("common.edit")}
|
||||||
</button>
|
</Button>
|
||||||
</h3>
|
</h3>
|
||||||
{open && (
|
{open && (
|
||||||
<>
|
<>
|
||||||
<div className="form">
|
<div className="form">
|
||||||
<label>{t("settings.kind")}</label>
|
<label>{t("settings.kind")}</label>
|
||||||
<select value={form.kind} onChange={(e) => setForm({ ...form, kind: e.target.value })}>
|
<Select value={form.kind} onChange={(e) => setForm({ ...form, kind: e.target.value })}>
|
||||||
<option value="anthropic">Anthropic Messages API</option>
|
<option value="anthropic">Anthropic Messages API</option>
|
||||||
<option value="openai">OpenAI-compatible</option>
|
<option value="openai">OpenAI-compatible</option>
|
||||||
</select>
|
</Select>
|
||||||
<label>{t("settings.baseUrl")}</label>
|
<label>{t("settings.baseUrl")}</label>
|
||||||
<input value={form.base_url} onChange={(e) => setForm({ ...form, base_url: e.target.value })} />
|
<Input value={form.base_url} onChange={(e) => setForm({ ...form, base_url: e.target.value })} />
|
||||||
<label>{t("settings.apiKey")}</label>
|
<label>{t("settings.apiKey")}</label>
|
||||||
<input
|
<Input.Password
|
||||||
type="password"
|
|
||||||
value={form.api_key}
|
value={form.api_key}
|
||||||
placeholder={p.api_key === MASK ? t("settings.apiKeyStored") : ""}
|
placeholder={p.api_key === MASK ? t("settings.apiKeyStored") : ""}
|
||||||
onChange={(e) => setForm({ ...form, api_key: e.target.value })}
|
onChange={(e) => setForm({ ...form, api_key: e.target.value })}
|
||||||
/>
|
/>
|
||||||
<div className="hint">{t("settings.apiKeyHint")}</div>
|
<div className="hint">{t("settings.apiKeyHint")}</div>
|
||||||
<label>{t("settings.authPrefix")}</label>
|
<label>{t("settings.authPrefix")}</label>
|
||||||
<input value={form.auth_prefix ?? ""} placeholder={form.kind === "openai" ? "Bearer " : ""} onChange={(e) => setForm({ ...form, auth_prefix: e.target.value })} />
|
<Input value={form.auth_prefix ?? ""} placeholder={form.kind === "openai" ? "Bearer " : ""} onChange={(e) => setForm({ ...form, auth_prefix: e.target.value })} />
|
||||||
<label>{t("settings.monthlyBudget")}</label>
|
<label>{t("settings.monthlyBudget")}</label>
|
||||||
<input type="number" min={0} step="1" value={form.monthly_budget ?? ""} placeholder="–" onChange={(e) => setForm({ ...form, monthly_budget: e.target.value })} />
|
<Input type="number" min={0} step="1" value={form.monthly_budget ?? ""} placeholder="–" onChange={(e) => setForm({ ...form, monthly_budget: e.target.value })} />
|
||||||
{/opencode\.ai\/(inference|zen)\/go/.test(form.base_url ?? "") && (
|
{/opencode\.ai\/(inference|zen)\/go/.test(form.base_url ?? "") && (
|
||||||
<>
|
<>
|
||||||
<label>{t("settings.planLimit")}</label>
|
<label>{t("settings.planLimit")}</label>
|
||||||
<input type="number" min={0} step="1" value={form.plan_limit ?? ""} placeholder="–" onChange={(e) => setForm({ ...form, plan_limit: e.target.value })} />
|
<Input type="number" min={0} step="1" value={form.plan_limit ?? ""} placeholder="–" onChange={(e) => setForm({ ...form, plan_limit: e.target.value })} />
|
||||||
<div className="hint">{t("settings.planLimitHint")}</div>
|
<div className="hint">{t("settings.planLimitHint")}</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{form.kind === "anthropic" && (
|
{form.kind === "anthropic" && (
|
||||||
<>
|
<>
|
||||||
<label>{t("settings.adminKey")}</label>
|
<label>{t("settings.adminKey")}</label>
|
||||||
<input type="password" value={form.admin_key} placeholder={p.admin_key === MASK ? t("settings.apiKeyStored") : "sk-ant-admin01-…"} onChange={(e) => setForm({ ...form, admin_key: e.target.value })} />
|
<Input.Password value={form.admin_key} placeholder={p.admin_key === MASK ? t("settings.apiKeyStored") : "sk-ant-admin01-…"} onChange={(e) => setForm({ ...form, admin_key: e.target.value })} />
|
||||||
<div className="hint">{t("settings.adminKeyHint")}</div>
|
<div className="hint">{t("settings.adminKeyHint")}</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<label>{t("settings.maxConcurrency")}</label>
|
<label>{t("settings.maxConcurrency")}</label>
|
||||||
<input type="number" min={1} value={form.max_concurrency ?? ""} placeholder="∞" onChange={(e) => setForm({ ...form, max_concurrency: e.target.value })} />
|
<Input type="number" min={1} value={form.max_concurrency ?? ""} placeholder="∞" onChange={(e) => setForm({ ...form, max_concurrency: e.target.value })} />
|
||||||
<div className="hint">{t("settings.maxConcurrencyHint")}</div>
|
<div className="hint">{t("settings.maxConcurrencyHint")}</div>
|
||||||
</div>
|
</div>
|
||||||
<h3 style={{ marginTop: 16 }}>
|
<h3 style={{ marginTop: 16 }}>
|
||||||
{t("settings.models")}
|
{t("settings.models")}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{(form.base_url?.includes("openrouter.ai") || form.base_url?.includes("opencode.ai")) && (
|
{(form.base_url?.includes("openrouter.ai") || form.base_url?.includes("opencode.ai")) && (
|
||||||
<button className="small" onClick={fetchPrices}>
|
<Button size="small" onClick={fetchPrices}>
|
||||||
{t("settings.fetchPrices")}
|
{t("settings.fetchPrices")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{discovered.length > 0 && (
|
{discovered.length > 0 && (
|
||||||
<button className="small" onClick={addDiscovered}>
|
<Button size="small" onClick={addDiscovered}>
|
||||||
{t("settings.addDiscovered", { n: discovered.length })}
|
{t("settings.addDiscovered", { n: discovered.length })}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button className="small" onClick={() => setModels([...models, { id: "" }])}>
|
<Button size="small" onClick={() => setModels([...models, { id: "" }])}>
|
||||||
+ {t("settings.addModel")}
|
+ {t("settings.addModel")}
|
||||||
</button>
|
</Button>
|
||||||
</h3>
|
</h3>
|
||||||
<div className="hint" style={{ marginBottom: 6, fontSize: 12, color: "var(--muted)" }}>
|
<div className="hint" style={{ marginBottom: 6, fontSize: 12, color: "var(--muted)" }}>
|
||||||
{t("settings.pricesHint")}
|
{t("settings.pricesHint")}
|
||||||
@@ -677,34 +659,34 @@ function ProviderEditor({ name, p, reload, status }: { name: string; p: Json; re
|
|||||||
{models.map((m, i) => (
|
{models.map((m, i) => (
|
||||||
<tr key={i}>
|
<tr key={i}>
|
||||||
<td>
|
<td>
|
||||||
<input value={m.id} onChange={(e) => setModel(i, { id: e.target.value })} style={{ minWidth: 160 }} />
|
<Input value={m.id} onChange={(e) => setModel(i, { id: e.target.value })} style={{ minWidth: 160 }} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input type="number" value={m.context ?? ""} onChange={(e) => setModel(i, { context: num(e.target.value) })} />
|
<Input type="number" value={m.context ?? ""} onChange={(e) => setModel(i, { context: num(e.target.value) })} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input type="number" value={m.max_output ?? ""} onChange={(e) => setModel(i, { max_output: num(e.target.value) })} />
|
<Input type="number" value={m.max_output ?? ""} onChange={(e) => setModel(i, { max_output: num(e.target.value) })} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input type="number" value={m.max_input ?? ""} placeholder="–" onChange={(e) => setModel(i, { max_input: num(e.target.value) })} />
|
<Input type="number" value={m.max_input ?? ""} placeholder="–" onChange={(e) => setModel(i, { max_input: num(e.target.value) })} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input type="checkbox" checked={!!m.reasoning} onChange={(e) => setModel(i, { reasoning: e.target.checked })} />
|
<Checkbox checked={!!m.reasoning} onChange={(e) => setModel(i, { reasoning: e.target.checked })} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input type="checkbox" checked={!!m.vision} onChange={(e) => setModel(i, { vision: e.target.checked })} />
|
<Checkbox checked={!!m.vision} onChange={(e) => setModel(i, { vision: e.target.checked })} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<select value={m.effort ?? ""} onChange={(e) => setModel(i, { effort: e.target.value || undefined })}>
|
<Select value={m.effort ?? ""} onChange={(e) => setModel(i, { effort: e.target.value || undefined })}>
|
||||||
<option value="">–</option>
|
<option value="">–</option>
|
||||||
{["low", "medium", "high", "xhigh", "max"].map((x) => (
|
{["low", "medium", "high", "xhigh", "max"].map((x) => (
|
||||||
<option key={x}>{x}</option>
|
<option key={x}>{x}</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</td>
|
</td>
|
||||||
{(["input_price", "output_price", "cache_read_price", "cache_write_price"] as const).map((k) => (
|
{(["input_price", "output_price", "cache_read_price", "cache_write_price"] as const).map((k) => (
|
||||||
<td key={k}>
|
<td key={k}>
|
||||||
<input type="number" step="0.01" value={m[k] ?? ""} onChange={(e) => setModel(i, { [k]: num(e.target.value) })} />
|
<Input type="number" step="0.01" value={m[k] ?? ""} onChange={(e) => setModel(i, { [k]: num(e.target.value) })} />
|
||||||
{k === "cache_write_price" && priceExtras(m) && (
|
{k === "cache_write_price" && priceExtras(m) && (
|
||||||
<span className="chip price-extra" title={priceExtras(m)}>
|
<span className="chip price-extra" title={priceExtras(m)}>
|
||||||
+{(m.price_tiers?.length ?? 0) + (m.price_multipliers?.length ?? 0)}
|
+{(m.price_tiers?.length ?? 0) + (m.price_multipliers?.length ?? 0)}
|
||||||
@@ -713,15 +695,15 @@ function ProviderEditor({ name, p, reload, status }: { name: string; p: Json; re
|
|||||||
</td>
|
</td>
|
||||||
))}
|
))}
|
||||||
<td>
|
<td>
|
||||||
<input type="number" min={1} value={m.max_concurrency ?? ""} placeholder="∞" onChange={(e) => setModel(i, { max_concurrency: num(e.target.value) })} />
|
<Input type="number" min={1} value={m.max_concurrency ?? ""} placeholder="∞" onChange={(e) => setModel(i, { max_concurrency: num(e.target.value) })} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<ModelSelect value={m.fallback ?? ""} onChange={(v) => setModel(i, { fallback: v || undefined })} emptyLabel="–" />
|
<ModelSelect value={m.fallback ?? ""} onChange={(v) => setModel(i, { fallback: v || undefined })} emptyLabel="–" />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<button className="small ghost danger" onClick={() => setModels(models.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
<Button type="text" danger size="small" onClick={() => setModels(models.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@@ -736,16 +718,16 @@ function ProviderEditor({ name, p, reload, status }: { name: string; p: Json; re
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ marginTop: 12 }}>
|
<div className="row" style={{ marginTop: 12 }}>
|
||||||
<button onClick={test} disabled={testing || !form.base_url}>
|
<Button onClick={test} disabled={testing || !form.base_url}>
|
||||||
<Icon name="plug" /> {testing ? t("settings.testing") : t("settings.testConnection")}
|
<Icon name="plug" /> {testing ? t("settings.testing") : t("settings.testConnection")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button className="danger" onClick={remove}>
|
<Button danger onClick={remove}>
|
||||||
{t("common.delete")}
|
{t("common.delete")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
@@ -786,10 +768,10 @@ function Providers({ cfg, reload }: { cfg: ConfigResponse; reload: () => void })
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="row" style={{ marginBottom: 12 }}>
|
<div className="row" style={{ marginBottom: 12 }}>
|
||||||
<button onClick={() => post("/providers/reload").then(reload)}>{t("settings.reloadProviders")}</button>
|
<Button onClick={() => post("/providers/reload").then(reload)}>{t("settings.reloadProviders")}</Button>
|
||||||
<button onClick={recheck} disabled={checking}>
|
<Button onClick={recheck} disabled={checking}>
|
||||||
{checking ? t("settings.providerChecking") : t("settings.providerCheck")}
|
{checking ? t("settings.providerChecking") : t("settings.providerCheck")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{Object.entries(providers).map(([n, p]) => (
|
{Object.entries(providers).map(([n, p]) => (
|
||||||
<ProviderEditor key={n + JSON.stringify(p)} name={n} p={p} reload={reload} status={status[n]} />
|
<ProviderEditor key={n + JSON.stringify(p)} name={n} p={p} reload={reload} status={status[n]} />
|
||||||
@@ -797,15 +779,15 @@ function Providers({ cfg, reload }: { cfg: ConfigResponse; reload: () => void })
|
|||||||
<div className="panel">
|
<div className="panel">
|
||||||
<h3>{t("settings.addProvider")}</h3>
|
<h3>{t("settings.addProvider")}</h3>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<select value={preset} onChange={(e) => setPreset(e.target.value)}>
|
<Select value={preset} onChange={(e) => setPreset(e.target.value)}>
|
||||||
{Object.keys(PRESETS).map((k) => (
|
{Object.keys(PRESETS).map((k) => (
|
||||||
<option key={k}>{k}</option>
|
<option key={k}>{k}</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<input placeholder={t("settings.providerName")} value={name} onChange={(e) => setName(e.target.value)} />
|
<Input placeholder={t("settings.providerName")} value={name} onChange={(e) => setName(e.target.value)} />
|
||||||
<button className="primary" onClick={add}>
|
<Button type="primary" onClick={add}>
|
||||||
+ {t("common.add")}
|
+ {t("common.add")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{view}
|
{view}
|
||||||
</div>
|
</div>
|
||||||
@@ -882,9 +864,9 @@ function McpEditor({ name, m, reload, isNew }: { name: string; m: Json; reload:
|
|||||||
{st?.state === "connected" && <span className="chip">{t("mcp.tools", { n: st.tools ?? 0 })}</span>}
|
{st?.state === "connected" && <span className="chip">{t("mcp.tools", { n: st.tools ?? 0 })}</span>}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{!isNew && (
|
{!isNew && (
|
||||||
<button className="small" onClick={() => setOpen(!open)}>
|
<Button size="small" onClick={() => setOpen(!open)}>
|
||||||
{open ? t("common.collapse") : t("common.edit")}
|
{open ? t("common.collapse") : t("common.edit")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</h3>
|
</h3>
|
||||||
{st?.state === "failed" && <div className="notice err">{st.error}</div>}
|
{st?.state === "failed" && <div className="notice err">{st.error}</div>}
|
||||||
@@ -892,40 +874,40 @@ function McpEditor({ name, m, reload, isNew }: { name: string; m: Json; reload:
|
|||||||
<>
|
<>
|
||||||
<div className="form">
|
<div className="form">
|
||||||
<label>{t("settings.name")}</label>
|
<label>{t("settings.name")}</label>
|
||||||
<input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
<Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||||
<label>{t("settings.kind")}</label>
|
<label>{t("settings.kind")}</label>
|
||||||
<select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })}>
|
<Select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })}>
|
||||||
<option value="stdio">stdio</option>
|
<option value="stdio">stdio</option>
|
||||||
<option value="http">Streamable HTTP</option>
|
<option value="http">Streamable HTTP</option>
|
||||||
</select>
|
</Select>
|
||||||
{form.type === "stdio" ? (
|
{form.type === "stdio" ? (
|
||||||
<>
|
<>
|
||||||
<label>{t("mcp.command")}</label>
|
<label>{t("mcp.command")}</label>
|
||||||
<input value={form.command} onChange={(e) => setForm({ ...form, command: e.target.value })} placeholder="npx" />
|
<Input value={form.command} onChange={(e) => setForm({ ...form, command: e.target.value })} placeholder="npx" />
|
||||||
<label>{t("mcp.args")}</label>
|
<label>{t("mcp.args")}</label>
|
||||||
<textarea rows={3} value={form.args} onChange={(e) => setForm({ ...form, args: e.target.value })} className="mono" />
|
<Input.TextArea rows={3} value={form.args} onChange={(e) => setForm({ ...form, args: e.target.value })} className="mono" />
|
||||||
<label>{t("mcp.env")}</label>
|
<label>{t("mcp.env")}</label>
|
||||||
<textarea rows={2} value={form.env} onChange={(e) => setForm({ ...form, env: e.target.value })} className="mono" placeholder="KEY=${SECRET}" />
|
<Input.TextArea rows={2} value={form.env} onChange={(e) => setForm({ ...form, env: e.target.value })} className="mono" placeholder="KEY=${SECRET}" />
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<label>URL</label>
|
<label>URL</label>
|
||||||
<input value={form.url} onChange={(e) => setForm({ ...form, url: e.target.value })} placeholder="https://…/mcp" />
|
<Input value={form.url} onChange={(e) => setForm({ ...form, url: e.target.value })} placeholder="https://…/mcp" />
|
||||||
<label>{t("mcp.headers")}</label>
|
<label>{t("mcp.headers")}</label>
|
||||||
<textarea rows={2} value={form.headers} onChange={(e) => setForm({ ...form, headers: e.target.value })} className="mono" placeholder="Authorization: Bearer ${TOKEN}" />
|
<Input.TextArea rows={2} value={form.headers} onChange={(e) => setForm({ ...form, headers: e.target.value })} className="mono" placeholder="Authorization: Bearer ${TOKEN}" />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<label>{t("settings.enabled")}</label>
|
<label>{t("settings.enabled")}</label>
|
||||||
<input type="checkbox" checked={form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} style={{ justifySelf: "start" }} />
|
<Checkbox checked={form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} style={{ justifySelf: "start" }} />
|
||||||
<label>{t("mcp.load")}</label>
|
<label>{t("mcp.load")}</label>
|
||||||
<select value={form.load} onChange={(e) => setForm({ ...form, load: e.target.value })}>
|
<Select value={form.load} onChange={(e) => setForm({ ...form, load: e.target.value })}>
|
||||||
<option value="auto">{t("mcp.loadAuto")}</option>
|
<option value="auto">{t("mcp.loadAuto")}</option>
|
||||||
<option value="always">{t("mcp.loadAlways")}</option>
|
<option value="always">{t("mcp.loadAlways")}</option>
|
||||||
<option value="on_demand">{t("mcp.loadOnDemand")}</option>
|
<option value="on_demand">{t("mcp.loadOnDemand")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<div className="hint">{t("mcp.loadHint")}</div>
|
<div className="hint">{t("mcp.loadHint")}</div>
|
||||||
<label>{t("mcp.users")}</label>
|
<label>{t("mcp.users")}</label>
|
||||||
<input value={form.users} onChange={(e) => setForm({ ...form, users: e.target.value })} placeholder={t("mcp.usersPlaceholder")} />
|
<Input value={form.users} onChange={(e) => setForm({ ...form, users: e.target.value })} placeholder={t("mcp.usersPlaceholder")} />
|
||||||
<div className="hint">{t("mcp.usersHint")}</div>
|
<div className="hint">{t("mcp.usersHint")}</div>
|
||||||
</div>
|
</div>
|
||||||
{status?.tools?.length ? (
|
{status?.tools?.length ? (
|
||||||
@@ -942,14 +924,14 @@ function McpEditor({ name, m, reload, isNew }: { name: string; m: Json; reload:
|
|||||||
) : null}
|
) : null}
|
||||||
{view}
|
{view}
|
||||||
<div className="row" style={{ marginTop: 12 }}>
|
<div className="row" style={{ marginTop: 12 }}>
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{!isNew && (
|
{!isNew && (
|
||||||
<button className="danger" onClick={() => void confirmDialog({ message: t("settings.deleteMcpConfirm", { name }), danger: true, confirmLabel: t("common.delete") }).then((ok): unknown => ok && run(() => savePatches([{ path: ["mcp", name], value: null }])))}>
|
<Button danger onClick={() => void confirmDialog({ message: t("settings.deleteMcpConfirm", { name }), danger: true, confirmLabel: t("common.delete") }).then((ok): unknown => ok && run(() => savePatches([{ path: ["mcp", name], value: null }])))}>
|
||||||
{t("common.delete")}
|
{t("common.delete")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
@@ -964,7 +946,7 @@ function Mcp({ cfg, reload }: { cfg: ConfigResponse; reload: () => void }) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="row" style={{ marginBottom: 12 }}>
|
<div className="row" style={{ marginBottom: 12 }}>
|
||||||
<button onClick={() => post("/mcp/reload")}>{t("mcp.reconnect")}</button>
|
<Button onClick={() => post("/mcp/reload")}>{t("mcp.reconnect")}</Button>
|
||||||
</div>
|
</div>
|
||||||
{Object.keys(servers).length === 0 && <div className="notice">{t("mcp.none")}</div>}
|
{Object.keys(servers).length === 0 && <div className="notice">{t("mcp.none")}</div>}
|
||||||
{Object.entries(servers).map(([n, m]) => (
|
{Object.entries(servers).map(([n, m]) => (
|
||||||
@@ -992,29 +974,29 @@ function RuleTable({ rules, setRules, choices, keyLabel }: { rules: [string, str
|
|||||||
{rules.map(([k, v], i) => (
|
{rules.map(([k, v], i) => (
|
||||||
<tr key={i}>
|
<tr key={i}>
|
||||||
<td>
|
<td>
|
||||||
<input className="mono" value={k} onChange={(e) => setRules(rules.map((r, j) => (j === i ? [e.target.value, r[1]] : r)))} />
|
<Input className="mono" value={k} onChange={(e) => setRules(rules.map((r, j) => (j === i ? [e.target.value, r[1]] : r)))} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<select value={v} onChange={(e) => setRules(rules.map((r, j) => (j === i ? [r[0], e.target.value] : r)))}>
|
<Select value={v} onChange={(e) => setRules(rules.map((r, j) => (j === i ? [r[0], e.target.value] : r)))}>
|
||||||
{choices.map((c) => (
|
{choices.map((c) => (
|
||||||
<option key={c} value={c}>
|
<option key={c} value={c}>
|
||||||
{t(`permissions.${c}` as Key)}
|
{t(`permissions.${c}` as Key)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<button className="small ghost danger" onClick={() => setRules(rules.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
<Button type="text" danger size="small" onClick={() => setRules(rules.filter((_, j) => j !== i))} aria-label={t("common.remove")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={3}>
|
<td colSpan={3}>
|
||||||
<button className="small" onClick={() => setRules([...rules, ["", choices[0]]])}>
|
<Button size="small" onClick={() => setRules([...rules, ["", choices[0]]])}>
|
||||||
+ {t("common.add")}
|
+ {t("common.add")}
|
||||||
</button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -1054,9 +1036,9 @@ function Permissions({ cfg, reload }: { cfg: ConfigResponse; reload: () => void
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{view}
|
{view}
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1074,13 +1056,13 @@ function Raw({ reload }: { reload: () => void }) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="notice">{t("settings.rawHint")}</div>
|
<div className="notice">{t("settings.rawHint")}</div>
|
||||||
<textarea className="raw-editor" spellCheck={false} value={text} onChange={(e) => setText(e.target.value)} />
|
<Input.TextArea className="raw-editor" spellCheck={false} value={text} onChange={(e) => setText(e.target.value)} />
|
||||||
{view}
|
{view}
|
||||||
<div className="row" style={{ marginTop: 8 }}>
|
<div className="row" style={{ marginTop: 8 }}>
|
||||||
<button className="primary" onClick={() => run(() => put("/config/raw", { text }))}>
|
<Button type="primary" onClick={() => run(() => put("/config/raw", { text }))}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={() => get<{ text: string }>("/config/raw").then((r) => setText(r.text))}>{t("settings.revert")}</button>
|
<Button onClick={() => get<{ text: string }>("/config/raw").then((r) => setText(r.text))}>{t("settings.revert")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -1088,8 +1070,8 @@ function Raw({ reload }: { reload: () => void }) {
|
|||||||
|
|
||||||
// --- page -------------------------------------------------------------------
|
// --- page -------------------------------------------------------------------
|
||||||
|
|
||||||
const ADMIN_TABS = ["general", "providers", "agents", "mcp", "permissions", "users", "folders", "tools", "audit", "templates", "modes", "account", "raw"] as const;
|
const ADMIN_TABS = ["general", "providers", "agents", "mcp", "permissions", "users", "folders", "tools", "audit", "templates", "modes", "skills", "account", "raw"] as const;
|
||||||
const USER_TABS = ["general", "templates", "modes", "account"] as const;
|
const USER_TABS = ["general", "templates", "modes", "skills", "account"] as const;
|
||||||
const TAB_ICONS: Record<string, string> = {
|
const TAB_ICONS: Record<string, string> = {
|
||||||
general: "gear",
|
general: "gear",
|
||||||
providers: "brain",
|
providers: "brain",
|
||||||
@@ -1102,6 +1084,7 @@ const TAB_ICONS: Record<string, string> = {
|
|||||||
audit: "scroll",
|
audit: "scroll",
|
||||||
templates: "template",
|
templates: "template",
|
||||||
modes: "sparkle",
|
modes: "sparkle",
|
||||||
|
skills: "scroll",
|
||||||
account: "user",
|
account: "user",
|
||||||
raw: "file-text",
|
raw: "file-text",
|
||||||
};
|
};
|
||||||
@@ -1116,29 +1099,36 @@ export function Settings({ tab, onMenu }: { tab?: string; onMenu: () => void })
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{t("nav.settings")}</h1>
|
<h1>{t("nav.settings")}</h1>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="page">
|
<div className="page">
|
||||||
<div className="page-inner">
|
<div className="page-inner">
|
||||||
<div className="tabs" role="tablist">
|
<Tabs
|
||||||
{TABS.map((x) => (
|
className="settings-tabs"
|
||||||
<button key={x} role="tab" aria-selected={active === x} className={active === x ? "active" : ""} onClick={() => navigate(`/settings/${x}`)}>
|
activeKey={active}
|
||||||
<Icon name={TAB_ICONS[x]} className="nav-icon" />
|
onChange={(x) => navigate(`/settings/${x}`)}
|
||||||
{t(`settings.tab.${x}` as Key)}
|
items={TABS.map((x) => ({
|
||||||
</button>
|
key: x,
|
||||||
))}
|
label: (
|
||||||
</div>
|
<span className="tab-label">
|
||||||
|
<Icon name={TAB_ICONS[x]} className="nav-icon" />
|
||||||
|
{t(`settings.tab.${x}` as Key)}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
{isAdmin && !cfg && !error && <div className="empty">{t("common.loading")}</div>}
|
{isAdmin && !cfg && !error && <div className="empty">{t("common.loading")}</div>}
|
||||||
{!isAdmin && active === "general" && <InterfaceSettings />}
|
{!isAdmin && active === "general" && <InterfaceSettings />}
|
||||||
{active === "account" && <Account />}
|
{active === "account" && <Account />}
|
||||||
{active === "templates" && <Templates />}
|
{active === "templates" && <Templates />}
|
||||||
{active === "modes" && <PersonalModes />}
|
{active === "modes" && <PersonalModes />}
|
||||||
|
{active === "skills" && <Skills />}
|
||||||
{cfg && active === "users" && <Users />}
|
{cfg && active === "users" && <Users />}
|
||||||
{cfg && active === "folders" && <Folders />}
|
{cfg && active === "folders" && <Folders />}
|
||||||
{cfg && active === "audit" && <Audit />}
|
{cfg && active === "audit" && <Audit />}
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { del, get, post, put } from "../api";
|
import { del, get, post, put } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -39,21 +42,21 @@ function Links({ sessionId }: { sessionId: string }) {
|
|||||||
<div className="hint">{t("link.hint")}</div>
|
<div className="hint">{t("link.hint")}</div>
|
||||||
{links.map((l) => (
|
{links.map((l) => (
|
||||||
<div key={l.token} className="row share-link">
|
<div key={l.token} className="row share-link">
|
||||||
<input readOnly value={l.url} onFocus={(e) => e.currentTarget.select()} aria-label={t("link.title")} />
|
<Input readOnly value={l.url} onFocus={(e) => e.currentTarget.select()} aria-label={t("link.title")} />
|
||||||
<span className="hint">{t("link.until", { date: fmtDate(l.expires_at, false) })}</span>
|
<span className="hint">{t("link.until", { date: fmtDate(l.expires_at, false) })}</span>
|
||||||
<button onClick={() => navigator.clipboard?.writeText(l.url).then(() => toast(t("link.copied"), "success"))}>{t("link.copy")}</button>
|
<Button onClick={() => navigator.clipboard?.writeText(l.url).then(() => toast(t("link.copied"), "success"))}>{t("link.copy")}</Button>
|
||||||
<button onClick={() => del(`/sessions/${sessionId}/links/${l.token}`).then(load).catch((e) => toast(e.message))}>{t("link.revoke")}</button>
|
<Button onClick={() => del(`/sessions/${sessionId}/links/${l.token}`).then(load).catch((e) => toast(e.message))}>{t("link.revoke")}</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<div className="row" style={{ marginTop: 6 }}>
|
<div className="row" style={{ marginTop: 6 }}>
|
||||||
<select value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label={t("link.validity")}>
|
<Select value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label={t("link.validity")}>
|
||||||
{[1, 7, 30, 90].map((d) => (
|
{[1, 7, 30, 90].map((d) => (
|
||||||
<option key={d} value={d}>
|
<option key={d} value={d}>
|
||||||
{t("link.days", { n: d })}
|
{t("link.days", { n: d })}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<button onClick={create}>{t("link.create")}</button>
|
<Button onClick={create}>{t("link.create")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -87,37 +90,30 @@ export function ShareDialog({ sessionId, onClose }: { sessionId: string; onClose
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} role="dialog" aria-label={t("share.title")}>
|
||||||
<div className="modal" role="dialog" aria-label={t("share.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("share.title")}</h3>
|
<h3>{t("share.title")}</h3>
|
||||||
<div style={{ fontSize: 13, color: "var(--muted)", marginBottom: 8 }}>{t("share.hint")}</div>
|
<div style={{ fontSize: 13, color: "var(--muted)", marginBottom: 8 }}>{t("share.hint")}</div>
|
||||||
<div className="check-list">
|
<div className="check-list">
|
||||||
{users.length === 0 && <div className="empty">{t("share.noUsers")}</div>}
|
{users.length === 0 && <div className="empty">{t("share.noUsers")}</div>}
|
||||||
{users.map((u) => (
|
{users.map((u) => (
|
||||||
<label key={u.id}>
|
<Checkbox key={u.id} checked={selected.has(u.id)} onChange={(e) => {
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={selected.has(u.id)}
|
|
||||||
onChange={(e) => {
|
|
||||||
const next = new Set(selected);
|
const next = new Set(selected);
|
||||||
if (e.target.checked) next.add(u.id);
|
if (e.target.checked) next.add(u.id);
|
||||||
else next.delete(u.id);
|
else next.delete(u.id);
|
||||||
setSelected(next);
|
setSelected(next);
|
||||||
}}
|
}}>
|
||||||
/>
|
|
||||||
{u.display_name || u.username} <span style={{ color: "var(--muted)" }}>@{u.username}</span>
|
{u.display_name || u.username} <span style={{ color: "var(--muted)" }}>@{u.username}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<Links sessionId={sessionId} />
|
<Links sessionId={sessionId} />
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
||||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
<Button onClick={onClose}>{t("common.cancel")}</Button>
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { fmtRelative, useT } from "../i18n";
|
import { fmtRelative, useT } from "../i18n";
|
||||||
import { navigate } from "../router";
|
import { navigate } from "../router";
|
||||||
@@ -28,32 +30,30 @@ export function ShareTarget({ shared, onClose }: { shared: string; onClose: () =
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={cancel}>
|
<Modal onClose={cancel} className="share-target" role="dialog" aria-label={t("shareIn.title")}>
|
||||||
<div className="modal share-target" role="dialog" aria-label={t("shareIn.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>{t("shareIn.title")}</h3>
|
<h3>{t("shareIn.title")}</h3>
|
||||||
<textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} />
|
<Input.TextArea value={text} onChange={(e) => setText(e.target.value)} rows={4} />
|
||||||
<button className="primary share-new" onClick={() => done("new")} disabled={!text.trim()}>
|
<Button type="primary" className="share-new" onClick={() => done("new")} disabled={!text.trim()}>
|
||||||
<Icon name="plus" /> {t("shareIn.newChat")}
|
<Icon name="plus" /> {t("shareIn.newChat")}
|
||||||
</button>
|
</Button>
|
||||||
{sessions.length > 0 && (
|
{sessions.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<div className="share-sep">{t("shareIn.appendTo")}</div>
|
<div className="share-sep">{t("shareIn.appendTo")}</div>
|
||||||
<div className="share-list">
|
<div className="share-list">
|
||||||
{sessions.map((s) => (
|
{sessions.map((s) => (
|
||||||
<button key={s.id} onClick={() => done(s.id)} disabled={!text.trim()}>
|
<Button key={s.id} onClick={() => done(s.id)} disabled={!text.trim()}>
|
||||||
<span className="share-title">{s.title || t("session.untitled")}</span>
|
<span className="share-title">{s.title || t("session.untitled")}</span>
|
||||||
<span className="share-meta">
|
<span className="share-meta">
|
||||||
{basename(s.cwd)} · {fmtRelative(s.updated_at)}
|
{basename(s.cwd)} · {fmtRelative(s.updated_at)}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
||||||
<button onClick={cancel}>{t("common.cancel")}</button>
|
<Button onClick={cancel}>{t("common.cancel")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Segmented } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get, post } from "../api";
|
import { get, post } from "../api";
|
||||||
@@ -44,37 +46,41 @@ export function ShellsChip({ sessionId, busy }: { sessionId: string; busy: boole
|
|||||||
{running ? <Spinner small /> : <Icon name="terminal" />} {t("shells.chip", { n: running, total: shells.length })}
|
{running ? <Spinner small /> : <Icon name="terminal" />} {t("shells.chip", { n: running, total: shells.length })}
|
||||||
</button>
|
</button>
|
||||||
{open && (
|
{open && (
|
||||||
<div className="modal-backdrop" onClick={() => setOpen(false)}>
|
<Modal onClose={() => setOpen(false)} className="wide" role="dialog" aria-label={t("shells.title")}>
|
||||||
<div className="modal wide" role="dialog" aria-label={t("shells.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="row" style={{ marginBottom: 8 }}>
|
<div className="row" style={{ marginBottom: 8 }}>
|
||||||
<h3 style={{ margin: 0 }}>{t("shells.title")}</h3>
|
<h3 style={{ margin: 0 }}>{t("shells.title")}</h3>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button className="small ghost" onClick={() => setOpen(false)} aria-label={t("common.close")}>
|
<Button type="text" size="small" onClick={() => setOpen(false)} aria-label={t("common.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
|
||||||
<div className="mode-tabs" style={{ flexWrap: "wrap", marginBottom: 8 }}>
|
|
||||||
{shells.map((s) => (
|
|
||||||
<button key={s.id} className={s.id === current.id ? "active" : ""} onClick={() => setSelected(s.id)}>
|
|
||||||
<Icon name={s.running ? "dot" : "radio-off"} className={`tiny ${s.running ? "ok" : ""}`} />{" "}
|
|
||||||
{s.command.slice(0, 40)}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
|
<Segmented
|
||||||
|
className="seg-wrap"
|
||||||
|
style={{ marginBottom: 8 }}
|
||||||
|
value={current.id}
|
||||||
|
onChange={setSelected}
|
||||||
|
options={shells.map((s) => ({
|
||||||
|
value: s.id,
|
||||||
|
label: (
|
||||||
|
<>
|
||||||
|
<Icon name={s.running ? "dot" : "radio-off"} className={`tiny ${s.running ? "ok" : ""}`} /> {s.command.slice(0, 40)}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
<div className="row" style={{ fontSize: 12.5, color: "var(--muted)", marginBottom: 6 }}>
|
<div className="row" style={{ fontSize: 12.5, color: "var(--muted)", marginBottom: 6 }}>
|
||||||
<code>{current.command}</code>
|
<code>{current.command}</code>
|
||||||
<span>· {fmtRelative(current.started_at)}</span>
|
<span>· {fmtRelative(current.started_at)}</span>
|
||||||
<span>· {current.running ? t("shells.running") : t("shells.exited", { code: current.exit_code ?? "?" })}</span>
|
<span>· {current.running ? t("shells.running") : t("shells.exited", { code: current.exit_code ?? "?" })}</span>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{current.running && (
|
{current.running && (
|
||||||
<button className="small danger" onClick={() => post(`/sessions/${sessionId}/shells/${current.id}/kill`).catch(toast)}>
|
<Button danger size="small" onClick={() => post(`/sessions/${sessionId}/shells/${current.id}/kill`).catch(toast)}>
|
||||||
<Icon name="stop" /> {t("shells.stop")}
|
<Icon name="stop" /> {t("shells.stop")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<pre className="shell-output">{current.output || t("shells.noOutput")}</pre>
|
<pre className="shell-output">{current.output || t("shells.noOutput")}</pre>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
import { deleteChat } from "../chatActions";
|
import { deleteChat } from "../chatActions";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { StatusLeds } from "./StatusLeds";
|
import { StatusLeds } from "./StatusLeds";
|
||||||
@@ -83,35 +84,34 @@ function SessionRow({ s, active, attention, busy, folders }: { s: Session; activ
|
|||||||
{menu && (
|
{menu && (
|
||||||
<div className="session-menu" role="menu" onClick={(e) => e.stopPropagation()}>
|
<div className="session-menu" role="menu" onClick={(e) => e.stopPropagation()}>
|
||||||
{!s.archived && (
|
{!s.archived && (
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { pinned: !s.pinned }))}>
|
<Button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { pinned: !s.pinned }))}>
|
||||||
<Icon name="pin" /> {t(s.pinned ? "sidebar.unpin" : "sidebar.pin")}
|
<Icon name="pin" /> {t(s.pinned ? "sidebar.unpin" : "sidebar.pin")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button role="menuitem" className="hide-mobile" onClick={() => (setMenu(false), openBeside(s.id))}>
|
<Button role="menuitem" className="hide-mobile" onClick={() => (setMenu(false), openBeside(s.id))}>
|
||||||
<Icon name="external" /> {t("sidebar.openBeside")}
|
<Icon name="external" /> {t("sidebar.openBeside")}
|
||||||
</button>
|
</Button>
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), void moveTo())}>
|
<Button role="menuitem" onClick={() => (setMenu(false), void moveTo())}>
|
||||||
<Icon name="folder" /> {t("sidebar.moveTo")}
|
<Icon name="folder" /> {t("sidebar.moveTo")}
|
||||||
</button>
|
</Button>
|
||||||
{s.folder && (
|
{s.folder && (
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { folder: "" }))}>
|
<Button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { folder: "" }))}>
|
||||||
<Icon name="folder-up" /> {t("sidebar.removeFromFolder")}
|
<Icon name="folder-up" /> {t("sidebar.removeFromFolder")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { archived: !s.archived }))}>
|
<Button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { archived: !s.archived }))}>
|
||||||
<Icon name="archive" /> {t(s.archived ? "sidebar.unarchive" : "sidebar.archiveOne")}
|
<Icon name="archive" /> {t(s.archived ? "sidebar.unarchive" : "sidebar.archiveOne")}
|
||||||
</button>
|
</Button>
|
||||||
{!s.shared && (
|
{!s.shared && (
|
||||||
<button
|
<Button danger
|
||||||
role="menuitem"
|
role="menuitem"
|
||||||
className="danger"
|
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
setMenu(false);
|
setMenu(false);
|
||||||
if ((await deleteChat(s)) && active) navigate("/new");
|
if ((await deleteChat(s)) && active) navigate("/new");
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon name="trash" /> {t("chat.delete")}
|
<Icon name="trash" /> {t("chat.delete")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -212,19 +212,19 @@ function GroupHeader({
|
|||||||
{menu && (
|
{menu && (
|
||||||
<div className="session-menu" role="menu" onClick={(e) => e.stopPropagation()}>
|
<div className="session-menu" role="menu" onClick={(e) => e.stopPropagation()}>
|
||||||
{g.id.startsWith("project:") && (
|
{g.id.startsWith("project:") && (
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), navigate(`/p/${encodeURIComponent(g.id.slice("project:".length))}`))}>
|
<Button role="menuitem" onClick={() => (setMenu(false), navigate(`/p/${encodeURIComponent(g.id.slice("project:".length))}`))}>
|
||||||
<Icon name="clock" /> {t("project.open")}
|
<Icon name="clock" /> {t("project.open")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), onPin?.())}>
|
<Button role="menuitem" onClick={() => (setMenu(false), onPin?.())}>
|
||||||
<Icon name="pin" /> {t(pinned ? "sidebar.groupUnpin" : "sidebar.groupPin")}
|
<Icon name="pin" /> {t(pinned ? "sidebar.groupUnpin" : "sidebar.groupPin")}
|
||||||
</button>
|
</Button>
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), onMove?.(-1))}>
|
<Button role="menuitem" onClick={() => (setMenu(false), onMove?.(-1))}>
|
||||||
<Icon name="arrow-up" /> {t("sidebar.groupUp")}
|
<Icon name="arrow-up" /> {t("sidebar.groupUp")}
|
||||||
</button>
|
</Button>
|
||||||
<button role="menuitem" onClick={() => (setMenu(false), onMove?.(1))}>
|
<Button role="menuitem" onClick={() => (setMenu(false), onMove?.(1))}>
|
||||||
<Icon name="arrow-down" /> {t("sidebar.groupDown")}
|
<Icon name="arrow-down" /> {t("sidebar.groupDown")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -398,12 +398,12 @@ export function Sidebar({ open, activeIds, section }: { open: boolean; activeIds
|
|||||||
<StatusLeds />
|
<StatusLeds />
|
||||||
</div>
|
</div>
|
||||||
<div style={{ padding: "0 12px 8px" }}>
|
<div style={{ padding: "0 12px 8px" }}>
|
||||||
<button className="primary" style={{ width: "100%" }} onClick={() => navigate("/new")}>
|
<Button type="primary" style={{ width: "100%" }} onClick={() => navigate("/new")}>
|
||||||
+ {t("sidebar.newSession")}
|
+ {t("sidebar.newSession")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="session-search">
|
<div className="session-search">
|
||||||
<input
|
<Input
|
||||||
type="search"
|
type="search"
|
||||||
value={query}
|
value={query}
|
||||||
placeholder={t("sidebar.search")}
|
placeholder={t("sidebar.search")}
|
||||||
@@ -433,10 +433,10 @@ export function Sidebar({ open, activeIds, section }: { open: boolean; activeIds
|
|||||||
{!hits && sessions.length === 0 && <div className="empty">{t("sidebar.noSessions")}</div>}
|
{!hits && sessions.length === 0 && <div className="empty">{t("sidebar.noSessions")}</div>}
|
||||||
{!hits && sessions.length > 0 && (
|
{!hits && sessions.length > 0 && (
|
||||||
<div className="session-view">
|
<div className="session-view">
|
||||||
<button className="ghost small" onClick={switchGroupBy} title={t("sidebar.groupByHint")}>
|
<Button type="text" size="small" onClick={switchGroupBy} title={t("sidebar.groupByHint")}>
|
||||||
<Icon name={groupBy === "time" ? "clock" : "folders"} className="tiny" />
|
<Icon name={groupBy === "time" ? "clock" : "folders"} className="tiny" />
|
||||||
{t(groupBy === "time" ? "sidebar.byTime" : "sidebar.byProject")}
|
{t(groupBy === "time" ? "sidebar.byTime" : "sidebar.byProject")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{!hits &&
|
{!hits &&
|
||||||
@@ -469,40 +469,40 @@ export function Sidebar({ open, activeIds, section }: { open: boolean; activeIds
|
|||||||
{me?.role === "admin" && <span className="chip" style={{ marginLeft: 6 }}>admin</span>}
|
{me?.role === "admin" && <span className="chip" style={{ marginLeft: 6 }}>admin</span>}
|
||||||
</span>
|
</span>
|
||||||
<ThemeModeButton />
|
<ThemeModeButton />
|
||||||
<button className="small ghost" onClick={() => post("/auth/logout").then(() => location.reload())}>
|
<Button type="text" size="small" onClick={() => post("/auth/logout").then(() => location.reload())}>
|
||||||
<Icon name="logout" className="nav-icon" />
|
<Icon name="logout" className="nav-icon" />
|
||||||
{t("nav.logout")}
|
{t("nav.logout")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="sidebar-foot">
|
<div className="sidebar-foot">
|
||||||
<button className={`ghost ${section === "files" ? "active" : ""}`} onClick={() => navigate("/files")}>
|
<Button type="text" className={section === "files" ? "active" : ""} onClick={() => navigate("/files")}>
|
||||||
<Icon name="folder" className="nav-icon" />
|
<Icon name="folder" className="nav-icon" />
|
||||||
{t("nav.files")}
|
{t("nav.files")}
|
||||||
</button>
|
</Button>
|
||||||
<button className={`ghost ${section === "images" ? "active" : ""}`} onClick={() => navigate("/images")}>
|
<Button type="text" className={section === "images" ? "active" : ""} onClick={() => navigate("/images")}>
|
||||||
<Icon name="image" className="nav-icon" />
|
<Icon name="image" className="nav-icon" />
|
||||||
{t("nav.images")}
|
{t("nav.images")}
|
||||||
</button>
|
</Button>
|
||||||
<button className={`ghost ${section === "terminal" ? "active" : ""}`} onClick={() => navigate("/terminal")}>
|
<Button type="text" className={section === "terminal" ? "active" : ""} onClick={() => navigate("/terminal")}>
|
||||||
<Icon name="terminal" className="nav-icon" />
|
<Icon name="terminal" className="nav-icon" />
|
||||||
{t("nav.terminal")}
|
{t("nav.terminal")}
|
||||||
</button>
|
</Button>
|
||||||
<button className={`ghost ${section === "jobs" ? "active" : ""}`} onClick={() => navigate("/jobs")}>
|
<Button type="text" className={section === "jobs" ? "active" : ""} onClick={() => navigate("/jobs")}>
|
||||||
<Icon name="clock" className="nav-icon" />
|
<Icon name="clock" className="nav-icon" />
|
||||||
{t("nav.jobs")}
|
{t("nav.jobs")}
|
||||||
</button>
|
</Button>
|
||||||
<button className={`ghost ${section === "factory" ? "active" : ""}`} onClick={() => navigate("/factory")}>
|
<Button type="text" className={section === "factory" ? "active" : ""} onClick={() => navigate("/factory")}>
|
||||||
<Icon name="toolbox" className="nav-icon" />
|
<Icon name="factory" className="nav-icon" />
|
||||||
{t("nav.factory")}
|
{t("nav.factory")}
|
||||||
</button>
|
</Button>
|
||||||
<button className={`ghost ${section === "stats" ? "active" : ""}`} onClick={() => navigate("/stats")}>
|
<Button type="text" className={section === "stats" ? "active" : ""} onClick={() => navigate("/stats")}>
|
||||||
<Icon name="chart" className="nav-icon" />
|
<Icon name="chart" className="nav-icon" />
|
||||||
{t("nav.stats")}
|
{t("nav.stats")}
|
||||||
</button>
|
</Button>
|
||||||
<button className={`ghost ${section === "settings" ? "active" : ""}`} onClick={() => navigate("/settings")}>
|
<Button type="text" className={section === "settings" ? "active" : ""} onClick={() => navigate("/settings")}>
|
||||||
<Icon name="wrench" className="nav-icon" />
|
<Icon name="wrench" className="nav-icon" />
|
||||||
{t("nav.settings")}
|
{t("nav.settings")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
@@ -515,8 +515,8 @@ function ThemeModeButton() {
|
|||||||
const icon = <Icon name={mode === "auto" ? "theme-auto" : mode === "light" ? "sun" : "moon"} />;
|
const icon = <Icon name={mode === "auto" ? "theme-auto" : mode === "light" ? "sun" : "moon"} />;
|
||||||
const label = t(mode === "auto" ? "settings.themeAuto" : mode === "light" ? "settings.themeLight" : "settings.themeDark");
|
const label = t(mode === "auto" ? "settings.themeAuto" : mode === "light" ? "settings.themeLight" : "settings.themeDark");
|
||||||
return (
|
return (
|
||||||
<button className="small ghost theme-toggle" onClick={cycleThemeMode} title={`${t("settings.themeToggle")} – ${label}`} aria-label={t("settings.themeToggle")}>
|
<Button type="text" size="small" className="theme-toggle" onClick={cycleThemeMode} title={`${t("settings.themeToggle")} – ${label}`} aria-label={t("settings.themeToggle")}>
|
||||||
{icon}
|
{icon}
|
||||||
</button>
|
</Button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Segmented } from "antd";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
import { Fragment, useEffect, useMemo, useState } from "react";
|
||||||
import { useFetch } from "../hooks";
|
import { useFetch } from "../hooks";
|
||||||
@@ -305,10 +307,10 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar stats-bar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow">
|
<div className="grow">
|
||||||
<h1>{t("nav.stats")}</h1>
|
<h1>{t("nav.stats")}</h1>
|
||||||
{data && (
|
{data && (
|
||||||
@@ -317,34 +319,32 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mode-tabs" role="tablist">
|
<Segmented
|
||||||
{RANGES.map((r) => (
|
value={range}
|
||||||
<button key={r.key} className={range === r.key ? "active" : ""} onClick={() => setRange(r.key)}>
|
onChange={(v) => setRange(v)}
|
||||||
{t(r.label)}
|
options={RANGES.map((r) => ({ value: r.key, label: t(r.label) }))}
|
||||||
</button>
|
/>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{years.length > 1 && (
|
{years.length > 1 && (
|
||||||
<select value={year ? range : ""} onChange={(e) => e.target.value && setRange(e.target.value)} aria-label={t("stats.year")} className={year ? "active" : ""}>
|
<Select value={year ? range : ""} onChange={(e) => e.target.value && setRange(e.target.value)} aria-label={t("stats.year")} className={year ? "active" : ""}>
|
||||||
<option value="">{t("stats.year")}</option>
|
<option value="">{t("stats.year")}</option>
|
||||||
{years.map((y) => (
|
{years.map((y) => (
|
||||||
<option key={y} value={`y${y}`}>
|
<option key={y} value={`y${y}`}>
|
||||||
{y}
|
{y}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
)}
|
)}
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<select value={userFilter} onChange={(e) => setUserFilter(e.target.value)} aria-label={t("stats.user")}>
|
<Select value={userFilter} onChange={(e) => setUserFilter(e.target.value)} aria-label={t("stats.user")}>
|
||||||
<option value="">{t("stats.allUsers")}</option>
|
<option value="">{t("stats.allUsers")}</option>
|
||||||
{users.map((u) => (
|
{users.map((u) => (
|
||||||
<option key={u.id} value={u.id}>
|
<option key={u.id} value={u.id}>
|
||||||
{u.username}
|
{u.username}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
)}
|
)}
|
||||||
<select value="" onChange={(e) => exportAs(e.target.value)} aria-label={t("stats.export")} title={t("stats.exportHint")}>
|
<Select value="" onChange={(e) => exportAs(e.target.value)} aria-label={t("stats.export")} title={t("stats.exportHint")}>
|
||||||
<option value="">{t("stats.export")}</option>
|
<option value="">{t("stats.export")}</option>
|
||||||
<option value="xlsx">{t("stats.exportXlsx")}</option>
|
<option value="xlsx">{t("stats.exportXlsx")}</option>
|
||||||
{(["day", "month", "model", "provider", "agent", "user", "session"] as const).map((k) => (
|
{(["day", "month", "model", "provider", "agent", "user", "session"] as const).map((k) => (
|
||||||
@@ -352,10 +352,10 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
|||||||
{t("stats.exportCsv", { table: t(`stats.table.${k}` as Key) })}
|
{t("stats.exportCsv", { table: t(`stats.table.${k}` as Key) })}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<button className="small" onClick={() => setTableView(!tableView)}>
|
<Button size="small" onClick={() => setTableView(!tableView)}>
|
||||||
{tableView ? t("stats.chartView") : t("stats.tableView")}
|
{tableView ? t("stats.chartView") : t("stats.tableView")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="page">
|
<div className="page">
|
||||||
<div className="page-inner">
|
<div className="page-inner">
|
||||||
@@ -393,11 +393,11 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
|||||||
</Fold>
|
</Fold>
|
||||||
<Fold id="heatmap" title={t("stats.heatmap")}>
|
<Fold id="heatmap" title={t("stats.heatmap")}>
|
||||||
<div className="row" style={{ justifyContent: "flex-end", marginBottom: 6 }}>
|
<div className="row" style={{ justifyContent: "flex-end", marginBottom: 6 }}>
|
||||||
<select value={heat} onChange={(e) => setHeat(e.target.value as HeatMetric)} aria-label={t("stats.heatmap")}>
|
<Select value={heat} onChange={(e) => setHeat(e.target.value as HeatMetric)} aria-label={t("stats.heatmap")}>
|
||||||
<option value="requests">{t("stats.requests")}</option>
|
<option value="requests">{t("stats.requests")}</option>
|
||||||
<option value="tokens">{t("stats.tokens")}</option>
|
<option value="tokens">{t("stats.tokens")}</option>
|
||||||
<option value="cost">{t("stats.cost")}</option>
|
<option value="cost">{t("stats.cost")}</option>
|
||||||
</select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<Heatmap cells={view.cells} rows={view.heatRows} format={heatFormat} />
|
<Heatmap cells={view.cells} rows={view.heatRows} format={heatFormat} />
|
||||||
</Fold>
|
</Fold>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { get, post } from "../api";
|
import { get, post } from "../api";
|
||||||
import { fmtCost, fmtPercent, useT, type Key } from "../i18n";
|
import { fmtCost, fmtPercent, useT, type Key } from "../i18n";
|
||||||
@@ -178,9 +179,9 @@ export function StatusLeds() {
|
|||||||
<Led level={models} /> {t("status.models")}
|
<Led level={models} /> {t("status.models")}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{admin && (
|
{admin && (
|
||||||
<button className="small ghost" onClick={recheck} disabled={checking} title={t("status.recheck")}>
|
<Button type="text" size="small" onClick={recheck} disabled={checking} title={t("status.recheck")}>
|
||||||
<Icon name="refresh" size={13} />
|
<Icon name="refresh" size={13} />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{providers.length === 0 && <div className="status-row hint">{t("status.noProviders")}</div>}
|
{providers.length === 0 && <div className="status-row hint">{t("status.noProviders")}</div>}
|
||||||
@@ -228,12 +229,12 @@ export function StatusLeds() {
|
|||||||
|
|
||||||
{admin && (
|
{admin && (
|
||||||
<div className="status-foot">
|
<div className="status-foot">
|
||||||
<button className="small ghost" onClick={() => go("providers")}>
|
<Button type="text" size="small" onClick={() => go("providers")}>
|
||||||
<Icon name="brain" size={13} /> {t("status.providerSettings")}
|
<Icon name="brain" size={13} /> {t("status.providerSettings")}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small ghost" onClick={() => go("mcp")}>
|
<Button type="text" size="small" onClick={() => go("mcp")}>
|
||||||
<Icon name="plug" size={13} /> {t("status.mcpSettings")}
|
<Icon name="plug" size={13} /> {t("status.mcpSettings")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { toast } from "../dialogs";
|
import { toast } from "../dialogs";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -43,14 +45,13 @@ export function TemplatePicker({ onPick, onClose }: { onPick: (text: string) =>
|
|||||||
const ph = chosen ? placeholders(chosen.text) : [];
|
const ph = chosen ? placeholders(chosen.text) : [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} className="tpl-picker" role="dialog" aria-label={t("templates.title")}>
|
||||||
<div className="modal tpl-picker" role="dialog" aria-label={t("templates.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
{!chosen ? (
|
{!chosen ? (
|
||||||
<>
|
<>
|
||||||
<h3>
|
<h3>
|
||||||
<Icon name="template" /> {t("templates.title")}
|
<Icon name="template" /> {t("templates.title")}
|
||||||
</h3>
|
</h3>
|
||||||
<input
|
<Input
|
||||||
autoFocus
|
autoFocus
|
||||||
style={{ width: "100%" }}
|
style={{ width: "100%" }}
|
||||||
value={q}
|
value={q}
|
||||||
@@ -79,11 +80,11 @@ export function TemplatePicker({ onPick, onClose }: { onPick: (text: string) =>
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="row" style={{ marginTop: 12 }}>
|
<div className="row" style={{ marginTop: 12 }}>
|
||||||
<button className="ghost small" onClick={() => (onClose(), navigate("/settings/templates"))}>
|
<Button type="text" size="small" onClick={() => (onClose(), navigate("/settings/templates"))}>
|
||||||
<Icon name="edit" /> {t("templates.manage")}
|
<Icon name="edit" /> {t("templates.manage")}
|
||||||
</button>
|
</Button>
|
||||||
<span className="grow" />
|
<span className="grow" />
|
||||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
<Button onClick={onClose}>{t("common.cancel")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -108,16 +109,15 @@ export function TemplatePicker({ onPick, onClose }: { onPick: (text: string) =>
|
|||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
||||||
<button type="button" onClick={() => setChosen(undefined)}>
|
<Button onClick={() => setChosen(undefined)}>
|
||||||
{t("common.back")}
|
{t("common.back")}
|
||||||
</button>
|
</Button>
|
||||||
<button type="submit" className="primary">
|
<Button type="primary" htmlType="submit">
|
||||||
{t("templates.insert")}
|
{t("templates.insert")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { Terminal as XTerm, type ITheme } from "@xterm/xterm";
|
import { Terminal as XTerm, type ITheme } from "@xterm/xterm";
|
||||||
import { FitAddon } from "@xterm/addon-fit";
|
import { FitAddon } from "@xterm/addon-fit";
|
||||||
@@ -98,23 +99,23 @@ export function TerminalPage({ id, onMenu }: { id?: string; onMenu: () => void }
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="topbar">
|
<div className="topbar">
|
||||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
<Button type="text" className="menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||||
<Icon name="menu" />
|
<Icon name="menu" />
|
||||||
</button>
|
</Button>
|
||||||
<div className="grow term-tabs">
|
<div className="grow term-tabs">
|
||||||
{list.map((x) => (
|
{list.map((x) => (
|
||||||
<span key={x.id} className={`term-tab ${x.id === id ? "active" : ""} ${x.alive ? "" : "dead"}`}>
|
<span key={x.id} className={`term-tab ${x.id === id ? "active" : ""} ${x.alive ? "" : "dead"}`}>
|
||||||
<button className="ghost small" onClick={() => navigate(`/terminal/${x.id}`)} title={x.cwd}>
|
<Button type="text" size="small" onClick={() => navigate(`/terminal/${x.id}`)} title={x.cwd}>
|
||||||
<Icon name="terminal" /> {basename(x.cwd)}
|
<Icon name="terminal" /> {basename(x.cwd)}
|
||||||
</button>
|
</Button>
|
||||||
<button className="ghost small" onClick={() => close(x.id)} aria-label={t("terminal.close")} title={t("terminal.close")}>
|
<Button type="text" size="small" onClick={() => close(x.id)} aria-label={t("terminal.close")} title={t("terminal.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
<button className="ghost small" onClick={open} title={t("terminal.new")} aria-label={t("terminal.new")}>
|
<Button type="text" size="small" onClick={open} title={t("terminal.new")} aria-label={t("terminal.new")}>
|
||||||
<Icon name="plus" />
|
<Icon name="plus" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
@@ -123,9 +124,9 @@ export function TerminalPage({ id, onMenu }: { id?: string; onMenu: () => void }
|
|||||||
) : (
|
) : (
|
||||||
<div className="empty">
|
<div className="empty">
|
||||||
{list.length === 0 && id !== "new" && (
|
{list.length === 0 && id !== "new" && (
|
||||||
<button className="primary" onClick={open}>
|
<Button type="primary" onClick={open}>
|
||||||
<Icon name="terminal" /> {t("terminal.new")}
|
<Icon name="terminal" /> {t("terminal.new")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -237,8 +238,8 @@ export function TermView({ info }: { info: TermInfo }) {
|
|||||||
<div className="term-host" ref={host} />
|
<div className="term-host" ref={host} />
|
||||||
{state !== "open" && <div className="term-state">{t(state === "connecting" ? "terminal.connecting" : "terminal.reconnecting")}</div>}
|
{state !== "open" && <div className="term-state">{t(state === "connecting" ? "terminal.connecting" : "terminal.reconnecting")}</div>}
|
||||||
<div className="term-keys" aria-label={t("terminal.keys")}>
|
<div className="term-keys" aria-label={t("terminal.keys")}>
|
||||||
<button onClick={() => key("\x1b")}>Esc</button>
|
<Button onClick={() => key("\x1b")}>Esc</Button>
|
||||||
<button onClick={() => key("\t")}>Tab</button>
|
<Button onClick={() => key("\t")}>Tab</Button>
|
||||||
<button
|
<button
|
||||||
className={ctrl ? "active" : ""}
|
className={ctrl ? "active" : ""}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -249,19 +250,19 @@ export function TermView({ info }: { info: TermInfo }) {
|
|||||||
>
|
>
|
||||||
Ctrl
|
Ctrl
|
||||||
</button>
|
</button>
|
||||||
<button onClick={() => key("\x03")}>^C</button>
|
<Button onClick={() => key("\x03")}>^C</Button>
|
||||||
<button onClick={() => key("\x1b[A")} aria-label="Up">
|
<Button onClick={() => key("\x1b[A")} aria-label="Up">
|
||||||
<Icon name="arrow-up" />
|
<Icon name="arrow-up" />
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={() => key("\x1b[B")} aria-label="Down">
|
<Button onClick={() => key("\x1b[B")} aria-label="Down">
|
||||||
<Icon name="arrow-down" />
|
<Icon name="arrow-down" />
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={() => key("\x1b[D")} aria-label="Left">
|
<Button onClick={() => key("\x1b[D")} aria-label="Left">
|
||||||
<Icon name="arrow-left" />
|
<Icon name="arrow-left" />
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={() => key("\x1b[C")} aria-label="Right">
|
<Button onClick={() => key("\x1b[C")} aria-label="Right">
|
||||||
<Icon name="arrow-right" />
|
<Icon name="arrow-right" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { FileFigure, imageSize, imageSrc } from "./FileFigure";
|
import { FileFigure, imageSize, imageSrc } from "./FileFigure";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
@@ -142,9 +143,9 @@ export function ToolCard({ call, result, running, baseDir }: { call: ToolCall; r
|
|||||||
{call.name === "bash" && <pre className="mono">$ {call.input?.command}</pre>}
|
{call.name === "bash" && <pre className="mono">$ {call.input?.command}</pre>}
|
||||||
{(call.name === "edit" || call.name === "write") && meta?.diff && <Diff diff={meta.diff} />}
|
{(call.name === "edit" || call.name === "write") && meta?.diff && <Diff diff={meta.diff} />}
|
||||||
{call.name === "task" && meta?.session_id && (
|
{call.name === "task" && meta?.session_id && (
|
||||||
<button className="small" onClick={() => navigate(`/s/${meta.session_id}`)}>
|
<Button size="small" onClick={() => navigate(`/s/${meta.session_id}`)}>
|
||||||
{t("tool.openSubagent")}
|
{t("tool.openSubagent")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{!["bash", "edit", "write", "task"].includes(call.name) && (
|
{!["bash", "edit", "write", "task"].includes(call.name) && (
|
||||||
<>
|
<>
|
||||||
@@ -165,8 +166,7 @@ export function ToolCard({ call, result, running, baseDir }: { call: ToolCall; r
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{typeof meta?.model_file === "string" && (
|
{typeof meta?.model_file === "string" && (
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
style={{ marginBottom: 8 }}
|
style={{ marginBottom: 8 }}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
sessionStorage.setItem("codecraft.openFile", meta.model_file);
|
sessionStorage.setItem("codecraft.openFile", meta.model_file);
|
||||||
@@ -174,7 +174,7 @@ export function ToolCard({ call, result, running, baseDir }: { call: ToolCall; r
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon name="cube" /> {t("tool.open3d")}
|
<Icon name="cube" /> {t("tool.open3d")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{Array.isArray(meta?.image_ids) ? (
|
{Array.isArray(meta?.image_ids) ? (
|
||||||
<div className="gallery small">
|
<div className="gallery small">
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { get } from "../api";
|
import { get } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -51,9 +52,9 @@ export function TurnChanges({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="turn-changes">
|
<div className="turn-changes">
|
||||||
<button className="small ghost" onClick={toggle} aria-expanded={open}>
|
<Button type="text" size="small" onClick={toggle} aria-expanded={open}>
|
||||||
<Icon name={open ? "chevron-down" : "chevron-right"} className="tiny" /> {t("turn.changes", { n: fileCount })}
|
<Icon name={open ? "chevron-down" : "chevron-right"} className="tiny" /> {t("turn.changes", { n: fileCount })}
|
||||||
</button>
|
</Button>
|
||||||
{open && (
|
{open && (
|
||||||
<div className="turn-changes-body">
|
<div className="turn-changes-body">
|
||||||
{error && <div className="notice err">{error}</div>}
|
{error && <div className="notice err">{error}</div>}
|
||||||
@@ -74,9 +75,9 @@ export function TurnChanges({
|
|||||||
</details>
|
</details>
|
||||||
))}
|
))}
|
||||||
{userMessage && onRewind && changes && changes.length > 0 && (
|
{userMessage && onRewind && changes && changes.length > 0 && (
|
||||||
<button className="small" onClick={() => onRewind(userMessage)}>
|
<Button size="small" onClick={() => onRewind(userMessage)}>
|
||||||
<Icon name="undo" /> {t("turn.rollback")}
|
<Icon name="undo" /> {t("turn.rollback")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { post } from "../api";
|
import { post } from "../api";
|
||||||
import { toast } from "../dialogs";
|
import { toast } from "../dialogs";
|
||||||
@@ -32,9 +33,9 @@ export function TurnCheck({ sessionId, messageId, canSend }: { sessionId: string
|
|||||||
<div className="turn-check-body">
|
<div className="turn-check-body">
|
||||||
<pre className="mono">{check.output || t("check.noOutput")}</pre>
|
<pre className="mono">{check.output || t("check.noOutput")}</pre>
|
||||||
{check.status !== "passed" && canSend && (
|
{check.status !== "passed" && canSend && (
|
||||||
<button className="small primary" onClick={fix}>
|
<Button type="primary" size="small" onClick={fix}>
|
||||||
<Icon name="sparkle" /> {t("check.fix")}
|
<Icon name="sparkle" /> {t("check.fix")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { useT } from "../i18n";
|
||||||
|
import { closeUploadBatch, useUploads } from "../uploads";
|
||||||
|
import { Icon } from "./Icon";
|
||||||
|
import { formatSize } from "./FileFigure";
|
||||||
|
|
||||||
|
/** Progress of running uploads: one box per batch with a bar for the total and one per file. */
|
||||||
|
export function UploadPanel() {
|
||||||
|
const t = useT();
|
||||||
|
const batches = useUploads();
|
||||||
|
if (!batches.length) return null;
|
||||||
|
return (
|
||||||
|
<div className="uploads" role="status" aria-live="polite">
|
||||||
|
{batches.map((b) => {
|
||||||
|
const total = b.items.reduce((a, i) => a + i.size, 0);
|
||||||
|
const sent = b.items.reduce((a, i) => a + i.sent, 0);
|
||||||
|
const finished = b.items.filter((i) => i.status === "done" || i.status === "error").length;
|
||||||
|
const running = finished < b.items.length;
|
||||||
|
const pct = (a: number, z: number) => (z ? Math.min(100, Math.round((a / z) * 100)) : 100);
|
||||||
|
return (
|
||||||
|
<div key={b.id} className="upload-batch">
|
||||||
|
<div className="upload-head">
|
||||||
|
<strong>{running ? t("upload.running", { done: finished, n: b.items.length }) : t("upload.finished", { n: b.items.length })}</strong>
|
||||||
|
<span className="hint">
|
||||||
|
{formatSize(sent)} / {formatSize(total)}
|
||||||
|
</span>
|
||||||
|
<Button type="text" size="small" onClick={() => closeUploadBatch(b.id)} aria-label={t("common.close")}>
|
||||||
|
<Icon name="close" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="upload-bar total" title={`${pct(sent, total)} %`}>
|
||||||
|
<i style={{ width: `${pct(sent, total)}%` }} />
|
||||||
|
</div>
|
||||||
|
<div className="upload-files">
|
||||||
|
{b.items.map((i) => (
|
||||||
|
<div key={i.id} className={`upload-file ${i.status}`}>
|
||||||
|
<span className="name" title={i.name}>
|
||||||
|
{i.name}
|
||||||
|
</span>
|
||||||
|
<span className="hint">{i.status === "error" ? i.error : i.status === "wait" ? formatSize(i.size) : `${pct(i.sent, i.size)} %`}</span>
|
||||||
|
<div className="upload-bar">
|
||||||
|
<i style={{ width: `${pct(i.sent, i.size)}%` }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { Icon } from "./Icon";
|
import { Icon } from "./Icon";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useFetch, useModels } from "../hooks";
|
import { useFetch, useModels } from "../hooks";
|
||||||
@@ -59,14 +61,13 @@ export function UsageOverlay({ session, onClose }: { session: Session; onClose:
|
|||||||
const ctxTokens = u ? u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens : 0;
|
const ctxTokens = u ? u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens : 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
<Modal onClose={onClose} className="wide" role="dialog" aria-label={t("usage.title")}>
|
||||||
<div className="modal wide" role="dialog" aria-label={t("usage.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="row" style={{ marginBottom: 8 }}>
|
<div className="row" style={{ marginBottom: 8 }}>
|
||||||
<h3 style={{ margin: 0 }}>{t("usage.title")}</h3>
|
<h3 style={{ margin: 0 }}>{t("usage.title")}</h3>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<button className="small ghost" onClick={onClose} aria-label={t("common.close")}>
|
<Button type="text" size="small" onClick={onClose} aria-label={t("common.close")}>
|
||||||
<Icon name="close" />
|
<Icon name="close" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{!data ? (
|
{!data ? (
|
||||||
<div className="empty">{t("common.loading")}</div>
|
<div className="empty">{t("common.loading")}</div>
|
||||||
@@ -194,7 +195,6 @@ export function UsageOverlay({ session, onClose }: { session: Session; onClose:
|
|||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { getLang, useT } from "../i18n";
|
import { getLang, useT } from "../i18n";
|
||||||
import { toast } from "../dialogs";
|
import { toast } from "../dialogs";
|
||||||
@@ -75,9 +76,9 @@ function RecorderButton({ onText, onInterim }: { onText: (text: string) => void;
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<Button
|
||||||
type="button"
|
|
||||||
className={`ghost small voice-btn ${state === "recording" ? "on" : ""}`}
|
type="text" size="small" className={`voice-btn ${state === "recording" ? "on" : ""}`}
|
||||||
disabled={state === "sending"}
|
disabled={state === "sending"}
|
||||||
onClick={() => void toggle()}
|
onClick={() => void toggle()}
|
||||||
title={t(state === "recording" ? "voice.stop" : "voice.start")}
|
title={t(state === "recording" ? "voice.stop" : "voice.start")}
|
||||||
@@ -85,7 +86,7 @@ function RecorderButton({ onText, onInterim }: { onText: (text: string) => void;
|
|||||||
aria-pressed={state === "recording"}
|
aria-pressed={state === "recording"}
|
||||||
>
|
>
|
||||||
<Icon name="mic" />
|
<Icon name="mic" />
|
||||||
</button>
|
</Button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,8 +139,8 @@ function BrowserVoiceButton({ onText, onInterim }: { onText: (text: string) => v
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button type="button" className={`ghost small voice-btn ${listening ? "on" : ""}`} onClick={toggle} title={t(listening ? "voice.stop" : "voice.start")} aria-label={t(listening ? "voice.stop" : "voice.start")} aria-pressed={listening}>
|
<Button type="text" size="small" className={`voice-btn ${listening ? "on" : ""}`} onClick={toggle} title={t(listening ? "voice.stop" : "voice.start")} aria-label={t(listening ? "voice.stop" : "voice.start")} aria-pressed={listening}>
|
||||||
<Icon name="mic" />
|
<Icon name="mic" />
|
||||||
</button>
|
</Button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { getLang, useT } from "../i18n";
|
import { getLang, useT } from "../i18n";
|
||||||
import { WHATS_NEW } from "../whatsnew";
|
import { WHATS_NEW } from "../whatsnew";
|
||||||
@@ -25,8 +27,7 @@ export function WhatsNew({ version }: { version: string }) {
|
|||||||
setOpen(false);
|
setOpen(false);
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className="modal-backdrop" onClick={close}>
|
<Modal onClose={close} role="dialog" aria-label={t("whatsnew.title")}>
|
||||||
<div className="modal" role="dialog" aria-label={t("whatsnew.title")} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<h3>
|
<h3>
|
||||||
<Icon name="sparkle" /> {t("whatsnew.title", { version })}
|
<Icon name="sparkle" /> {t("whatsnew.title", { version })}
|
||||||
</h3>
|
</h3>
|
||||||
@@ -36,11 +37,10 @@ export function WhatsNew({ version }: { version: string }) {
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
<div className="row" style={{ justifyContent: "flex-end" }}>
|
<div className="row" style={{ justifyContent: "flex-end" }}>
|
||||||
<button className="primary" onClick={close}>
|
<Button type="primary" onClick={close}>
|
||||||
{t("common.ok")}
|
{t("common.ok")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get, post } from "../api";
|
import { get, post } from "../api";
|
||||||
import { useT } from "../i18n";
|
import { useT } from "../i18n";
|
||||||
@@ -69,12 +70,12 @@ export function WorktreeChip({ session, busy }: { session: Session; busy: boolea
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ gap: 6, marginTop: 8 }}>
|
<div className="row" style={{ gap: 6, marginTop: 8 }}>
|
||||||
<button className="small primary" disabled={busy || !!working} onClick={() => act("merge")}>
|
<Button type="primary" size="small" disabled={busy || !!working} onClick={() => act("merge")}>
|
||||||
{working === "merge" ? <Spinner small /> : <Icon name="check" />} {t("worktree.merge", { base: wt.base })}
|
{working === "merge" ? <Spinner small /> : <Icon name="check" />} {t("worktree.merge", { base: wt.base })}
|
||||||
</button>
|
</Button>
|
||||||
<button className="small danger" disabled={busy || !!working} onClick={() => act("remove")}>
|
<Button danger size="small" disabled={busy || !!working} onClick={() => act("remove")}>
|
||||||
<Icon name="trash" /> {t("worktree.remove")}
|
<Icon name="trash" /> {t("worktree.remove")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{busy && <div className="hint">{t("worktree.busy")}</div>}
|
{busy && <div className="hint">{t("worktree.busy")}</div>}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { post } from "../../api";
|
import { post } from "../../api";
|
||||||
import { useT } from "../../i18n";
|
import { useT } from "../../i18n";
|
||||||
@@ -38,18 +39,18 @@ export function Account() {
|
|||||||
{me?.has_password && (
|
{me?.has_password && (
|
||||||
<>
|
<>
|
||||||
<label>{t("account.current")}</label>
|
<label>{t("account.current")}</label>
|
||||||
<input type="password" value={form.current} onChange={(e) => setForm({ ...form, current: e.target.value })} autoComplete="current-password" />
|
<Input.Password value={form.current} onChange={(e) => setForm({ ...form, current: e.target.value })} autoComplete="current-password" />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<label>{t("account.new")}</label>
|
<label>{t("account.new")}</label>
|
||||||
<input type="password" value={form.next} onChange={(e) => setForm({ ...form, next: e.target.value })} autoComplete="new-password" />
|
<Input.Password value={form.next} onChange={(e) => setForm({ ...form, next: e.target.value })} autoComplete="new-password" />
|
||||||
<label>{t("login.passwordRepeat")}</label>
|
<label>{t("login.passwordRepeat")}</label>
|
||||||
<input type="password" value={form.repeat} onChange={(e) => setForm({ ...form, repeat: e.target.value })} autoComplete="new-password" />
|
<Input.Password value={form.repeat} onChange={(e) => setForm({ ...form, repeat: e.target.value })} autoComplete="new-password" />
|
||||||
</div>
|
</div>
|
||||||
{notice && <div className={`notice ${notice.ok ? "ok" : "err"}`} style={{ marginTop: 10 }}>{notice.text}</div>}
|
{notice && <div className={`notice ${notice.ok ? "ok" : "err"}`} style={{ marginTop: 10 }}>{notice.text}</div>}
|
||||||
<button className="primary" style={{ marginTop: 12 }} disabled={!form.next} onClick={save}>
|
<Button type="primary" style={{ marginTop: 12 }} disabled={!form.next} onClick={save}>
|
||||||
{t("account.change")}
|
{t("account.change")}
|
||||||
</button>
|
</Button>
|
||||||
<div style={{ fontSize: 12, color: "var(--muted)", marginTop: 8 }}>{t("account.hint")}</div>
|
<div style={{ fontSize: 12, color: "var(--muted)", marginTop: 8 }}>{t("account.hint")}</div>
|
||||||
</div>
|
</div>
|
||||||
<Memory />
|
<Memory />
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
|
import { Select } from "../../ui/Select";
|
||||||
import { Icon } from "../Icon";
|
import { Icon } from "../Icon";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { del, patch } from "../../api";
|
import { del, patch } from "../../api";
|
||||||
@@ -26,16 +28,14 @@ export function ToolPicker({ tools, value, onChange, readOnly }: { tools: ToolIn
|
|||||||
<div className="hint">{value.length ? t("agents.toolsSome", { n: value.length }) : t("agents.toolsAll")}</div>
|
<div className="hint">{value.length ? t("agents.toolsSome", { n: value.length }) : t("agents.toolsAll")}</div>
|
||||||
<div className="tool-grid">
|
<div className="tool-grid">
|
||||||
{tools.map((x) => (
|
{tools.map((x) => (
|
||||||
<label key={x.name} className={`tool-item ${readOnly && !x.read_only ? "disabled" : ""}`} title={x.description}>
|
<Checkbox key={x.name} className={`tool-item ${readOnly && !x.read_only ? "disabled" : ""}`} title={x.description} checked={value.includes(x.name)} disabled={readOnly && !x.read_only} onChange={() => toggle(x.name)}>
|
||||||
<input type="checkbox" checked={value.includes(x.name)} disabled={readOnly && !x.read_only} onChange={() => toggle(x.name)} />
|
|
||||||
<span className="mono">{x.name}</span>
|
<span className="mono">{x.name}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
))}
|
))}
|
||||||
{extra.map((n) => (
|
{extra.map((n) => (
|
||||||
<label key={n} className="tool-item">
|
<Checkbox key={n} className="tool-item" checked onChange={() => toggle(n)}>
|
||||||
<input type="checkbox" checked onChange={() => toggle(n)} />
|
|
||||||
<span className="mono">{n}</span>
|
<span className="mono">{n}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -125,13 +125,13 @@ function AgentRow({ a, raw, tools, onSaved }: { a: AgentInfo; raw: any; tools: T
|
|||||||
{a.read_only && <span className="chip">{t("agents.readOnly")}</span>}
|
{a.read_only && <span className="chip">{t("agents.readOnly")}</span>}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{!builtin && (a.source === "config" || a.source === "file") && (
|
{!builtin && (a.source === "config" || a.source === "file") && (
|
||||||
<button className="small ghost danger" onClick={a.source === "file" ? removeFile : reset} title={t("common.delete")} aria-label={t("common.delete")}>
|
<Button type="text" danger size="small" onClick={a.source === "file" ? removeFile : reset} title={t("common.delete")} aria-label={t("common.delete")}>
|
||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button className="small" onClick={() => setOpen(!open)}>
|
<Button size="small" onClick={() => setOpen(!open)}>
|
||||||
{open ? t("common.collapse") : t("common.edit")}
|
{open ? t("common.collapse") : t("common.edit")}
|
||||||
</button>
|
</Button>
|
||||||
</h3>
|
</h3>
|
||||||
<div style={{ fontSize: 13, color: "var(--fg3)" }}>{a.description}</div>
|
<div style={{ fontSize: 13, color: "var(--fg3)" }}>{a.description}</div>
|
||||||
<div className="row" style={{ marginTop: 8 }}>
|
<div className="row" style={{ marginTop: 8 }}>
|
||||||
@@ -149,75 +149,72 @@ function AgentRow({ a, raw, tools, onSaved }: { a: AgentInfo; raw: any; tools: T
|
|||||||
{a.mode !== "primary" && (
|
{a.mode !== "primary" && (
|
||||||
<>
|
<>
|
||||||
<label>{t("agents.maxParallel")}</label>
|
<label>{t("agents.maxParallel")}</label>
|
||||||
<input type="number" min={1} value={form.max_parallel} placeholder="∞" onChange={(e) => setForm({ ...form, max_parallel: e.target.value })} />
|
<Input type="number" min={1} value={form.max_parallel} placeholder="∞" onChange={(e) => setForm({ ...form, max_parallel: e.target.value })} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{a.mode === "primary" && (
|
{a.mode === "primary" && (
|
||||||
<>
|
<>
|
||||||
<label>{t("agents.refineRounds")}</label>
|
<label>{t("agents.refineRounds")}</label>
|
||||||
<input type="number" min={0} max={10} value={form.refine_rounds} placeholder={t("agents.refineOff")} onChange={(e) => setForm({ ...form, refine_rounds: e.target.value })} />
|
<Input type="number" min={0} max={10} value={form.refine_rounds} placeholder={t("agents.refineOff")} onChange={(e) => setForm({ ...form, refine_rounds: e.target.value })} />
|
||||||
<label>{t("agents.refineModel")}</label>
|
<label>{t("agents.refineModel")}</label>
|
||||||
<ModelSelect value={form.refine_model} onChange={(v) => setForm({ ...form, refine_model: v })} emptyLabel={t("agents.sessionModel")} />
|
<ModelSelect value={form.refine_model} onChange={(v) => setForm({ ...form, refine_model: v })} emptyLabel={t("agents.sessionModel")} />
|
||||||
<label>{t("agents.refineCriteria")}</label>
|
<label>{t("agents.refineCriteria")}</label>
|
||||||
<textarea rows={3} value={form.refine_criteria} onChange={(e) => setForm({ ...form, refine_criteria: e.target.value })} />
|
<Input.TextArea rows={3} value={form.refine_criteria} onChange={(e) => setForm({ ...form, refine_criteria: e.target.value })} />
|
||||||
<div className="hint">{t("agents.refineCriteriaHint")}</div>
|
<div className="hint">{t("agents.refineCriteriaHint")}</div>
|
||||||
<label className="check">
|
<Checkbox checked={form.refine_after_todos} onChange={(e) => setForm({ ...form, refine_after_todos: e.target.checked })}>
|
||||||
<input type="checkbox" checked={form.refine_after_todos} onChange={(e) => setForm({ ...form, refine_after_todos: e.target.checked })} />
|
|
||||||
{t("agents.refineAfterTodos")}
|
{t("agents.refineAfterTodos")}
|
||||||
</label>
|
</Checkbox>
|
||||||
<div className="hint">{t("agents.refineAfterTodosHint")}</div>
|
<div className="hint">{t("agents.refineAfterTodosHint")}</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{a.name !== "craft" && (
|
{a.name !== "craft" && (
|
||||||
<>
|
<>
|
||||||
<label className="check">
|
<Checkbox checked={form.reverse_tools} onChange={(e) => setForm({ ...form, reverse_tools: e.target.checked })}>
|
||||||
<input type="checkbox" checked={form.reverse_tools} onChange={(e) => setForm({ ...form, reverse_tools: e.target.checked })} />
|
|
||||||
{t("agents.reverseTools")}
|
{t("agents.reverseTools")}
|
||||||
</label>
|
</Checkbox>
|
||||||
<div className="hint">{t("agents.reverseToolsHint")}</div>
|
<div className="hint">{t("agents.reverseToolsHint")}</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<label>{t("agents.description")}</label>
|
<label>{t("agents.description")}</label>
|
||||||
<input value={form.description} placeholder={a.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
|
<Input value={form.description} placeholder={a.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
|
||||||
{a.mode !== "primary" && <div className="hint">{t("agents.descriptionHint")}</div>}
|
{a.mode !== "primary" && <div className="hint">{t("agents.descriptionHint")}</div>}
|
||||||
{!builtin && (
|
{!builtin && (
|
||||||
<>
|
<>
|
||||||
<label>{t("agents.mode")}</label>
|
<label>{t("agents.mode")}</label>
|
||||||
<select value={form.mode} onChange={(e) => setForm({ ...form, mode: e.target.value })}>
|
<Select value={form.mode} onChange={(e) => setForm({ ...form, mode: e.target.value })}>
|
||||||
<option value="subagent">{t("agents.modeSubagent")}</option>
|
<option value="subagent">{t("agents.modeSubagent")}</option>
|
||||||
<option value="primary">{t("agents.modePrimary")}</option>
|
<option value="primary">{t("agents.modePrimary")}</option>
|
||||||
</select>
|
</Select>
|
||||||
{form.mode === "primary" && (
|
{form.mode === "primary" && (
|
||||||
<>
|
<>
|
||||||
<label>{t("agents.style")}</label>
|
<label>{t("agents.style")}</label>
|
||||||
<select value={form.style} onChange={(e) => setForm({ ...form, style: e.target.value as "coding" | "chat" })}>
|
<Select value={form.style} onChange={(e) => setForm({ ...form, style: e.target.value as "coding" | "chat" })}>
|
||||||
<option value="coding">{t("agents.styleCoding")}</option>
|
<option value="coding">{t("agents.styleCoding")}</option>
|
||||||
<option value="chat">{t("agents.styleChat")}</option>
|
<option value="chat">{t("agents.styleChat")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<div className="hint">{t("agents.styleHint")}</div>
|
<div className="hint">{t("agents.styleHint")}</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<label>{t("agents.readOnlyLabel")}</label>
|
<label>{t("agents.readOnlyLabel")}</label>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
<Checkbox className="row" style={{ gap: 6, alignItems: "center" }} checked={form.read_only} onChange={(e) => setForm({ ...form, read_only: e.target.checked })}>
|
||||||
<input type="checkbox" checked={form.read_only} onChange={(e) => setForm({ ...form, read_only: e.target.checked })} />
|
|
||||||
<span className="hint">{t("agents.readOnlyHint")}</span>
|
<span className="hint">{t("agents.readOnlyHint")}</span>
|
||||||
</label>
|
</Checkbox>
|
||||||
<label>{t("agents.tools")}</label>
|
<label>{t("agents.tools")}</label>
|
||||||
<ToolPicker tools={tools} value={form.tools} onChange={(v) => setForm({ ...form, tools: v })} readOnly={form.read_only} />
|
<ToolPicker tools={tools} value={form.tools} onChange={(v) => setForm({ ...form, tools: v })} readOnly={form.read_only} />
|
||||||
<label>{t("agents.prompt")}</label>
|
<label>{t("agents.prompt")}</label>
|
||||||
<textarea rows={6} value={form.prompt} onChange={(e) => setForm({ ...form, prompt: e.target.value })} />
|
<Input.TextArea rows={6} value={form.prompt} onChange={(e) => setForm({ ...form, prompt: e.target.value })} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="row" style={{ marginTop: 12 }}>
|
<div className="row" style={{ marginTop: 12 }}>
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{a.source === "config" && builtin && (
|
{a.source === "config" && builtin && (
|
||||||
<button className="danger" onClick={reset}>
|
<Button danger onClick={reset}>
|
||||||
{t("agents.reset")}
|
{t("agents.reset")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
@@ -274,14 +271,14 @@ export function AgentsEditor({ rawAgents, reloadConfig }: { rawAgents: Record<st
|
|||||||
<div className="panel">
|
<div className="panel">
|
||||||
<h3>{t("agents.add")}</h3>
|
<h3>{t("agents.add")}</h3>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<input placeholder={t("settings.name")} value={name} onChange={(e) => setName(e.target.value)} />
|
<Input placeholder={t("settings.name")} value={name} onChange={(e) => setName(e.target.value)} />
|
||||||
<button className="primary" onClick={() => add("mode")} disabled={!name.trim()}>
|
<Button type="primary" onClick={() => add("mode")} disabled={!name.trim()}>
|
||||||
+ {t("agents.addMode")}
|
+ {t("agents.addMode")}
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={() => add("writer")}>+ {t("agents.addWriter")}</button>
|
<Button onClick={() => add("writer")}>+ {t("agents.addWriter")}</Button>
|
||||||
<button onClick={() => add("blank")} disabled={!name.trim()}>
|
<Button onClick={() => add("blank")} disabled={!name.trim()}>
|
||||||
+ {t("agents.addBlank")}
|
+ {t("agents.addBlank")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="two-col">
|
<div className="two-col">
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Input } from "antd";
|
||||||
|
import { Select } from "../../ui/Select";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { del, get, post } from "../../api";
|
import { del, get, post } from "../../api";
|
||||||
import { fmtRelative, useT } from "../../i18n";
|
import { fmtRelative, useT } from "../../i18n";
|
||||||
@@ -52,12 +54,11 @@ export function ApiTokens() {
|
|||||||
<div>{t("tokens.copyNow")}</div>
|
<div>{t("tokens.copyNow")}</div>
|
||||||
<div className="row" style={{ gap: 6, marginTop: 6 }}>
|
<div className="row" style={{ gap: 6, marginTop: 6 }}>
|
||||||
<code className="token-value">{created}</code>
|
<code className="token-value">{created}</code>
|
||||||
<button
|
<Button size="small"
|
||||||
className="small"
|
|
||||||
onClick={() => navigator.clipboard.writeText(created).then(() => toast(t("tokens.copied"), "success"))}
|
onClick={() => navigator.clipboard.writeText(created).then(() => toast(t("tokens.copied"), "success"))}
|
||||||
>
|
>
|
||||||
<Icon name="copy" /> {t("tokens.copy")}
|
<Icon name="copy" /> {t("tokens.copy")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<pre className="mono token-example">{`codecraft login ${location.origin}`}</pre>
|
<pre className="mono token-example">{`codecraft login ${location.origin}`}</pre>
|
||||||
</div>
|
</div>
|
||||||
@@ -83,8 +84,7 @@ export function ApiTokens() {
|
|||||||
<td>{k.last_used ? fmtRelative(k.last_used) : "–"}</td>
|
<td>{k.last_used ? fmtRelative(k.last_used) : "–"}</td>
|
||||||
<td>{k.expires_at ? new Date(k.expires_at).toLocaleDateString() : t("tokens.never")}</td>
|
<td>{k.expires_at ? new Date(k.expires_at).toLocaleDateString() : t("tokens.never")}</td>
|
||||||
<td>
|
<td>
|
||||||
<button
|
<Button type="text" danger size="small"
|
||||||
className="small ghost danger"
|
|
||||||
aria-label={t("tokens.revoke")}
|
aria-label={t("tokens.revoke")}
|
||||||
title={t("tokens.revoke")}
|
title={t("tokens.revoke")}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
@@ -95,7 +95,7 @@ export function ApiTokens() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@@ -103,20 +103,20 @@ export function ApiTokens() {
|
|||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
<div className="row" style={{ gap: 6, marginTop: 10, flexWrap: "wrap" }}>
|
<div className="row" style={{ gap: 6, marginTop: 10, flexWrap: "wrap" }}>
|
||||||
<input style={{ flex: 1, minWidth: 160 }} placeholder={t("tokens.namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} />
|
<Input style={{ flex: 1, minWidth: 160 }} placeholder={t("tokens.namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} />
|
||||||
<select value={scope} onChange={(e) => setScope(e.target.value as "full" | "read")}>
|
<Select value={scope} onChange={(e) => setScope(e.target.value as "full" | "read")}>
|
||||||
<option value="full">{t("tokens.scopeFull")}</option>
|
<option value="full">{t("tokens.scopeFull")}</option>
|
||||||
<option value="read">{t("tokens.scopeRead")}</option>
|
<option value="read">{t("tokens.scopeRead")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<select value={days} onChange={(e) => setDays(e.target.value)}>
|
<Select value={days} onChange={(e) => setDays(e.target.value)}>
|
||||||
<option value="">{t("tokens.noExpiry")}</option>
|
<option value="">{t("tokens.noExpiry")}</option>
|
||||||
<option value="30">30 {t("tokens.days")}</option>
|
<option value="30">30 {t("tokens.days")}</option>
|
||||||
<option value="90">90 {t("tokens.days")}</option>
|
<option value="90">90 {t("tokens.days")}</option>
|
||||||
<option value="365">365 {t("tokens.days")}</option>
|
<option value="365">365 {t("tokens.days")}</option>
|
||||||
</select>
|
</Select>
|
||||||
<button className="primary" disabled={!name.trim()} onClick={create}>
|
<Button type="primary" disabled={!name.trim()} onClick={create}>
|
||||||
<Icon name="plus" /> {t("tokens.create")}
|
<Icon name="plus" /> {t("tokens.create")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Select } from "../../ui/Select";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useFetch } from "../../hooks";
|
import { useFetch } from "../../hooks";
|
||||||
import { fmtDate, useT } from "../../i18n";
|
import { fmtDate, useT } from "../../i18n";
|
||||||
@@ -24,17 +26,17 @@ export function Audit() {
|
|||||||
<h3>
|
<h3>
|
||||||
{t("audit.title")}
|
{t("audit.title")}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
|
<Select value={filter} onChange={(e) => setFilter(e.target.value)}>
|
||||||
<option value="">{t("audit.all")}</option>
|
<option value="">{t("audit.all")}</option>
|
||||||
{["login", "permission", "config", "user", "folder", "session", "git", "backup"].map((a) => (
|
{["login", "permission", "config", "user", "folder", "session", "git", "backup"].map((a) => (
|
||||||
<option key={a} value={a}>
|
<option key={a} value={a}>
|
||||||
{a}
|
{a}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
<button className="small" onClick={reload} aria-label={t("common.refresh")}>
|
<Button size="small" onClick={reload} aria-label={t("common.refresh")}>
|
||||||
<Icon name="refresh" />
|
<Icon name="refresh" />
|
||||||
</button>
|
</Button>
|
||||||
</h3>
|
</h3>
|
||||||
<div style={{ overflowX: "auto" }}>
|
<div style={{ overflowX: "auto" }}>
|
||||||
<table className="grid">
|
<table className="grid">
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
|
import { uploadBatch } from "../../uploads";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { api, get, patch, post } from "../../api";
|
import { api, get, patch, post } from "../../api";
|
||||||
import { confirmDialog, toast } from "../../dialogs";
|
import { confirmDialog, toast } from "../../dialogs";
|
||||||
@@ -100,7 +102,11 @@ export function Backups() {
|
|||||||
setRestoring(true);
|
setRestoring(true);
|
||||||
try {
|
try {
|
||||||
if ("name" in source) await post(`/backups/${encodeURIComponent(source.name)}/restore`);
|
if ("name" in source) await post(`/backups/${encodeURIComponent(source.name)}/restore`);
|
||||||
else await api("/backups/restore", { method: "POST", body: source.file, headers: { "Content-Type": "application/zip" } });
|
else {
|
||||||
|
const sent = await uploadBatch([{ file: source.file, path: "", name: source.file.name, endpoint: "/api/backups/upload" }]);
|
||||||
|
if (!sent.length) throw new Error(t("backup.uploadFailed"));
|
||||||
|
await post("/backups/restore-uploaded");
|
||||||
|
}
|
||||||
toast(t("backup.restarting"), "info");
|
toast(t("backup.restarting"), "info");
|
||||||
// Wait until the server is gone and back, then reload with the restored data.
|
// Wait until the server is gone and back, then reload with the restored data.
|
||||||
await new Promise((r) => setTimeout(r, 2500));
|
await new Promise((r) => setTimeout(r, 2500));
|
||||||
@@ -137,9 +143,9 @@ export function Backups() {
|
|||||||
<a className="button small" href="/api/backup">
|
<a className="button small" href="/api/backup">
|
||||||
<Icon name="download" /> {t("audit.download")}
|
<Icon name="download" /> {t("audit.download")}
|
||||||
</a>
|
</a>
|
||||||
<button className="small" onClick={() => fileInput.current?.click()} disabled={restoring}>
|
<Button size="small" onClick={() => fileInput.current?.click()} disabled={restoring}>
|
||||||
<Icon name="upload" /> {restoring ? t("backup.restoring") : t("backup.restoreFile")}
|
<Icon name="upload" /> {restoring ? t("backup.restoring") : t("backup.restoreFile")}
|
||||||
</button>
|
</Button>
|
||||||
<input
|
<input
|
||||||
ref={fileInput}
|
ref={fileInput}
|
||||||
type="file"
|
type="file"
|
||||||
@@ -151,9 +157,9 @@ export function Backups() {
|
|||||||
if (file) void restore({ file });
|
if (file) void restore({ file });
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<button className="small primary" onClick={runNow} disabled={busy}>
|
<Button type="primary" size="small" onClick={runNow} disabled={busy}>
|
||||||
{busy ? t("backup.running") : t("backup.now")}
|
{busy ? t("backup.running") : t("backup.now")}
|
||||||
</button>
|
</Button>
|
||||||
</h3>
|
</h3>
|
||||||
<div className="hint" style={{ marginBottom: 10 }}>
|
<div className="hint" style={{ marginBottom: 10 }}>
|
||||||
{t("audit.backupHint")}
|
{t("audit.backupHint")}
|
||||||
@@ -161,18 +167,17 @@ export function Backups() {
|
|||||||
{form && (
|
{form && (
|
||||||
<>
|
<>
|
||||||
<div className="row" style={{ gap: 12, flexWrap: "wrap", alignItems: "center" }}>
|
<div className="row" style={{ gap: 12, flexWrap: "wrap", alignItems: "center" }}>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
<Checkbox className="row" style={{ gap: 6, alignItems: "center" }} checked={form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })}>
|
||||||
<input type="checkbox" checked={form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} />
|
|
||||||
{t("backup.daily")}
|
{t("backup.daily")}
|
||||||
</label>
|
</Checkbox>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
||||||
{t("backup.at")}
|
{t("backup.at")}
|
||||||
<input type="number" min={0} max={23} style={{ width: 64 }} value={form.hour} onChange={(e) => setForm({ ...form, hour: Number(e.target.value) })} />
|
<Input type="number" min={0} max={23} style={{ width: 64 }} value={form.hour} onChange={(e) => setForm({ ...form, hour: Number(e.target.value) })} />
|
||||||
{t("backup.oclock")}
|
{t("backup.oclock")}
|
||||||
</label>
|
</label>
|
||||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
||||||
{t("backup.keep")}
|
{t("backup.keep")}
|
||||||
<input type="number" min={1} style={{ width: 70 }} value={form.keep} onChange={(e) => setForm({ ...form, keep: Number(e.target.value) })} />
|
<Input type="number" min={1} style={{ width: 70 }} value={form.keep} onChange={(e) => setForm({ ...form, keep: Number(e.target.value) })} />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
{data && <div className="hint mono" style={{ marginTop: 6 }}>{data.dir}</div>}
|
{data && <div className="hint mono" style={{ marginTop: 6 }}>{data.dir}</div>}
|
||||||
@@ -189,8 +194,7 @@ export function Backups() {
|
|||||||
{s3("access_key", t("backup.accessKey"), "AKIA… or ${S3_ACCESS_KEY}")}
|
{s3("access_key", t("backup.accessKey"), "AKIA… or ${S3_ACCESS_KEY}")}
|
||||||
<label className="field">
|
<label className="field">
|
||||||
<span>{t("backup.secretKey")}</span>
|
<span>{t("backup.secretKey")}</span>
|
||||||
<input
|
<Input.Password
|
||||||
type="password"
|
|
||||||
value={secret}
|
value={secret}
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
placeholder={form.s3.secret_key === MASK ? t("backup.secretStored") : form.s3.secret_key || "${S3_SECRET_KEY}"}
|
placeholder={form.s3.secret_key === MASK ? t("backup.secretStored") : form.s3.secret_key || "${S3_SECRET_KEY}"}
|
||||||
@@ -201,9 +205,9 @@ export function Backups() {
|
|||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end" }}>
|
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end" }}>
|
||||||
<button className="primary" onClick={save}>
|
<Button type="primary" onClick={save}>
|
||||||
{t("common.save")}
|
{t("common.save")}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
@@ -220,9 +224,9 @@ export function Backups() {
|
|||||||
<Icon name="file" />
|
<Icon name="file" />
|
||||||
<span className="grow">{f.name}</span>
|
<span className="grow">{f.name}</span>
|
||||||
<span className="hint">{formatSize(f.size)}</span>
|
<span className="hint">{formatSize(f.size)}</span>
|
||||||
<button className="small" title={t("backup.restore")} onClick={() => void restore({ name: f.name })} disabled={restoring}>
|
<Button size="small" title={t("backup.restore")} onClick={() => void restore({ name: f.name })} disabled={restoring}>
|
||||||
<Icon name="undo" />
|
<Icon name="undo" />
|
||||||
</button>
|
</Button>
|
||||||
<a className="button small" title={t("audit.download")} href={`/api/backups/${encodeURIComponent(f.name)}`}>
|
<a className="button small" title={t("audit.download")} href={`/api/backups/${encodeURIComponent(f.name)}`}>
|
||||||
<Icon name="download" />
|
<Icon name="download" />
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Checkbox, Input } from "antd";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { api, get, post } from "../../api";
|
import { api, get, post } from "../../api";
|
||||||
import { confirmDialog, toast } from "../../dialogs";
|
import { confirmDialog, toast } from "../../dialogs";
|
||||||
@@ -111,9 +112,9 @@ export function ClaudeCode() {
|
|||||||
<Icon name="robot" /> {t("claude.title")}
|
<Icon name="robot" /> {t("claude.title")}
|
||||||
<span className="spacer" />
|
<span className="spacer" />
|
||||||
{status?.logged_in && (
|
{status?.logged_in && (
|
||||||
<button className="small ghost danger" onClick={logout}>
|
<Button type="text" danger size="small" onClick={logout}>
|
||||||
{t("claude.logout")}
|
{t("claude.logout")}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="hint" style={{ marginBottom: 10 }}>{t("claude.intro")}</div>
|
<div className="hint" style={{ marginBottom: 10 }}>{t("claude.intro")}</div>
|
||||||
@@ -126,9 +127,9 @@ export function ClaudeCode() {
|
|||||||
<>
|
<>
|
||||||
<span className="chip warn">{t("claude.updateAvailable", { version: status.latest ?? "" })}</span>
|
<span className="chip warn">{t("claude.updateAvailable", { version: status.latest ?? "" })}</span>
|
||||||
{isAdmin ? (
|
{isAdmin ? (
|
||||||
<button className="small primary" disabled={updating} onClick={update}>
|
<Button type="primary" size="small" disabled={updating} onClick={update}>
|
||||||
{updating ? <Spinner small /> : <Icon name="download" />} {updating ? t("claude.updating") : t("claude.update")}
|
{updating ? <Spinner small /> : <Icon name="download" />} {updating ? t("claude.updating") : t("claude.update")}
|
||||||
</button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<span className="hint">{t("claude.updateAdmin")}</span>
|
<span className="hint">{t("claude.updateAdmin")}</span>
|
||||||
)}
|
)}
|
||||||
@@ -136,9 +137,9 @@ export function ClaudeCode() {
|
|||||||
) : (
|
) : (
|
||||||
status.latest && <span className="chip">{t("claude.upToDate")}</span>
|
status.latest && <span className="chip">{t("claude.upToDate")}</span>
|
||||||
)}
|
)}
|
||||||
<button className="small ghost" disabled={checking || updating} onClick={check} title={t("claude.checkNow")} aria-label={t("claude.checkNow")}>
|
<Button type="text" size="small" disabled={checking || updating} onClick={check} title={t("claude.checkNow")} aria-label={t("claude.checkNow")}>
|
||||||
{checking ? <Spinner small /> : <Icon name="refresh" />}
|
{checking ? <Spinner small /> : <Icon name="refresh" />}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{updateLog && (
|
{updateLog && (
|
||||||
@@ -158,12 +159,11 @@ export function ClaudeCode() {
|
|||||||
)}
|
)}
|
||||||
{status?.installed && !status.logged_in && !url && (
|
{status?.installed && !status.logged_in && !url && (
|
||||||
<>
|
<>
|
||||||
<label className="row" style={{ marginBottom: 8 }}>
|
<Checkbox className="row" style={{ marginBottom: 8 }} checked={console_} onChange={(e) => setConsole(e.target.checked)}> {t("claude.console")}
|
||||||
<input type="checkbox" checked={console_} onChange={(e) => setConsole(e.target.checked)} /> {t("claude.console")}
|
</Checkbox>
|
||||||
</label>
|
<Button type="primary" disabled={busy} onClick={start}>
|
||||||
<button className="primary" disabled={busy} onClick={start}>
|
|
||||||
{busy ? <Spinner small /> : <Icon name="lock" />} {t("claude.signIn")}
|
{busy ? <Spinner small /> : <Icon name="lock" />} {t("claude.signIn")}
|
||||||
</button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{url && (
|
{url && (
|
||||||
@@ -177,11 +177,11 @@ export function ClaudeCode() {
|
|||||||
<li>
|
<li>
|
||||||
{t("claude.step2")}
|
{t("claude.step2")}
|
||||||
<div className="row" style={{ marginTop: 6 }}>
|
<div className="row" style={{ marginTop: 6 }}>
|
||||||
<input style={{ flex: 1 }} value={code} placeholder={t("claude.codePlaceholder")} autoComplete="off" autoCapitalize="off" spellCheck={false} onChange={(e) => setCode(e.target.value)} onKeyDown={(e) => e.key === "Enter" && code.trim() && void submit()} />
|
<Input style={{ flex: 1 }} value={code} placeholder={t("claude.codePlaceholder")} autoComplete="off" autoCapitalize="off" spellCheck={false} onChange={(e) => setCode(e.target.value)} onKeyDown={(e) => e.key === "Enter" && code.trim() && void submit()} />
|
||||||
<button className="primary" disabled={busy || !code.trim()} onClick={submit}>
|
<Button type="primary" disabled={busy || !code.trim()} onClick={submit}>
|
||||||
{busy ? <Spinner small /> : <Icon name="check" />} {t("claude.confirm")}
|
{busy ? <Spinner small /> : <Icon name="check" />} {t("claude.confirm")}
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={cancel}>{t("common.cancel")}</button>
|
<Button onClick={cancel}>{t("common.cancel")}</Button>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|||||||