Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e2454ae3d | ||
|
|
9913a202ec | ||
|
|
738b39584d | ||
|
|
ccad2c1f6e | ||
|
|
45503de195 | ||
|
|
486c49d50b | ||
|
|
aa6ee7fd31 | ||
|
|
e1baf6f00f | ||
|
|
c5572cad54 | ||
|
|
b309778be8 | ||
|
|
771c6f5245 | ||
|
|
5fc405d86a | ||
|
|
c82ab5028b | ||
|
|
d8c5a0bf0e | ||
|
|
dad2685ea3 | ||
|
|
84ee68d4da | ||
|
|
43b07aca48 | ||
|
|
0fd10df43d | ||
|
|
a84a3acaa0 | ||
|
|
e150de3c93 | ||
|
|
a0c95a035c | ||
|
|
843194b429 | ||
|
|
462171f27b | ||
|
|
18818c1bd4 | ||
|
|
d644c97dd9 | ||
|
|
0a724142ff | ||
|
|
18aa63e3e6 | ||
|
|
dd3dd48969 | ||
|
|
e66574b529 | ||
|
|
df02556132 | ||
|
|
fcbc052f8e | ||
|
|
fa6173d224 | ||
|
|
a9a98a25e7 | ||
|
|
cb1e31b6e9 | ||
|
|
06c1b8df1b | ||
|
|
af89b91e01 | ||
|
|
5ebdfee1a8 | ||
|
|
56c20d92f8 | ||
|
|
a0a4082383 | ||
|
|
e0c550f14d | ||
|
|
4612643081 | ||
|
|
78c4eeaa28 | ||
|
|
ef60b68a32 | ||
|
|
962d37e485 | ||
|
|
1897dd1e0a | ||
|
|
e09e295f60 | ||
|
|
3f39f4bd65 | ||
|
|
1772c8cd07 | ||
|
|
c551171c18 | ||
|
|
4000084560 | ||
|
|
b5e2ef146c | ||
|
|
a2b9528e0b | ||
|
|
81d9df4e6e | ||
|
|
ead75e78e0 | ||
|
|
77f9d4b0e0 | ||
|
|
103132a359 | ||
|
|
5d5c0f8124 | ||
|
|
f77b101847 | ||
|
|
12a3198e77 | ||
|
|
4e6f74d477 | ||
|
|
658148ada7 | ||
|
|
b6e4500233 | ||
|
|
126c7719b9 | ||
|
|
fccaee4b94 | ||
|
|
d58b23d35f | ||
|
|
6e8e739906 | ||
|
|
247ddcf14a | ||
|
|
f0cd404f59 | ||
|
|
ec95f9b8ad | ||
|
|
99ba3835f3 | ||
|
|
92a99c6a65 | ||
|
|
4c7d67cabf | ||
|
|
4423148552 | ||
|
|
388ca96419 | ||
|
|
c08c6c7436 | ||
|
|
1b3e3af4b7 | ||
|
|
44dd6978d4 | ||
|
|
8a90f83db5 | ||
|
|
ce0d8afe69 | ||
|
|
f34a0c7a73 | ||
|
|
62fe5bf467 | ||
|
|
084452abf6 | ||
|
|
8b4bd59572 | ||
|
|
c3df4a23cc | ||
|
|
48621f21d6 | ||
|
|
d7baa77922 | ||
|
|
1e8418336d | ||
|
|
33612bf6d4 | ||
|
|
ffecd62b83 | ||
|
|
c77dcf5890 | ||
|
|
9c80f2c857 | ||
|
|
1253430ed4 | ||
|
|
e7d4b9ff76 |
No files matched your search
@@ -9,6 +9,9 @@ CODECRAFT_ADMIN_PASSWORD=
|
||||
# Directory with your projects, mounted as /workspace.
|
||||
WORKSPACE=/path/to/your/projects
|
||||
|
||||
# Directory of the software factory (clones it works in), mounted as /factory.
|
||||
FACTORY_DIR=./factory
|
||||
|
||||
# Host port and address (127.0.0.1 = only reachable through a local reverse proxy).
|
||||
PORT=8787
|
||||
BIND_ADDR=127.0.0.1
|
||||
|
||||
@@ -3,6 +3,487 @@
|
||||
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
|
||||
until 1.0, minor versions may contain breaking changes.
|
||||
|
||||
## [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
|
||||
|
||||
### Added
|
||||
|
||||
- **Factory build phase**: approved issues are built automatically. The build agent works in its own git
|
||||
worktree on branch `factory/issue-<n>` (inside the factory area, never in the workspace), with the
|
||||
model chosen for the build phase. The server – not the agent – commits, pushes and opens the pull
|
||||
request; the spec file is restored if the agent touched it. A build that makes no changes, times out or
|
||||
returns no result is retried once, then marked `failed`; a `blocked` answer is reported on the issue.
|
||||
Finished builds move to `factory:qa` (acceptance follows in a later version).
|
||||
|
||||
## [v202611-00041] – 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- **Software factory** (sidebar → Factory): specs arrive as issues (label `factory`) on Gitea, GitHub or
|
||||
GitLab and are worked off by agents in phases, each phase with its own model, agent, permission mode
|
||||
and time limit. This version contains the **review phase**: an agent reads the spec and the code and
|
||||
decides *approved*, *questions* (posted as an issue comment; your answer restarts the review) or
|
||||
*rejected*, and writes acceptance scenarios that stay in the database, away from the builder. Build and
|
||||
acceptance follow.
|
||||
- **Connections per user**: every user sets up their own accounts (Gitea, GitHub, GitLab) with their own
|
||||
token; repositories use the token of their connection or one of their own. Models are free per user,
|
||||
project and phase.
|
||||
- **New project with a model**: *Factory → New project* opens a spec chat. When the spec is done, the
|
||||
*Create project* bar picks name, connection and owner, creates the repository (private), commits the
|
||||
spec as `docs/specs/<name>.md` and opens the issue that starts the workflow.
|
||||
- **Overview**: board with all issues by state, a tile per project, and per run the model, status,
|
||||
duration, tokens and cost, with a link into the chat of that run.
|
||||
- **Separate factory area**: repositories are cloned into their own mount `/factory` (`FACTORY_DIR` in
|
||||
`.env`), not into the workspace. The API token is handed to git only as a header and never reaches
|
||||
agents.
|
||||
|
||||
## [v202611-00040] – 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Images you upload reach Claude Code**: its chats read the history without the image bytes, so the
|
||||
files it was pointed to were empty. Images without data are no longer written as empty files.
|
||||
|
||||
## [v202611-00039] – 2026-11-15
|
||||
|
||||
### Changed
|
||||
|
||||
- A chat's colour no longer tints the chat background (pane, message field, agent bubbles, top bar
|
||||
fill); it still marks the top bar line, the list entry, the badge and your own bubbles.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Claude Code can ask questions again**: its `AskUserQuestion` was always rejected; now the question
|
||||
appears as a question card in the chat (single and multiple choice) and the answers go back to it.
|
||||
|
||||
## [v202611-00038] – 2026-11-15
|
||||
|
||||
### Changed
|
||||
|
||||
- The chat menu in the sidebar has a **Delete** entry (with the question about the chat's own folder);
|
||||
colour and icon selection moved out of it – they remain in the ⋯ menu inside the chat.
|
||||
|
||||
## [v202611-00037] – 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- **Deleting a chat asks about its folder**: if the chat has a folder of its own (inside your folders,
|
||||
not shared with any other chat, no project folder), you can delete it with the chat – with the
|
||||
number of files, size and a warning for git repositories. The server checks again before deleting.
|
||||
|
||||
## [v202611-00036] – 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- **Claude Code gets all CodeCraft tools** (image generation, 3D, OpenSCAD, browser, scheduling,
|
||||
diagnostics, reverse engineering, skills, ask_user, the server's MCP tools …) over an MCP bridge,
|
||||
as `mcp__codecraft__<name>`. Tools the CLI has itself (read, write, edit, bash, grep …) are not
|
||||
offered twice. Calls go through the usual approval cards and rules.
|
||||
|
||||
## [v202611-00035] – 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Creating an SSH key failed with "No user exists for uid 99": `ssh-keygen`, `ssh-keyscan` and
|
||||
`ssh-add` get the same passwd workaround as `ssh`.
|
||||
|
||||
## [v202611-00034] – 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- `ssh`, `scp` and `sftp` failed with "No user exists for uid 99" because the container runs as a uid
|
||||
without passwd entry; the image now wraps them with nss_wrapper (also used by the key wrappers).
|
||||
|
||||
## [v202611-00033] – 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- **SSH keys** (Settings → Account): generate (ed25519) or import keys; agents, the terminal and the
|
||||
git panel use them automatically for `ssh`, `scp`, `sftp`, `rsync` and git over ssh. Hosts are
|
||||
trusted on first contact; the public key can be copied for the server's `authorized_keys`.
|
||||
|
||||
## [v202611-00032] – 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Agents now know that git credentials are stored (hosts, no secrets) and no longer search the
|
||||
environment for them; the system prompt explains `git push` just works and how to read the token
|
||||
for REST calls without printing it. Claude Code runs get the user's git credentials and identity too.
|
||||
|
||||
## [v202611-00031] – 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Images read by an agent (Read tool) are shown right away; with Claude Code they were dropped.
|
||||
|
||||
## [v202611-00030] – 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- **`/clear`**: the model forgets the conversation so far; the chat keeps showing it, a divider marks
|
||||
the cut. Also starts a fresh session with Claude Code.
|
||||
|
||||
## [v202611-00029] – 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- **Statistics**: sections and models fold; long history with a year filter (monthly bars for long
|
||||
ranges); export of the shown figures as XLSX (all tables) or CSV (one table).
|
||||
- **Prompt snippets**: own text blocks, inserted with `/name` in the message field (Settings → Account).
|
||||
- **Read-only links**: share a chat's text with people without an account (valid 1–90 days, revocable).
|
||||
- **Git panel**: the small model suggests a commit message for the staged changes.
|
||||
- **Weekly review** as a push notification (Mondays 08:00: chats, checks, costs; opt-in).
|
||||
- **Speech-to-text on the server** (`server.transcribe_model`) for browsers without dictation (Firefox).
|
||||
- **Offline**: the chat list and the last opened chats stay readable without a connection.
|
||||
- **Planning model** setting: plan mode always uses it, other modes the chat's model.
|
||||
- **Automations** send their report as a push notification when a run ends (switchable).
|
||||
|
||||
### Fixed
|
||||
|
||||
- fal.ai: the provider check no longer reports "API key rejected" when only the model listing is not offered.
|
||||
|
||||
## [v202611-00028] – 2026-11-14
|
||||
|
||||
### Added
|
||||
|
||||
- **18 more chat icons** (gamepad, computer, food, coffee, home, book, code, camera, cart, heart,
|
||||
star, globe, calendar, car, plane, bulb, money, palette).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The ⋯ menu of a message sits inside its bubble** (in the foot next to the time, also in your own
|
||||
bubbles); its popup opens upwards within the bubble and is no wider than the bubble.
|
||||
|
||||
## [v202611-00027] – 2026-11-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Chat bubbles:** your messages on the right in their own colour (the chat's colour tag if it
|
||||
has one), the agent's answers on the left; tool-only steps and system notes stay without bubble.
|
||||
- **Icons for chats:** pick one of 22 icons in the ⋯ menu (chat and session list); it shows in the
|
||||
list, the top bar and the project page, in the chat's colour, and is part of the project default.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Colour tags are more vivid and more distinct:** eight fixed hues (new: pink), drawn with a
|
||||
lightness that fits the theme (light/dark) and the highest chroma sRGB allows, so no two tags
|
||||
look alike; backgrounds are tinted more strongly. Browsers without relative colours keep the
|
||||
theme's own colours.
|
||||
|
||||
## [v202611-00026] – 2026-11-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Claude Code as an engine:** chats with a "Claude Code" model (Opus, Sonnet, Haiku, default) are
|
||||
run by the `claude` CLI. Its events become normal chat messages; its tool approvals go through
|
||||
CodeCraft's permission system (cards, push buttons, "allow for this project", diffs, sandbox).
|
||||
Sign in from the web UI (Settings → Account → Claude Code: open the sign-in URL, paste the code),
|
||||
see the CLI version and install updates (admins; installed into the persistent home). The Docker
|
||||
image now contains the CLI.
|
||||
- **Small models (8k context) for side tasks:** `small_model` jobs cut their input to the model's
|
||||
context window. New with it: a one-line status per chat in the session list, "What does this
|
||||
do?" on approvals, and "Plan as automation" (drafts job instructions from a chat).
|
||||
- **Mobile:** the top bar no longer pushes the page sideways (extra actions moved into the ⋯ menu);
|
||||
an image viewer for all images (zoom, swipe between images, mark up and attach to the message,
|
||||
use in the message); jump to the previous own message; message menu (copy, quote, fork from
|
||||
here, edit and resend); date and time under every message.
|
||||
- **Approvals:** push notifications can allow or reject right away; "always allow in this project"
|
||||
is remembered per folder (never for dangerous commands) and can be revoked in the ⋯ menu.
|
||||
- **Changes per turn:** files changed by a turn with diffs and "roll back to before this turn".
|
||||
- **Check after each turn:** a command per project (e.g. `cargo test`) runs after turns that
|
||||
changed files; green/red badge with output and "let the agent fix it".
|
||||
- **Colour tags for chats:** tinted chat background and a badge in the list, drawn in the colours
|
||||
of the active theme.
|
||||
- **Project defaults, project page, offline queue:** new chats in a folder inherit model, mode,
|
||||
colour, instructions and folder; a timeline of a project's chats (sidebar → project → ⋯);
|
||||
messages written without a connection are sent when it is back.
|
||||
|
||||
## [v202611-00025] – 2026-11-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Models did not find built-in tools via `mcp_search`** (e.g. `generate_3d` in a chat that
|
||||
had just been switched from plan to build): the search only looked at MCP servers. It now also
|
||||
lists matching built-in tools and says whether the current mode has them ("available – call it
|
||||
directly", or "not in the read-only mode plan – ask the user to switch to build").
|
||||
|
||||
## [v202611-00024] – 2026-11-12
|
||||
|
||||
### Added
|
||||
|
||||
- **3D models with fal.ai (`generate_3d`):** from an image (a project file or one pasted into the
|
||||
chat, optional back/left/right views), from a text prompt, or from an image steered by a prompt
|
||||
(the image is refined with the prompt first – the 3D models take no text with an image).
|
||||
Styles textured, geometry (untextured, for 3D printing) and low-poly, optional PBR. Uses fal.ai's
|
||||
queue (takes minutes, with progress), saves a GLB plus a preview image, books the cost.
|
||||
Defaults: Hunyuan3D v3 image-to-3D / text-to-3D (`[images] model_3d`, `model_3d_text`); Tripo
|
||||
and Trellis endpoints work too.
|
||||
- The chat card offers "Open in the 3D view"; the media overview lists 3D models (also STL/3MF
|
||||
written by the agent) with their previews.
|
||||
|
||||
## [v202611-00023] – 2026-11-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Tokens and cost under every answer:** a small line under each answer of the model shows the
|
||||
tokens sent/received and the cost of all requests of that turn.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Total cost of chats stopped growing (opencode Go):** opencode now reports plan requests as
|
||||
"nothing charged" (cost 0, usage in `allowance`), and CodeCraft took the 0. Plan requests are
|
||||
valued at the model's list prices again; earlier ones are corrected once on start.
|
||||
- **Saving opencode Go models failed after fetching prices** ("data did not match any variant of
|
||||
untagged enum ModelEntry"): opencode lists cache prices per duration for some models
|
||||
(`{"30m": …, "12h": …}`); the shortest duration is used now.
|
||||
- The chat title in the top bar no longer shrinks to a single letter when there are many chips.
|
||||
|
||||
## [v202611-00022] – 2026-11-11
|
||||
|
||||
### Added
|
||||
|
||||
- **Theme "Tintenblau"** (dark: ink blue with cream text; light: paper with dark ink), from the
|
||||
Tintenblau desktop theme; also in the terminal client.
|
||||
|
||||
## [v202611-00021] – 2026-11-11
|
||||
|
||||
### Added
|
||||
|
||||
- **Commits of agents name the model:** every `git commit` an agent makes gets the trailer
|
||||
`Co-Authored-By: <model> (<provider>) via CodeCraft` (a git wrapper in the agent shell, also in
|
||||
the sandbox; your own commits stay unchanged). The text is set under *Settings → General*
|
||||
(`server.commit_trailer`, `{model}`, `{provider}`, `{model_id}`; empty = off).
|
||||
|
||||
## [v202611-00020] – 2026-11-11
|
||||
|
||||
### Added
|
||||
|
||||
- **Reverse engineering outside craft:** *Settings → Agents & commands* can give any mode the
|
||||
`binary_info` and `decompile` (Ghidra) tools; the clean-room rule stays a craft rule.
|
||||
- **Raw firmware in `decompile`:** optional `processor` (Ghidra language id, e.g.
|
||||
`ARM:LE:32:Cortex`) and `base_address` for images without a file format (.bin, converted .hex).
|
||||
- **Skill "reverse-engineering":** how to identify, decompile and explore programs and firmware
|
||||
(processor table for common chips, HEX conversion, notes in `analysis/`).
|
||||
|
||||
## [v202611-00019] – 2026-11-11
|
||||
|
||||
### Added
|
||||
|
||||
@@ -74,6 +74,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 \
|
||||
&& 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
|
||||
# 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 ------------------------------------------------------------------
|
||||
# Node is included so agents can work on JS projects and run npx-based MCP servers.
|
||||
@@ -85,17 +89,27 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential pkg-config libssl-dev cmake zlib1g-dev binutils-multiarch \
|
||||
chromium fonts-dejavu-core fonts-noto-color-emoji poppler-utils openmpt123 \
|
||||
openscad xvfb xauth \
|
||||
openssh-client rsync mc \
|
||||
openssh-client libnss-wrapper rsync mc \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# Language servers for diagnostics after edits (rust-analyzer/gopls/clangd can be
|
||||
# installed by agents: rustup component add rust-analyzer, go install …).
|
||||
RUN npm install -g typescript@5 typescript-language-server pyright && npm cache clean --force
|
||||
RUN npm install -g typescript@5 typescript-language-server pyright @anthropic-ai/claude-code && npm cache clean --force
|
||||
COPY --from=server /codecraft /usr/local/bin/codecraft
|
||||
COPY --from=web /web/dist /app/web
|
||||
COPY --from=cli /out /app/cli
|
||||
# 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-buildx /usr/local/lib/docker/cli-plugins/docker-buildx
|
||||
COPY server/ghidra /app/ghidra
|
||||
# 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
|
||||
# ssh, scp, sftp and the ssh-* tools (the server creates keys with ssh-keygen) also work when the container runs as a uid without passwd entry.
|
||||
COPY --chmod=755 docker/ssh-nss /usr/local/bin/ssh
|
||||
COPY --chmod=755 docker/ssh-nss /usr/local/bin/scp
|
||||
COPY --chmod=755 docker/ssh-nss /usr/local/bin/sftp
|
||||
COPY --chmod=755 docker/ssh-nss /usr/local/bin/ssh-keygen
|
||||
COPY --chmod=755 docker/ssh-nss /usr/local/bin/ssh-keyscan
|
||||
COPY --chmod=755 docker/ssh-nss /usr/local/bin/ssh-add
|
||||
COPY server/resources /app/resources
|
||||
# The agent's home lives on the data volume: tools it installs in user space
|
||||
# (pip --user, pipx, rustup, npm -g, downloaded binaries) survive rebuilds.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="Version v202611-00019" src="https://img.shields.io/badge/version-v202611--00019-d69e2e?style=flat-square">
|
||||
<img alt="Version v202611-00064" src="https://img.shields.io/badge/version-v202611--00064-d69e2e?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="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="#terminal-client">Terminal client</a> ·
|
||||
<a href="#automations">Automations</a> ·
|
||||
<a href="#code-factory">Code factory</a> ·
|
||||
<a href="#integrations">Integrations</a> ·
|
||||
<a href="#users-and-security">Users</a> ·
|
||||
<a href="#statistics">Statistics</a> ·
|
||||
@@ -36,7 +37,7 @@
|
||||
<br>
|
||||
|
||||
<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>
|
||||
<sub>A session: the agent works through its task list, shows diffs, and asks before anything outside the rules.</sub>
|
||||
</p>
|
||||
@@ -129,7 +130,7 @@ opens the command palette, and prompt templates with placeholders save typing.
|
||||
<table>
|
||||
<tr>
|
||||
<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>
|
||||
</td>
|
||||
<td width="60%" valign="top">
|
||||
@@ -153,6 +154,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
|
||||
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
|
||||
|
||||
Every provider is an endpoint with a list of models. Each model can have a context size,
|
||||
@@ -176,6 +190,10 @@ output limit, reasoning effort, extra request options and prices per million tok
|
||||
- **Images (fal.ai):** the agent drafts cheap previews (FLUX schnell), asks which one to
|
||||
refine, and creates the final image with the best model for the purpose – Nano Banana Pro
|
||||
refines the chosen draft, Ideogram handles lettering, Recraft design work.
|
||||
- **3D models (fal.ai):** `generate_3d` turns an image (also one pasted into the chat, plus
|
||||
optional back/left/right views), a text prompt, or an image steered by a prompt into a GLB
|
||||
model – textured, untextured for 3D printing, or low-poly (Hunyuan3D v3 by default,
|
||||
`[images] model_3d` / `model_3d_text`). Open it in the 3D view of the file manager.
|
||||
|
||||
## Terminal client
|
||||
|
||||
@@ -199,7 +217,7 @@ platforms: `cargo install --locked --git https://git.familie-zink.org/zink/codec
|
||||
## Automations
|
||||
|
||||
<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>
|
||||
|
||||
An automation is an agent that starts on a schedule. Its instructions are a Markdown file
|
||||
@@ -215,6 +233,96 @@ read and continue it.
|
||||
**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.
|
||||
|
||||
## 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. 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.
|
||||
|
||||
**Files in the repository** (all optional, kept in `.factory/`):
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `setup.json` | How acceptance installs and starts the app: `install`, `start`, `url` |
|
||||
| `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.
|
||||
|
||||
## Integrations
|
||||
|
||||
- **Telegram:** connect your own bot (*Settings → Account → Telegram*) and use CodeCraft from
|
||||
@@ -296,6 +404,7 @@ in turn are based on:
|
||||
| Coffee | Dark, Latte | [megabyte0x/omarchy-coffee-theme](https://github.com/megabyte0x/omarchy-coffee-theme) | MIT |
|
||||
| Solarized | Dark, Light | [Solarized by Ethan Schoonover](https://ethanschoonover.com/solarized/) | MIT |
|
||||
| Tokyo Night | Night, Day | [folke/tokyonight.nvim](https://github.com/folke/tokyonight.nvim) | Apache-2.0 |
|
||||
| Tintenblau | Dark, Light | original (zink/tintenblau desktop theme) | private |
|
||||
|
||||
Further standard themes (palettes re-created from the published colour specifications):
|
||||
|
||||
|
||||
@@ -701,6 +701,60 @@
|
||||
"syntax-type": "#b58900",
|
||||
"syntax-variable": "#586e75"
|
||||
},
|
||||
"tintenblau-dark": {
|
||||
"accent": "#7aa0cc",
|
||||
"accent2": "#d4b46a",
|
||||
"aqua": "#96b4bc",
|
||||
"bg0": "#232a44",
|
||||
"bg1": "#2b3352",
|
||||
"bg2": "#353e60",
|
||||
"bg3": "#4a5478",
|
||||
"blue": "#7aa0cc",
|
||||
"fg0": "#f5efe3",
|
||||
"fg1": "#eae4d6",
|
||||
"fg2": "#d6d0c2",
|
||||
"fg3": "#bdcfd4",
|
||||
"green": "#96b4bc",
|
||||
"muted": "#8e96b4",
|
||||
"on-accent": "#232a44",
|
||||
"purple": "#c896b2",
|
||||
"red": "#d47a6a",
|
||||
"syntax-comment": "#8e96b4",
|
||||
"syntax-function": "#7aa0cc",
|
||||
"syntax-keyword": "#c896b2",
|
||||
"syntax-meta": "#baa0c4",
|
||||
"syntax-number": "#96b4bc",
|
||||
"syntax-string": "#d47a6a",
|
||||
"syntax-type": "#d4b46a",
|
||||
"syntax-variable": "#eae4d6"
|
||||
},
|
||||
"tintenblau-light": {
|
||||
"accent": "#2a3f6f",
|
||||
"accent2": "#6a4a2c",
|
||||
"aqua": "#3a5a6a",
|
||||
"bg0": "#f0ead9",
|
||||
"bg1": "#e6dfd0",
|
||||
"bg2": "#dbd3c1",
|
||||
"bg3": "#c9c0ac",
|
||||
"blue": "#3a5a8a",
|
||||
"fg0": "#0f1628",
|
||||
"fg1": "#1e2a4a",
|
||||
"fg2": "#3a3f5a",
|
||||
"fg3": "#5e5a6a",
|
||||
"green": "#4a5a3a",
|
||||
"muted": "#8a8694",
|
||||
"on-accent": "#f0ead9",
|
||||
"purple": "#5a4a72",
|
||||
"red": "#8a3028",
|
||||
"syntax-comment": "#8a8694",
|
||||
"syntax-function": "#3a5a6a",
|
||||
"syntax-keyword": "#2a3f6f",
|
||||
"syntax-meta": "#4a5a3a",
|
||||
"syntax-number": "#5a4a72",
|
||||
"syntax-string": "#8a3028",
|
||||
"syntax-type": "#6a4a2c",
|
||||
"syntax-variable": "#1e2a4a"
|
||||
},
|
||||
"tokyonight-dark": {
|
||||
"accent": "#7aa2f7",
|
||||
"accent2": "#ff9e64",
|
||||
|
||||
@@ -159,7 +159,13 @@ impl ModelConfig {
|
||||
/// Cost of one request now. Cache prices default to the input price.
|
||||
/// The provider's own figure wins when it reports one (opencode).
|
||||
pub fn cost(&self, u: &crate::types::Usage) -> f64 {
|
||||
u.cost.unwrap_or_else(|| self.cost_at(u, chrono::Utc::now()))
|
||||
match u.cost {
|
||||
// A plan request (opencode Go): nothing charged, the usage counts toward the plan –
|
||||
// its value at the model's list prices.
|
||||
Some(c) if c == 0.0 && u.allowance.is_some_and(|a| a > 0.0) => self.cost_at(u, chrono::Utc::now()),
|
||||
Some(c) => c,
|
||||
None => self.cost_at(u, chrono::Utc::now()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cost of one request at a given time: context tiers and time factors applied.
|
||||
@@ -187,6 +193,21 @@ mod price_tests {
|
||||
Usage { input_tokens: input, output_tokens: output, cache_read_tokens: read, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_requests_are_valued_at_list_prices() {
|
||||
let m = ModelConfig { input_price: Some(1.0), output_price: Some(2.0), ..Default::default() };
|
||||
let mut u = usage(1_000_000, 1_000_000, 0);
|
||||
u.cost = Some(0.0);
|
||||
u.allowance = Some(0.4);
|
||||
assert_eq!(m.cost(&u), 3.0);
|
||||
// Charged by the provider: that amount; free without a plan: free.
|
||||
u.cost = Some(0.7);
|
||||
assert_eq!(m.cost(&u), 0.7);
|
||||
u.cost = Some(0.0);
|
||||
u.allowance = None;
|
||||
assert_eq!(m.cost(&u), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiers_and_multipliers() {
|
||||
let m = ModelConfig {
|
||||
|
||||
@@ -187,8 +187,30 @@ pub struct Session {
|
||||
/// unless it is the chat currently open in Telegram.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub telegram_quiet: bool,
|
||||
/// One-line "where things stand", written by the small model after a turn (session list).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub summary: String,
|
||||
/// Colour tag of the chat (a palette name, see `SESSION_COLORS`); the client maps it to the theme.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<String>,
|
||||
/// 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")]
|
||||
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.
|
||||
pub const SESSION_COLORS: &[&str] = &["red", "orange", "yellow", "green", "aqua", "blue", "purple", "pink"];
|
||||
|
||||
/// Icons a chat can get (names of the client's icon set).
|
||||
pub const SESSION_ICONS: &[&str] = &[
|
||||
"robot", "brain", "terminal", "wrench", "gear", "chart", "shield", "image", "music", "cube", "file-text", "folder", "search", "sparkle", "clock", "lock",
|
||||
"users", "toolbox", "plug", "scroll", "eye", "template",
|
||||
"gamepad", "computer", "food", "coffee", "home", "book", "code", "camera", "cart", "heart", "star", "globe", "calendar", "car", "plane", "bulb", "money", "palette",
|
||||
];
|
||||
|
||||
impl Session {
|
||||
pub fn clean_room(&self, default: bool) -> bool {
|
||||
self.clean_room.unwrap_or(default)
|
||||
@@ -243,6 +265,8 @@ pub enum Event {
|
||||
/// Compaction of the history: state "started", "done" or "failed"; auto = triggered by
|
||||
/// a nearly full context (tokens of limit).
|
||||
Compaction { session_id: String, state: String, auto: bool, tokens: Option<u64>, limit: Option<u64> },
|
||||
/// The project's check command ran after a turn: status "running" | "passed" | "failed" | "timeout".
|
||||
CheckResult { session_id: String, message_id: String, status: String, exit_code: Option<i32>, duration_ms: u64, output: String },
|
||||
}
|
||||
|
||||
impl Event {
|
||||
@@ -265,7 +289,8 @@ impl Event {
|
||||
| Waiting { session_id, .. }
|
||||
| QueueUpdated { session_id, .. }
|
||||
| StepStarted { session_id, .. }
|
||||
| Compaction { session_id, .. } => Some(session_id),
|
||||
| Compaction { session_id, .. }
|
||||
| CheckResult { session_id, .. } => Some(session_id),
|
||||
McpStatus { .. } => None,
|
||||
}
|
||||
}
|
||||
@@ -278,3 +303,23 @@ pub fn new_id() -> String {
|
||||
pub fn now_ms() -> i64 {
|
||||
chrono::Utc::now().timestamp_millis()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod icon_tests {
|
||||
use super::*;
|
||||
|
||||
/// The client's picker (ColorSwatches.tsx) and the server's whitelist must list the same names.
|
||||
#[test]
|
||||
fn session_icons_match_the_client() {
|
||||
let ts = include_str!("../../web/src/components/ColorSwatches.tsx");
|
||||
let list = ts.split("SESSION_ICONS = [").nth(1).and_then(|r| r.split("] as const").next()).expect("icon list in ColorSwatches.tsx");
|
||||
let mut client: Vec<&str> = list.split('"').skip(1).step_by(2).collect();
|
||||
let mut server: Vec<&str> = SESSION_ICONS.to_vec();
|
||||
client.sort();
|
||||
server.sort();
|
||||
assert_eq!(client, server);
|
||||
let mut dedup = server.clone();
|
||||
dedup.dedup();
|
||||
assert_eq!(dedup.len(), server.len(), "duplicate icon names");
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,8 @@ services:
|
||||
- codecraft-data:/data
|
||||
# The projects the agents may work on.
|
||||
- ${WORKSPACE:-./workspace}:/workspace
|
||||
# Separate area for the software factory (clones of the watched repositories).
|
||||
- ${FACTORY_DIR:-./factory}:/factory
|
||||
# Reach self-hosted models (Ollama, vLLM, ...) on the host.
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
@@ -30,6 +30,8 @@ services:
|
||||
- codecraft-data:/data
|
||||
# The projects the agents may work on.
|
||||
- ${WORKSPACE:-./workspace}:/workspace
|
||||
# Separate area for the software factory (clones of the watched repositories).
|
||||
- ${FACTORY_DIR:-./factory}:/factory
|
||||
# Reach self-hosted models (Ollama, vLLM, ...) on the host.
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
# git for the shells of CodeCraft agents: `git commit` gets the co-author trailer from
|
||||
# $CODECRAFT_COMMIT_TRAILER (model, provider, CodeCraft). Everything else goes to the real
|
||||
# git unchanged. Git itself skips the trailer when the message already ends with it.
|
||||
real=${CODECRAFT_REAL_GIT:-/usr/bin/git}
|
||||
[[ -n $CODECRAFT_COMMIT_TRAILER ]] || exec "$real" "$@"
|
||||
# The subcommand comes after git's global options (-C dir, -c key=value, --git-dir=…).
|
||||
i=1
|
||||
while (( i <= $# )); do
|
||||
case ${!i} in
|
||||
-C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) i=$((i + 2)) ;;
|
||||
--) break ;;
|
||||
-*) i=$((i + 1)) ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
if (( i <= $# )) && [[ ${!i} == commit ]]; then
|
||||
# Right after "commit", so it stays an option even before "-- <paths>".
|
||||
exec "$real" "${@:1:i}" --trailer "$CODECRAFT_COMMIT_TRAILER" "${@:i+1}"
|
||||
fi
|
||||
exec "$real" "$@"
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# ssh, scp and sftp for containers that run as an arbitrary uid (docker-compose `user:`):
|
||||
# OpenSSH refuses to start without a passwd entry for the uid ("No user exists for uid N").
|
||||
# Without an entry, nss_wrapper provides one for this process; otherwise nothing changes.
|
||||
if ! getent passwd "$(id -u)" >/dev/null 2>&1; then
|
||||
d=${TMPDIR:-/tmp}/codecraft-nss-$(id -u)
|
||||
mkdir -p "$d" 2>/dev/null
|
||||
printf 'codecraft:x:%s:%s:CodeCraft:%s:/bin/sh\n' "$(id -u)" "$(id -g)" "${HOME:-/}" > "$d/passwd"
|
||||
printf 'codecraft:x:%s:\n' "$(id -g)" > "$d/group"
|
||||
export NSS_WRAPPER_PASSWD="$d/passwd" NSS_WRAPPER_GROUP="$d/group"
|
||||
export LD_PRELOAD="libnss_wrapper.so${LD_PRELOAD:+:$LD_PRELOAD}"
|
||||
fi
|
||||
exec "/usr/bin/$(basename "$0")" "$@"
|
||||
|
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 |
@@ -0,0 +1,64 @@
|
||||
---
|
||||
name: reverse-engineering
|
||||
description: Analyse programs and firmware – identify the format, inspect with binary_info, decompile with Ghidra (decompile tool, also raw firmware with processor/base address), explore the output and write down findings. For file formats, protocols, bugs and interoperability.
|
||||
---
|
||||
# Reverse engineering of programs and firmware
|
||||
|
||||
You analyse a binary to understand how it works – a file format, a protocol, an algorithm,
|
||||
a bug, or how to talk to a device. Work from cheap to expensive and write down what you learn.
|
||||
|
||||
Only analyse binaries the user owns or may analyse (their own builds, their devices, programs
|
||||
for interoperability). Decompiled code is third-party material: never commit it and never paste
|
||||
it into the user's source – describe behaviour in your own words.
|
||||
|
||||
## 1. Identify
|
||||
- `file <path>` – format, architecture, stripped or not.
|
||||
- Executables and libraries (PE .exe/.dll, ELF, Mach-O): `binary_info` – sections, imports,
|
||||
exports, strings. Imports and strings tell a lot (file names, error messages, protocol
|
||||
keywords, library names) before any decompiling.
|
||||
- Archives and update packages: unpack first (`unzip`, `7z x`), then identify the parts.
|
||||
- Intel HEX / S-record firmware: convert to a raw image –
|
||||
`objcopy -I ihex -O binary fw.hex fw.bin` (the lowest address in the HEX file is the base
|
||||
address). An ELF from the firmware's build (e.g. `zephyr.elf`, `firmware.elf`) is far better
|
||||
than a raw image: symbols and addresses are included – look for it first.
|
||||
- Raw images: look for clues with `strings -n 6 fw.bin | head -200` and
|
||||
`python3 -c` one-liners (vector table, magic numbers, embedded file systems).
|
||||
|
||||
## 2. Raw firmware: processor and load address
|
||||
`decompile` needs both for images without a file format:
|
||||
|
||||
| Chip family | `processor` | typical `base_address` |
|
||||
|---|---|---|
|
||||
| ARM Cortex-M (STM32, nRF52, RP2040, SAMD) | `ARM:LE:32:Cortex` | STM32 `0x08000000`, nRF52 `0x00000000`, RP2040 `0x10000000` |
|
||||
| ARM Cortex-A / ARMv7 | `ARM:LE:32:v7` | from the bootloader / datasheet |
|
||||
| AArch64 | `AARCH64:LE:64:v8A` | |
|
||||
| ESP32 (Xtensa) | `Xtensa:LE:32:default` | per segment (use the ELF if possible) |
|
||||
| AVR (Arduino) | `AVR8:LE:16:atmega256` or `AVR8:LE:16:default` | `0x0` |
|
||||
| MIPS (routers) | `MIPS:BE:32:default` or `MIPS:LE:32:default` | e.g. `0x80000000` |
|
||||
|
||||
Cortex-M check: the first word of the image is the initial stack pointer (0x2000xxxx = RAM),
|
||||
the second the reset vector – it points just behind the base address. If the decompiled output
|
||||
is mostly garbage, the processor or base address is wrong: fix it and run again (results are
|
||||
cached per file *and* processor/address).
|
||||
|
||||
## 3. Decompile
|
||||
- `decompile` with the path (plus `processor`/`base_address` for raw images). Large programs:
|
||||
start with `max_functions` (e.g. 2000), widen when needed.
|
||||
- Output in `.codecraft/decompiled/<name>/`: `functions.tsv` (address, name, size, file,
|
||||
signature), `functions/*.c`, `strings.tsv`, `imports.tsv`, `exports.tsv`.
|
||||
|
||||
## 4. Explore
|
||||
- Start from what you know: a string, an import or an export.
|
||||
`grep -l "SetCommState" .codecraft/decompiled/<name>/functions` finds the functions that use it.
|
||||
- Follow the calls by reading the functions; note addresses (`FUN_00401a30`) as you go.
|
||||
- Broad searches through thousands of functions: delegate them to an `explore` subagent with a
|
||||
precise question and let it report file:line.
|
||||
- File formats: compare the reading/writing code with a sample file (`python3` to dump the bytes)
|
||||
until every field is explained.
|
||||
|
||||
## 5. Write it down
|
||||
Keep findings in `analysis/notes.md` (create it; it is not committed): structure of the
|
||||
program, important functions with addresses, data structures, file formats and protocols with
|
||||
field tables, open questions. Make sure `.gitignore` excludes `analysis/`, `original/` and
|
||||
`.codecraft/decompiled/`. At the end, report what you found and how sure you are – mark guesses
|
||||
as guesses.
|
||||
@@ -20,6 +20,8 @@ pub enum PermissionReply {
|
||||
Once,
|
||||
/// Allow this tool (or bash command prefix) for the rest of the session.
|
||||
Always,
|
||||
/// Like `Always`, and remembered for the project folder (all chats, survives restarts).
|
||||
Project,
|
||||
Reject,
|
||||
}
|
||||
|
||||
@@ -144,6 +146,11 @@ impl App {
|
||||
Ok(n) => tracing::info!("moved {n} images of older chats to the image store"),
|
||||
Err(e) => tracing::warn!("moving images to the image store: {e:#}"),
|
||||
}
|
||||
match crate::budget::value_plan_requests(&self) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => tracing::info!("valued {n} plan requests (opencode Go) at list prices"),
|
||||
Err(e) => tracing::warn!("valuing plan requests: {e:#}"),
|
||||
}
|
||||
match crate::images::backfill_copies(&self) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => tracing::info!("kept copies of {n} generated images in the image store"),
|
||||
@@ -182,6 +189,20 @@ impl App {
|
||||
std::fs::canonicalize(&ws).unwrap_or(ws)
|
||||
}
|
||||
|
||||
/// Separate area of the software factory (mounted outside the workspace); None when absent.
|
||||
pub fn factory_dir(&self) -> Option<PathBuf> {
|
||||
let p = std::env::var("CODECRAFT_FACTORY_DIR").ok().filter(|p| !p.is_empty()).unwrap_or_else(|| "/factory".into());
|
||||
let p = PathBuf::from(p);
|
||||
p.is_dir().then(|| std::fs::canonicalize(&p).unwrap_or(p))
|
||||
}
|
||||
|
||||
/// The user's own folder in the factory area (created on demand).
|
||||
pub fn factory_home(&self, user: &crate::store::User) -> Option<PathBuf> {
|
||||
let dir = self.factory_dir()?.join(&user.username);
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
Some(dir)
|
||||
}
|
||||
|
||||
/// Directories a session owner may work in: admins (and legacy sessions
|
||||
/// without owner) the whole workspace, users their own folder plus shared folders.
|
||||
pub fn user_roots(&self, owner_id: Option<&str>) -> Vec<PathBuf> {
|
||||
@@ -189,12 +210,15 @@ impl App {
|
||||
let Some(user) = owner_id.and_then(|id| self.store.user(id).ok().flatten()) else {
|
||||
return vec![ws];
|
||||
};
|
||||
// The user's factory folder (if the area is mounted) is an additional root.
|
||||
let factory = self.factory_dir().map(|d| d.join(&user.username)).filter(|d| d.is_dir());
|
||||
if user.is_admin() {
|
||||
return vec![ws];
|
||||
return std::iter::once(ws).chain(factory).collect();
|
||||
}
|
||||
let own = ws.join(&user.username);
|
||||
let _ = std::fs::create_dir_all(&own);
|
||||
let mut roots = vec![own];
|
||||
roots.extend(factory);
|
||||
for p in self.store.folders_for_user(&user.id).unwrap_or_default() {
|
||||
let p = PathBuf::from(p);
|
||||
if p.starts_with(&ws) && p.is_dir() {
|
||||
|
||||
@@ -186,6 +186,12 @@ fn is_public(path: &str) -> bool {
|
||||
["/info", "/health", "/auth/login", "/auth/cli-login", "/auth/setup", "/auth/logout", "/auth/oidc/start", "/auth/oidc/callback"]
|
||||
.iter()
|
||||
.any(|p| path.ends_with(p))
|
||||
// Read-only chat links (the token is the credential).
|
||||
|| path.starts_with("/public/chat/")
|
||||
|| path.starts_with("/api/public/chat/")
|
||||
// MCP bridge for the Claude Code CLI (per-run token).
|
||||
|| path.starts_with("/mcp-bridge/")
|
||||
|| path.starts_with("/api/mcp-bridge/")
|
||||
}
|
||||
|
||||
pub async fn require_user(State(app): State<Arc<App>>, mut req: Request, next: Next) -> Response {
|
||||
|
||||
@@ -361,6 +361,49 @@ fn opencode_when(w: &Value) -> Option<When> {
|
||||
Some((days, hours, from, until))
|
||||
}
|
||||
|
||||
/// Plan requests (opencode Go) that were booked at 0: value them at the model's list
|
||||
/// prices of the time of the request. Idempotent – valued rows no longer match.
|
||||
pub fn value_plan_requests(app: &App) -> Result<usize> {
|
||||
let mut n = 0;
|
||||
for (row, ts, spec, usage) in app.store.plan_requests_without_cost()? {
|
||||
let Ok((_, model)) = app.registry().resolve(&spec) else { continue };
|
||||
let Some(at) = chrono::DateTime::from_timestamp_millis(ts) else { continue };
|
||||
let cost = model.cost_at(&usage, at);
|
||||
if cost > 0.0 {
|
||||
app.store.set_usage_cost(row, cost)?;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// A price from opencode's list: a number, or one price per cache duration
|
||||
/// (`{"30m": 0.125, "12h": 0.25}`) – then the shortest duration (the default caching).
|
||||
fn price_of(v: &Value) -> Value {
|
||||
match v {
|
||||
Value::Number(_) => v.clone(),
|
||||
Value::Object(o) => {
|
||||
let secs = |k: &str| -> Option<f64> {
|
||||
let (num, unit) = k.split_at(k.find(|c: char| c.is_ascii_alphabetic())?);
|
||||
let n: f64 = num.parse().ok()?;
|
||||
Some(n * match unit {
|
||||
"s" => 1.0,
|
||||
"m" => 60.0,
|
||||
"h" => 3600.0,
|
||||
"d" => 86400.0,
|
||||
_ => return None,
|
||||
})
|
||||
};
|
||||
o.iter()
|
||||
.filter(|(_, x)| x.is_number())
|
||||
.min_by(|a, b| secs(a.0).unwrap_or(f64::MAX).total_cmp(&secs(b.0).unwrap_or(f64::MAX)))
|
||||
.map(|(_, x)| x.clone())
|
||||
.unwrap_or(Value::Null)
|
||||
}
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// Model row from opencode's model list (prices per 1M tokens, tiers, time factors).
|
||||
fn opencode_model(m: &Value) -> Value {
|
||||
let cost = &m["cost"]["text"];
|
||||
@@ -371,13 +414,13 @@ fn opencode_model(m: &Value) -> Value {
|
||||
for o in side["overrides"].as_array().into_iter().flatten() {
|
||||
let Some(gt) = o["when"]["context"]["gt"].as_u64() else { continue };
|
||||
let t = tiers.entry(gt).or_default();
|
||||
t.insert(field.into(), o["price"].clone());
|
||||
t.insert(field.into(), price_of(&o["price"]));
|
||||
if field == "input_price" {
|
||||
if o["cache"]["read"].is_number() {
|
||||
t.insert("cache_read_price".into(), o["cache"]["read"].clone());
|
||||
}
|
||||
if o["cache"]["write"].is_number() {
|
||||
t.insert("cache_write_price".into(), o["cache"]["write"].clone());
|
||||
for (key, k) in [("read", "cache_read_price"), ("write", "cache_write_price")] {
|
||||
let p = price_of(&o["cache"][key]);
|
||||
if !p.is_null() {
|
||||
t.insert(k.into(), p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -412,10 +455,10 @@ fn opencode_model(m: &Value) -> Value {
|
||||
"max_input": m["limit"]["input"],
|
||||
"vision": images,
|
||||
"reasoning": m["capabilities"]["reasoning"]["supported"].as_bool().unwrap_or(false),
|
||||
"input_price": input["price"],
|
||||
"output_price": output["price"],
|
||||
"cache_read_price": input["cache"]["read"],
|
||||
"cache_write_price": input["cache"]["write"],
|
||||
"input_price": price_of(&input["price"]),
|
||||
"output_price": price_of(&output["price"]),
|
||||
"cache_read_price": price_of(&input["cache"]["read"]),
|
||||
"cache_write_price": price_of(&input["cache"]["write"]),
|
||||
"price_tiers": price_tiers,
|
||||
"price_multipliers": price_multipliers,
|
||||
"notes": notes,
|
||||
@@ -481,6 +524,25 @@ pub async fn discover_prices(app: &App, provider: &str) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn prices_per_cache_duration() {
|
||||
use super::{opencode_model, price_of};
|
||||
use serde_json::{Value, json};
|
||||
assert_eq!(price_of(&json!(0.5)), json!(0.5));
|
||||
assert_eq!(price_of(&json!({"12h": 0.25, "30m": 0.125})), json!(0.125));
|
||||
assert_eq!(price_of(&json!({"1h": 2.0, "5m": 1.25})), json!(1.25));
|
||||
assert_eq!(price_of(&Value::Null), Value::Null);
|
||||
// A model of opencode's list with per-duration cache write prices.
|
||||
let m = json!({"id": "gpt-6-luna", "limit": {"context": 1050000, "input": 922000, "output": 128000},
|
||||
"cost": {"text": {"input": {"price": 0.1, "cache": {"read": 0.01, "write": {"30m": 0.125, "12h": 0.25}},
|
||||
"overrides": [{"when": {"context": {"gt": 272000}}, "price": 0.2, "cache": {"read": 0.02, "write": {"30m": 0.25, "12h": 0.5}}}]},
|
||||
"output": {"price": 0.5, "overrides": [{"when": {"context": {"gt": 272000}}, "price": 0.75}]}}}});
|
||||
let row = opencode_model(&m);
|
||||
assert_eq!(row["cache_write_price"], json!(0.125));
|
||||
assert_eq!(row["price_tiers"][0]["cache_write_price"], json!(0.25));
|
||||
assert_eq!(row["max_input"], json!(922000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opencode_cost_conversion() {
|
||||
let m: serde_json::Value = serde_json::from_str(r#"{"id":"grok","limit":{"context":500000,"output":8000},
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! A check command per project folder (tests, build, lint) that runs after every turn that changed
|
||||
//! files. The result is a green/red badge on the turn; a failed run can be handed to the agent.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::types::{Event, Role, Session, now_ms};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
const MAX_OUTPUT: usize = 12_000;
|
||||
|
||||
/// Last `max` bytes of the output (failures show at the end).
|
||||
fn tail(s: &str, max: usize) -> String {
|
||||
if s.len() <= max {
|
||||
return s.to_string();
|
||||
}
|
||||
let mut start = s.len() - max;
|
||||
while !s.is_char_boundary(start) {
|
||||
start += 1;
|
||||
}
|
||||
format!("…\n{}", &s[start..])
|
||||
}
|
||||
|
||||
fn command(app: &App, session: &Session, script: &str) -> Result<tokio::process::Command> {
|
||||
let script = format!("exec 2>&1\n{script}");
|
||||
let cwd = std::path::Path::new(&session.cwd);
|
||||
if let Some(spec) = crate::sandbox::spec_for(app, session.owner_id.as_deref()) {
|
||||
if !crate::sandbox::available() {
|
||||
bail!("the sandbox (bubblewrap) is not available");
|
||||
}
|
||||
return Ok(crate::sandbox::command(&spec, cwd, "bash", &["-c", &script]));
|
||||
}
|
||||
let mut c = tokio::process::Command::new("bash");
|
||||
c.arg("-c").arg(&script).current_dir(cwd).env("CODECRAFT", "1").env("CI", "1").env("GIT_TERMINAL_PROMPT", "0").env("PAGER", "cat");
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
/// Run the project's check for the turn that ended with `message_id` and publish the result.
|
||||
pub async fn run(app: &Arc<App>, session: &Session, message_id: &str) -> Result<()> {
|
||||
let (cmd, _) = app.store.project_check(&session.cwd)?.ok_or_else(|| anyhow!("no check command set for this project"))?;
|
||||
let sid = session.id.clone();
|
||||
let emit = |status: &str, code: Option<i32>, ms: u64, out: &str| {
|
||||
let _ = app.store.set_turn_check(&sid, message_id, status, code, ms, out);
|
||||
app.emit(Event::CheckResult { session_id: sid.clone(), message_id: message_id.into(), status: status.into(), exit_code: code, duration_ms: ms, output: out.into() });
|
||||
};
|
||||
emit("running", None, 0, "");
|
||||
let started = now_ms();
|
||||
let mut c = match command(app, session, &cmd) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
emit("failed", None, 0, &format!("{e:#}"));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let res = tokio::time::timeout(TIMEOUT, c.stdin(Stdio::null()).kill_on_drop(true).output()).await;
|
||||
let ms = (now_ms() - started).max(0) as u64;
|
||||
match res {
|
||||
Err(_) => emit("timeout", None, ms, &format!("Stopped after {} minutes.", TIMEOUT.as_secs() / 60)),
|
||||
Ok(Err(e)) => emit("failed", None, ms, &format!("could not run the command: {e}")),
|
||||
Ok(Ok(o)) => {
|
||||
let mut text = String::from_utf8_lossy(&o.stdout).to_string();
|
||||
text.push_str(&String::from_utf8_lossy(&o.stderr));
|
||||
emit(if o.status.success() { "passed" } else { "failed" }, o.status.code(), ms, &tail(text.trim(), MAX_OUTPUT));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After a turn: run the check if the project has one and the turn changed files.
|
||||
pub fn spawn_after_turn(app: Arc<App>, session_id: String, turn_started: i64) {
|
||||
tokio::spawn(async move {
|
||||
let Ok(session) = app.session(&session_id) else { return };
|
||||
if session.parent_id.is_some() {
|
||||
return;
|
||||
}
|
||||
let Ok(Some((_, true))) = app.store.project_check(&session.cwd) else { return };
|
||||
if app.store.checkpoints_since(&session_id, turn_started).map(|c| c.is_empty()).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let Some(last) = app.store.messages(&session_id).ok().and_then(|m| m.into_iter().rev().find(|m| m.role == Role::Assistant)) else { return };
|
||||
if let Err(e) = run(&app, &session, &last.id).await {
|
||||
tracing::debug!("check failed to start: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -36,7 +36,7 @@ pub async fn config(Extension(user): Extension<User>, State(app): State<AppState
|
||||
.filter(|c| c.description.len() < 400)
|
||||
.map(|c| json!({"name": c.name, "description": c.description, "body": c.body, "agent": c.agent}))
|
||||
.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 mut mcp_tools: Vec<ToolDef> = direct.iter().map(|t| t.def()).collect();
|
||||
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).
|
||||
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 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 content = std::fs::read_to_string(&sk.path)?;
|
||||
let mut files = Vec::new();
|
||||
@@ -231,6 +231,29 @@ pub async fn put_prefs(Extension(user): Extension<User>, State(app): State<AppSt
|
||||
Ok(Json(b))
|
||||
}
|
||||
|
||||
/// Personal prompt snippets (`/name` in the composer): [{id, name, text}].
|
||||
pub async fn get_snippets(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||
let v: Value = app.store.user_setting(&user.id, "snippets")?;
|
||||
Ok(Json(if v.is_array() { v } else { json!([]) }))
|
||||
}
|
||||
|
||||
pub async fn put_snippets(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<Value>) -> ApiResult {
|
||||
let ok = b.as_array().is_some_and(|a| {
|
||||
a.len() <= 100
|
||||
&& a.iter().all(|x| {
|
||||
let name = x["name"].as_str().unwrap_or("");
|
||||
!name.is_empty() && name.len() <= 40 && !name.contains(char::is_whitespace) && x["text"].as_str().is_some_and(|t| !t.is_empty() && t.len() <= 8000)
|
||||
})
|
||||
});
|
||||
if !ok {
|
||||
return Err(ApiError(StatusCode::BAD_REQUEST, "invalid snippets (name: one word, up to 40 characters; text: up to 8000)".into()));
|
||||
}
|
||||
let clean: Vec<Value> = b.as_array().unwrap().iter().map(|x| json!({"id": x["id"].as_str().filter(|i| i.len() <= 64).map(str::to_string).unwrap_or_else(crate::types::new_id), "name": x["name"], "text": x["text"]})).collect();
|
||||
let v = Value::Array(clean);
|
||||
app.store.set_user_setting(&user.id, "snippets", &v)?;
|
||||
Ok(Json(v))
|
||||
}
|
||||
|
||||
/// Order and pinning of the groups (folders, projects) in the chat list – per user, so
|
||||
/// every device shows the same order: {"order": [group ids], "pinned": [group ids]}.
|
||||
pub async fn get_sidebar(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||
|
||||
@@ -177,6 +177,19 @@ pub struct ImagesConfig {
|
||||
/// Optional fal.ai Admin key to query the account balance.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub admin_key: String,
|
||||
/// fal.ai model for 3D models from images (generate_3d).
|
||||
#[serde(default = "default_model_3d")]
|
||||
pub model_3d: String,
|
||||
/// fal.ai model for 3D models from a text prompt only.
|
||||
#[serde(default = "default_model_3d_text")]
|
||||
pub model_3d_text: String,
|
||||
}
|
||||
|
||||
fn default_model_3d() -> String {
|
||||
"fal-ai/hunyuan3d-v3/image-to-3d".into()
|
||||
}
|
||||
fn default_model_3d_text() -> String {
|
||||
"fal-ai/hunyuan3d-v3/text-to-3d".into()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
|
||||
@@ -215,6 +228,8 @@ impl Default for ImagesConfig {
|
||||
models: vec![ImageModel { id: "fal-ai/flux/schnell".into(), name: Some("FLUX.1 schnell".into()), price: Some(0.003), ..Default::default() }],
|
||||
monthly_budget: None,
|
||||
admin_key: String::new(),
|
||||
model_3d: default_model_3d(),
|
||||
model_3d_text: default_model_3d_text(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,6 +302,9 @@ pub struct ServerConfig {
|
||||
pub data_dir: String,
|
||||
pub default_model: String,
|
||||
pub small_model: String,
|
||||
/// Speech-to-text for browsers without dictation (Firefox): "provider/model" of an
|
||||
/// OpenAI-compatible /audio/transcriptions endpoint, e.g. "openai/whisper-1". Empty = off.
|
||||
pub transcribe_model: String,
|
||||
pub auto_compact_threshold: f64,
|
||||
/// Currency label for cost statistics (display only).
|
||||
pub currency: String,
|
||||
@@ -307,8 +325,13 @@ pub struct ServerConfig {
|
||||
/// Bearer token for GET /metrics (Prometheus); empty = /metrics disabled.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub metrics_token: String,
|
||||
/// Trailer added to every git commit an agent makes ({model}, {provider}, {model_id});
|
||||
/// empty = off.
|
||||
pub commit_trailer: String,
|
||||
}
|
||||
|
||||
pub const DEFAULT_COMMIT_TRAILER: &str = "Co-Authored-By: {model} ({provider}) via CodeCraft";
|
||||
|
||||
impl Default for ServerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -317,6 +340,7 @@ impl Default for ServerConfig {
|
||||
data_dir: "./data".into(),
|
||||
default_model: String::new(),
|
||||
small_model: String::new(),
|
||||
transcribe_model: String::new(),
|
||||
auto_compact_threshold: 0.85,
|
||||
currency: "USD".into(),
|
||||
max_parallel_subagents: 4,
|
||||
@@ -327,6 +351,7 @@ impl Default for ServerConfig {
|
||||
max_upload_mb: 500,
|
||||
update_url: "https://git.familie-zink.org/api/v1/repos/zink/codecraft/releases/latest".into(),
|
||||
metrics_token: String::new(),
|
||||
commit_trailer: DEFAULT_COMMIT_TRAILER.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -398,6 +423,10 @@ pub struct AgentConfig {
|
||||
/// Review loop after each turn of this mode.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub refine: Option<RefineConfig>,
|
||||
/// Reverse engineering tools (binary_info, decompile with Ghidra) in this mode;
|
||||
/// craft has them anyway (deep mode).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reverse_tools: Option<bool>,
|
||||
}
|
||||
|
||||
/// Refinement loop: after the agent finishes, a reviewer checks the result
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! user via the user setting "cost_push").
|
||||
|
||||
use crate::app::App;
|
||||
use chrono::{Local, Timelike};
|
||||
use chrono::{Datelike, Local, Timelike};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -54,11 +54,59 @@ pub fn summary(app: &App, user_id: &str) -> Option<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// The last seven days for one user (None when nothing happened).
|
||||
pub fn weekly(app: &App, user_id: &str) -> Option<Value> {
|
||||
let now = Local::now();
|
||||
let since = now.timestamp_millis() - 7 * 86_400_000;
|
||||
let offset = now.offset().local_minus_utc() as i64 / 60;
|
||||
let stats = app.store.global_stats(since, now.timestamp_millis() + 1, offset, Some(user_id)).ok()?;
|
||||
let requests = stats["total"]["requests"].as_i64().unwrap_or(0);
|
||||
let (chats, failed, checks) = app.store.weekly_counts(user_id, since).ok()?;
|
||||
if requests == 0 && chats == 0 {
|
||||
return None;
|
||||
}
|
||||
let prefs: Value = app.store.user_setting(user_id, "prefs").unwrap_or_default();
|
||||
let de = prefs["lang"].as_str().unwrap_or("").starts_with("de");
|
||||
let currency = app.config().server.currency.clone();
|
||||
let cost = money(stats["total"]["cost"].as_f64().unwrap_or(0.0), ¤cy, de);
|
||||
let top = stats["top_sessions"].as_array().and_then(|a| a.first()).and_then(|s| s["title"].as_str()).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
let mut parts = if de { vec![format!("{chats} Chats aktiv"), format!("{requests} Anfragen · {cost}")] } else { vec![format!("{chats} chats active"), format!("{requests} requests · {cost}")] };
|
||||
if checks > 0 {
|
||||
parts.push(if de { format!("Checks: {failed} von {checks} fehlgeschlagen") } else { format!("checks: {failed} of {checks} failed") });
|
||||
}
|
||||
if let Some(t) = top {
|
||||
parts.push(if de { format!("teuerster Chat: {t}") } else { format!("most expensive chat: {t}") });
|
||||
}
|
||||
Some(json!({
|
||||
"kind": "digest",
|
||||
"title": if de { "CodeCraft – Wochenrückblick" } else { "CodeCraft – weekly review" },
|
||||
"body": parts.join("\n"),
|
||||
"tag": "weekly-digest",
|
||||
"url": "/#/stats",
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn spawn(app: Arc<App>) {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
let now = Local::now();
|
||||
// Weekly review: Monday morning, opt-in (user setting "weekly_push").
|
||||
if now.hour() == 8 && now.weekday() == chrono::Weekday::Mon {
|
||||
let week = now.format("%G-W%V").to_string();
|
||||
for user in app.store.users().unwrap_or_default() {
|
||||
let on: bool = app.store.user_setting(&user.id, "weekly_push").unwrap_or(false);
|
||||
let last: String = app.store.user_setting(&user.id, "weekly_push_last").unwrap_or_default();
|
||||
if !on || user.disabled || last == week {
|
||||
continue;
|
||||
}
|
||||
let _ = app.store.set_user_setting(&user.id, "weekly_push_last", &week);
|
||||
if let Some(payload) = weekly(&app, &user.id) {
|
||||
let (sent, errors) = crate::push::send_to_user(&app, &user.id, &payload).await;
|
||||
tracing::info!(user = %user.username, sent, errors = errors.len(), "weekly review");
|
||||
}
|
||||
}
|
||||
}
|
||||
if now.hour() != HOUR {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
//! 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;
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -174,7 +174,8 @@ fn parse_status(raw: &str) -> Value {
|
||||
pub async fn handle(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<GitBody>) -> ApiResult {
|
||||
let spec = crate::sandbox::spec_for(&app, Some(&user.id));
|
||||
let cfg = crate::gitcreds::global_config(&app, &user);
|
||||
let env = crate::gitcreds::identity_env(&app, &user.id);
|
||||
let mut env = crate::gitcreds::identity_env(&app, &user.id);
|
||||
env.extend(crate::sshkeys::env(&app, &user));
|
||||
SANDBOX.scope(spec, GITCONFIG.scope(cfg, GITENV.scope(env, handle_inner(user, app, b)))).await
|
||||
}
|
||||
|
||||
@@ -254,6 +255,15 @@ async fn handle_inner(user: User, app: AppState, b: GitBody) -> ApiResult {
|
||||
git_ok(&repo, &args, 60).await?;
|
||||
json!({"ok": true})
|
||||
}
|
||||
"suggest" => {
|
||||
let diff = git_ok(&repo, &["diff", "--cached", "--no-color", "--no-ext-diff", "--stat", "--patch", "-U2"], 60).await?;
|
||||
if diff.trim().is_empty() {
|
||||
return Err(ApiError(StatusCode::BAD_REQUEST, "nothing is staged".into()));
|
||||
}
|
||||
let recent = git_ok(&repo, &["log", "-n", "8", "--pretty=%s"], 15).await.unwrap_or_default();
|
||||
let message = crate::runner::suggest_commit_message(&app, &user.id, &diff, &recent).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, e.to_string()))?;
|
||||
json!({"message": message})
|
||||
}
|
||||
"commit" => {
|
||||
let msg = b.message.as_deref().unwrap_or("").trim().to_string();
|
||||
if msg.is_empty() && !b.amend {
|
||||
@@ -392,7 +402,8 @@ fn wt_str<'a>(wt: &'a Value, key: &str) -> &'a str {
|
||||
pub async fn worktree(app: &std::sync::Arc<App>, user: &User, session: &mut crate::types::Session, action: &str) -> Result<Value, ApiError> {
|
||||
let spec = crate::sandbox::spec_for(app, Some(&user.id));
|
||||
let cfg = crate::gitcreds::global_config(app, user);
|
||||
let env = crate::gitcreds::identity_env(app, &user.id);
|
||||
let mut env = crate::gitcreds::identity_env(app, &user.id);
|
||||
env.extend(crate::sshkeys::env(app, user));
|
||||
let s = session.clone();
|
||||
let res = SANDBOX.scope(spec, GITCONFIG.scope(cfg, GITENV.scope(env, worktree_inner(s, action)))).await?;
|
||||
if let Some(cwd) = res.get("cwd").and_then(|v| v.as_str()) {
|
||||
|
||||
@@ -53,6 +53,35 @@ pub fn identity_env(app: &App, user_id: &str) -> Vec<(String, String)> {
|
||||
env
|
||||
}
|
||||
|
||||
/// What an agent needs to know about the stored git access (no secrets): git already has the
|
||||
/// credentials, so it must not look for them. None when nothing is stored.
|
||||
pub fn prompt_section(app: &App, user_id: &str) -> Option<String> {
|
||||
render_prompt(&app.store.user_setting(user_id, "git").unwrap_or_default())
|
||||
}
|
||||
|
||||
fn render_prompt(s: &GitSettings) -> Option<String> {
|
||||
let creds: Vec<&GitCredential> = s.credentials.iter().filter(|c| !c.host.trim().is_empty() && !c.token.is_empty()).collect();
|
||||
if creds.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut t = String::from("\n# Git access\nThe user has stored git credentials for these hosts (HTTPS):\n");
|
||||
for c in &creds {
|
||||
t.push_str(&format!("- {} (user {})\n", c.host.trim(), c.username.trim()));
|
||||
}
|
||||
t.push_str(
|
||||
"git uses them automatically through its credential helper: `git clone`, `fetch`, `pull` and `push` with an https:// URL of these hosts just work, no login or token needed. \
|
||||
Do NOT ask the user for a token and do NOT search the environment, config files, `gh`, SSH keys or the keychain for credentials – they are not there, and the command line shows none because git keeps them in its credential store. \
|
||||
Use https:// remote URLs (SSH keys are not set up). \
|
||||
For a REST API of such a host (pull requests, issues, releases) take the token straight from git without printing it, e.g. \
|
||||
`curl -s -H \"Authorization: token $(printf 'protocol=https\\nhost=HOST\\n\\n' | git credential fill | sed -n 's/^password=//p')\" https://HOST/api/...` \
|
||||
(GitHub: `Authorization: Bearer`). Never echo the token or write it into files, commits or your answer.\n",
|
||||
);
|
||||
if !s.name.trim().is_empty() || !s.email.trim().is_empty() {
|
||||
t.push_str(&format!("Commits are made as {} <{}> automatically.\n", s.name.trim(), s.email.trim()));
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
|
||||
pub fn home_of(app: &App, user: &User) -> PathBuf {
|
||||
app.data_dir().join("users").join(&user.username).join("home")
|
||||
}
|
||||
@@ -159,6 +188,19 @@ pub fn merge(old: &GitSettings, mut new: GitSettings) -> GitSettings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prompt_names_hosts_but_never_tokens() {
|
||||
assert!(render_prompt(&GitSettings::default()).is_none());
|
||||
let settings = GitSettings { name: "Ann".into(), email: "ann@x.org".into(), credentials: vec![GitCredential { host: "git.x.org".into(), username: "ann".into(), token: "s3cret-token".into(), protocol: String::new() }] };
|
||||
let p = render_prompt(&settings).unwrap();
|
||||
println!("{p}");
|
||||
assert!(p.contains("git.x.org (user ann)") && p.contains("git credential fill") && p.contains("Ann <ann@x.org>"));
|
||||
assert!(!p.contains("s3cret-token"));
|
||||
// Entries without a token are not offered.
|
||||
let none = GitSettings { credentials: vec![GitCredential { host: "h".into(), username: "u".into(), ..Default::default() }], ..Default::default() };
|
||||
assert!(render_prompt(&none).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_masked_tokens() {
|
||||
let old = GitSettings { credentials: vec![GitCredential { host: "git.x".into(), username: "me".into(), token: "secret".into(), protocol: String::new() }], ..Default::default() };
|
||||
|
||||
@@ -42,8 +42,9 @@ pub async fn probe(provider: Arc<dyn crate::provider::Provider>) -> (ProviderSta
|
||||
Ok(Err(e)) => (Some(e.to_string().chars().take(300).collect()), 0),
|
||||
Err(_) => (Some("timed out".to_string()), 0),
|
||||
};
|
||||
// The host answered but has no model list: reachable.
|
||||
let error = error.filter(|e| !(e.contains("HTTP 404") || e.contains("HTTP 405")));
|
||||
// The host answered but has no model list: reachable. (fal.ai's router answers 403
|
||||
// "endpoint_not_priced" for /models: the key is fine, the listing is just not offered.)
|
||||
let error = error.filter(|e| !(e.contains("HTTP 404") || e.contains("HTTP 405") || e.contains("endpoint_not_priced")));
|
||||
let state = match &error {
|
||||
None => "ok",
|
||||
Some(e) if e.contains("HTTP 401") || e.contains("HTTP 403") => "auth",
|
||||
@@ -83,3 +84,13 @@ pub fn spawn_checker(app: Arc<App>) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn unpriced_model_listing_is_not_an_auth_failure() {
|
||||
let e = r#"provider returned HTTP 403 Forbidden: {"detail":"Endpoint openrouter/router/openai/v1/models is not available: no billing definition.","type":"endpoint_not_priced"}"#.to_string();
|
||||
let kept = Some(e).filter(|e| !(e.contains("HTTP 404") || e.contains("HTTP 405") || e.contains("endpoint_not_priced")));
|
||||
assert!(kept.is_none());
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ pub struct GenerateRequest {
|
||||
pub references: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn slug(s: &str) -> String {
|
||||
pub(crate) fn slug(s: &str) -> String {
|
||||
let mut out: String = s
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
|
||||
@@ -121,7 +121,7 @@ fn pick(all: &[ImageModel], stage: &str, purpose: Option<&str>, with_reference:
|
||||
}
|
||||
|
||||
/// Read local reference images as data URIs (fal.ai accepts them in place of URLs).
|
||||
async fn reference_uris(paths: &[PathBuf]) -> Result<Vec<String>> {
|
||||
pub(crate) async fn reference_uris(paths: &[PathBuf]) -> Result<Vec<String>> {
|
||||
let mut out = Vec::new();
|
||||
for p in paths {
|
||||
let bytes = tokio::fs::read(p).await.with_context(|| format!("reference image {}", p.display()))?;
|
||||
@@ -135,7 +135,7 @@ async fn reference_uris(paths: &[PathBuf]) -> Result<Vec<String>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn download(url: &str) -> Result<(Vec<u8>, String)> {
|
||||
pub(crate) async fn download(url: &str) -> Result<(Vec<u8>, String)> {
|
||||
if let Some(rest) = url.strip_prefix("data:") {
|
||||
let (meta, data) = rest.split_once(',').context("malformed data URI")?;
|
||||
let ctype = meta.split(';').next().unwrap_or("image/png").to_string();
|
||||
@@ -348,7 +348,7 @@ pub fn backfill_copies(app: &App) -> Result<usize> {
|
||||
}
|
||||
|
||||
/// Downscaled copy for the model's context.
|
||||
fn preview_for_model(path: &Path) -> Option<ImageData> {
|
||||
pub(crate) fn preview_for_model(path: &Path) -> Option<ImageData> {
|
||||
let img = image::open(path).ok()?;
|
||||
let img = img.resize(1024, 1024, image::imageops::FilterType::Triangle);
|
||||
let mut buf = Vec::new();
|
||||
|
||||
@@ -68,6 +68,13 @@ pub struct JobSettings {
|
||||
/// Chat in which the user works out the prompt with a model.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub assistant_session: Option<String>,
|
||||
/// Push notification with the report when a run ends.
|
||||
#[serde(default = "default_notify")]
|
||||
pub notify: bool,
|
||||
}
|
||||
|
||||
fn default_notify() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl JobSettings {
|
||||
@@ -81,6 +88,7 @@ impl JobSettings {
|
||||
timeout_minutes: default_timeout(),
|
||||
cwd: None,
|
||||
assistant_session: None,
|
||||
notify: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +129,7 @@ pub struct JobSpec {
|
||||
pub cwd: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub assistant_session: Option<String>,
|
||||
pub notify: bool,
|
||||
pub prompt: String,
|
||||
}
|
||||
|
||||
@@ -135,6 +144,7 @@ impl JobSpec {
|
||||
timeout_minutes: s.timeout_minutes,
|
||||
cwd: s.cwd.clone(),
|
||||
assistant_session: s.assistant_session.clone(),
|
||||
notify: s.notify,
|
||||
prompt,
|
||||
}
|
||||
}
|
||||
@@ -149,6 +159,7 @@ impl JobSpec {
|
||||
timeout_minutes: self.timeout_minutes,
|
||||
cwd: self.cwd.clone(),
|
||||
assistant_session: self.assistant_session.clone(),
|
||||
notify: self.notify,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,6 +229,7 @@ pub fn parse(path: &Path) -> Result<JobSpec> {
|
||||
timeout_minutes: meta.get("timeout_minutes").and_then(|v| unquote(v).parse().ok()).unwrap_or(60).clamp(1, 24 * 60),
|
||||
cwd: meta.get("cwd").map(unquote).filter(|c| !c.is_empty()),
|
||||
assistant_session: None,
|
||||
notify: meta.get("notify").map(|v| unquote(v) != "false").unwrap_or(true),
|
||||
prompt: body.trim().to_string(),
|
||||
})
|
||||
}
|
||||
@@ -321,6 +333,9 @@ pub async fn run_with(app: &Arc<App>, job: &Job, trigger: &str, payload: Option<
|
||||
instructions: String::new(),
|
||||
// New chats keep their approvals and questions out of Telegram (⋯ menu turns it on).
|
||||
telegram_quiet: true,
|
||||
summary: String::new(),
|
||||
color: None,
|
||||
icon: None, skills: Vec::new(),
|
||||
};
|
||||
let session = app.save_session(session)?;
|
||||
app.store.job_started(&job.id, &session.id, now)?;
|
||||
@@ -339,6 +354,7 @@ pub async fn run_with(app: &Arc<App>, job: &Job, trigger: &str, payload: Option<
|
||||
let job_id = job.id.clone();
|
||||
let sid = session.id.clone();
|
||||
let timeout = Duration::from_secs(spec.timeout_minutes * 60);
|
||||
let (spec_name, spec_notify) = (spec.name.clone(), spec.notify);
|
||||
tokio::spawn(async move {
|
||||
let started = std::time::Instant::now();
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
@@ -346,15 +362,48 @@ pub async fn run_with(app: &Arc<App>, job: &Job, trigger: &str, payload: Option<
|
||||
if started.elapsed() > timeout {
|
||||
crate::runner::abort(&app2, &sid);
|
||||
let _ = app2.store.job_finished(&job_id, Some(&sid), "timeout");
|
||||
report(&app2, &sid, &spec_name, spec_notify, "timeout").await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
let _ = app2.store.job_finished(&job_id, Some(&sid), "done");
|
||||
report(&app2, &sid, &spec_name, spec_notify, "done").await;
|
||||
});
|
||||
Ok(session.id)
|
||||
}
|
||||
|
||||
/// Push the report of a finished run (the agent's last message) to the owner.
|
||||
async fn report(app: &App, session_id: &str, name: &str, notify: bool, status: &str) {
|
||||
if !notify {
|
||||
return;
|
||||
}
|
||||
let Ok(session) = app.session(session_id) else { return };
|
||||
let Some(owner) = session.owner_id.clone() else { return };
|
||||
let prefs: Value = app.store.user_setting(&owner, "prefs").unwrap_or_default();
|
||||
let de = prefs["lang"].as_str().unwrap_or("").starts_with("de");
|
||||
let last = app
|
||||
.store
|
||||
.messages(session_id)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|m| matches!(m.role, crate::types::Role::Assistant))
|
||||
.map(|m| m.parts.iter().filter_map(|p| if let Part::Text { text } = p { Some(text.as_str()) } else { None }).collect::<Vec<_>>().join("\n"))
|
||||
.unwrap_or_default();
|
||||
let flat: String = last.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let body: String = if flat.chars().count() > 220 { format!("{}…", flat.chars().take(220).collect::<String>()) } else { flat };
|
||||
let title = match (status, de) {
|
||||
("timeout", true) => format!("{name} – Zeitlimit erreicht"),
|
||||
("timeout", false) => format!("{name} – timed out"),
|
||||
(_, true) => format!("{name} – fertig"),
|
||||
(_, false) => format!("{name} – finished"),
|
||||
};
|
||||
let payload = json!({"kind": "job", "title": title, "body": body, "tag": format!("job-{session_id}"), "url": format!("/#/s/{session_id}")});
|
||||
let (sent, _) = crate::push::send_to_user(app, &owner, &payload).await;
|
||||
tracing::info!(job = name, sent, "automation report");
|
||||
}
|
||||
|
||||
/// Background scheduler: checks every 30 s which jobs are due.
|
||||
pub fn spawn_scheduler(app: Arc<App>) {
|
||||
tokio::spawn(async move {
|
||||
|
||||
@@ -5,12 +5,16 @@ mod app;
|
||||
mod auth;
|
||||
mod backup;
|
||||
mod blobs;
|
||||
mod checks;
|
||||
mod claude_code;
|
||||
mod cli_api;
|
||||
mod budget;
|
||||
mod config;
|
||||
mod digest;
|
||||
mod docs;
|
||||
mod export;
|
||||
mod factory;
|
||||
mod factory_version;
|
||||
mod files;
|
||||
mod git;
|
||||
mod health;
|
||||
@@ -22,15 +26,20 @@ mod lsp;
|
||||
mod mentions;
|
||||
mod metrics;
|
||||
mod mcp;
|
||||
mod mcp_bridge;
|
||||
mod media;
|
||||
mod mesh3d;
|
||||
mod permission;
|
||||
mod prompts;
|
||||
mod push;
|
||||
mod provider;
|
||||
mod reverse;
|
||||
mod runner;
|
||||
mod skills_api;
|
||||
mod sandbox;
|
||||
mod shells;
|
||||
mod sshkeys;
|
||||
mod stats_export;
|
||||
mod store;
|
||||
mod telegram;
|
||||
mod terminal;
|
||||
@@ -72,6 +81,7 @@ async fn main() -> Result<()> {
|
||||
push::spawn_listener(app.clone());
|
||||
terminal::spawn_reaper(app.clone());
|
||||
jobs::spawn_scheduler(app.clone());
|
||||
factory::spawn(app.clone());
|
||||
update::spawn_checker(app.clone());
|
||||
health::spawn_checker(app.clone());
|
||||
digest::spawn(app.clone());
|
||||
|
||||
@@ -558,6 +558,42 @@ impl McpManager {
|
||||
/// Search the on-demand MCP tools by keywords.
|
||||
pub struct McpSearch;
|
||||
|
||||
/// Built-in tools matching the search words, with their availability in the current mode.
|
||||
fn builtin_matches(ctx: &ToolCtx, words: &[&str]) -> String {
|
||||
if words.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let app = &ctx.app;
|
||||
let owner_id = app.session(&ctx.session_id).ok().and_then(|s| s.owner_id);
|
||||
let owner_user = owner_id.as_deref().and_then(|id| app.store.user(id).ok().flatten());
|
||||
let root = app.root_for(owner_id.as_deref(), &ctx.cwd);
|
||||
let agent = crate::prompts::find_agent_for(app, &root, &ctx.cwd, &ctx.agent, owner_id.as_deref());
|
||||
let available: std::collections::HashSet<String> = crate::runner::available_tools(app, &agent, owner_user.as_ref()).iter().map(|t| t.name().to_string()).collect();
|
||||
let mut hits: Vec<(usize, String)> = crate::tools::builtin_tools()
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let name = t.name().to_lowercase();
|
||||
let desc = t.description().to_lowercase();
|
||||
let score: usize = words.iter().map(|w| if name.contains(w) { 3 } else if desc.contains(w) { 1 } else { 0 }).sum();
|
||||
let state = if available.contains(t.name()) {
|
||||
"available – call it directly".to_string()
|
||||
} else if agent.read_only && !t.read_only() {
|
||||
format!("exists, but not in the read-only mode \"{}\" – ask the user to switch to build mode", agent.name)
|
||||
} else {
|
||||
format!("exists, but not available in mode \"{}\" (or disabled in the settings)", agent.name)
|
||||
};
|
||||
(score, format!("- {}: {state}", t.name()))
|
||||
})
|
||||
.filter(|(s, _)| *s >= 2 || words.len() == 1 && *s >= 1)
|
||||
.collect();
|
||||
hits.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
if hits.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let list: Vec<String> = hits.into_iter().take(4).map(|(_, l)| l).collect();
|
||||
format!("Built-in tools (not MCP – call them directly by name, not via mcp_call):\n{}\n\n", list.join("\n"))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for McpSearch {
|
||||
fn name(&self) -> &str {
|
||||
@@ -602,10 +638,13 @@ impl Tool for McpSearch {
|
||||
.filter(|(s, _)| *s > 0 || words.is_empty())
|
||||
.collect();
|
||||
scored.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
// Models also look here for built-in tools (e.g. generate_3d): say that they exist,
|
||||
// whether this mode has them, and that they are called directly.
|
||||
let builtin = if server.is_none() { builtin_matches(ctx, &words) } else { String::new() };
|
||||
if scored.is_empty() {
|
||||
return Ok(ToolOutput::text("No matching tools. Try other keywords or another server."));
|
||||
return Ok(ToolOutput::text(if builtin.is_empty() { "No matching tools. Try other keywords or another server.".to_string() } else { builtin }));
|
||||
}
|
||||
let mut out = String::new();
|
||||
let mut out = builtin;
|
||||
for (_, t) in scored.iter().take(8) {
|
||||
let desc: String = t.info.description.chars().take(300).collect();
|
||||
out.push_str(&format!("## {}\n{}\nInput schema: {}\n\n", t.full_name, desc, t.info.input_schema));
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
//! CodeCraft's tools for the Claude Code CLI, as an MCP server (streamable HTTP, JSON answers).
|
||||
//!
|
||||
//! The CLI only knows its own tools. For every run the server registers a secret token and
|
||||
//! passes `--mcp-config` with `http://127.0.0.1:<port>/api/mcp-bridge/<token>`; the CLI then
|
||||
//! lists and calls the tools like any MCP tool (`mcp__codecraft__<name>`). The token is the
|
||||
//! credential (the route is public) and binds the calls to the chat that started the run.
|
||||
//! Permissions are asked by the CLI through the usual `can_use_tool` request, so the approval
|
||||
//! cards, rules and project approvals work as for the CLI's own tools.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::tools::{Tool, ToolCtx, ToolOutput};
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub const SERVER: &str = "codecraft";
|
||||
/// Prefix the CLI gives our tools.
|
||||
pub const PREFIX: &str = "mcp__codecraft__";
|
||||
|
||||
/// Our tools the CLI brings itself (same job): not offered twice.
|
||||
const CLI_HAS: &[&str] = &["read", "write", "edit", "list", "glob", "grep", "bash", "bash_output", "kill_shell", "web_fetch", "web_search", "todo_write", "task", "change_directory"];
|
||||
|
||||
static TOKENS: LazyLock<Mutex<HashMap<String, String>>> = LazyLock::new(Default::default);
|
||||
|
||||
/// A registered run; the token stops working when this is dropped.
|
||||
pub struct Registration {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
impl Drop for Registration {
|
||||
fn drop(&mut self) {
|
||||
TOKENS.lock().unwrap().remove(&self.token);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(session_id: &str) -> Registration {
|
||||
let token = format!("{}{}", crate::types::new_id(), crate::types::new_id());
|
||||
TOKENS.lock().unwrap().insert(token.clone(), session_id.to_string());
|
||||
Registration { token }
|
||||
}
|
||||
|
||||
/// `--mcp-config` value for a run.
|
||||
pub fn config_json(app: &App, token: &str) -> String {
|
||||
let port = app.config().server.bind.rsplit(':').next().and_then(|p| p.parse::<u16>().ok()).unwrap_or(8787);
|
||||
json!({"mcpServers": {SERVER: {"type": "http", "url": format!("http://127.0.0.1:{port}/api/mcp-bridge/{token}")}}}).to_string()
|
||||
}
|
||||
|
||||
/// The tools the CLI gets for a chat: what the chat's own agent would have (mode, images,
|
||||
/// the server's MCP tools …) without the ones the CLI has itself.
|
||||
pub fn tools_for(app: &Arc<App>, session: &crate::types::Session) -> Vec<Arc<dyn Tool>> {
|
||||
let cwd = PathBuf::from(&session.cwd);
|
||||
let root = app.root_for(session.owner_id.as_deref(), &cwd);
|
||||
let agent = crate::prompts::find_agent_for(app, &root, &cwd, &session.agent, session.owner_id.as_deref());
|
||||
let owner = session.owner_id.as_deref().and_then(|id| app.store.user(id).ok().flatten());
|
||||
crate::runner::available_tools(app, &agent, owner.as_ref()).into_iter().filter(|t| !CLI_HAS.contains(&t.name())).collect()
|
||||
}
|
||||
|
||||
/// Short note for the system prompt: what the extra tools are called.
|
||||
pub fn prompt_section(tools: &[Arc<dyn Tool>]) -> Option<String> {
|
||||
if tools.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<String> = tools.iter().map(|t| format!("{PREFIX}{}", t.name())).collect();
|
||||
Some(format!(
|
||||
"\n# CodeCraft tools\nBesides your own tools you have the tools of the CodeCraft server (MCP server `{SERVER}`): {}. \
|
||||
Use them for what they do – e.g. image generation (generate_image), 3D models, OpenSCAD, scheduling automations, diagnostics, the browser. \
|
||||
If one is not in your tool list, load it with ToolSearch (query `select:<name>`).\n",
|
||||
names.join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
// --- protocol ----------------------------------------------------------------------------
|
||||
|
||||
fn tools_list(tools: &[Arc<dyn Tool>]) -> Value {
|
||||
json!({"tools": tools.iter().map(|t| json!({"name": t.name(), "description": t.description(), "inputSchema": t.schema()})).collect::<Vec<_>>()})
|
||||
}
|
||||
|
||||
fn call_result(res: anyhow::Result<ToolOutput>) -> Value {
|
||||
match res {
|
||||
Ok(out) => {
|
||||
let mut content = vec![json!({"type": "text", "text": out.content})];
|
||||
for img in out.images.iter().filter(|i| !i.data.is_empty()) {
|
||||
content.push(json!({"type": "image", "data": img.data, "mimeType": img.media_type}));
|
||||
}
|
||||
json!({"content": content, "isError": out.is_error})
|
||||
}
|
||||
Err(e) => json!({"content": [{"type": "text", "text": format!("Error: {e:#}")}], "isError": true}),
|
||||
}
|
||||
}
|
||||
|
||||
fn answer(id: &Value, result: Value) -> Response {
|
||||
Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response()
|
||||
}
|
||||
|
||||
fn failure(id: &Value, code: i64, message: &str) -> Response {
|
||||
Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})).into_response()
|
||||
}
|
||||
|
||||
pub async fn handle(State(app): State<Arc<App>>, Path(token): Path<String>, Json(req): Json<Value>) -> Response {
|
||||
let Some(session_id) = TOKENS.lock().unwrap().get(&token).cloned() else {
|
||||
return (StatusCode::NOT_FOUND, "unknown or finished run").into_response();
|
||||
};
|
||||
let id = req["id"].clone();
|
||||
let method = req["method"].as_str().unwrap_or("");
|
||||
// Notifications have no answer.
|
||||
if req.get("id").is_none() || method.starts_with("notifications/") {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
}
|
||||
match method {
|
||||
"initialize" => answer(
|
||||
&id,
|
||||
json!({
|
||||
"protocolVersion": req["params"]["protocolVersion"].as_str().unwrap_or("2025-03-26"),
|
||||
"capabilities": {"tools": {"listChanged": false}},
|
||||
"serverInfo": {"name": "codecraft", "version": env!("CARGO_PKG_VERSION")},
|
||||
}),
|
||||
),
|
||||
"ping" => answer(&id, json!({})),
|
||||
"tools/list" | "tools/call" => {
|
||||
let Ok(session) = app.session(&session_id) else { return failure(&id, -32000, "the chat is gone") };
|
||||
let tools = tools_for(&app, &session);
|
||||
if method == "tools/list" {
|
||||
return answer(&id, tools_list(&tools));
|
||||
}
|
||||
let name = req["params"]["name"].as_str().unwrap_or("");
|
||||
let Some(tool) = tools.iter().find(|t| t.name() == name).cloned() else {
|
||||
return failure(&id, -32602, &format!("unknown tool '{name}'"));
|
||||
};
|
||||
let cwd = PathBuf::from(&session.cwd);
|
||||
let agent = crate::prompts::find_agent_for(&app, &app.root_for(session.owner_id.as_deref(), &cwd), &cwd, &session.agent, session.owner_id.as_deref());
|
||||
let ctx = ToolCtx {
|
||||
app: app.clone(),
|
||||
session_id: session_id.clone(),
|
||||
call_id: crate::types::new_id(),
|
||||
cwd,
|
||||
cancel: CancellationToken::new(),
|
||||
agent: agent.name.clone(),
|
||||
roots: app.user_roots(session.owner_id.as_deref()),
|
||||
sandbox: crate::sandbox::spec_for(&app, session.owner_id.as_deref()),
|
||||
clean_room: session.clean_room(app.config().craft.clean_room) && agent.name == "craft",
|
||||
owner_id: None,
|
||||
};
|
||||
let input = req["params"]["arguments"].clone();
|
||||
let input = if input.is_null() { json!({}) } else { input };
|
||||
answer(&id, call_result(tool.run(input, &ctx).await))
|
||||
}
|
||||
_ => failure(&id, -32601, "method not found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::types::ImageData;
|
||||
|
||||
#[test]
|
||||
fn registration_lives_as_long_as_the_run() {
|
||||
let r = register("s1");
|
||||
assert_eq!(TOKENS.lock().unwrap().get(&r.token).map(String::as_str), Some("s1"));
|
||||
let t = r.token.clone();
|
||||
drop(r);
|
||||
assert!(!TOKENS.lock().unwrap().contains_key(&t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_results_carry_text_and_images() {
|
||||
let out = ToolOutput {
|
||||
content: "saved".into(),
|
||||
images: vec![ImageData { media_type: "image/png".into(), data: "QUJD".into(), blob: None, size: None }, ImageData { media_type: "image/png".into(), data: String::new(), blob: Some("x".into()), size: None }],
|
||||
..Default::default()
|
||||
};
|
||||
let v = call_result(Ok(out));
|
||||
assert_eq!(v["isError"], false);
|
||||
let c = v["content"].as_array().unwrap();
|
||||
assert_eq!(c.len(), 2); // the image without data is left out
|
||||
assert_eq!((c[1]["type"].as_str(), c[1]["mimeType"].as_str()), (Some("image"), Some("image/png")));
|
||||
assert_eq!(call_result(Err(anyhow::anyhow!("boom")))["isError"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_builtins_are_not_offered_twice() {
|
||||
let all = crate::tools::builtin_tools();
|
||||
let ours: Vec<&str> = all.iter().map(|t| t.name()).filter(|n| !CLI_HAS.contains(n)).collect();
|
||||
for n in ["generate_image", "generate_3d", "openscad", "browser", "schedule", "remember", "diagnostics", "ask_user", "skill"] {
|
||||
assert!(ours.contains(&n), "{n} missing");
|
||||
}
|
||||
assert!(!ours.contains(&"read") && !ours.contains(&"bash"));
|
||||
let list = tools_list(&all.into_iter().filter(|t| t.name() == "remember").collect::<Vec<_>>());
|
||||
assert!(list["tools"][0]["inputSchema"].is_object());
|
||||
}
|
||||
|
||||
/// The whole protocol against a real App: initialize, list, call, unknown token.
|
||||
#[tokio::test]
|
||||
async fn protocol_roundtrip_with_a_real_app() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-bridge-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("ws")).unwrap();
|
||||
let toml = crate::config::EXAMPLE_CONFIG.lines().map(|l| {
|
||||
if l.starts_with("workspace = ") { format!("workspace = \"{}\"", dir.join("ws").display()) }
|
||||
else if l.starts_with("data_dir = ") { format!("data_dir = \"{}\"", dir.join("data").display()) }
|
||||
else { l.to_string() }
|
||||
}).collect::<Vec<_>>().join("\n");
|
||||
let cfg = crate::config::Config::parse(&toml).unwrap();
|
||||
let app = App::new(dir.join("config.toml"), cfg).await.unwrap();
|
||||
let now = crate::types::now_ms();
|
||||
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(),
|
||||
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, skills: Vec::new(),
|
||||
};
|
||||
let session = app.save_session(session).unwrap();
|
||||
let reg = register(&session.id);
|
||||
let rpc = |req: Value| {
|
||||
let app = app.clone();
|
||||
let token = reg.token.clone();
|
||||
async move {
|
||||
let resp = handle(State(app), Path(token), Json(req)).await;
|
||||
let status = resp.status();
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap();
|
||||
(status, serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null))
|
||||
}
|
||||
};
|
||||
let (st, init) = rpc(json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}})).await;
|
||||
assert_eq!(st, StatusCode::OK);
|
||||
assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
|
||||
assert!(init["result"]["capabilities"]["tools"].is_object());
|
||||
let (st, _) = rpc(json!({"jsonrpc": "2.0", "method": "notifications/initialized"})).await;
|
||||
assert_eq!(st, StatusCode::ACCEPTED);
|
||||
let (_, list) = rpc(json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})).await;
|
||||
let names: Vec<&str> = list["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
assert!(names.contains(&"remember") && names.contains(&"openscad") && names.contains(&"browser"), "{names:?}");
|
||||
assert!(!names.contains(&"read") && !names.contains(&"bash"), "{names:?}");
|
||||
// A real tool call: `remember` writes the project memory.
|
||||
let (_, call) = rpc(json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "remember", "arguments": {"note": "bridge works"}}})).await;
|
||||
assert_eq!(call["result"]["isError"], false, "{call}");
|
||||
let mem = std::fs::read_to_string(dir.join("ws/.codecraft/memory.md")).unwrap_or_default();
|
||||
assert!(mem.contains("bridge works"), "{mem}");
|
||||
let (_, bad) = rpc(json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "bash", "arguments": {"command": "id"}}})).await;
|
||||
assert!(bad["error"].is_object());
|
||||
// A finished run's token is dead.
|
||||
let token = reg.token.clone();
|
||||
drop(reg);
|
||||
let resp = handle(State(app.clone()), Path(token), Json(json!({"jsonrpc": "2.0", "id": 5, "method": "ping"}))).await;
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq)]
|
||||
pub struct MediaItem {
|
||||
/// "image", "video" or "audio".
|
||||
/// "image", "video", "audio" or "model" (3D).
|
||||
pub kind: &'static str,
|
||||
pub url: String,
|
||||
pub name: String,
|
||||
@@ -21,11 +21,17 @@ pub struct MediaItem {
|
||||
/// Message to jump to (only for messages of the chat itself, not of subagents).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message_id: Option<String>,
|
||||
/// 3D models: absolute path (opened in the 3D view) and a preview image.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preview: Option<String>,
|
||||
}
|
||||
|
||||
const IMAGE: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "avif"];
|
||||
const VIDEO: &[&str] = &["mp4", "webm", "mov", "m4v", "ogv"];
|
||||
const AUDIO: &[&str] = &["mp3", "wav", "ogg", "oga", "m4a", "flac", "opus", "aac"];
|
||||
const MODEL: &[&str] = &["glb", "gltf", "stl", "3mf", "obj", "step", "stp"];
|
||||
|
||||
/// Kind of a media file by its extension.
|
||||
pub fn kind_of(path: &str) -> Option<&'static str> {
|
||||
@@ -36,6 +42,8 @@ pub fn kind_of(path: &str) -> Option<&'static str> {
|
||||
Some("video")
|
||||
} else if AUDIO.contains(&ext.as_str()) {
|
||||
Some("audio")
|
||||
} else if MODEL.contains(&ext.as_str()) {
|
||||
Some("model")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -118,7 +126,7 @@ pub fn collect(app: &App, session_id: &str) -> anyhow::Result<Vec<MediaItem>> {
|
||||
// Generated images whose tool result was not found (e.g. removed by a rewind).
|
||||
for img in app.store.images_of_sessions(&sessions)? {
|
||||
push(
|
||||
MediaItem { kind: "image", url: format!("/api/images/{}/file", img.id), name: file_name(&img.path), source: "generated", created_at: img.created_at, message_id: None },
|
||||
MediaItem { kind: "image", url: format!("/api/images/{}/file", img.id), name: file_name(&img.path), source: "generated", created_at: img.created_at, message_id: None, path: None, preview: None },
|
||||
&mut out,
|
||||
);
|
||||
}
|
||||
@@ -133,6 +141,10 @@ pub fn collect(app: &App, session_id: &str) -> anyhow::Result<Vec<MediaItem>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn raw_url(p: &Path) -> String {
|
||||
format!("/api/files/raw?path={}", encode(&p.display().to_string()))
|
||||
}
|
||||
|
||||
fn file_name(p: &str) -> String {
|
||||
Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or(p).to_string()
|
||||
}
|
||||
@@ -144,25 +156,33 @@ fn collect_message(m: &Message, cwd: &Path, own: bool, call_msg: Option<&str>, a
|
||||
let file = |p: &str, source: &'static str| -> Option<MediaItem> {
|
||||
let kind = kind_of(p)?;
|
||||
let abs = resolve(p, cwd);
|
||||
abs.is_file().then(|| MediaItem { kind, url: format!("/api/files/raw?path={}", encode(&abs.display().to_string())), name: file_name(p), source, created_at: at, message_id: mid.clone() })
|
||||
abs.is_file().then(|| MediaItem { kind, url: raw_url(&abs), name: file_name(p), source, created_at: at, message_id: mid.clone(), path: Some(abs.display().to_string()), preview: None })
|
||||
};
|
||||
for p in &m.parts {
|
||||
match p {
|
||||
Part::Image { image } if m.role == Role::User => {
|
||||
if let Some(h) = &image.blob {
|
||||
add(MediaItem { kind: kind_of_mime(&image.media_type), url: format!("/api/blobs/{h}"), name: "image".into(), source: "upload", created_at: at, message_id: mid.clone() });
|
||||
add(MediaItem { kind: kind_of_mime(&image.media_type), url: format!("/api/blobs/{h}"), name: "image".into(), source: "upload", created_at: at, message_id: mid.clone(), path: None, preview: None });
|
||||
}
|
||||
}
|
||||
// generate_3d: the model with its preview (not the preview as a separate image).
|
||||
Part::ToolResult { meta: Some(meta), .. } if meta["model_file"].is_string() => {
|
||||
let file = PathBuf::from(meta["model_file"].as_str().unwrap_or_default());
|
||||
if file.is_file() {
|
||||
let preview = meta["preview"].as_str().map(PathBuf::from).filter(|p| p.is_file()).map(|p| raw_url(&p));
|
||||
add(MediaItem { kind: "model", url: raw_url(&file), name: file_name(&file.display().to_string()), source: "generated", created_at: at, message_id: result_mid.clone(), path: Some(file.display().to_string()), preview });
|
||||
}
|
||||
}
|
||||
Part::ToolResult { images, meta, .. } => {
|
||||
let ids: Vec<&str> = meta.as_ref().and_then(|v| v["image_ids"].as_array()).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
if !ids.is_empty() {
|
||||
for id in ids {
|
||||
add(MediaItem { kind: "image", url: format!("/api/images/{id}/file"), name: "image".into(), source: "generated", created_at: at, message_id: result_mid.clone() });
|
||||
add(MediaItem { kind: "image", url: format!("/api/images/{id}/file"), name: "image".into(), source: "generated", created_at: at, message_id: result_mid.clone(), path: None, preview: None });
|
||||
}
|
||||
} else {
|
||||
for img in images {
|
||||
if let Some(h) = &img.blob {
|
||||
add(MediaItem { kind: kind_of_mime(&img.media_type), url: format!("/api/blobs/{h}"), name: "screenshot".into(), source: "tool", created_at: at, message_id: result_mid.clone() });
|
||||
add(MediaItem { kind: kind_of_mime(&img.media_type), url: format!("/api/blobs/{h}"), name: "screenshot".into(), source: "tool", created_at: at, message_id: result_mid.clone(), path: None, preview: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
//! 3D models with fal.ai (generate_3d): from an image (plus optional back/left/right
|
||||
//! views), from a text prompt, or from an image steered by text – the 3D models take no
|
||||
//! text with an image, so the image is first refined with the prompt (image edit model)
|
||||
//! and then converted. The result is a GLB file (plus a preview image) in the project.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::config::expand_env;
|
||||
use crate::store::UsageRecord;
|
||||
use crate::tools::{Tool, ToolCtx, ToolOutput};
|
||||
use crate::types::now_ms;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use async_trait::async_trait;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
const STYLES: &[&str] = &["textured", "geometry", "lowpoly"];
|
||||
|
||||
/// Request body for a fal.ai 3D endpoint (the families name their fields differently).
|
||||
fn request_body(model: &str, prompt: Option<&str>, images: &Views, style: &str, pbr: bool, faces: Option<u64>) -> Value {
|
||||
let mut b = json!({});
|
||||
if model.contains("tripo") {
|
||||
// Tripo: image_url / prompt, texture + pbr flags, face_limit.
|
||||
if let Some(front) = &images.front {
|
||||
b["image_url"] = json!(front);
|
||||
}
|
||||
if let Some(p) = prompt {
|
||||
b["prompt"] = json!(p);
|
||||
}
|
||||
b["texture"] = json!(style != "geometry");
|
||||
b["pbr"] = json!(style != "geometry" && pbr);
|
||||
if let Some(f) = faces {
|
||||
b["face_limit"] = json!(f);
|
||||
}
|
||||
if style == "lowpoly" {
|
||||
b["face_limit"] = json!(faces.unwrap_or(20_000));
|
||||
}
|
||||
} else if model.contains("trellis") {
|
||||
if let Some(front) = &images.front {
|
||||
b["image_url"] = json!(front);
|
||||
}
|
||||
} else {
|
||||
// Hunyuan3D: front + optional views, generate_type, enable_pbr, face_count.
|
||||
if let Some(front) = &images.front {
|
||||
b["input_image_url"] = json!(front);
|
||||
}
|
||||
for (k, v) in [("back_image_url", &images.back), ("left_image_url", &images.left), ("right_image_url", &images.right)] {
|
||||
if let Some(v) = v {
|
||||
b[k] = json!(v);
|
||||
}
|
||||
}
|
||||
if let Some(p) = prompt {
|
||||
b["prompt"] = json!(p);
|
||||
}
|
||||
b["generate_type"] = json!(match style {
|
||||
"geometry" => "Geometry",
|
||||
"lowpoly" => "LowPoly",
|
||||
_ => "Normal",
|
||||
});
|
||||
b["enable_pbr"] = json!(style != "geometry" && pbr);
|
||||
if let Some(f) = faces {
|
||||
b["face_count"] = json!(f.clamp(40_000, 1_500_000));
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Data URIs of the views (front required for image-to-3D).
|
||||
#[derive(Default)]
|
||||
struct Views {
|
||||
front: Option<String>,
|
||||
back: Option<String>,
|
||||
left: Option<String>,
|
||||
right: Option<String>,
|
||||
}
|
||||
|
||||
impl Views {
|
||||
fn extra(&self) -> usize {
|
||||
[&self.back, &self.left, &self.right].iter().filter(|v| v.is_some()).count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Price of one generation (USD) by the published fal.ai prices; a price configured for
|
||||
/// the model under [images] models wins.
|
||||
fn price(app: &App, model: &str, style: &str, pbr: bool, multiview: bool, faces: bool) -> f64 {
|
||||
if let Some(p) = app.config().images.models.iter().find(|m| m.id == model).and_then(|m| m.price) {
|
||||
return p;
|
||||
}
|
||||
if model.contains("tripo") {
|
||||
return match style {
|
||||
"geometry" => 0.20,
|
||||
_ => 0.30,
|
||||
};
|
||||
}
|
||||
if model.contains("hunyuan") {
|
||||
let base = match style {
|
||||
"geometry" => 0.225,
|
||||
"lowpoly" => 0.45,
|
||||
_ => 0.375,
|
||||
};
|
||||
let extras = [pbr && style != "geometry", multiview, faces].iter().filter(|x| **x).count() as f64;
|
||||
return base + 0.15 * extras;
|
||||
}
|
||||
0.0
|
||||
}
|
||||
|
||||
/// URL of the queue API for fal.ai (requests that take minutes).
|
||||
fn queue_base(app: &App) -> String {
|
||||
let base = expand_env(&app.config().images.base_url);
|
||||
if base.contains("://fal.run") { "https://queue.fal.run".into() } else { base.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
/// Submit to fal.ai's queue and wait for the result, reporting progress.
|
||||
async fn run_queued(app: &App, ctx: &ToolCtx, model: &str, body: &Value) -> Result<Value> {
|
||||
let key = expand_env(&app.config().images.api_key);
|
||||
let client = crate::provider::http_client();
|
||||
let submit = client
|
||||
.post(format!("{}/{}", queue_base(app), model.trim_matches('/')))
|
||||
.header("Authorization", format!("Key {key}"))
|
||||
.timeout(Duration::from_secs(120))
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.context("fal.ai request failed")?;
|
||||
if !submit.status().is_success() {
|
||||
return Err(crate::provider::http_error(submit).await);
|
||||
}
|
||||
let sub: Value = submit.json().await?;
|
||||
let status_url = sub["status_url"].as_str().context("fal.ai: no status_url")?.to_string();
|
||||
let response_url = sub["response_url"].as_str().context("fal.ai: no response_url")?.to_string();
|
||||
let started = std::time::Instant::now();
|
||||
loop {
|
||||
if ctx.cancel.is_cancelled() {
|
||||
bail!("cancelled");
|
||||
}
|
||||
if started.elapsed() > Duration::from_secs(20 * 60) {
|
||||
bail!("fal.ai did not finish within 20 minutes");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(4)).await;
|
||||
let st: Value = client.get(&status_url).header("Authorization", format!("Key {key}")).timeout(Duration::from_secs(30)).send().await?.json().await?;
|
||||
match st["status"].as_str().unwrap_or("") {
|
||||
"COMPLETED" => break,
|
||||
"IN_QUEUE" => ctx.progress(format!("waiting in fal.ai's queue (position {}) – {} s", st["queue_position"].as_u64().unwrap_or(0), started.elapsed().as_secs())),
|
||||
"IN_PROGRESS" => ctx.progress(format!("generating the 3D model – {} s", started.elapsed().as_secs())),
|
||||
other => bail!("fal.ai: unexpected status {other}: {st}"),
|
||||
}
|
||||
}
|
||||
let resp = client.get(&response_url).header("Authorization", format!("Key {key}")).timeout(Duration::from_secs(60)).send().await?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(crate::provider::http_error(resp).await);
|
||||
}
|
||||
Ok(resp.json().await?)
|
||||
}
|
||||
|
||||
/// URL of the mesh and of the preview image in a fal.ai 3D result.
|
||||
fn result_urls(out: &Value) -> (Option<String>, Option<String>) {
|
||||
let s = |v: &Value| v.as_str().map(String::from);
|
||||
let mesh = s(&out["model_glb"]["url"])
|
||||
.or_else(|| s(&out["model_mesh"]["url"]))
|
||||
.or_else(|| s(&out["model_urls"]["glb"]["url"]))
|
||||
.or_else(|| s(&out["model_file"]["url"]))
|
||||
.or_else(|| s(&out["mesh"]["url"]));
|
||||
let thumb = s(&out["thumbnail"]["url"]).or_else(|| s(&out["rendered_image"]["url"]));
|
||||
(mesh, thumb)
|
||||
}
|
||||
|
||||
/// File extension of a downloaded mesh: from the URL, else GLB (what the models return).
|
||||
fn ext_of(url: &str) -> &'static str {
|
||||
let path = url.split(['?', '#']).next().unwrap_or(url).to_ascii_lowercase();
|
||||
["glb", "gltf", "fbx", "obj", "usdz", "stl"].into_iter().find(|e| path.ends_with(&format!(".{e}"))).unwrap_or("glb")
|
||||
}
|
||||
|
||||
/// An image the user attached to the chat ("attached" = the first image of the latest
|
||||
/// message with images, "attached:2" = its second), written to `dir` so it can be used
|
||||
/// like a project file.
|
||||
async fn attached_image(app: &App, session_id: &str, spec: &str, dir: &Path) -> Result<PathBuf> {
|
||||
let n: usize = spec.strip_prefix("attached").map(|r| r.trim_start_matches(':').trim()).filter(|r| !r.is_empty()).map(|r| r.parse()).transpose().map_err(|_| anyhow!("use \"attached\" or \"attached:2\""))?.unwrap_or(1);
|
||||
let root = app.root_session_id(session_id);
|
||||
let messages = app.store.messages(&root)?;
|
||||
let images: Vec<crate::types::ImageData> = messages
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|m| m.role == crate::types::Role::User)
|
||||
.map(|m| m.parts.iter().filter_map(|p| if let crate::types::Part::Image { image } = p { Some(image.clone()) } else { None }).collect::<Vec<_>>())
|
||||
.find(|imgs| !imgs.is_empty())
|
||||
.ok_or_else(|| anyhow!("no image attached to this chat"))?;
|
||||
let img = images.get(n.saturating_sub(1)).ok_or_else(|| anyhow!("the latest message has only {} image(s)", images.len()))?;
|
||||
let (mime, bytes) = match &img.blob {
|
||||
Some(h) => app.store.blob(h)?.ok_or_else(|| anyhow!("attached image not found"))?,
|
||||
None => (img.media_type.clone(), base64::Engine::decode(&base64::engine::general_purpose::STANDARD, img.data.as_bytes())?),
|
||||
};
|
||||
let ext = match mime.as_str() {
|
||||
"image/jpeg" => "jpg",
|
||||
"image/webp" => "webp",
|
||||
_ => "png",
|
||||
};
|
||||
tokio::fs::create_dir_all(dir).await?;
|
||||
let path = dir.join(format!("{}-attached-{n}.{ext}", chrono::Local::now().format("%Y%m%d-%H%M%S")));
|
||||
tokio::fs::write(&path, &bytes).await?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// An image argument: a project file, or an image attached to the chat.
|
||||
async fn image_arg(ctx: &ToolCtx, spec: &str, dir: &Path) -> Result<PathBuf> {
|
||||
if spec.starts_with("attached") {
|
||||
attached_image(&ctx.app, &ctx.session_id, spec, dir).await
|
||||
} else {
|
||||
ctx.resolve(spec)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Generate3d;
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for Generate3d {
|
||||
fn name(&self) -> &str {
|
||||
"generate_3d"
|
||||
}
|
||||
fn description(&self) -> String {
|
||||
"Generate a 3D model (GLB) with fal.ai and save it in the project – from an image of the \
|
||||
object (a file, or image: \"attached\" for an image the user pasted into the chat; best: a \
|
||||
clean front view; optional back/left/right views improve the shape), from a \
|
||||
text prompt alone, or from an image steered by a prompt (the image is refined with the \
|
||||
prompt first, then converted). style: \"textured\" (default), \"geometry\" (untextured – for \
|
||||
3D printing), \"lowpoly\" (games). Takes one to several minutes and costs money (about \
|
||||
$0.25–0.75): generate only what the user asked for. The user can open the model in the 3D \
|
||||
view of the file manager."
|
||||
.into()
|
||||
}
|
||||
fn schema(&self) -> Value {
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "description": "What the model should be (English). With an image: how to change/clean it up before the conversion."},
|
||||
"image": {"type": "string", "description": "Image of the object (front view): a file path, or \"attached\" for the image the user attached to the chat (\"attached:2\" = the second of that message)"},
|
||||
"back": {"type": "string", "description": "Optional back view image (path or \"attached:N\")"},
|
||||
"left": {"type": "string", "description": "Optional left view image (path or \"attached:N\")"},
|
||||
"right": {"type": "string", "description": "Optional right view image (path or \"attached:N\")"},
|
||||
"style": {"type": "string", "enum": STYLES},
|
||||
"pbr": {"type": "boolean", "description": "PBR materials (metal/roughness), textured models only; costs extra"},
|
||||
"face_count": {"type": "integer", "description": "Target number of faces (optional)"},
|
||||
"directory": {"type": "string", "description": "Target directory relative to the working directory (default: <images.output_dir>/3d)"},
|
||||
"model": {"type": "string", "description": "fal.ai model id – only if the user asks for a specific one"}
|
||||
}
|
||||
})
|
||||
}
|
||||
fn title(&self, input: &Value) -> String {
|
||||
let what = input["prompt"].as_str().map(|p| p.chars().take(70).collect::<String>()).or_else(|| input["image"].as_str().map(String::from)).unwrap_or_default();
|
||||
format!("3D model: {what}")
|
||||
}
|
||||
fn read_only(&self) -> bool {
|
||||
false
|
||||
}
|
||||
async fn run(&self, input: Value, ctx: &ToolCtx) -> Result<ToolOutput> {
|
||||
let app = ctx.app.clone();
|
||||
let cfg = app.config();
|
||||
if !cfg.images.enabled {
|
||||
bail!("fal.ai is disabled – enable image generation in the settings");
|
||||
}
|
||||
if expand_env(&cfg.images.api_key).is_empty() {
|
||||
bail!("no fal.ai API key configured");
|
||||
}
|
||||
let owner = app.session(&ctx.session_id).ok().and_then(|s| s.owner_id);
|
||||
crate::budget::check(&app, "fal", owner.as_deref())?;
|
||||
let prompt = input["prompt"].as_str().map(str::trim).filter(|p| !p.is_empty()).map(String::from);
|
||||
let dir_arg = input["directory"].as_str().map(String::from).unwrap_or_else(|| format!("{}/3d", cfg.images.output_dir.trim_end_matches('/')));
|
||||
let dir = ctx.resolve(&dir_arg)?;
|
||||
let image = match input["image"].as_str() {
|
||||
Some(spec) => Some(image_arg(ctx, spec, &dir).await?),
|
||||
None => None,
|
||||
};
|
||||
if prompt.is_none() && image.is_none() {
|
||||
bail!("give an image of the object, a prompt, or both");
|
||||
}
|
||||
let style = input["style"].as_str().filter(|s| STYLES.contains(s)).unwrap_or("textured");
|
||||
let pbr = input["pbr"].as_bool().unwrap_or(false);
|
||||
let faces = input["face_count"].as_u64();
|
||||
let mut notes = Vec::new();
|
||||
|
||||
// Image + prompt: refine the image with the prompt first (3D models take no text).
|
||||
let mut front = image.clone();
|
||||
if let (Some(img), Some(p)) = (&image, &prompt) {
|
||||
ctx.progress("refining the image with the prompt");
|
||||
let edit = crate::images::choose_model(&app, "final", Some("illustration"), true);
|
||||
if edit.reference_param.is_some() {
|
||||
let records = crate::images::generate(
|
||||
&app,
|
||||
crate::images::GenerateRequest {
|
||||
prompt: format!(
|
||||
"{p}. Show exactly one object, complete and centered, as a clean product shot: plain light neutral background, soft even lighting, no text, no other objects."
|
||||
),
|
||||
model: Some(edit.id.clone()),
|
||||
size: None,
|
||||
count: 1,
|
||||
dir: dir.clone(),
|
||||
user_id: owner.clone(),
|
||||
session_id: Some(ctx.session_id.clone()),
|
||||
references: vec![img.clone()],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| anyhow!("refining the image failed: {e:#}"))?;
|
||||
if let Some(r) = records.first() {
|
||||
front = Some(PathBuf::from(&r.path));
|
||||
notes.push(format!("Refined image: {}", rel(&r.path, &ctx.cwd)));
|
||||
}
|
||||
} else {
|
||||
notes.push("No image edit model configured – the prompt was not applied to the image.".into());
|
||||
}
|
||||
}
|
||||
|
||||
let mut views = Views::default();
|
||||
if let Some(f) = &front {
|
||||
views.front = crate::images::reference_uris(std::slice::from_ref(f)).await?.pop();
|
||||
for (field, slot) in [("back", &mut views.back), ("left", &mut views.left), ("right", &mut views.right)] {
|
||||
if let Some(p) = input[field].as_str() {
|
||||
*slot = crate::images::reference_uris(&[image_arg(ctx, p, &dir).await?]).await?.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
let model = input["model"].as_str().filter(|m| !m.is_empty()).map(String::from).unwrap_or_else(|| if front.is_some() { cfg.images.model_3d.clone() } else { cfg.images.model_3d_text.clone() });
|
||||
if views.extra() > 0 && !model.contains("hunyuan") {
|
||||
notes.push("This model takes only the front view; the other views were not used.".into());
|
||||
}
|
||||
let text = if front.is_none() { prompt.as_deref() } else { None };
|
||||
let body = request_body(&model, text, &views, style, pbr, faces);
|
||||
ctx.progress(format!("sending to {model}"));
|
||||
let out = run_queued(&app, ctx, &model, &body).await?;
|
||||
let (mesh_url, thumb_url) = result_urls(&out);
|
||||
let mesh_url = mesh_url.ok_or_else(|| anyhow!("fal.ai returned no 3D model: {}", out.to_string().chars().take(300).collect::<String>()))?;
|
||||
|
||||
tokio::fs::create_dir_all(&dir).await?;
|
||||
let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S");
|
||||
// Named after the prompt, else the image (without a time stamp it already carries).
|
||||
let stem = image.as_ref().and_then(|p| p.file_stem()).and_then(|s| s.to_str()).unwrap_or("model");
|
||||
let stem = if stem.len() > 16 && stem.as_bytes()[8] == b'-' && stem[..8].bytes().all(|b| b.is_ascii_digit()) { &stem[16..] } else { stem };
|
||||
let base = crate::images::slug(prompt.as_deref().unwrap_or(stem).trim_start_matches('-'));
|
||||
let (bytes, _) = crate::images::download(&mesh_url).await?;
|
||||
let mesh_path = dir.join(format!("{stamp}-{base}.{}", ext_of(&mesh_url)));
|
||||
tokio::fs::write(&mesh_path, &bytes).await?;
|
||||
let mut thumb_path = None;
|
||||
if let Some(t) = thumb_url {
|
||||
if let Ok((tb, _)) = crate::images::download(&t).await {
|
||||
let p = dir.join(format!("{stamp}-{base}-preview.png"));
|
||||
if tokio::fs::write(&p, &tb).await.is_ok() {
|
||||
thumb_path = Some(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cost into the statistics (provider "fal", like images).
|
||||
let cost = price(&app, &model, style, pbr, views.extra() > 0 && model.contains("hunyuan"), faces.is_some());
|
||||
let session = ctx.session_id.clone();
|
||||
let _ = app.store.add_usage(&UsageRecord {
|
||||
ts: now_ms(),
|
||||
session_id: session.clone(),
|
||||
root_session_id: app.root_session_id(&session),
|
||||
provider: "fal".into(),
|
||||
model: model.clone(),
|
||||
agent: "3d".into(),
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
ttft_ms: 0,
|
||||
duration_ms: 0,
|
||||
cost,
|
||||
error: false,
|
||||
user_id: owner,
|
||||
allowance: None,
|
||||
});
|
||||
|
||||
let mesh_rel = rel(&mesh_path.display().to_string(), &ctx.cwd);
|
||||
let mut text = format!("3D model ({model}, {style}{}): {mesh_rel} ({} KB)", if pbr && style != "geometry" { ", PBR" } else { "" }, bytes.len() / 1024);
|
||||
if let Some(t) = &thumb_path {
|
||||
text.push_str(&format!("\nPreview: {}", rel(&t.display().to_string(), &ctx.cwd)));
|
||||
}
|
||||
if cost > 0.0 {
|
||||
text.push_str(&format!("\nCost: about ${cost:.2}"));
|
||||
}
|
||||
for n in ¬es {
|
||||
text.push_str(&format!("\n{n}"));
|
||||
}
|
||||
text.push_str("\nThe user can open the model in the 3D view of the file manager.");
|
||||
let images = thumb_path.as_deref().and_then(crate::images::preview_for_model).into_iter().collect();
|
||||
Ok(ToolOutput {
|
||||
content: text,
|
||||
images,
|
||||
meta: Some(json!({
|
||||
"model_file": mesh_path.display().to_string(),
|
||||
"preview": thumb_path.map(|p| p.display().to_string()),
|
||||
})),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn rel(path: &str, cwd: &Path) -> String {
|
||||
Path::new(path).strip_prefix(cwd).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bodies_per_model_family() {
|
||||
let views = Views { front: Some("data:a".into()), back: Some("data:b".into()), ..Default::default() };
|
||||
let h = request_body("fal-ai/hunyuan3d-v3/image-to-3d", None, &views, "geometry", true, Some(10));
|
||||
assert_eq!(h["input_image_url"], "data:a");
|
||||
assert_eq!(h["back_image_url"], "data:b");
|
||||
assert_eq!(h["generate_type"], "Geometry");
|
||||
assert_eq!(h["enable_pbr"], false);
|
||||
assert_eq!(h["face_count"], 40_000);
|
||||
let t = request_body("tripo3d/h3.1/image-to-3d", None, &views, "textured", true, None);
|
||||
assert_eq!((t["image_url"].as_str(), t["texture"].as_bool(), t["pbr"].as_bool()), (Some("data:a"), Some(true), Some(true)));
|
||||
let txt = request_body("fal-ai/hunyuan3d-v3/text-to-3d", Some("a chair"), &Views::default(), "textured", false, None);
|
||||
assert_eq!((txt["prompt"].as_str(), txt["generate_type"].as_str()), (Some("a chair"), Some("Normal")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_urls_of_the_families() {
|
||||
let h = json!({"model_glb": {"url": "https://x/m.glb"}, "thumbnail": {"url": "https://x/t.png"}});
|
||||
assert_eq!(result_urls(&h), (Some("https://x/m.glb".into()), Some("https://x/t.png".into())));
|
||||
let t = json!({"model_mesh": {"url": "https://x/m.glb"}, "rendered_image": {"url": "https://x/r.webp"}});
|
||||
assert_eq!(result_urls(&t).1.as_deref(), Some("https://x/r.webp"));
|
||||
assert_eq!(ext_of("https://x/a.FBX?sig=1"), "fbx");
|
||||
assert_eq!(ext_of("https://x/blob"), "glb");
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ pub struct Agent {
|
||||
pub max_parallel: Option<usize>,
|
||||
/// Review loop after each turn (None/0 rounds = off).
|
||||
pub refine: Option<crate::config::RefineConfig>,
|
||||
/// binary_info and decompile available (besides craft).
|
||||
pub reverse: bool,
|
||||
/// Source file of Markdown agents.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
@@ -43,12 +45,12 @@ pub use codecraft_core::prompts::*;
|
||||
pub fn builtin_agents(clean_room: bool) -> Vec<Agent> {
|
||||
let craft = craft_prompt(clean_room);
|
||||
vec![
|
||||
Agent { name: "build".into(), description: "Full access: implement, edit, run".into(), mode: "primary".into(), prompt: BUILD_PROMPT.into(), tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "plan".into(), description: "Read-only: analyse and propose a plan".into(), mode: "primary".into(), prompt: PLAN_PROMPT.into(), tools: None, read_only: true, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "chat".into(), description: "Just talk: answers, explanations, web search – no files or shell".into(), mode: "primary".into(), prompt: CHAT_PROMPT.into(), tools: Some(vec!["web_search".into(), "web_fetch".into()]), read_only: true, style: "chat".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "craft".into(), description: "Study a target, build your own version, check and refine".into(), mode: "primary".into(), prompt: craft, tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "general".into(), description: "General-purpose subagent for multi-step tasks".into(), mode: "subagent".into(), prompt: GENERAL_PROMPT.into(), tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "explore".into(), description: "Read-only subagent for fast codebase searches".into(), mode: "subagent".into(), prompt: EXPLORE_PROMPT.into(), tools: None, read_only: true, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "build".into(), description: "Full access: implement, edit, run".into(), mode: "primary".into(), prompt: BUILD_PROMPT.into(), tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, reverse: false, path: None },
|
||||
Agent { name: "plan".into(), description: "Read-only: analyse and propose a plan".into(), mode: "primary".into(), prompt: PLAN_PROMPT.into(), tools: None, read_only: true, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, reverse: false, path: None },
|
||||
Agent { name: "chat".into(), description: "Just talk: answers, explanations, web search – no files or shell".into(), mode: "primary".into(), prompt: CHAT_PROMPT.into(), tools: Some(vec!["web_search".into(), "web_fetch".into()]), read_only: true, style: "chat".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, reverse: false, path: None },
|
||||
Agent { name: "craft".into(), description: "Study a target, build your own version, check and refine".into(), mode: "primary".into(), prompt: craft, tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, reverse: false, path: None },
|
||||
Agent { name: "general".into(), description: "General-purpose subagent for multi-step tasks".into(), mode: "subagent".into(), prompt: GENERAL_PROMPT.into(), tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, reverse: false, path: None },
|
||||
Agent { name: "explore".into(), description: "Read-only subagent for fast codebase searches".into(), mode: "subagent".into(), prompt: EXPLORE_PROMPT.into(), tools: None, read_only: true, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, reverse: false, path: None },
|
||||
]
|
||||
}
|
||||
|
||||
@@ -122,6 +124,7 @@ pub fn agents(app: &App, root: &Path, cwd: &Path) -> Vec<Agent> {
|
||||
source: "file".into(),
|
||||
max_parallel: meta.get("max_parallel").and_then(|v| v.parse().ok()),
|
||||
refine: meta.get("refine_rounds").and_then(|v| v.parse().ok()).map(|rounds| crate::config::RefineConfig { rounds, model: meta.get("refine_model").cloned(), criteria: None, after_todos: meta.get("refine_after_todos").is_none_or(|v| v != "false") }),
|
||||
reverse: meta.get("reverse_tools").is_some_and(|v| v == "true"),
|
||||
path: Some(p.display().to_string()),
|
||||
});
|
||||
}
|
||||
@@ -141,6 +144,7 @@ pub fn agents(app: &App, root: &Path, cwd: &Path) -> Vec<Agent> {
|
||||
source: "config".into(),
|
||||
max_parallel: a.max_parallel.or(base.as_ref().and_then(|b| b.max_parallel)),
|
||||
refine: a.refine.clone().or(base.as_ref().and_then(|b| b.refine.clone())),
|
||||
reverse: a.reverse_tools.unwrap_or_else(|| base.as_ref().is_some_and(|b| b.reverse)),
|
||||
path: None,
|
||||
});
|
||||
}
|
||||
@@ -173,6 +177,7 @@ pub fn agents_for(app: &App, root: &Path, cwd: &Path, user_id: Option<&str>) ->
|
||||
source: "personal".into(),
|
||||
max_parallel: None,
|
||||
refine: a.refine,
|
||||
reverse: a.reverse_tools.unwrap_or(false),
|
||||
path: None,
|
||||
});
|
||||
}
|
||||
@@ -280,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(", ")));
|
||||
}
|
||||
}
|
||||
let skills = skills(app, root, cwd);
|
||||
let skills = skills(app, root, cwd, owner.map(|u| u.id.as_str()));
|
||||
if !skills.is_empty() {
|
||||
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
|
||||
for sk in &skills {
|
||||
s.push_str(&format!("- {}: {}\n", sk.name, sk.description));
|
||||
if skills.len() <= SKILL_LIST_MAX {
|
||||
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
|
||||
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 {
|
||||
@@ -293,6 +303,12 @@ pub fn system_prompt(app: &App, agent: &Agent, root: &Path, cwd: &Path, model: &
|
||||
s.push_str(&format!("\n# About the user (personal memory)\n{}\n", memory.trim()));
|
||||
}
|
||||
}
|
||||
if let Some(git) = owner.and_then(|u| crate::gitcreds::prompt_section(app, &u.id)) {
|
||||
s.push_str(&git);
|
||||
}
|
||||
if let Some(ssh) = owner.and_then(|u| crate::sshkeys::prompt_section(app, &u.id)) {
|
||||
s.push_str(&ssh);
|
||||
}
|
||||
match std::fs::read_to_string(cwd.join(".codecraft").join("memory.md")) {
|
||||
Ok(mem) => s.push_str(&format!("\n# Project memory\nFacts learned earlier in this project (keep it current with the remember tool):\n{}\n", mem.chars().take(20_000).collect::<String>())),
|
||||
Err(_) if !agent.read_only => s.push_str("\n# Project memory\nWhen you learn something lasting about this project (how to build/test, conventions, pitfalls), save it with the remember tool.\n"),
|
||||
@@ -370,23 +386,91 @@ pub struct Skill {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
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();
|
||||
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 };
|
||||
for e in entries.flatten() {
|
||||
let p = e.path().join("SKILL.md");
|
||||
let Ok(text) = std::fs::read_to_string(&p) else { continue };
|
||||
let (meta, _) = frontmatter(&text);
|
||||
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()
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
#[async_trait]
|
||||
@@ -395,23 +479,60 @@ impl Tool for SkillTool {
|
||||
"skill"
|
||||
}
|
||||
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 {
|
||||
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 {
|
||||
true
|
||||
}
|
||||
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 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}'")));
|
||||
};
|
||||
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 (_, body) = frontmatter(&text);
|
||||
let dir = sk.path.parent().unwrap_or(Path::new("."));
|
||||
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}", dir.display())))
|
||||
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}{files}", dir.display())))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,9 +61,21 @@ impl Registry {
|
||||
ProviderEntry { name: name.clone(), provider, models },
|
||||
);
|
||||
}
|
||||
// Claude Code (the CLI's own agent) appears as a model list when it is installed.
|
||||
if !providers.contains_key(crate::claude_code::PROVIDER) && crate::claude_code::binary().is_some() {
|
||||
providers.insert(
|
||||
crate::claude_code::PROVIDER.to_string(),
|
||||
ProviderEntry { name: crate::claude_code::PROVIDER.to_string(), provider: Arc::new(crate::claude_code::Marker), models: crate::claude_code::models() },
|
||||
);
|
||||
}
|
||||
Self { providers, limits }
|
||||
}
|
||||
|
||||
/// First model of any provider but `skip`.
|
||||
pub fn first_model_excluding(&self, skip: &str) -> Option<String> {
|
||||
self.providers.values().filter(|e| e.name != skip).find_map(|e| e.models.first().map(|m| format!("{}/{}", e.name, m.id)))
|
||||
}
|
||||
|
||||
/// Wait for a free slot on the model and its provider. Always acquired in the
|
||||
/// same order (model, then provider), so concurrent requests cannot deadlock.
|
||||
pub async fn acquire(&self, spec: &str) -> Slot {
|
||||
|
||||
@@ -200,8 +200,12 @@ pub fn spawn_listener(app: Arc<App>) {
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(_) => break,
|
||||
};
|
||||
let mut permission_id = None;
|
||||
let (session_id, kind, body) = match &ev {
|
||||
Event::PermissionRequest { session_id, title, tool, .. } => (session_id.clone(), "permission", format!("{tool}: {title}")),
|
||||
Event::PermissionRequest { id, session_id, title, tool, .. } => {
|
||||
permission_id = Some(id.clone());
|
||||
(session_id.clone(), "permission", format!("{tool}: {title}"))
|
||||
}
|
||||
Event::QuestionRequest { session_id, questions, .. } => {
|
||||
let q = questions.first().map(|q| q.question.clone()).unwrap_or_default();
|
||||
(session_id.clone(), "question", q)
|
||||
@@ -228,6 +232,8 @@ pub fn spawn_listener(app: Arc<App>) {
|
||||
continue;
|
||||
}
|
||||
let payload = json!({
|
||||
// Lets the notification itself approve or reject (service worker → POST /api/permissions/<id>).
|
||||
"permission_id": permission_id,
|
||||
"kind": kind,
|
||||
"title": title,
|
||||
"body": body.chars().take(180).collect::<String>(),
|
||||
|
||||
@@ -142,7 +142,10 @@ impl Tool for Decompile {
|
||||
"Decompile an executable or library with Ghidra (x86/x64/ARM/MIPS/PowerPC/68k …, PE, ELF, \
|
||||
Mach-O, raw DOS). Writes pseudo-C for every function plus strings, imports and exports \
|
||||
into .codecraft/decompiled/<name>/ and returns an overview. Can take several minutes for \
|
||||
large programs; results are cached per file."
|
||||
large programs; results are cached per file. Raw firmware images (.bin without a file \
|
||||
format) need `processor` (Ghidra language id, e.g. \"ARM:LE:32:Cortex\" for Cortex-M, \
|
||||
\"ARM:LE:32:v8\", \"AVR8:LE:16:atmega256\", \"Xtensa:LE:32:default\" for ESP32) and usually \
|
||||
`base_address` (load address, e.g. \"0x08000000\" for STM32 flash)."
|
||||
.into()
|
||||
}
|
||||
fn schema(&self) -> Value {
|
||||
@@ -151,7 +154,9 @@ impl Tool for Decompile {
|
||||
"properties": {
|
||||
"path": {"type": "string"},
|
||||
"max_functions": {"type": "integer", "description": "Limit for very large binaries (default: all)"},
|
||||
"force": {"type": "boolean", "description": "Re-run even if cached"}
|
||||
"force": {"type": "boolean", "description": "Re-run even if cached"},
|
||||
"processor": {"type": "string", "description": "Ghidra language id for raw images, e.g. ARM:LE:32:Cortex (default: detected from the file format)"},
|
||||
"base_address": {"type": "string", "description": "Load address of a raw image, e.g. 0x08000000"}
|
||||
},
|
||||
"required": ["path"]
|
||||
})
|
||||
@@ -171,7 +176,20 @@ impl Tool for Decompile {
|
||||
bail!("{} is not a file", path.display());
|
||||
}
|
||||
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("binary").replace(|c: char| !c.is_ascii_alphanumeric() && c != '.' && c != '-', "_");
|
||||
let out_dir = ctx.cwd.join(".codecraft/decompiled").join(format!("{name}-{}", file_hash(&path)?));
|
||||
let processor = input["processor"].as_str().map(str::trim).filter(|s| !s.is_empty()).map(String::from);
|
||||
let base = input["base_address"].as_str().map(str::trim).filter(|s| !s.is_empty()).map(String::from);
|
||||
if processor.as_deref().is_some_and(|p| !p.chars().all(|c| c.is_ascii_alphanumeric() || ":_-.".contains(c))) {
|
||||
bail!("invalid processor id (expected e.g. ARM:LE:32:Cortex)");
|
||||
}
|
||||
if base.as_deref().is_some_and(|b| !b.trim_start_matches("0x").chars().all(|c| c.is_ascii_hexdigit())) {
|
||||
bail!("invalid base_address (expected e.g. 0x08000000)");
|
||||
}
|
||||
// Another processor or load address is another analysis.
|
||||
let variant = match (&processor, &base) {
|
||||
(None, None) => String::new(),
|
||||
(p, b) => format!("-{}", crate::blobs::hash(format!("{p:?}{b:?}").as_bytes()).get(..8).unwrap_or("")),
|
||||
};
|
||||
let out_dir = ctx.cwd.join(".codecraft/decompiled").join(format!("{name}-{}{variant}", file_hash(&path)?));
|
||||
if out_dir.join(".done").exists() && !input["force"].as_bool().unwrap_or(false) {
|
||||
return Ok(ToolOutput::text(format!("(cached)\n{}", summarize(&out_dir, &ctx.cwd)?)));
|
||||
}
|
||||
@@ -183,7 +201,15 @@ impl Tool for Decompile {
|
||||
let scripts = scripts_dir().display().to_string();
|
||||
let max = input["max_functions"].as_u64().map(|n| n.to_string()).unwrap_or_else(|| "2147483647".into());
|
||||
let (p, proj, out) = (path.display().to_string(), project.display().to_string(), out_dir.display().to_string());
|
||||
let args = vec![proj.as_str(), "cc", "-import", p.as_str(), "-scriptPath", scripts.as_str(), "-postScript", "CodeCraftExport.java", out.as_str(), max.as_str(), "-deleteProject", "-max-cpu", "2"];
|
||||
let mut args = vec![proj.as_str(), "cc", "-import", p.as_str()];
|
||||
// Raw firmware: the binary loader with the given processor and load address.
|
||||
if let Some(proc_id) = processor.as_deref() {
|
||||
args.extend(["-processor", proc_id]);
|
||||
}
|
||||
if let Some(addr) = base.as_deref() {
|
||||
args.extend(["-loader", "BinaryLoader", "-loader-baseAddr", addr]);
|
||||
}
|
||||
args.extend(["-scriptPath", scripts.as_str(), "-postScript", "CodeCraftExport.java", out.as_str(), max.as_str(), "-deleteProject", "-max-cpu", "2"]);
|
||||
let java = tools.join("jdk").display().to_string();
|
||||
let mut cmd = match &ctx.sandbox {
|
||||
Some(spec) => {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! checks), feed results back, repeat until the model stops.
|
||||
|
||||
use crate::app::{App, PermissionReply};
|
||||
use crate::permission::{Decision, Evaluator, bash_prefix, split_command};
|
||||
use crate::permission::{Decision, Evaluator, bash_prefix, is_dangerous, split_command};
|
||||
use crate::prompts::{self, Agent};
|
||||
use crate::provider::{ChatRequest, Provider, StreamEvent};
|
||||
use crate::store::UsageRecord;
|
||||
@@ -73,6 +73,7 @@ pub fn submit(app: Arc<App>, session_id: String, parts: Vec<Part>, source: &str)
|
||||
.join("\n");
|
||||
app.emit(Event::SessionStatus { session_id: session_id.clone(), busy: true });
|
||||
let source = source.to_string();
|
||||
let turn_started = now_ms();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let res = async {
|
||||
@@ -114,6 +115,10 @@ pub fn submit(app: Arc<App>, session_id: String, parts: Vec<Part>, source: &str)
|
||||
if cancel.is_cancelled() { Vec::new() } else { take_queue(&app, &session_id) }
|
||||
});
|
||||
app.emit(Event::SessionStatus { session_id: session_id.clone(), busy: false });
|
||||
if leftover.is_empty() && !cancel.is_cancelled() {
|
||||
spawn_summary(app.clone(), session_id.clone());
|
||||
crate::checks::spawn_after_turn(app.clone(), session_id.clone(), turn_started);
|
||||
}
|
||||
if !leftover.is_empty() {
|
||||
let _ = start_prompt(app, session_id, leftover);
|
||||
}
|
||||
@@ -145,7 +150,7 @@ pub fn abort(app: &App, session_id: &str) {
|
||||
/// Messages since the last compaction summary. Tool calls left without a
|
||||
/// result (run interrupted, e.g. by a server restart) get a synthetic result:
|
||||
/// providers reject histories with unanswered tool calls.
|
||||
fn active_history(all: Vec<Message>) -> Vec<Message> {
|
||||
pub(crate) fn active_history(all: Vec<Message>) -> Vec<Message> {
|
||||
let start = all
|
||||
.iter()
|
||||
.rposition(|m| m.parts.iter().any(|p| matches!(p, Part::Summary { .. })))
|
||||
@@ -215,7 +220,7 @@ pub fn available_tools(app: &App, agent: &Agent, owner: Option<&crate::store::Us
|
||||
let cfg = app.config();
|
||||
let mut all = tools::builtin_tools();
|
||||
if !cfg.images.enabled {
|
||||
all.retain(|t| t.name() != "generate_image");
|
||||
all.retain(|t| t.name() != "generate_image" && t.name() != "generate_3d");
|
||||
}
|
||||
let (direct, deferred) = app.mcp.tools(&cfg, owner);
|
||||
all.extend(direct);
|
||||
@@ -226,7 +231,12 @@ pub fn available_tools(app: &App, agent: &Agent, owner: Option<&crate::store::Us
|
||||
all.into_iter()
|
||||
.filter(|t| !agent.read_only || t.read_only())
|
||||
// Craft tools only where they are useful.
|
||||
.filter(|t| agent.name == "craft" || !matches!(t.name(), "browser_snapshot" | "image_compare" | "binary_info" | "decompile" | "craft_phase") || agent.tools.is_some())
|
||||
.filter(|t| {
|
||||
agent.name == "craft"
|
||||
|| agent.tools.is_some()
|
||||
|| (agent.reverse && matches!(t.name(), "binary_info" | "decompile"))
|
||||
|| !matches!(t.name(), "browser_snapshot" | "image_compare" | "binary_info" | "decompile" | "craft_phase")
|
||||
})
|
||||
.filter(|t| match &agent.tools {
|
||||
None => true,
|
||||
Some(list) => {
|
||||
@@ -258,6 +268,10 @@ fn run_session_boxed(
|
||||
|
||||
/// Run the loop for a session until the model stops. Returns the final text.
|
||||
pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationToken, depth: usize) -> Result<String> {
|
||||
// Chats on a "claude-code/…" model are run by the Claude Code CLI.
|
||||
if depth == 0 && crate::claude_code::is_claude_code(&app.session(session_id)?.model) {
|
||||
return crate::claude_code::run(app, session_id, cancel).await;
|
||||
}
|
||||
let mut final_text = String::new();
|
||||
let mut stop_hooks = 0;
|
||||
let mut refine_done = 0u32;
|
||||
@@ -279,6 +293,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 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());
|
||||
// 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);
|
||||
// The craft prompt follows the session's clean room / deep switch.
|
||||
if agent.name == "craft" && agent.source == "builtin" {
|
||||
@@ -317,7 +335,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 tools = available_tools(&app, &agent, owner.as_ref());
|
||||
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,
|
||||
tools: tools.iter().map(|t| t.def()).collect(),
|
||||
max_tokens,
|
||||
@@ -456,7 +474,8 @@ pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationTo
|
||||
agent: agent.name.clone(),
|
||||
roots: roots.clone(),
|
||||
sandbox: crate::sandbox::spec_for(&app, session.owner_id.as_deref()),
|
||||
clean_room,
|
||||
// Clean room is a craft rule; other modes with reverse tools may analyse binaries.
|
||||
clean_room: clean_room && agent.name == "craft",
|
||||
owner_id: None,
|
||||
};
|
||||
let by_name = |n: &str| tools.iter().find(|t| t.name() == n).cloned();
|
||||
@@ -633,9 +652,18 @@ async fn execute_call(
|
||||
// Permission check. Approvals are tracked on the top-level session.
|
||||
let root = app.root_session_id(&session.id);
|
||||
let cfg = app.config();
|
||||
let decision = app.with_runtime(&root, |r| {
|
||||
Evaluator { cfg: &cfg.permissions, mode: &session.permission_mode, approved: &r.approved }.evaluate(tool.as_ref(), &input)
|
||||
let (mut decision, session_approved) = app.with_runtime(&root, |r| {
|
||||
(Evaluator { cfg: &cfg.permissions, mode: &session.permission_mode, approved: &r.approved }.evaluate(tool.as_ref(), &input), r.approved.clone())
|
||||
});
|
||||
// What the user allowed "for this project" earlier counts as well.
|
||||
if decision == Decision::Ask {
|
||||
let project = app.store.project_approvals(&session.cwd).unwrap_or_default();
|
||||
if !project.is_empty() {
|
||||
let mut all = session_approved;
|
||||
all.extend(project);
|
||||
decision = Evaluator { cfg: &cfg.permissions, mode: &session.permission_mode, approved: &all }.evaluate(tool.as_ref(), &input);
|
||||
}
|
||||
}
|
||||
match decision {
|
||||
Decision::Deny => {
|
||||
return tool_result(call_id, call_name, "Denied by the permission rules in the configuration.".into(), true, None);
|
||||
@@ -653,16 +681,27 @@ async fn execute_call(
|
||||
}
|
||||
return tool_result(call_id, call_name, text, true, None);
|
||||
}
|
||||
PermissionReply::Always => app.with_runtime(&root, |r| {
|
||||
PermissionReply::Always | PermissionReply::Project => {
|
||||
// (key, may be remembered for the whole project)
|
||||
let mut keys: Vec<(String, bool)> = Vec::new();
|
||||
if name == "bash" {
|
||||
let cmd = input["command"].as_str().unwrap_or("");
|
||||
for part in split_command(cmd).unwrap_or_default() {
|
||||
r.approved.insert(format!("bash:{}", bash_prefix(&part)));
|
||||
// Dangerous commands (rm -r, git push, docker …) are never remembered beyond this chat.
|
||||
keys.push((format!("bash:{}", bash_prefix(&part)), !is_dangerous(&part)));
|
||||
}
|
||||
} else {
|
||||
r.approved.insert(name.to_string());
|
||||
keys.push((name.to_string(), true));
|
||||
}
|
||||
}),
|
||||
app.with_runtime(&root, |r| r.approved.extend(keys.iter().map(|(k, _)| k.clone())));
|
||||
if reply == PermissionReply::Project {
|
||||
for (k, ok) in &keys {
|
||||
if *ok {
|
||||
let _ = app.store.add_project_approval(&session.cwd, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PermissionReply::Once => {}
|
||||
}
|
||||
if let Some(sel) = hunks {
|
||||
@@ -862,6 +901,9 @@ fn create_child(app: &Arc<App>, ctx: &ToolCtx, agent_name: &str, description: &s
|
||||
folder: None,
|
||||
instructions: String::new(),
|
||||
telegram_quiet: false,
|
||||
summary: String::new(),
|
||||
color: None,
|
||||
icon: None, skills: Vec::new(),
|
||||
};
|
||||
let child = app.save_session(child)?;
|
||||
let msg = Message::new(Role::User, vec![Part::Text { text: prompt }]);
|
||||
@@ -1107,7 +1149,8 @@ async fn stream_step(
|
||||
let mut message = Message::new(Role::Assistant, parts);
|
||||
message.id = msg_id;
|
||||
message.model = Some(model_spec.to_string());
|
||||
message.usage = Some(usage.clone());
|
||||
// With its cost (charged, or valued at list prices) for the line under the answer.
|
||||
message.usage = Some(Usage { cost: Some(req.model.cost(&usage)), ..usage.clone() });
|
||||
if !message.parts.is_empty() {
|
||||
app.store.add_message(&session.id, &message)?;
|
||||
app.emit(Event::MessageAdded { session_id: session.id.clone(), message: message.clone() });
|
||||
@@ -1142,6 +1185,9 @@ fn small_model(app: &App, session: &Session) -> String {
|
||||
let cfg = app.config();
|
||||
if !cfg.server.small_model.is_empty() && app.registry().resolve(&cfg.server.small_model).is_ok() {
|
||||
cfg.server.small_model.clone()
|
||||
} else if crate::claude_code::is_claude_code(&session.model) {
|
||||
// Claude Code runs itself; side tasks need an ordinary model.
|
||||
app.registry().first_model_excluding(crate::claude_code::PROVIDER).unwrap_or_else(|| session.model.clone())
|
||||
} else {
|
||||
session.model.clone()
|
||||
}
|
||||
@@ -1169,6 +1215,174 @@ fn record_side_usage(app: &App, session: &Session, spec: &str, model: &crate::co
|
||||
});
|
||||
}
|
||||
|
||||
/// Cut a text down to `max` bytes keeping the beginning (the goal) and the end (where it went).
|
||||
pub(crate) fn fit(s: &str, max: usize) -> String {
|
||||
if s.len() <= max {
|
||||
return s.to_string();
|
||||
}
|
||||
let head = clip(s, max * 2 / 3);
|
||||
let mut start = s.len() - max / 3;
|
||||
while !s.is_char_boundary(start) {
|
||||
start += 1;
|
||||
}
|
||||
format!("{}\n…\n{}", head.split(" […").next().unwrap_or(&head), &s[start..])
|
||||
}
|
||||
|
||||
/// A short, tool-free job for the small model (summaries, explanations). The input is cut to the
|
||||
/// model's context window, so models with 8k tokens work as well as large ones: tokens left for
|
||||
/// the input = context − answer − prompt, at a conservative 2.5 bytes per token.
|
||||
async fn side_task(app: &App, session: &Session, kind: &str, system: &str, input: &str, max_out: u64) -> Result<String> {
|
||||
let spec = small_model(app, session);
|
||||
let (provider, mut model) = app.registry().resolve(&spec)?;
|
||||
model.effort = Some("low".into());
|
||||
let ctx = model.context.unwrap_or(32_000);
|
||||
let room_tokens = ctx.saturating_sub(max_out + system.len() as u64 / 3 + 400).max(600);
|
||||
let input = fit(input, (room_tokens as usize * 5 / 2).min(60_000));
|
||||
let req = ChatRequest {
|
||||
system: system.into(),
|
||||
messages: vec![Message::new(Role::User, vec![Part::Text { text: input }])],
|
||||
tools: vec![],
|
||||
max_tokens: max_out,
|
||||
reasoning: false,
|
||||
session_id: Some(session.id.clone()),
|
||||
model: model.clone(),
|
||||
};
|
||||
let (text, usage) = complete_text(app, &spec, provider, req, CancellationToken::new()).await?;
|
||||
record_side_usage(app, session, &spec, &model, &usage, kind);
|
||||
Ok(strip_think(&text))
|
||||
}
|
||||
|
||||
/// A commit message for staged changes (small model; the diff is cut to its context window).
|
||||
/// `recent` are the latest commit subjects, so the style matches the repository.
|
||||
pub async fn suggest_commit_message(app: &App, user_id: &str, diff: &str, recent: &str) -> Result<String> {
|
||||
let cfg = app.config();
|
||||
let spec = if !cfg.server.small_model.is_empty() && app.registry().resolve(&cfg.server.small_model).is_ok() {
|
||||
cfg.server.small_model.clone()
|
||||
} else {
|
||||
app.registry().first_model_excluding(crate::claude_code::PROVIDER).ok_or_else(|| anyhow!("no model available"))?
|
||||
};
|
||||
let (provider, mut model) = app.registry().resolve(&spec)?;
|
||||
model.effort = Some("low".into());
|
||||
let max_out = 200u64;
|
||||
let system = "You write a git commit message for the staged changes. Reply with the message only: a subject line of at most 72 characters in the imperative mood, then optionally a blank line and up to 4 short bullet points on what changed and why. No quotes, no code fences. Match the style of the recent commit subjects (language, prefixes).";
|
||||
let ctx = model.context.unwrap_or(32_000);
|
||||
let room = ctx.saturating_sub(max_out + system.len() as u64 / 3 + 500).max(600) as usize * 5 / 2;
|
||||
let input = format!("<recent-commits>\n{}\n</recent-commits>\n<staged-diff>\n{}\n</staged-diff>", fit(recent, 600), fit(diff, room.saturating_sub(700).clamp(500, 40_000)));
|
||||
let req = ChatRequest {
|
||||
system: system.into(),
|
||||
messages: vec![Message::new(Role::User, vec![Part::Text { text: input }])],
|
||||
tools: vec![],
|
||||
max_tokens: max_out,
|
||||
reasoning: false,
|
||||
session_id: None,
|
||||
model: model.clone(),
|
||||
};
|
||||
let (text, usage) = complete_text(app, &spec, provider, req, CancellationToken::new()).await?;
|
||||
let (p, m) = spec.split_once('/').unwrap_or(("", spec.as_str()));
|
||||
let _ = app.store.add_usage(&UsageRecord {
|
||||
ts: now_ms(),
|
||||
session_id: "cli:git-commit".into(),
|
||||
root_session_id: "cli:git-commit".into(),
|
||||
provider: p.into(),
|
||||
model: m.into(),
|
||||
agent: "commit-message".into(),
|
||||
input_tokens: usage.input_tokens,
|
||||
output_tokens: usage.output_tokens,
|
||||
cache_read_tokens: usage.cache_read_tokens,
|
||||
cache_write_tokens: usage.cache_write_tokens,
|
||||
ttft_ms: 0,
|
||||
duration_ms: 0,
|
||||
cost: model.cost(&usage),
|
||||
error: false,
|
||||
user_id: Some(user_id.to_string()),
|
||||
allowance: usage.allowance,
|
||||
});
|
||||
let msg = strip_think(&text).trim().trim_matches('`').trim().to_string();
|
||||
if msg.is_empty() {
|
||||
bail!("the model returned no message");
|
||||
}
|
||||
Ok(msg)
|
||||
}
|
||||
|
||||
fn message_text(m: &Message) -> String {
|
||||
m.parts.iter().filter_map(|p| if let Part::Text { text } = p { Some(text.as_str()) } else { None }).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
/// After a turn: one line "where things stand" for the session list (small model, ~1k tokens of input).
|
||||
fn spawn_summary(app: Arc<App>, session_id: String) {
|
||||
tokio::spawn(async move {
|
||||
let Ok(session) = app.session(&session_id) else { return };
|
||||
if session.parent_id.is_some() {
|
||||
return;
|
||||
}
|
||||
let Ok(history) = app.store.messages(&session_id) else { return };
|
||||
let history = active_history(history);
|
||||
let last_user = history.iter().rev().find(|m| matches!(m.role, Role::User) && !message_text(m).trim().is_empty() && !message_text(m).trim_start().starts_with('<'));
|
||||
let last_answer = history.iter().rev().find(|m| matches!(m.role, Role::Assistant) && !message_text(m).trim().is_empty());
|
||||
let (Some(u), Some(a)) = (last_user, last_answer) else { return };
|
||||
let input = format!(
|
||||
"<previous-line>{}</previous-line>\n<user-request>\n{}\n</user-request>\n<agent-answer>\n{}\n</agent-answer>",
|
||||
session.summary,
|
||||
fit(&message_text(u), 1500),
|
||||
fit(&message_text(a), 2500)
|
||||
);
|
||||
let system = "You write the status line of a coding chat for a list. One line, at most 14 words: what was done or where things stand, concrete (file/feature names). \
|
||||
Use the language of the user's request. No quotes, no markdown, no trailing period. Reply with the line only.";
|
||||
match side_task(&app, &session, "summary", system, &input, 120).await {
|
||||
Ok(text) => {
|
||||
let line = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim().trim_matches(['"', '\'', '*', '#', ' ', '.']).chars().take(140).collect::<String>();
|
||||
if !line.is_empty() {
|
||||
let _ = app.modify_session(&session_id, false, |s| s.summary = line);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::debug!("summary failed: {e:#}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// "What does this do?" for a pending approval, in plain words (for phones: approve without reading code).
|
||||
pub async fn explain_tool_call(app: &App, session: &Session, tool: &str, title: &str, input: &Value, diff: Option<&str>, lang: &str) -> Result<String> {
|
||||
let language = if lang.starts_with("de") { "German" } else { "English" };
|
||||
let system = format!(
|
||||
"You explain a pending action of an AI coding agent to the user who has to approve it. Answer in {language}, plain words, at most 3 short sentences: \
|
||||
what it does, and whether anything is risky (deletes or overwrites data, network access, secrets, changes outside the project, hard to undo). \
|
||||
If it is harmless, say so. No markdown headings, no code blocks."
|
||||
);
|
||||
let mut body = format!("<tool>{tool}</tool>\n<title>{title}</title>\n<input>\n{}\n</input>", clip(&input.to_string(), 3000));
|
||||
if let Some(d) = diff {
|
||||
body.push_str(&format!("\n<diff>\n{}\n</diff>", clip(d, 3000)));
|
||||
}
|
||||
side_task(app, session, "explain", &system, &body, 300).await
|
||||
}
|
||||
|
||||
/// Turn a chat into the instructions of a repeatable automation: (name, instructions in Markdown).
|
||||
/// Works with a small model: the transcript is cut to its context window.
|
||||
pub async fn draft_job(app: &App, session: &Session) -> Result<(String, String)> {
|
||||
let history = active_history(app.store.messages(&session.id)?);
|
||||
let transcript = transcript_of(&history);
|
||||
if transcript.trim().is_empty() {
|
||||
bail!("the session has no messages yet");
|
||||
}
|
||||
let system = "You turn a finished coding-assistant conversation into instructions for an AUTOMATION that repeats the useful work on a schedule, without a human in the loop. \
|
||||
Reply in exactly this format. First line: NAME: <at most 5 words>. Then the instructions in Markdown with the headings '## Goal', '## Steps' (numbered), '## Result' and '## Limits'. \
|
||||
Write them standalone: never refer to 'the conversation' or 'above'; name concrete paths, commands and checks that were used. \
|
||||
Use the language of the user's messages. Keep it under 300 words.";
|
||||
let text = side_task(app, session, "job-draft", system, &format!("<conversation>\n{transcript}\n</conversation>"), 1200).await?;
|
||||
let mut lines = text.lines().skip_while(|l| l.trim().is_empty());
|
||||
let first = lines.next().unwrap_or("");
|
||||
let (name, body) = match first.trim().strip_prefix("NAME:").or_else(|| first.trim().strip_prefix("Name:")) {
|
||||
Some(n) => (n.trim().trim_matches(['"', '*', '#', ' ']).to_string(), lines.collect::<Vec<_>>().join("\n")),
|
||||
None => (String::new(), text.clone()),
|
||||
};
|
||||
let body = body.trim().to_string();
|
||||
if body.is_empty() {
|
||||
bail!("the model returned no instructions");
|
||||
}
|
||||
let name = if name.is_empty() { session.title.clone() } else { name };
|
||||
let name: String = if name.trim().is_empty() { "Automation".into() } else { name.chars().take(60).collect() };
|
||||
Ok((name.clone(), format!("# {name}\n\n{body}\n")))
|
||||
}
|
||||
|
||||
fn maybe_generate_title(app: Arc<App>, session_id: &str, text: &str) {
|
||||
let Ok(session) = app.session(session_id) else { return };
|
||||
if session.parent_id.is_some() || !session.title.is_empty() {
|
||||
@@ -1513,10 +1727,56 @@ async fn compact_inner(app: Arc<App>, session_id: &str, cancel: CancellationToke
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Text of the marker `/clear` puts into the history (the chat view recognises it).
|
||||
pub const CLEARED_MARKER: &str = "[Context cleared by the user. Earlier messages are no longer part of this conversation – start fresh and do not refer to them.]";
|
||||
|
||||
/// `/clear`: the model forgets the conversation so far (the chat keeps showing it). Like a
|
||||
/// compaction without a summary: history before the marker is not sent any more.
|
||||
pub fn clear_context(app: &App, session_id: &str) -> Result<()> {
|
||||
save_user_parts(app, session_id, vec![Part::Summary { text: CLEARED_MARKER.into(), auto: false, tokens: None }])?;
|
||||
app.update_session(session_id, |s| {
|
||||
s.last_usage = None;
|
||||
s.todos = Value::Null;
|
||||
})?;
|
||||
app.with_runtime(session_id, |r| r.read_files.clear());
|
||||
// Claude Code continues its own conversation: start a new one.
|
||||
if let Some(owner) = app.session(session_id).ok().and_then(|s| s.owner_id) {
|
||||
let _ = app.store.set_user_setting(&owner, &format!("claude_sid:{session_id}"), &Option::<String>::None);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cleared_marker_starts_a_new_history() {
|
||||
let mk = |role, parts| Message::new(role, parts);
|
||||
let all = vec![
|
||||
mk(Role::User, vec![Part::Text { text: "old question".into() }]),
|
||||
mk(Role::Assistant, vec![Part::Text { text: "old answer".into() }]),
|
||||
mk(Role::User, vec![Part::Summary { text: CLEARED_MARKER.into(), auto: false, tokens: None }]),
|
||||
mk(Role::User, vec![Part::Text { text: "new question".into() }]),
|
||||
];
|
||||
let active = active_history(all);
|
||||
assert_eq!(active.len(), 2);
|
||||
assert!(!active.iter().any(|m| message_text(m).contains("old")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_keeps_head_and_tail_within_budget() {
|
||||
let text = format!("{}{}{}", "A".repeat(5000), "M".repeat(5000), "Z".repeat(5000));
|
||||
let out = fit(&text, 3000);
|
||||
assert!(out.len() <= 3100, "{}", out.len());
|
||||
assert!(out.starts_with("AAAA") && out.ends_with("ZZZZ") && out.contains('…'));
|
||||
// Multi-byte text is cut on character boundaries.
|
||||
let de = "äöüß".repeat(2000);
|
||||
assert!(fit(&de, 1000).is_char_boundary(0));
|
||||
assert_eq!(fit("short", 100), "short");
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn todo_completion_and_reopening() {
|
||||
let before = serde_json::json!([{"content": "A", "status": "in_progress"}, {"content": "B", "status": "completed"}, {"content": "C", "status": "pending"}]);
|
||||
|
||||
@@ -132,7 +132,10 @@ pub fn bwrap_args(spec: &SandboxSpec, cwd: &Path, extra_ro: &[&Path], new_sessio
|
||||
if new_session {
|
||||
push(&[&"--new-session"]);
|
||||
}
|
||||
let path = format!("{home}/.local/bin:{home}/.cargo/bin:{home}/.npm-global/bin:/usr/local/bin:/usr/bin:/bin");
|
||||
// SSH wrappers (user's keys); only when keys are set up.
|
||||
let ssh_wrapper = spec.home.join(crate::sshkeys::SANDBOX_BIN).join("ssh");
|
||||
let ssh_bin = format!("{home}/{}", crate::sshkeys::SANDBOX_BIN);
|
||||
let path = format!("{}{home}/.local/bin:{home}/.cargo/bin:{home}/.npm-global/bin:/usr/local/bin:/usr/bin:/bin", if ssh_wrapper.exists() { format!("{ssh_bin}:") } else { String::new() });
|
||||
let npm = format!("{home}/.npm-global");
|
||||
let pipx = format!("{home}/.local/pipx");
|
||||
let pipx_bin = format!("{home}/.local/bin");
|
||||
@@ -152,6 +155,10 @@ pub fn bwrap_args(spec: &SandboxSpec, cwd: &Path, extra_ro: &[&Path], new_sessio
|
||||
] {
|
||||
push(&[&"--setenv", &k, &v]);
|
||||
}
|
||||
if ssh_wrapper.exists() {
|
||||
let cmd = format!("{ssh_bin}/ssh");
|
||||
push(&[&"--setenv", &"GIT_SSH_COMMAND", &cmd]);
|
||||
}
|
||||
for (k, v) in &spec.env {
|
||||
push(&[&"--setenv", k, v]);
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Per-user SSH keys for agents, terminals and the git panel.
|
||||
//!
|
||||
//! The keys live in the database and are rendered into the user's home (`.ssh/`), like the git
|
||||
//! credentials. OpenSSH takes `~` from the passwd entry, not from `$HOME`, so plain `ssh` would
|
||||
//! not look into the sandbox home. A small `ssh`/`scp`/`sftp` wrapper directory goes first in PATH
|
||||
//! and applies the managed config with `-F`; `GIT_SSH_COMMAND` points at the wrapper. Two
|
||||
//! variants: one for the sandbox (paths through `${HOME}`) and one for unsandboxed runs (admins;
|
||||
//! absolute host paths).
|
||||
|
||||
use crate::app::App;
|
||||
use crate::store::User;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SshKey {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub public: String,
|
||||
pub fingerprint: String,
|
||||
/// OpenSSH private key (never sent to the UI).
|
||||
#[serde(default)]
|
||||
pub private: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SshSettings {
|
||||
#[serde(default)]
|
||||
pub keys: Vec<SshKey>,
|
||||
}
|
||||
|
||||
/// Keys without the private part, for the UI.
|
||||
pub fn masked(s: &SshSettings) -> Vec<SshKey> {
|
||||
s.keys.iter().map(|k| SshKey { private: String::new(), ..k.clone() }).collect()
|
||||
}
|
||||
|
||||
fn ssh_dir(home: &Path) -> PathBuf {
|
||||
home.join(".ssh")
|
||||
}
|
||||
|
||||
/// Wrappers for unsandboxed runs.
|
||||
fn bin_dir(home: &Path) -> PathBuf {
|
||||
home.join(".codecraft-bin")
|
||||
}
|
||||
|
||||
/// Wrappers inside the sandbox (see `sandbox::bwrap_args`).
|
||||
pub const SANDBOX_BIN: &str = ".codecraft-sbin";
|
||||
|
||||
fn key_file(id: &str) -> String {
|
||||
format!("codecraft_{id}")
|
||||
}
|
||||
|
||||
/// SSH client config. `sandbox`: paths through `${HOME}` (the home is mounted at a different
|
||||
/// place there); otherwise absolute paths below `home` (wrapper for unsandboxed runs).
|
||||
pub fn render_config(keys: &[SshKey], home: &Path, sandbox: bool) -> String {
|
||||
let mut c = String::from("# Managed by CodeCraft (Settings → Account → SSH keys). Do not edit.\nHost *\n");
|
||||
for k in keys {
|
||||
if sandbox {
|
||||
c.push_str(&format!("\tIdentityFile ${{HOME}}/.ssh/{}\n", key_file(&k.id)));
|
||||
} else {
|
||||
c.push_str(&format!("\tIdentityFile {}\n", ssh_dir(home).join(key_file(&k.id)).display()));
|
||||
}
|
||||
}
|
||||
// Trust a host on first contact and refuse changed keys afterwards.
|
||||
c.push_str("\tStrictHostKeyChecking accept-new\n\tServerAliveInterval 30\n");
|
||||
if sandbox {
|
||||
c.push_str("\tUserKnownHostsFile ${HOME}/.ssh/known_hosts\n");
|
||||
} else {
|
||||
c.push_str(&format!("\tUserKnownHostsFile {}\n", ssh_dir(home).join("known_hosts").display()));
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn chmod(p: &Path, mode: u32) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode))?;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
fn chmod(_: &Path, _: u32) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write keys, config and wrappers into the user's home (removes files of deleted keys).
|
||||
pub fn write_files(app: &App, user: &User, s: &SshSettings) -> Result<()> {
|
||||
let home = crate::gitcreds::home_of(app, user);
|
||||
let dir = ssh_dir(&home);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
chmod(&dir, 0o700)?;
|
||||
// Old key files.
|
||||
for e in std::fs::read_dir(&dir)?.flatten() {
|
||||
let n = e.file_name().to_string_lossy().into_owned();
|
||||
if n.starts_with("codecraft_") && !s.keys.iter().any(|k| n == key_file(&k.id) || n == format!("{}.pub", key_file(&k.id))) {
|
||||
let _ = std::fs::remove_file(e.path());
|
||||
}
|
||||
}
|
||||
if s.keys.is_empty() {
|
||||
// No keys: no wrappers either, ssh behaves as usual.
|
||||
let _ = std::fs::remove_dir_all(bin_dir(&home));
|
||||
let _ = std::fs::remove_dir_all(home.join(SANDBOX_BIN));
|
||||
for f in ["config-sandbox", "config-host"] {
|
||||
let _ = std::fs::remove_file(dir.join(f));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for k in &s.keys {
|
||||
let p = dir.join(key_file(&k.id));
|
||||
// The file is replaced, not appended: remove it first so the mode applies.
|
||||
let _ = std::fs::remove_file(&p);
|
||||
std::fs::write(&p, &k.private)?;
|
||||
chmod(&p, 0o600)?;
|
||||
let pubp = dir.join(format!("{}.pub", key_file(&k.id)));
|
||||
std::fs::write(&pubp, format!("{}\n", k.public.trim()))?;
|
||||
chmod(&pubp, 0o644)?;
|
||||
}
|
||||
// The user's own ~/.ssh/config (if any) is included after the managed part.
|
||||
let own = dir.join("config");
|
||||
let sandbox_cfg = dir.join("config-sandbox");
|
||||
std::fs::write(&sandbox_cfg, format!("{}\nInclude /home/{}/.ssh/config\n", render_config(&s.keys, &home, true), user.username))?;
|
||||
chmod(&sandbox_cfg, 0o600)?;
|
||||
let host_cfg = dir.join("config-host");
|
||||
std::fs::write(&host_cfg, format!("{}\nInclude {}\n", render_config(&s.keys, &home, false), own.display()))?;
|
||||
chmod(&host_cfg, 0o600)?;
|
||||
for (bin, config) in [(bin_dir(&home), format!("'{}'", host_cfg.display())), (home.join(SANDBOX_BIN), "\"$HOME/.ssh/config-sandbox\"".to_string())] {
|
||||
std::fs::create_dir_all(&bin)?;
|
||||
for name in ["ssh", "scp", "sftp"] {
|
||||
// The image's /usr/local/bin wrappers cope with a uid without passwd entry.
|
||||
let local = format!("/usr/local/bin/{name}");
|
||||
let real = if Path::new(&local).exists() { local } else { format!("/usr/bin/{name}") };
|
||||
let p = bin.join(name);
|
||||
std::fs::write(&p, format!("#!/bin/sh\nexec {real} -F {config} \"$@\"\n"))?;
|
||||
chmod(&p, 0o755)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Environment for processes that run without the sandbox: the wrappers first in PATH, git over
|
||||
/// SSH through the wrapper. Empty when the user has no keys.
|
||||
pub fn env(app: &App, user: &User) -> Vec<(String, String)> {
|
||||
let s: SshSettings = app.store.user_setting(&user.id, "ssh").unwrap_or_default();
|
||||
if s.keys.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let bin = bin_dir(&crate::gitcreds::home_of(app, user));
|
||||
if !bin.join("ssh").exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into()));
|
||||
vec![("PATH".into(), path), ("GIT_SSH_COMMAND".into(), bin.join("ssh").display().to_string())]
|
||||
}
|
||||
|
||||
/// What an agent needs to know (public keys only). None without keys.
|
||||
pub fn prompt_section(app: &App, user_id: &str) -> Option<String> {
|
||||
render_prompt(&app.store.user_setting(user_id, "ssh").unwrap_or_default())
|
||||
}
|
||||
|
||||
fn render_prompt(s: &SshSettings) -> Option<String> {
|
||||
if s.keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<&str> = s.keys.iter().map(|k| k.name.as_str()).collect();
|
||||
Some(format!(
|
||||
"\n# SSH access\nThe user has SSH keys set up ({}). `ssh`, `scp`, `sftp`, `rsync -e ssh` and `git` over ssh:// or git@host use them automatically – \
|
||||
no password, no `ssh-add`, no agent. A host is trusted on first contact. Do NOT generate new keys or search for keys or passwords; \
|
||||
if a server refuses the connection, tell the user that their public key must be added to the server's authorized_keys. \
|
||||
Commands run without a terminal, so password or passphrase prompts fail.\n",
|
||||
names.join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
// --- creating keys ---------------------------------------------------------------------
|
||||
|
||||
async fn keygen(args: &[&str], stdin: Option<&str>) -> Result<String> {
|
||||
let mut cmd = Command::new("ssh-keygen");
|
||||
cmd.args(args).env_clear().env("PATH", std::env::var("PATH").unwrap_or_default()).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
|
||||
let mut child = cmd.spawn().context("ssh-keygen is not installed on the server")?;
|
||||
if let Some(mut si) = child.stdin.take() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
if let Some(t) = stdin {
|
||||
let _ = si.write_all(t.as_bytes()).await;
|
||||
}
|
||||
}
|
||||
let out = tokio::time::timeout(std::time::Duration::from_secs(20), child.wait_with_output()).await.map_err(|_| anyhow!("ssh-keygen timed out"))??;
|
||||
if !out.status.success() {
|
||||
bail!("{}", String::from_utf8_lossy(&out.stderr).trim());
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
fn temp_dir() -> Result<PathBuf> {
|
||||
let d = std::env::temp_dir().join(format!("cc-ssh-{}", crate::types::new_id()));
|
||||
std::fs::create_dir_all(&d)?;
|
||||
chmod(&d, 0o700)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// A new ed25519 key without passphrase.
|
||||
pub async fn generate(name: &str) -> Result<SshKey> {
|
||||
let d = temp_dir()?;
|
||||
let f = d.join("key");
|
||||
let comment = format!("codecraft-{}", name.replace(char::is_whitespace, "-"));
|
||||
let res = async {
|
||||
keygen(&["-q", "-t", "ed25519", "-N", "", "-C", &comment, "-f", &f.to_string_lossy()], None).await?;
|
||||
let private = std::fs::read_to_string(&f)?;
|
||||
let public = std::fs::read_to_string(d.join("key.pub"))?;
|
||||
finish(name, private, public.trim().to_string()).await
|
||||
}
|
||||
.await;
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
res
|
||||
}
|
||||
|
||||
/// An existing private key (OpenSSH or PEM, without passphrase).
|
||||
pub async fn import(name: &str, private: &str) -> Result<SshKey> {
|
||||
let mut text = private.trim().replace("\r\n", "\n");
|
||||
if !text.starts_with("-----BEGIN ") || !text.contains("PRIVATE KEY-----") {
|
||||
bail!("that does not look like a private key (-----BEGIN … PRIVATE KEY-----)");
|
||||
}
|
||||
text.push('\n');
|
||||
let d = temp_dir()?;
|
||||
let f = d.join("key");
|
||||
let res = async {
|
||||
std::fs::write(&f, &text)?;
|
||||
chmod(&f, 0o600)?;
|
||||
let public = keygen(&["-y", "-P", "", "-f", &f.to_string_lossy()], None).await.map_err(|e| anyhow!("cannot read the key (keys with a passphrase are not supported): {e}"))?;
|
||||
finish(name, text.clone(), public.trim().to_string()).await
|
||||
}
|
||||
.await;
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
res
|
||||
}
|
||||
|
||||
async fn finish(name: &str, private: String, public: String) -> Result<SshKey> {
|
||||
let fp = keygen(&["-l", "-f", "-"], Some(&format!("{public}\n"))).await.unwrap_or_default();
|
||||
let fingerprint = fp.split_whitespace().nth(1).unwrap_or("").to_string();
|
||||
Ok(SshKey { id: crate::types::new_id().chars().take(10).collect(), name: name.to_string(), public, fingerprint, private })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key(id: &str) -> SshKey {
|
||||
SshKey { id: id.into(), name: "laptop".into(), public: "ssh-ed25519 AAAA x".into(), fingerprint: "SHA256:x".into(), private: "SECRET".into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_has_both_path_styles() {
|
||||
let home = Path::new("/data/users/ann/home");
|
||||
let t = render_config(&[key("k1")], home, true);
|
||||
assert!(t.contains("IdentityFile ${HOME}/.ssh/codecraft_k1") && t.contains("UserKnownHostsFile ${HOME}/.ssh/known_hosts"));
|
||||
assert!(t.contains("StrictHostKeyChecking accept-new"));
|
||||
let a = render_config(&[key("k1")], home, false);
|
||||
assert!(a.contains("IdentityFile /data/users/ann/home/.ssh/codecraft_k1"));
|
||||
assert!(a.contains("UserKnownHostsFile /data/users/ann/home/.ssh/known_hosts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sandbox_config_resolves_through_home() {
|
||||
if std::process::Command::new("ssh").arg("-V").output().is_err() {
|
||||
return;
|
||||
}
|
||||
let d = std::env::temp_dir().join(format!("cc-sshcfg-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let cfg = d.join("cfg");
|
||||
std::fs::write(&cfg, render_config(&[key("k1")], Path::new("/unused"), true)).unwrap();
|
||||
let out = std::process::Command::new("ssh").arg("-F").arg(&cfg).args(["-G", "example.org"]).env("HOME", "/sandbox/home").output().unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
|
||||
// `-G` shows identity files unexpanded (expanded when used, ssh_config(5)).
|
||||
assert!(text.contains("identityfile ${home}/.ssh/codecraft_k1"), "{text}");
|
||||
assert!(text.contains("userknownhostsfile /sandbox/home/.ssh/known_hosts"), "{text}");
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_and_ui_view_never_contain_the_private_key() {
|
||||
let s = SshSettings { keys: vec![key("k1")] };
|
||||
assert!(masked(&s).iter().all(|k| k.private.is_empty()));
|
||||
let p = render_prompt(&s).unwrap();
|
||||
assert!(p.contains("laptop") && !p.contains("SECRET"));
|
||||
assert!(render_prompt(&SshSettings::default()).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generated_and_imported_keys_match() {
|
||||
if std::process::Command::new("ssh-keygen").arg("-?").output().is_err() {
|
||||
return; // not installed here
|
||||
}
|
||||
let k = generate("test key").await.unwrap();
|
||||
assert!(k.public.starts_with("ssh-ed25519 ") && k.fingerprint.starts_with("SHA256:") && k.private.contains("PRIVATE KEY"));
|
||||
let again = import("copy", &k.private).await.unwrap();
|
||||
assert_eq!(again.fingerprint, k.fingerprint);
|
||||
assert!(import("bad", "hello").await.is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Statistics as CSV (one table) or XLSX (all tables, one sheet each).
|
||||
|
||||
use serde_json::Value;
|
||||
use std::io::Write;
|
||||
|
||||
/// A table: header row and rows of cells.
|
||||
pub struct Table {
|
||||
pub id: &'static str,
|
||||
pub title: String,
|
||||
pub rows: Vec<Vec<Cell>>,
|
||||
}
|
||||
|
||||
pub enum Cell {
|
||||
Text(String),
|
||||
Num(f64),
|
||||
}
|
||||
|
||||
fn num(v: &Value, k: &str) -> Cell {
|
||||
Cell::Num(v[k].as_f64().unwrap_or(0.0))
|
||||
}
|
||||
|
||||
/// Column titles (English, German).
|
||||
fn columns(first: &str, de: bool) -> Vec<Cell> {
|
||||
let t: [&str; 10] = if de {
|
||||
["Anfragen", "Input-Tokens", "Cache gelesen", "Cache geschrieben", "Output-Tokens", "Fehler", "Ø Latenz (ms)", "Output (Tok/s)", "Prefill (Tok/s)", "Kosten"]
|
||||
} else {
|
||||
["Requests", "Input tokens", "Cache read", "Cache write", "Output tokens", "Errors", "Avg TTFT (ms)", "Output (tok/s)", "Prefill (tok/s)", "Cost"]
|
||||
};
|
||||
std::iter::once(first).chain(t).map(|s| Cell::Text(s.to_string())).collect()
|
||||
}
|
||||
|
||||
fn agg_table(id: &'static str, title: &str, first: &str, key: &str, rows: &Value, de: bool) -> Table {
|
||||
let mut out = vec![columns(first, de)];
|
||||
for r in rows.as_array().into_iter().flatten() {
|
||||
out.push(vec![
|
||||
Cell::Text(r[key].as_str().unwrap_or("").to_string()),
|
||||
num(r, "requests"),
|
||||
num(r, "input_tokens"),
|
||||
num(r, "cache_read_tokens"),
|
||||
num(r, "cache_write_tokens"),
|
||||
num(r, "output_tokens"),
|
||||
num(r, "errors"),
|
||||
num(r, "avg_ttft_ms"),
|
||||
num(r, "output_tps"),
|
||||
num(r, "prefill_tps"),
|
||||
num(r, "cost"),
|
||||
]);
|
||||
}
|
||||
Table { id, title: title.to_string(), rows: out }
|
||||
}
|
||||
|
||||
/// All tables of a statistics result (as returned by `Store::global_stats`).
|
||||
pub fn tables(stats: &Value, de: bool) -> Vec<Table> {
|
||||
let (day, month, model, provider, agent, user, session) = if de {
|
||||
("Tag", "Monat", "Modell", "Anbieter", "Modus", "Benutzer", "Chat")
|
||||
} else {
|
||||
("Day", "Month", "Model", "Provider", "Agent", "User", "Chat")
|
||||
};
|
||||
let mut out = vec![
|
||||
agg_table("day", if de { "Pro Tag" } else { "Per day" }, day, "day", &stats["by_day"], de),
|
||||
agg_table("month", if de { "Pro Monat" } else { "Per month" }, month, "month", &stats["by_month"], de),
|
||||
agg_table("model", model, model, "model", &stats["by_model"], de),
|
||||
agg_table("provider", provider, provider, "provider", &stats["by_provider"], de),
|
||||
agg_table("agent", agent, agent, "agent", &stats["by_agent"], de),
|
||||
agg_table("user", user, user, "user", &stats["by_user"], de),
|
||||
agg_table("session", if de { "Teuerste Chats" } else { "Top chats" }, session, "title", &stats["top_sessions"], de),
|
||||
];
|
||||
// The grand total first, as a one-row table.
|
||||
let mut total = vec![columns(if de { "Zeitraum" } else { "Range" }, de)];
|
||||
let t = &stats["total"];
|
||||
total.push(vec![
|
||||
Cell::Text(format!("{} – {}", date(stats["from"].as_i64().unwrap_or(0)), date(stats["to"].as_i64().unwrap_or(0)))),
|
||||
num(t, "requests"),
|
||||
num(t, "input_tokens"),
|
||||
num(t, "cache_read_tokens"),
|
||||
num(t, "cache_write_tokens"),
|
||||
num(t, "output_tokens"),
|
||||
num(t, "errors"),
|
||||
num(t, "avg_ttft_ms"),
|
||||
num(t, "output_tps"),
|
||||
num(t, "prefill_tps"),
|
||||
num(t, "cost"),
|
||||
]);
|
||||
out.insert(0, Table { id: "total", title: (if de { "Gesamt" } else { "Total" }).to_string(), rows: total });
|
||||
out
|
||||
}
|
||||
|
||||
fn date(ms: i64) -> String {
|
||||
if ms <= 0 {
|
||||
return "-".into();
|
||||
}
|
||||
chrono::DateTime::from_timestamp_millis(ms).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
// --- CSV -----------------------------------------------------------------------------
|
||||
|
||||
/// CSV for spreadsheets: `;` and decimal comma in German, `,` and decimal point otherwise;
|
||||
/// UTF-8 with BOM (Excel). Cells starting with = + - @ are prefixed against formula injection.
|
||||
pub fn csv(table: &Table, de: bool) -> String {
|
||||
let sep = if de { ';' } else { ',' };
|
||||
let mut out = String::from('\u{feff}');
|
||||
for row in &table.rows {
|
||||
let line: Vec<String> = row
|
||||
.iter()
|
||||
.map(|c| match c {
|
||||
Cell::Num(n) => {
|
||||
let s = if n.fract() == 0.0 { format!("{n:.0}") } else { format!("{n:.4}") };
|
||||
if de { s.replace('.', ",") } else { s }
|
||||
}
|
||||
Cell::Text(t) => {
|
||||
let t = if t.starts_with(['=', '+', '-', '@', '\t', '\r']) { format!("'{t}") } else { t.clone() };
|
||||
if t.contains([sep, '"', '\n', '\r']) { format!("\"{}\"", t.replace('"', "\"\"")) } else { t }
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&line.join(&sep.to_string()));
|
||||
out.push_str("\r\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// --- XLSX ----------------------------------------------------------------------------
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.chars()
|
||||
.filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
|
||||
.map(|c| match c {
|
||||
'&' => "&".to_string(),
|
||||
'<' => "<".to_string(),
|
||||
'>' => ">".to_string(),
|
||||
'"' => """.to_string(),
|
||||
c => c.to_string(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn col_name(mut i: usize) -> String {
|
||||
let mut s = String::new();
|
||||
loop {
|
||||
s.insert(0, (b'A' + (i % 26) as u8) as char);
|
||||
if i < 26 {
|
||||
break;
|
||||
}
|
||||
i = i / 26 - 1;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn sheet_xml(t: &Table) -> String {
|
||||
let mut x = String::from(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews><cols><col min="1" max="1" width="34" customWidth="1"/><col min="2" max="11" width="16" customWidth="1"/></cols><sheetData>"#);
|
||||
for (r, row) in t.rows.iter().enumerate() {
|
||||
x.push_str(&format!(r#"<row r="{}">"#, r + 1));
|
||||
for (c, cell) in row.iter().enumerate() {
|
||||
let at = format!("{}{}", col_name(c), r + 1);
|
||||
let style = if r == 0 { r#" s="1""# } else { "" };
|
||||
match cell {
|
||||
// Text as inline strings: no shared string table needed.
|
||||
Cell::Text(s) => x.push_str(&format!(r#"<c r="{at}" t="inlineStr"{style}><is><t xml:space="preserve">{}</t></is></c>"#, esc(s))),
|
||||
Cell::Num(n) => x.push_str(&format!(r#"<c r="{at}"{style}><v>{n}</v></c>"#)),
|
||||
}
|
||||
}
|
||||
x.push_str("</row>");
|
||||
}
|
||||
x.push_str("</sheetData></worksheet>");
|
||||
x
|
||||
}
|
||||
|
||||
/// Sheet names: at most 31 characters, none of []:*?/\
|
||||
fn sheet_name(s: &str) -> String {
|
||||
s.chars().filter(|c| !"[]:*?/\\".contains(*c)).take(31).collect()
|
||||
}
|
||||
|
||||
pub fn xlsx(tables: &[Table]) -> anyhow::Result<Vec<u8>> {
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
{
|
||||
let mut z = zip::ZipWriter::new(&mut buf);
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
let mut put = |name: &str, body: &str| -> anyhow::Result<()> {
|
||||
z.start_file(name, opts)?;
|
||||
z.write_all(body.as_bytes())?;
|
||||
Ok(())
|
||||
};
|
||||
let mut types = String::from(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>"#);
|
||||
let mut sheets = String::new();
|
||||
let mut rels = String::new();
|
||||
for (i, t) in tables.iter().enumerate() {
|
||||
let n = i + 1;
|
||||
types.push_str(&format!(r#"<Override PartName="/xl/worksheets/sheet{n}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>"#));
|
||||
sheets.push_str(&format!(r#"<sheet name="{}" sheetId="{n}" r:id="rId{n}"/>"#, esc(&sheet_name(&t.title))));
|
||||
rels.push_str(&format!(r#"<Relationship Id="rId{n}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{n}.xml"/>"#));
|
||||
}
|
||||
types.push_str("</Types>");
|
||||
let styles_id = tables.len() + 1;
|
||||
rels.push_str(&format!(r#"<Relationship Id="rId{styles_id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#));
|
||||
put("[Content_Types].xml", &types)?;
|
||||
put("_rels/.rels", r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#)?;
|
||||
put("xl/workbook.xml", &format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>{sheets}</sheets></workbook>"#))?;
|
||||
put("xl/_rels/workbook.xml.rels", &format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{rels}</Relationships>"#))?;
|
||||
// Style 1 = bold header.
|
||||
put("xl/styles.xml", r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs></styleSheet>"#)?;
|
||||
for (i, t) in tables.iter().enumerate() {
|
||||
put(&format!("xl/worksheets/sheet{}.xml", i + 1), &sheet_xml(t))?;
|
||||
}
|
||||
z.finish()?;
|
||||
}
|
||||
Ok(buf.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn sample() -> Value {
|
||||
json!({
|
||||
"from": 0, "to": 1_700_000_000_000i64,
|
||||
"total": {"requests": 3, "cost": 1.5},
|
||||
"by_day": [{"day": "2026-01-02", "requests": 2, "cost": 1.25, "input_tokens": 10}],
|
||||
"by_month": [], "by_model": [{"model": "=evil, \"x\"", "requests": 1}],
|
||||
"by_provider": [], "by_agent": [], "by_user": [], "top_sessions": []
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_uses_locale_and_blocks_formulas() {
|
||||
let tabs = tables(&sample(), true);
|
||||
let day = tabs.iter().find(|t| t.id == "day").unwrap();
|
||||
let c = csv(day, true);
|
||||
assert!(c.starts_with('\u{feff}'));
|
||||
assert!(c.contains("2026-01-02;2;10;0;0;0;0;0;0;0;1,2500"), "{c}");
|
||||
let model = csv(tabs.iter().find(|t| t.id == "model").unwrap(), false);
|
||||
assert!(model.contains("\"'=evil, \"\"x\"\"\""), "{model}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xlsx_is_a_zip_with_every_sheet() {
|
||||
let tabs = tables(&sample(), false);
|
||||
let bytes = xlsx(&tabs).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
for i in 1..=tabs.len() {
|
||||
assert!(z.by_name(&format!("xl/worksheets/sheet{i}.xml")).is_ok());
|
||||
}
|
||||
let mut wb = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("xl/workbook.xml").unwrap(), &mut wb).unwrap();
|
||||
assert!(wb.contains("Per day") && wb.contains("Total"));
|
||||
assert_eq!(col_name(0), "A");
|
||||
assert_eq!(col_name(26), "AA");
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,88 @@ impl Store {
|
||||
content BLOB
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS checkpoints_session ON checkpoints(session_id, ts);
|
||||
CREATE TABLE IF NOT EXISTS project_approvals (
|
||||
cwd TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (cwd, key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS share_links (
|
||||
token TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
owner_id TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS share_links_session ON share_links(session_id);
|
||||
CREATE TABLE IF NOT EXISTS factory_issues (
|
||||
repo_url TEXT NOT NULL,
|
||||
number INTEGER NOT NULL,
|
||||
owner_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
author TEXT NOT NULL DEFAULT '',
|
||||
state TEXT NOT NULL DEFAULT 'new',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
rounds INTEGER NOT NULL DEFAULT 0,
|
||||
last_comment INTEGER NOT NULL DEFAULT 0,
|
||||
scenarios TEXT NOT NULL DEFAULT '',
|
||||
branch TEXT NOT NULL DEFAULT '',
|
||||
pr_url TEXT NOT NULL DEFAULT '',
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (repo_url, number)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS factory_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL,
|
||||
repo_url TEXT NOT NULL,
|
||||
issue INTEGER NOT NULL,
|
||||
phase TEXT NOT NULL,
|
||||
round INTEGER NOT NULL DEFAULT 0,
|
||||
session_id TEXT NOT NULL,
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
started_at INTEGER NOT NULL,
|
||||
ended_at INTEGER,
|
||||
status TEXT NOT NULL DEFAULT 'running',
|
||||
result TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
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 (
|
||||
cwd TEXT PRIMARY KEY,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS project_checks (
|
||||
cwd TEXT PRIMARY KEY,
|
||||
command TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS turn_checks (
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
message_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
exit_code INTEGER,
|
||||
duration_ms INTEGER NOT NULL DEFAULT 0,
|
||||
output TEXT NOT NULL DEFAULT '',
|
||||
ts INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_id, message_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS session_shares (
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
@@ -172,6 +254,7 @@ impl Store {
|
||||
("jobs", "settings", "ALTER TABLE jobs ADD COLUMN settings TEXT"),
|
||||
("images", "blob", "ALTER TABLE images ADD COLUMN blob TEXT"),
|
||||
("usage", "allowance", "ALTER TABLE usage ADD COLUMN allowance REAL"),
|
||||
("factory_issues", "version", "ALTER TABLE factory_issues ADD COLUMN version TEXT NOT NULL DEFAULT ''"),
|
||||
] {
|
||||
let exists: bool = conn
|
||||
.prepare(&format!("SELECT 1 FROM pragma_table_info('{table}') WHERE name = ?1"))?
|
||||
@@ -376,6 +459,16 @@ impl Store {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// (title, cwd) of all other chats (subagent sessions of this chat excluded).
|
||||
pub fn other_session_cwds(&self, id: &str) -> Result<Vec<(String, String)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT COALESCE(json_extract(data, '$.title'), ''), COALESCE(json_extract(data, '$.cwd'), '') FROM sessions WHERE id != ?1 AND COALESCE(parent_id, '') != ?1",
|
||||
)?;
|
||||
let rows = stmt.query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))?;
|
||||
Ok(rows.collect::<std::result::Result<_, _>>()?)
|
||||
}
|
||||
|
||||
pub fn add_message(&self, session_id: &str, m: &Message) -> Result<()> {
|
||||
// Images go to the blob table (encoded before taking the lock).
|
||||
let mut m = m.clone();
|
||||
@@ -653,6 +746,39 @@ impl Store {
|
||||
Ok(json!({"total": total, "by_model": by_model, "by_agent": by_agent, "first": first, "last": last}))
|
||||
}
|
||||
|
||||
/// Plan requests booked at 0 (opencode Go reports nothing charged, only `allowance`):
|
||||
/// (row id, ts, "provider/model", usage).
|
||||
pub fn plan_requests_without_cost(&self) -> Result<Vec<(i64, i64, String, crate::types::Usage)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, ts, provider || '/' || model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, allowance
|
||||
FROM usage WHERE cost = 0 AND allowance > 0",
|
||||
)?;
|
||||
let rows = stmt
|
||||
.query_map([], |r| {
|
||||
Ok((
|
||||
r.get(0)?,
|
||||
r.get(1)?,
|
||||
r.get(2)?,
|
||||
crate::types::Usage {
|
||||
input_tokens: r.get::<_, i64>(3)? as u64,
|
||||
output_tokens: r.get::<_, i64>(4)? as u64,
|
||||
cache_read_tokens: r.get::<_, i64>(5)? as u64,
|
||||
cache_write_tokens: r.get::<_, i64>(6)? as u64,
|
||||
allowance: r.get(7)?,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
pub fn set_usage_cost(&self, row: i64, cost: f64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute("UPDATE usage SET cost = ?2 WHERE id = ?1", params![row, cost])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Global statistics in [from, to) (ms). `tz_offset_min` shifts day/hour buckets
|
||||
/// into the viewer's local time.
|
||||
pub fn global_stats(&self, from: i64, to: i64, tz_offset_min: i64, user: Option<&str>) -> Result<Value> {
|
||||
@@ -686,6 +812,9 @@ impl Store {
|
||||
|
||||
let day_sql = "strftime('%Y-%m-%d', (ts + ?3) / 1000, 'unixepoch')";
|
||||
let by_day = grouped(day_sql, "day")?;
|
||||
// Long ranges are shown per month.
|
||||
let by_month = grouped("strftime('%Y-%m', (ts + ?3) / 1000, 'unixepoch')", "month")?;
|
||||
let first_ts: Option<i64> = conn.query_row("SELECT MIN(ts) FROM usage WHERE (?1 IS NULL OR user_id = ?1)", params![user], |r| r.get(0))?;
|
||||
let by_model = grouped("provider || '/' || model", "model")?;
|
||||
let by_provider = grouped("provider", "provider")?;
|
||||
let by_agent = grouped("agent", "agent")?;
|
||||
@@ -737,6 +866,8 @@ impl Store {
|
||||
Ok(json!({
|
||||
"total": total,
|
||||
"by_day": by_day,
|
||||
"by_month": by_month,
|
||||
"first_ts": first_ts,
|
||||
"by_day_model": by_day_model,
|
||||
"by_model": by_model,
|
||||
"by_provider": by_provider,
|
||||
@@ -1346,6 +1477,159 @@ impl Store {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- software factory ---------------------------------------------------------
|
||||
|
||||
pub fn factory_issue(&self, repo: &str, number: i64) -> Result<Option<Value>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(conn
|
||||
.query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id, version 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)?, "version": r.get::<_, String>(13)?}))
|
||||
})
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn factory_issue_add(&self, repo: &str, number: i64, owner: &str, title: &str, author: &str) -> Result<()> {
|
||||
let now = crate::types::now_ms();
|
||||
self.conn.lock().unwrap().execute(
|
||||
"INSERT OR IGNORE INTO factory_issues (repo_url, number, owner_id, title, author, created_at, updated_at) VALUES (?1,?2,?3,?4,?5,?6,?6)",
|
||||
params![repo, number, owner, title, author, now],
|
||||
)?;
|
||||
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.
|
||||
pub fn factory_issue_set(&self, repo: &str, number: i64, fields: &[(&str, Value)]) -> Result<()> {
|
||||
const COLS: [&str; 11] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author", "version"];
|
||||
let conn = self.conn.lock().unwrap();
|
||||
for (k, v) in fields {
|
||||
if !COLS.contains(k) {
|
||||
anyhow::bail!("unknown column {k}");
|
||||
}
|
||||
let sql = format!("UPDATE factory_issues SET {k} = ?3, updated_at = ?4 WHERE repo_url = ?1 AND number = ?2");
|
||||
let now = crate::types::now_ms();
|
||||
match v {
|
||||
Value::Number(n) => conn.execute(&sql, params![repo, number, n.as_i64().unwrap_or(0), now])?,
|
||||
other => conn.execute(&sql, params![repo, number, other.as_str().unwrap_or(""), now])?,
|
||||
};
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
pub fn factory_issues(&self, owner: &str) -> Result<Vec<Value>> {
|
||||
let nums: Vec<(String, i64)> = {
|
||||
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")?;
|
||||
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())
|
||||
}
|
||||
|
||||
pub fn factory_run_add(&self, id: &str, owner: &str, repo: &str, issue: i64, phase: &str, round: i64, session: &str, model: &str) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute(
|
||||
"INSERT INTO factory_runs (id, owner_id, repo_url, issue, phase, round, session_id, model, started_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
|
||||
params![id, owner, repo, issue, phase, round, session, model, crate::types::now_ms()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn factory_run_end(&self, id: &str, status: &str, result: &str) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute("UPDATE factory_runs SET ended_at = ?2, status = ?3, result = ?4 WHERE id = ?1", params![id, crate::types::now_ms(), status, result])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn factory_running(&self, repo: &str) -> Result<i64> {
|
||||
// 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))?)
|
||||
}
|
||||
|
||||
/// Runs with token and cost totals (joined from the usage table).
|
||||
pub fn factory_runs(&self, owner: &str, repo: Option<&str>, issue: Option<i64>, limit: i64) -> Result<Vec<Value>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut st = conn.prepare(
|
||||
"SELECT f.id, f.repo_url, f.issue, f.phase, f.round, f.session_id, f.model, f.started_at, f.ended_at, f.status, f.result,
|
||||
COALESCE((SELECT SUM(input_tokens + cache_read_tokens + cache_write_tokens) FROM usage WHERE session_id = f.session_id),0),
|
||||
COALESCE((SELECT SUM(output_tokens) FROM usage WHERE session_id = f.session_id),0),
|
||||
COALESCE((SELECT SUM(cost) FROM usage WHERE session_id = f.session_id),0.0)
|
||||
FROM factory_runs f WHERE f.owner_id = ?1 AND (?2 IS NULL OR f.repo_url = ?2) AND (?3 IS NULL OR f.issue = ?3)
|
||||
ORDER BY f.started_at DESC LIMIT ?4",
|
||||
)?;
|
||||
let rows = st.query_map(params![owner, repo, issue, limit], |r| {
|
||||
Ok(json!({"id": r.get::<_, String>(0)?, "repo": r.get::<_, String>(1)?, "issue": r.get::<_, i64>(2)?, "phase": r.get::<_, String>(3)?, "round": r.get::<_, i64>(4)?, "session_id": r.get::<_, String>(5)?, "model": r.get::<_, String>(6)?, "started_at": r.get::<_, i64>(7)?, "ended_at": r.get::<_, Option<i64>>(8)?, "status": r.get::<_, String>(9)?, "result": r.get::<_, String>(10)?, "input_tokens": r.get::<_, i64>(11)?, "output_tokens": r.get::<_, i64>(12)?, "cost": r.get::<_, f64>(13)?}))
|
||||
})?;
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
/// After a restart: runs that were still going are over; their issues go back one step.
|
||||
pub fn factory_recover(&self) -> Result<usize> {
|
||||
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()])?;
|
||||
conn.execute("UPDATE factory_issues SET state = 'new' WHERE state = 'review'", [])?;
|
||||
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 = '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)
|
||||
}
|
||||
|
||||
pub fn job_touch(&self, id: &str, ts: i64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute("UPDATE jobs SET last_run = ?2 WHERE id = ?1", rusqlite::params![id, ts])?;
|
||||
Ok(())
|
||||
@@ -1448,6 +1732,167 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
// --- project overview ------------------------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
/// Per chat: files the agent changed, the latest check result and the cost.
|
||||
pub fn project_overview(&self, session_ids: &[String]) -> Result<Value> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut out = serde_json::Map::new();
|
||||
for id in session_ids {
|
||||
let files: i64 = conn.query_row("SELECT COUNT(DISTINCT path) FROM checkpoints WHERE session_id = ?1", params![id], |r| r.get(0))?;
|
||||
let check: Option<String> = conn
|
||||
.query_row("SELECT status FROM turn_checks WHERE session_id = ?1 ORDER BY ts DESC LIMIT 1", params![id], |r| r.get(0))
|
||||
.optional()?;
|
||||
let failed: i64 = conn.query_row("SELECT COUNT(*) FROM turn_checks WHERE session_id = ?1 AND status IN ('failed','timeout')", params![id], |r| r.get(0))?;
|
||||
let cost: Option<f64> = conn.query_row("SELECT SUM(cost) FROM usage WHERE root_session_id = ?1", params![id], |r| r.get(0))?;
|
||||
out.insert(id.clone(), json!({"files": files, "check": check, "checks_failed": failed, "cost": cost.unwrap_or(0.0)}));
|
||||
}
|
||||
Ok(Value::Object(out))
|
||||
}
|
||||
}
|
||||
|
||||
// --- weekly overview ----------------------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
/// (chats with activity, failed checks, checks run) of a user's own top-level chats since `since` (ms).
|
||||
pub fn weekly_counts(&self, user_id: &str, since: i64) -> Result<(i64, i64, i64)> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let chats: i64 = conn.query_row("SELECT COUNT(*) FROM sessions WHERE owner_id = ?1 AND parent_id IS NULL AND updated_at >= ?2", params![user_id, since], |r| r.get(0))?;
|
||||
let (failed, total): (i64, i64) = conn.query_row(
|
||||
"SELECT COALESCE(SUM(c.status IN ('failed','timeout')),0), COUNT(*) FROM turn_checks c JOIN sessions s ON s.id = c.session_id WHERE s.owner_id = ?1 AND c.ts >= ?2",
|
||||
params![user_id, since],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
Ok((chats, failed, total))
|
||||
}
|
||||
}
|
||||
|
||||
// --- read-only links ----------------------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
pub fn add_share_link(&self, token: &str, session_id: &str, owner_id: &str, created_at: i64, expires_at: i64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute(
|
||||
"INSERT INTO share_links (token, session_id, owner_id, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![token, session_id, owner_id, created_at, expires_at],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// (token, created_at, expires_at) of the links of a chat, newest first.
|
||||
pub fn share_links(&self, session_id: &str) -> Result<Vec<(String, i64, i64)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT token, created_at, expires_at FROM share_links WHERE session_id = ?1 ORDER BY created_at DESC")?;
|
||||
let rows = stmt.query_map([session_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;
|
||||
Ok(rows.collect::<std::result::Result<_, _>>()?)
|
||||
}
|
||||
|
||||
/// The chat a link points to while it is valid.
|
||||
pub fn share_link_session(&self, token: &str, now: i64) -> Result<Option<String>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(conn.query_row("SELECT session_id FROM share_links WHERE token = ?1 AND expires_at > ?2", params![token, now], |r| r.get(0)).optional()?)
|
||||
}
|
||||
|
||||
pub fn delete_share_link(&self, session_id: &str, token: &str) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute("DELETE FROM share_links WHERE session_id = ?1 AND token = ?2", params![session_id, token])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Links are dropped with their chat and when expired.
|
||||
pub fn purge_share_links(&self, now: i64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute("DELETE FROM share_links WHERE expires_at <= ?1 OR session_id NOT IN (SELECT id FROM sessions)", params![now])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- defaults of new chats in a project -------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
/// {model, agent, permission_mode, color, instructions, folder} new chats of the folder start with.
|
||||
pub fn project_defaults(&self, cwd: &str) -> Result<Option<Value>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let v: Option<String> = conn.query_row("SELECT data FROM project_defaults WHERE cwd = ?1", params![cwd], |r| r.get(0)).optional()?;
|
||||
Ok(v.and_then(|v| serde_json::from_str(&v).ok()))
|
||||
}
|
||||
|
||||
pub fn set_project_defaults(&self, cwd: &str, data: Option<&Value>) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
match data {
|
||||
Some(d) => conn.execute("INSERT INTO project_defaults (cwd, data) VALUES (?1, ?2) ON CONFLICT(cwd) DO UPDATE SET data = ?2", params![cwd, d.to_string()])?,
|
||||
None => conn.execute("DELETE FROM project_defaults WHERE cwd = ?1", params![cwd])?,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- checks after a turn ------------------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
/// (command, enabled) of a project folder.
|
||||
pub fn project_check(&self, cwd: &str) -> Result<Option<(String, bool)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(conn.query_row("SELECT command, enabled FROM project_checks WHERE cwd = ?1", params![cwd], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? != 0))).optional()?)
|
||||
}
|
||||
|
||||
pub fn set_project_check(&self, cwd: &str, command: &str, enabled: bool) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
if command.trim().is_empty() {
|
||||
conn.execute("DELETE FROM project_checks WHERE cwd = ?1", params![cwd])?;
|
||||
} else {
|
||||
conn.execute(
|
||||
"INSERT INTO project_checks (cwd, command, enabled) VALUES (?1, ?2, ?3) ON CONFLICT(cwd) DO UPDATE SET command = ?2, enabled = ?3",
|
||||
params![cwd, command.trim(), enabled as i64],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_turn_check(&self, session_id: &str, message_id: &str, status: &str, exit_code: Option<i32>, duration_ms: u64, output: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO turn_checks (session_id, message_id, status, exit_code, duration_ms, output, ts) VALUES (?1,?2,?3,?4,?5,?6,?7)
|
||||
ON CONFLICT(session_id, message_id) DO UPDATE SET status = ?3, exit_code = ?4, duration_ms = ?5, output = ?6, ts = ?7",
|
||||
params![session_id, message_id, status, exit_code, duration_ms as i64, output, now_ms()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn turn_checks(&self, session_id: &str) -> Result<Vec<Value>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT message_id, status, exit_code, duration_ms, output FROM turn_checks WHERE session_id = ?1 ORDER BY ts DESC LIMIT 300")?;
|
||||
let rows = stmt
|
||||
.query_map(params![session_id], |r| {
|
||||
Ok(json!({"message_id": r.get::<_, String>(0)?, "status": r.get::<_, String>(1)?, "exit_code": r.get::<_, Option<i32>>(2)?, "duration_ms": r.get::<_, i64>(3)?, "output": r.get::<_, String>(4)?}))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
|
||||
// --- project-wide approvals ---------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
/// Approvals ("bash:<prefix>" or a tool name) remembered for a project folder.
|
||||
pub fn project_approvals(&self, cwd: &str) -> Result<Vec<String>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT key FROM project_approvals WHERE cwd = ?1 ORDER BY key")?;
|
||||
let rows = stmt.query_map(params![cwd], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
pub fn add_project_approval(&self, cwd: &str, key: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute("INSERT OR IGNORE INTO project_approvals (cwd, key, created_at) VALUES (?1, ?2, ?3)", params![cwd, key, now_ms()])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_project_approval(&self, cwd: &str, key: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute("DELETE FROM project_approvals WHERE cwd = ?1 AND key = ?2", params![cwd, key])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- file checkpoints ------------------------------------------------------------
|
||||
|
||||
impl Store {
|
||||
@@ -1463,13 +1908,18 @@ impl Store {
|
||||
|
||||
/// Per path, the oldest snapshot taken at or after `since` (ms): the state to restore.
|
||||
pub fn checkpoints_since(&self, session_id: &str, since: i64) -> Result<Vec<(String, Option<Vec<u8>>)>> {
|
||||
self.checkpoints_between(session_id, since, i64::MAX)
|
||||
}
|
||||
|
||||
/// Per file the state before its first change in the time range [since, until).
|
||||
pub fn checkpoints_between(&self, session_id: &str, since: i64, until: i64) -> Result<Vec<(String, Option<Vec<u8>>)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT path, existed, content FROM checkpoints c WHERE session_id = ?1 AND ts >= ?2
|
||||
AND id = (SELECT MIN(id) FROM checkpoints WHERE session_id = ?1 AND ts >= ?2 AND path = c.path)",
|
||||
"SELECT path, existed, content FROM checkpoints c WHERE session_id = ?1 AND ts >= ?2 AND ts < ?3
|
||||
AND id = (SELECT MIN(id) FROM checkpoints WHERE session_id = ?1 AND ts >= ?2 AND ts < ?3 AND path = c.path)",
|
||||
)?;
|
||||
let rows = stmt
|
||||
.query_map(params![session_id, since], |r| {
|
||||
.query_map(params![session_id, since, until], |r| {
|
||||
let existed: i64 = r.get(1)?;
|
||||
Ok((r.get::<_, String>(0)?, if existed != 0 { r.get::<_, Option<Vec<u8>>>(2)? } else { None }))
|
||||
})?
|
||||
@@ -1539,3 +1989,36 @@ fn snippet_in(m: &Message, needle: &str) -> Option<String> {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod link_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn share_links_expire_and_can_be_revoked() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-links-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let store = Store::open(&dir.join("t.db")).unwrap();
|
||||
store.add_share_link("tok1", "s1", "u", 1_000, 5_000).unwrap();
|
||||
store.add_share_link("tok2", "s1", "u", 2_000, 9_000).unwrap();
|
||||
// Valid until the expiry time, then gone.
|
||||
assert_eq!(store.share_link_session("tok1", 4_999).unwrap().as_deref(), Some("s1"));
|
||||
assert_eq!(store.share_link_session("tok1", 5_000).unwrap(), None);
|
||||
assert_eq!(store.share_link_session("nope", 1).unwrap(), None);
|
||||
// Revoking removes only the named link of that chat.
|
||||
store.delete_share_link("other", "tok2").unwrap();
|
||||
assert!(store.share_link_session("tok2", 3_000).unwrap().is_some());
|
||||
store.delete_share_link("s1", "tok2").unwrap();
|
||||
assert_eq!(store.share_link_session("tok2", 3_000).unwrap(), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weekly_counts_of_an_empty_user_are_zero() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-weekly-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let store = Store::open(&dir.join("t.db")).unwrap();
|
||||
assert_eq!(store.weekly_counts("nobody", 0).unwrap(), (0, 0, 0));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,48 @@ pub struct Settings {
|
||||
/// Reasoning effort for the next messages (/effort).
|
||||
#[serde(default)]
|
||||
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 {
|
||||
@@ -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"))
|
||||
}
|
||||
|
||||
/// 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).
|
||||
pub fn german(app: &App, user_id: &str) -> bool {
|
||||
let prefs: Value = app.store.user_setting(user_id, "prefs").unwrap_or_default();
|
||||
@@ -541,6 +595,9 @@ async fn new_session(app: &Arc<App>, u: &User, bot: &Bot, chat: i64, arg: &str,
|
||||
instructions: String::new(),
|
||||
// Started from Telegram: keeps reporting there after switching to another chat.
|
||||
telegram_quiet: false,
|
||||
summary: String::new(),
|
||||
color: None,
|
||||
icon: None, skills: Vec::new(),
|
||||
})?;
|
||||
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?;
|
||||
@@ -872,6 +929,10 @@ async fn listen(app: Arc<App>) {
|
||||
let Some(chat) = st.chat_id else { continue };
|
||||
let de = german(&app, &owner);
|
||||
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
|
||||
// (subagents follow their top-level chat; the chat open in Telegram always reports).
|
||||
if !is_current && matches!(ev, Event::PermissionRequest { .. } | Event::QuestionRequest { .. }) {
|
||||
@@ -1201,3 +1262,30 @@ mod tests {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,8 @@ pub fn spawn(app: &Arc<App>, user: &User, cwd: &Path, session_id: Option<String>
|
||||
.current_dir(cwd)
|
||||
.env("TERM", "xterm-256color")
|
||||
.env("CODECRAFT", "1")
|
||||
.envs(crate::gitcreds::identity_env(app, &user.id));
|
||||
.envs(crate::gitcreds::identity_env(app, &user.id))
|
||||
.envs(crate::sshkeys::env(app, user));
|
||||
match crate::gitcreds::global_config(app, user) {
|
||||
Some(cfg) => c.env("GIT_CONFIG_GLOBAL", cfg),
|
||||
None => c,
|
||||
|
||||
@@ -135,7 +135,7 @@ impl Tool for Bash {
|
||||
/// The bash command for a script, sandboxed for non-admin users.
|
||||
pub fn shell_command(ctx: &ToolCtx, command: &str) -> std::result::Result<Command, ToolOutput> {
|
||||
// stderr of every command (not just the last one) goes into the output.
|
||||
let script = format!("exec 2>&1\n{command}");
|
||||
let script = format!("exec 2>&1\n{}{command}", commit_attribution(ctx));
|
||||
Ok(match &ctx.sandbox {
|
||||
Some(spec) => {
|
||||
if !crate::sandbox::available() {
|
||||
@@ -155,12 +155,43 @@ pub fn shell_command(ctx: &ToolCtx, command: &str) -> std::result::Result<Comman
|
||||
c.env("GIT_CONFIG_GLOBAL", cfg);
|
||||
}
|
||||
c.envs(crate::gitcreds::identity_env(&ctx.app, &u.id));
|
||||
c.envs(crate::sshkeys::env(&ctx.app, &u));
|
||||
}
|
||||
c
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Directory with the git wrapper that adds the co-author trailer to commits.
|
||||
fn git_wrapper_dir() -> String {
|
||||
std::env::var("CODECRAFT_GIT_WRAPPER").unwrap_or_else(|_| "/usr/local/lib/codecraft/bin".into())
|
||||
}
|
||||
|
||||
/// Shell lines that make `git commit` in this command carry the co-author trailer of
|
||||
/// the session's model (see docker/git-coauthor). Set in the script itself, so it
|
||||
/// works inside the sandbox (which clears the environment) too.
|
||||
fn commit_attribution(ctx: &ToolCtx) -> String {
|
||||
let template = ctx.app.config().server.commit_trailer.clone();
|
||||
let dir = git_wrapper_dir();
|
||||
if template.trim().is_empty() || !std::path::Path::new(&dir).join("git").exists() {
|
||||
return String::new();
|
||||
}
|
||||
let Ok(session) = ctx.app.session(&ctx.session_id) else { return String::new() };
|
||||
let (provider, model_id) = session.model.split_once('/').unwrap_or(("", session.model.as_str()));
|
||||
let name = ctx.app.registry().resolve(&session.model).ok().and_then(|(_, m)| m.name).filter(|n| !n.trim().is_empty()).unwrap_or_else(|| model_id.to_string());
|
||||
let trailer = commit_trailer(&template, &name, provider, model_id);
|
||||
format!("export PATH={}:\"$PATH\" CODECRAFT_COMMIT_TRAILER={}\n", shell_quote(&dir), shell_quote(&trailer))
|
||||
}
|
||||
|
||||
/// The trailer text for a model ("Co-Authored-By: DeepSeek V4.1 Flash (opencode-go) via CodeCraft").
|
||||
pub fn commit_trailer(template: &str, model: &str, provider: &str, model_id: &str) -> String {
|
||||
template.replace("{model}", model).replace("{provider}", provider).replace("{model_id}", model_id).replace(['\n', '\r'], " ").trim().to_string()
|
||||
}
|
||||
|
||||
fn shell_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
fn tail(s: &str, max: usize) -> String {
|
||||
if s.len() <= max {
|
||||
return s.to_string();
|
||||
@@ -171,3 +202,18 @@ fn tail(s: &str, max: usize) -> String {
|
||||
}
|
||||
s[start..].to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod commit_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commit_trailer_text() {
|
||||
assert_eq!(
|
||||
commit_trailer(crate::config::DEFAULT_COMMIT_TRAILER, "DeepSeek V4.1 Flash", "opencode-go", "deepseek-v4.1-flash"),
|
||||
"Co-Authored-By: DeepSeek V4.1 Flash (opencode-go) via CodeCraft"
|
||||
);
|
||||
assert_eq!(commit_trailer("By {model_id}\nx", "M", "p", "m-1"), "By m-1 x");
|
||||
assert_eq!(shell_quote("it's"), "'it'\\''s'");
|
||||
}
|
||||
}
|
||||
@@ -177,6 +177,7 @@ pub fn builtin_tools() -> Vec<Arc<dyn Tool>> {
|
||||
Arc::new(craft::ImageCompare),
|
||||
Arc::new(crate::prompts::SkillTool),
|
||||
Arc::new(crate::images::GenerateImage),
|
||||
Arc::new(crate::mesh3d::Generate3d),
|
||||
Arc::new(crate::reverse::BinaryInfo),
|
||||
Arc::new(crate::reverse::Decompile),
|
||||
]
|
||||
|
||||
@@ -7,6 +7,12 @@ self.addEventListener("push", (event) => {
|
||||
data = { body: event.data ? event.data.text() : "" };
|
||||
}
|
||||
const title = data.title || "CodeCraft";
|
||||
const de = String((self.navigator && self.navigator.language) || "").toLowerCase().startsWith("de");
|
||||
// Approvals can be answered right from the notification.
|
||||
const actions = data.kind === "permission" && data.permission_id ? [
|
||||
{ action: "allow", title: de ? "Erlauben" : "Allow" },
|
||||
{ action: "reject", title: de ? "Ablehnen" : "Reject" },
|
||||
] : [];
|
||||
const prefix = { permission: "🔐 ", question: "❓ ", done: "✅ " }[data.kind] || "";
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(prefix + title, {
|
||||
@@ -15,13 +21,40 @@ self.addEventListener("push", (event) => {
|
||||
renotify: true,
|
||||
icon: "/icon-192.png",
|
||||
badge: "/icon-192.png",
|
||||
data: { url: data.url || "/" },
|
||||
actions,
|
||||
requireInteraction: data.kind === "permission",
|
||||
data: { url: data.url || "/", permission_id: data.permission_id || null },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close();
|
||||
const info = event.notification.data || {};
|
||||
if ((event.action === "allow" || event.action === "reject") && info.permission_id) {
|
||||
const de = String((self.navigator && self.navigator.language) || "").toLowerCase().startsWith("de");
|
||||
const target = new URL(info.url || "/", self.location.origin).href;
|
||||
event.waitUntil(
|
||||
fetch("/api/permissions/" + encodeURIComponent(info.permission_id), {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ reply: event.action === "allow" ? "once" : "reject" }),
|
||||
})
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
// Short confirmation, so the tap does not feel lost.
|
||||
return self.registration.showNotification(event.action === "allow" ? (de ? "Erlaubt" : "Allowed") : (de ? "Abgelehnt" : "Rejected"), {
|
||||
tag: "perm-" + info.permission_id,
|
||||
icon: "/icon-192.png",
|
||||
silent: true,
|
||||
data: { url: info.url },
|
||||
}).then(() => new Promise((res) => setTimeout(res, 2500))).then(() => self.registration.getNotifications({ tag: "perm-" + info.permission_id })).then((l) => l.forEach((n) => n.close()));
|
||||
})
|
||||
.catch(() => self.clients.openWindow(target)), // expired, answered elsewhere or signed out: open the app
|
||||
);
|
||||
return;
|
||||
}
|
||||
const url = new URL((event.notification.data && event.notification.data.url) || "/", self.location.origin).href;
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((list) => {
|
||||
|
||||
@@ -2,8 +2,10 @@ import { lazy, Suspense, useEffect, useState } from "react";
|
||||
import { connectEvents, get, setUnauthorizedHandler } from "./api";
|
||||
import { useT } from "./i18n";
|
||||
import { navigate, useRoute, closePane, MAX_PANES } from "./router";
|
||||
import { applyEvent, loadSessions, resync, setState } from "./store";
|
||||
import { applyEvent, loadSessions, resync, setState, useStore } from "./store";
|
||||
import type { Info } from "./types";
|
||||
import { ImageViewer } from "./components/ImageViewer";
|
||||
import { ProjectPage } from "./components/ProjectPage";
|
||||
import { Sidebar } from "./components/Sidebar";
|
||||
import { Login } from "./components/Login";
|
||||
import { ChatView } from "./components/ChatView";
|
||||
@@ -11,6 +13,7 @@ import { NewSession } from "./components/NewSession";
|
||||
import { Settings } from "./components/Settings";
|
||||
import { Stats } from "./components/Stats";
|
||||
import { Images } from "./components/Images";
|
||||
import { Factory } from "./components/Factory";
|
||||
import { Jobs } from "./components/Jobs";
|
||||
import { JobEditor } from "./components/JobEditor";
|
||||
import { Spinner, useTitleActivity } from "./components/Activity";
|
||||
@@ -20,6 +23,8 @@ import { WhatsNew } from "./components/WhatsNew";
|
||||
import { ShareTarget } from "./components/ShareTarget";
|
||||
import { Palette } from "./components/Palette";
|
||||
import { pendingShare } from "./share";
|
||||
import { cacheInfo, cachedInfo, isOffline } from "./offline";
|
||||
import { PublicChat } from "./components/PublicChat";
|
||||
|
||||
// The file manager (editor, git) is loaded on demand to keep the chat small.
|
||||
const Files = lazy(() => import("./components/Files").then((m) => ({ default: m.Files })));
|
||||
@@ -31,12 +36,39 @@ export function App() {
|
||||
const [info, setInfo] = useState<Info>();
|
||||
const [error, setError] = useState<string>();
|
||||
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 offline = useStore((s) => s.offline);
|
||||
useTitleActivity();
|
||||
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const i = await get<Info>("/info");
|
||||
let i: Info;
|
||||
try {
|
||||
i = await get<Info>("/info");
|
||||
cacheInfo(i);
|
||||
} catch (e) {
|
||||
// No connection: open with the saved copy (chats are read-only).
|
||||
const saved = isOffline(e) ? cachedInfo() : undefined;
|
||||
if (!saved) throw e;
|
||||
i = saved;
|
||||
}
|
||||
setState(() => ({ me: i.user, update: i.update ?? null }));
|
||||
if (i.user) {
|
||||
await loadSessions();
|
||||
@@ -69,6 +101,7 @@ export function App() {
|
||||
// Close the mobile menu on navigation.
|
||||
useEffect(() => setMenuOpen(false), [route.join("/")]);
|
||||
|
||||
if (route[0] === "shared" && route[1]) return <PublicChat token={route[1]} />;
|
||||
if (error) return <div className="empty">{error}</div>;
|
||||
if (!info) return <div className="empty">{t("common.loading")}</div>;
|
||||
if (!info.user)
|
||||
@@ -82,43 +115,49 @@ export function App() {
|
||||
const [section, arg] = route;
|
||||
let content;
|
||||
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)
|
||||
content = (
|
||||
<div className="split-view">
|
||||
{chatIds.map((id) => (
|
||||
<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>
|
||||
);
|
||||
else if (section === "settings") content = <Settings tab={arg} onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "stats") content = <Stats onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "images") content = <Images onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "jobs" && arg) content = <JobEditor key={arg} id={arg} onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "jobs") content = <Jobs 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={openMenu} />;
|
||||
else if (section === "factory") content = <Factory onMenu={openMenu} />;
|
||||
else if (section === "stats") content = <Stats onMenu={openMenu} />;
|
||||
else if (section === "images") content = <Images onMenu={openMenu} />;
|
||||
else if (section === "jobs" && arg) content = <JobEditor key={arg} id={arg} onMenu={openMenu} />;
|
||||
else if (section === "jobs") content = <Jobs onMenu={openMenu} />;
|
||||
else if (section === "terminal")
|
||||
content = (
|
||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||
<TerminalPage id={arg} onMenu={() => setMenuOpen(true)} />
|
||||
<TerminalPage id={arg} onMenu={openMenu} />
|
||||
</Suspense>
|
||||
);
|
||||
else if (section === "files")
|
||||
content = (
|
||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||
<Files onMenu={() => setMenuOpen(true)} />
|
||||
<Files onMenu={openMenu} />
|
||||
</Suspense>
|
||||
);
|
||||
else content = <NewSession onMenu={() => setMenuOpen(true)} onCreated={(id) => navigate(`/s/${id}`)} />;
|
||||
else content = <NewSession onMenu={openMenu} onCreated={(id) => navigate(`/s/${id}`)} />;
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<div className={`app ${folded ? "side-folded" : ""}`}>
|
||||
{menuOpen && <div className="backdrop" onClick={() => setMenuOpen(false)} />}
|
||||
<Sidebar open={menuOpen} activeIds={chatIds} section={section ?? ""} />
|
||||
<main className="main">{content}</main>
|
||||
<main className="main">
|
||||
{offline && <div className="offline-bar" role="status">{t("offline.banner")}</div>}
|
||||
{content}
|
||||
</main>
|
||||
<WhatsNew version={info.version} />
|
||||
<Palette />
|
||||
<ImageViewer />
|
||||
{shared && <ShareTarget shared={shared} onClose={() => setShared(null)} />}
|
||||
<DialogHost />
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ServerEvent } from "./types";
|
||||
import { chunkedUpload } from "./uploads";
|
||||
|
||||
// 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
|
||||
* server's max_upload_mb). `onProgress` gets the uploaded fraction 0..1.
|
||||
* Upload a single file in chunks (see uploads.ts). `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> {
|
||||
let offset = 0;
|
||||
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);
|
||||
await chunkedUpload(`/api/files/upload?path=${encodeURIComponent(path)}`, file, (n) => onProgress?.(file.size ? n / file.size : 1));
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { del, get } from "./api";
|
||||
import { choiceDialog, confirmDialog, toast } from "./dialogs";
|
||||
import { t } from "./i18n";
|
||||
import { formatSize } from "./components/FileFigure";
|
||||
|
||||
interface FolderInfo {
|
||||
own: boolean;
|
||||
path?: string;
|
||||
files?: number;
|
||||
bytes?: number;
|
||||
git?: boolean;
|
||||
truncated?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a chat after asking. A chat with a folder of its own (not shared with other chats, not a
|
||||
* project) gets the question whether the folder goes with it. Resolves to true when it was deleted.
|
||||
*/
|
||||
export async function deleteChat(session: { id: string; parent_id?: string | null }): Promise<boolean> {
|
||||
const folder = session.parent_id ? undefined : await get<FolderInfo>(`/sessions/${session.id}/folder`).catch(() => undefined);
|
||||
let withFolder = false;
|
||||
if (folder?.own) {
|
||||
const size = `${folder.truncated ? "> " : ""}${t("chat.folderFiles", { n: folder.files ?? 0 })}, ${formatSize(folder.bytes ?? 0)}`;
|
||||
const choice = await choiceDialog({
|
||||
title: t("chat.deleteTitle"),
|
||||
message: `${t("chat.deleteWithFolder", { path: folder.path ?? "", size })}${folder.git ? `\n\n${t("chat.folderHasGit")}` : ""}`,
|
||||
choices: [
|
||||
{ value: "chat", label: t("chat.deleteOnlyChat") },
|
||||
{ value: "both", label: t("chat.deleteChatAndFolder"), danger: true },
|
||||
],
|
||||
});
|
||||
if (!choice) return false;
|
||||
withFolder = choice === "both";
|
||||
} else if (!(await confirmDialog({ message: t("chat.deleteConfirm"), danger: true, confirmLabel: t("common.delete") }))) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const r = await del<{ folder_deleted?: boolean; folder_error?: string }>(`/sessions/${session.id}${withFolder ? "?delete_folder=true" : ""}`);
|
||||
if (r?.folder_error) toast(r.folder_error);
|
||||
else if (r?.folder_deleted) toast(t("chat.folderDeleted"), "success");
|
||||
return true;
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
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 (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("skills.chatTitle")} onClick={(e) => e.stopPropagation()}>
|
||||
<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) => (
|
||||
<label key={s.name} className="row" style={{ gap: 8, alignItems: "flex-start", padding: "2px 0" }}>
|
||||
<input type="checkbox" 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>
|
||||
</label>
|
||||
))}
|
||||
</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 className="primary" onClick={() => void save()} disabled={busy}>
|
||||
{busy ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import { DraftBar, IssueBar, isDraftChat, isIssueChat } from "./FactoryDraft";
|
||||
import { takePrefill } from "../share";
|
||||
import { Icon } from "./Icon";
|
||||
import { FileChip, FileFigure, fileType, imageSize, imageSrc } from "./FileFigure";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
|
||||
import { del, get, patch, post } from "../api";
|
||||
import { del, get, patch, post, put } from "../api";
|
||||
import { useFetch, useModels } from "../hooks";
|
||||
import { fmtCompact, fmtCost, fmtNumber, fmtPercent, useT, type Key } from "../i18n";
|
||||
import { fmtCompact, fmtCost, fmtMsgTime, fmtNumber, fmtPercent, useT, type Key } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
import { dismissError, getState, loadAround, loadOlder, loadSession, loadSessions, useStore } from "../store";
|
||||
import { dismissError, getState, loadAround, loadChecks, loadOlder, loadSession, loadSessions, useStore } from "../store";
|
||||
import type { Aggregate, ImageData, Message, Part, Session, Todo } from "../types";
|
||||
import { ActivityLine, Dots, Spinner, ThinkIcon, WorkBar } from "./Activity";
|
||||
import { useReasoningMode, useTodosCollapsed } from "../prefs";
|
||||
@@ -14,6 +15,7 @@ import { Composer } from "./Composer";
|
||||
import { ShareDialog } from "./ShareDialog";
|
||||
import { RenameDialog } from "./RenameDialog";
|
||||
import { InstructionsDialog } from "./InstructionsDialog";
|
||||
import { ChatSkillsDialog } from "./ChatSkills";
|
||||
import { RegenerateButton } from "./Regenerate";
|
||||
import { WorktreeChip } from "./WorktreeChip";
|
||||
import { QueueList } from "./QueueList";
|
||||
@@ -24,8 +26,16 @@ import { UsageOverlay } from "./UsageOverlay";
|
||||
import { RewindDialog } from "./RewindDialog";
|
||||
import { ShellsChip } from "./ShellsPanel";
|
||||
import { TodoList, ToolCard } from "./ToolCard";
|
||||
import { confirmDialog, promptDialog, toast } from "../dialogs";
|
||||
import { promptDialog, toast } from "../dialogs";
|
||||
import { deleteChat } from "../chatActions";
|
||||
import { ChatTabBar, ChatTabPanes, useChatTabs } from "./ChatTabs";
|
||||
import { ColorSwatches, IconPicker } from "./ColorSwatches";
|
||||
import { ProjectPermissions } from "./ProjectPermissions";
|
||||
import { OutboxBar } from "./OutboxBar";
|
||||
import { addToOutbox, isOffline } from "../outbox";
|
||||
import { TurnCheck } from "./TurnCheck";
|
||||
import { TurnChanges } from "./TurnChanges";
|
||||
import { ChatCtx, MessageMenu } from "./MessageMenu";
|
||||
import { MediaGallery } from "./MediaGallery";
|
||||
|
||||
type ToolResult = Extract<Part, { type: "tool_result" }>;
|
||||
@@ -245,8 +255,10 @@ const MessageList = memo(function MessageList({
|
||||
baseDir,
|
||||
onRewind,
|
||||
highlight,
|
||||
currency,
|
||||
}: {
|
||||
messages: Message[];
|
||||
currency: string;
|
||||
results: Map<string, ToolResult>;
|
||||
busy: boolean;
|
||||
canEdit: boolean;
|
||||
@@ -280,13 +292,71 @@ const MessageList = memo(function MessageList({
|
||||
));
|
||||
// Finished turns with tool steps fold into one line (the answer stays visible).
|
||||
const steps = b.messages.flatMap((m) => m.parts.filter((p) => p.type === "tool_call")) as ToolCall[];
|
||||
if (i === lastWork || steps.length < 2) return <div key={key}>{items}</div>;
|
||||
return <WorkBlock key={key} messages={b.messages} steps={steps} open={!!highlight && b.messages.some((m) => m.id === highlight)} baseDir={baseDir}>{items}</WorkBlock>;
|
||||
const usage = !(busy && i === lastWork) && <TurnUsage messages={b.messages} currency={currency} />;
|
||||
// Files the agent wrote or edited in this turn: diffs and "roll back" (not while it is still working).
|
||||
const changed = new Set(steps.filter((c) => (c.name === "write" || c.name === "edit") && typeof c.input?.path === "string").map((c) => c.input.path as string));
|
||||
const lastAnswer = [...b.messages].reverse().find((m) => m.role === "assistant");
|
||||
const checkBadge = lastAnswer && !(busy && i === lastWork) && <TurnCheck sessionId={sessionId} messageId={lastAnswer.id} canSend={canEdit} />;
|
||||
const prev = blocks[i - 1];
|
||||
const changes = changed.size > 0 && !(busy && i === lastWork) && (
|
||||
<TurnChanges
|
||||
sessionId={sessionId}
|
||||
fromId={b.messages[0].id}
|
||||
untilId={blocks[i + 1]?.messages[0].id}
|
||||
fileCount={changed.size}
|
||||
userMessage={canEdit && prev?.kind === "user" ? prev.messages[0] : undefined}
|
||||
onRewind={onRewind}
|
||||
/>
|
||||
);
|
||||
if (i === lastWork || steps.length < 2)
|
||||
return (
|
||||
<div key={key}>
|
||||
{items}
|
||||
{usage}
|
||||
{checkBadge}
|
||||
{changes}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div key={key}>
|
||||
<WorkBlock messages={b.messages} steps={steps} open={!!highlight && b.messages.some((m) => m.id === highlight)} baseDir={baseDir}>
|
||||
{items}
|
||||
</WorkBlock>
|
||||
{usage}
|
||||
{checkBadge}
|
||||
{changes}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
/** Tokens (in/out) and cost of one answer: all requests of the turn together. */
|
||||
function TurnUsage({ messages, currency }: { messages: Message[]; currency: string }) {
|
||||
const t = useT();
|
||||
let inp = 0;
|
||||
let out = 0;
|
||||
let cost = 0;
|
||||
let requests = 0;
|
||||
for (const m of messages) {
|
||||
const u = m.role === "assistant" ? m.usage : undefined;
|
||||
if (!u) continue;
|
||||
requests++;
|
||||
inp += u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
|
||||
out += u.output_tokens;
|
||||
cost += u.cost ?? 0;
|
||||
}
|
||||
if (!requests) return null;
|
||||
return (
|
||||
<div className="turn-usage" title={t("chat.turnUsageHint", { n: requests })}>
|
||||
{fmtCompact(inp)}
|
||||
<Icon name="arrow-up" className="tiny" /> {fmtCompact(out)}
|
||||
<Icon name="arrow-down" className="tiny" /> · {fmtCost(cost, currency)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A finished turn: "42 steps · 3 files" and the answer; the steps on click. */
|
||||
function WorkBlock({ messages, steps, open: forced, baseDir, children }: { messages: Message[]; steps: ToolCall[]; open: boolean; baseDir: string; children: ReactNode }) {
|
||||
const t = useT();
|
||||
@@ -307,7 +377,7 @@ function WorkBlock({ messages, steps, open: forced, baseDir, children }: { messa
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="msg work-block" data-mid={answer?.id}>
|
||||
<div className={`msg work-block ${answerText ? "bubble agent" : ""}`} data-mid={answer?.id}>
|
||||
<button className="work-head" onClick={() => setOpen(true)} aria-expanded={false}>
|
||||
<Icon name="chevron-right" className="tiny" /> {t("chat.workSteps", { n: steps.length })}
|
||||
{files.size > 0 && <span> · {t("chat.workFiles", { n: files.size })}</span>}
|
||||
@@ -316,12 +386,36 @@ function WorkBlock({ messages, steps, open: forced, baseDir, children }: { messa
|
||||
<>
|
||||
<Markdown text={answerText} baseDir={baseDir} />
|
||||
<ImageRefs text={answerText} baseDir={baseDir} />
|
||||
{answer && <MsgFoot ms={answer.created_at} menu={<MessageMenu messageId={answer.id} text={answerText} forkable={!answer.parts.some((p) => p.type === "tool_call")} />} />}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Foot of a bubble: time on the left, the ⋯ menu inside the bubble on the right. */
|
||||
function MsgFoot({ ms, menu }: { ms: number; menu: ReactNode }) {
|
||||
return (
|
||||
<div className="msg-foot">
|
||||
<MsgTime ms={ms} />
|
||||
{menu}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Text parts of a message. */
|
||||
const textOfMessage = (m: Message) => (m.parts.filter((p) => p.type === "text") as { text: string }[]).map((p) => p.text).join("\n\n");
|
||||
|
||||
/** Small date/time line under a message. */
|
||||
function MsgTime({ ms }: { ms: number }) {
|
||||
if (!ms) return null;
|
||||
return (
|
||||
<time className="msg-time" dateTime={new Date(ms).toISOString()} title={new Date(ms).toLocaleString()}>
|
||||
{fmtMsgTime(ms)}
|
||||
</time>
|
||||
);
|
||||
}
|
||||
|
||||
/** An assistant message, or a user message that only carries tool results / harness notes. */
|
||||
const AssistantOrNote = memo(function AssistantOrNote({
|
||||
m,
|
||||
@@ -341,8 +435,9 @@ const AssistantOrNote = memo(function AssistantOrNote({
|
||||
const cls = `msg ${highlight === m.id ? "highlight" : ""}`;
|
||||
if (m.role === "assistant") {
|
||||
return (
|
||||
<div className={cls} data-mid={m.id}>
|
||||
<div className={`${cls} ${textOfMessage(m).trim() ? "bubble agent" : ""}`} data-mid={m.id}>
|
||||
<AssistantParts parts={m.parts} results={results} running={busy} live={false} baseDir={baseDir} />
|
||||
<MsgFoot ms={m.created_at} menu={<MessageMenu messageId={m.id} text={textOfMessage(m)} forkable={!m.parts.some((p) => p.type === "tool_call")} />} />
|
||||
{regenerate && <RegenerateButton sessionId={regenerate.sessionId} messageId={m.id} model={regenerate.model} />}
|
||||
</div>
|
||||
);
|
||||
@@ -367,13 +462,15 @@ const MessageItem = memo(function MessageItem({ m, canEdit, onRewind, highlight
|
||||
return (
|
||||
<details className="summary-divider" data-mid={m.id} onToggle={(e) => setSummaryOpen((e.currentTarget as HTMLDetailsElement).open)}>
|
||||
<summary>
|
||||
{summary.auto
|
||||
{summary.text.startsWith("[Context cleared")
|
||||
? t("chat.cleared")
|
||||
: summary.auto
|
||||
? t("chat.compactedAuto", { tokens: summary.tokens ? fmtCompact(summary.tokens) : "?" })
|
||||
: summary.tokens
|
||||
? t("chat.compactedManual", { tokens: fmtCompact(summary.tokens) })
|
||||
: t("chat.compacted")}
|
||||
</summary>
|
||||
{summaryOpen && <Markdown text={summary.text} />}
|
||||
{summaryOpen && !summary.text.startsWith("[Context cleared") && <Markdown text={summary.text} />}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -382,18 +479,11 @@ const MessageItem = memo(function MessageItem({ m, canEdit, onRewind, highlight
|
||||
const texts = allTexts.filter((p) => !isHarnessNote(p.text));
|
||||
const imgs = m.parts.filter((p) => p.type === "image") as { image: ImageData }[];
|
||||
return (
|
||||
<div className={`msg ${highlight === m.id ? "highlight" : ""}`} data-mid={m.id}>
|
||||
<div className={`msg user-msg ${highlight === m.id ? "highlight" : ""}`} data-mid={m.id}>
|
||||
{background.map((p, i) => (
|
||||
<HarnessMessage key={i} text={p.text} />
|
||||
))}
|
||||
<div className="msg-user">
|
||||
{canEdit && (
|
||||
<div className="msg-actions">
|
||||
<button className="small ghost" onClick={() => onRewind(m)} title={t("chat.rewind")}>
|
||||
<Icon name="edit" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<UserText text={texts.map((p) => p.text).join("\n\n")} />
|
||||
{imgs.length > 0 && (
|
||||
<div className="user-files">
|
||||
@@ -404,6 +494,7 @@ const MessageItem = memo(function MessageItem({ m, canEdit, onRewind, highlight
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<MsgFoot ms={m.created_at} menu={<MessageMenu messageId={m.id} text={texts.map((p) => p.text).join("\n\n")} forkable onRewind={canEdit ? () => onRewind(m) : undefined} />} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -475,6 +566,9 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
// The Telegram switch in the ⋯ menu only matters with a paired bot.
|
||||
const telegramPaired = useFetch<{ paired: boolean }>("/account/telegram").data?.paired ?? false;
|
||||
const [editingInstructions, setEditingInstructions] = useState(false);
|
||||
const [pickingSkills, setPickingSkills] = useState(false);
|
||||
const [showApprovals, setShowApprovals] = useState(false);
|
||||
const [planning, setPlanning] = useState(false);
|
||||
const models = useModels();
|
||||
const [loadError, setLoadError] = useState<string>();
|
||||
const [text, setText] = useState(() => takePrefill(sessionId) ?? "");
|
||||
@@ -496,11 +590,25 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
if (el) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
|
||||
};
|
||||
|
||||
// Scrolled away from the top: the jump buttons show up.
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
/** Scroll to the closest own message above the visible area (long chats on a phone). */
|
||||
const jumpPrevOwn = () => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const above = [...el.querySelectorAll<HTMLElement>(".msg-user")].filter((n) => n.getBoundingClientRect().top < top - 12);
|
||||
const target = above[above.length - 1];
|
||||
if (target) target.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
else el.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
// Every chat starts following.
|
||||
useEffect(() => follow(true), [sessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadSession(sessionId).catch((e) => setLoadError(e.message));
|
||||
void loadChecks(sessionId);
|
||||
}, [sessionId]);
|
||||
|
||||
const permissions = allPermissions.filter((p) => p.session_id === sessionId || p.root_session_id === sessionId);
|
||||
@@ -592,7 +700,12 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
setText("");
|
||||
follow(true);
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
// No connection: keep the text on this device and send it when the server is reachable again.
|
||||
if (isOffline(e) && txt && images.length === 0) {
|
||||
addToOutbox(sessionId, txt, effort || undefined);
|
||||
setText("");
|
||||
toast(t("outbox.saved"));
|
||||
} else toast(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -607,10 +720,48 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
setText(m.parts.map((p) => (p.type === "text" ? p.text : "")).join(""));
|
||||
};
|
||||
|
||||
/** New chats in this project start like this one (model, mode, colour, instructions, folder). */
|
||||
const saveDefaults = async (remove: boolean) => {
|
||||
try {
|
||||
if (remove) await del(`/sessions/${sessionId}/project-defaults`);
|
||||
else await put(`/sessions/${sessionId}/project-defaults`, {});
|
||||
toast(t(remove ? "projectDefaults.removed" : "projectDefaults.saved"), "success");
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
/** The project's check command (tests, build …), run after every turn that changed files. */
|
||||
const editCheck = async () => {
|
||||
try {
|
||||
const cur = await get<{ command: string; enabled: boolean }>(`/sessions/${sessionId}/check`);
|
||||
const cmd = await promptDialog({ title: t("check.title"), message: t("check.hint", { project: session.cwd }), defaultValue: cur.command, placeholder: "cargo test", confirmLabel: t("common.save") });
|
||||
if (cmd === null) return;
|
||||
await put(`/sessions/${sessionId}/check`, { command: cmd.trim(), enabled: cmd.trim() !== "" });
|
||||
toast(cmd.trim() ? t("check.saved") : t("check.removed"), "success");
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
/** Draft an automation from this chat (small model), create it switched off and open its editor. */
|
||||
const planJob = async () => {
|
||||
if (planning) return;
|
||||
setPlanning(true);
|
||||
toast(t("job.drafting"));
|
||||
try {
|
||||
const d = await post<{ name: string; prompt: string; cwd: string; agent: string }>(`/sessions/${sessionId}/job-draft`, {});
|
||||
const job = await post<{ id: string }>("/jobs/create", { cwd: d.cwd, name: d.name, prompt: d.prompt, agent: d.agent === "plan" ? undefined : d.agent });
|
||||
navigate(`/jobs/${job.id}`);
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setPlanning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
if (!(await confirmDialog({ message: t("chat.deleteConfirm"), danger: true, confirmLabel: t("common.delete") }))) return;
|
||||
await del(`/sessions/${sessionId}`);
|
||||
navigate(session.parent_id ? `/s/${session.parent_id}` : "/new");
|
||||
if (await deleteChat(session)) navigate(session.parent_id ? `/s/${session.parent_id}` : "/new");
|
||||
};
|
||||
|
||||
// Context usage of the last request relative to the model's window.
|
||||
@@ -629,8 +780,8 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
const pendingTool = busy && pendingCall ? { name: pendingCall.name, input: pendingCall.input, since: lastMsg.created_at } : undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="topbar">
|
||||
<ChatCtx.Provider value={{ sessionId, canFork: !session.parent_id && !readOnly && !busy, canReply: !readOnly }}>
|
||||
<div className="topbar" data-color={session.color}>
|
||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||
<Icon name="menu" />
|
||||
</button>
|
||||
@@ -641,6 +792,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
<Icon name="undo" />
|
||||
</a>
|
||||
)}
|
||||
{session.icon && <Icon name={session.icon} className="chat-icon" />}
|
||||
{session.title || t("session.untitled")}
|
||||
{!readOnly && (
|
||||
<button className="ghost small title-edit" onClick={() => setEditingTitle(true)} title={t("rename.title")} aria-label={t("rename.title")}>
|
||||
@@ -673,11 +825,16 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
<Icon name="edit" /> {t("instructions.chip")}
|
||||
</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 && (
|
||||
<>
|
||||
{!session.parent_id && (
|
||||
<button className="small ghost" onClick={() => setSharing(true)} title={t("share.title")}>
|
||||
<button className="small ghost hide-mobile" onClick={() => setSharing(true)} title={t("share.title")}>
|
||||
<Icon name="share" />
|
||||
</button>
|
||||
)}
|
||||
@@ -691,11 +848,11 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
<button className={`small ghost ${searching ? "active" : ""}`} onClick={() => setSearching(!searching)} title={t("chat.search")} aria-label={t("chat.search")}>
|
||||
<Icon name="search" />
|
||||
</button>
|
||||
<button className="small ghost" onClick={tabs.openFiles} title={t("files.newTab")}>
|
||||
<button className="small ghost hide-mobile" onClick={tabs.openFiles} title={t("files.newTab")}>
|
||||
<Icon name="folder" />
|
||||
</button>
|
||||
{!session.parent_id && (
|
||||
<button className="small ghost" onClick={forkSession} disabled={busy} title={t("chat.fork")}>
|
||||
<button className="small ghost hide-mobile" onClick={forkSession} disabled={busy} title={t("chat.fork")}>
|
||||
<Icon name="fork" />
|
||||
</button>
|
||||
)}
|
||||
@@ -704,6 +861,28 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
<Icon name="more" />
|
||||
</summary>
|
||||
<div className="menu-pop-body">
|
||||
{/* The buttons that do not fit into the narrow bar. */}
|
||||
{!session.parent_id && (
|
||||
<a href="#" className="mobile-only" onClick={(e) => (e.preventDefault(), (e.currentTarget.closest("details") as HTMLDetailsElement).open = false, setSharing(true))}>
|
||||
<Icon name="share" /> {t("share.title")}
|
||||
</a>
|
||||
)}
|
||||
<a href="#" className="mobile-only" onClick={(e) => (e.preventDefault(), (e.currentTarget.closest("details") as HTMLDetailsElement).open = false, tabs.openFiles())}>
|
||||
<Icon name="folder" /> {t("files.newTab")}
|
||||
</a>
|
||||
{!session.parent_id && !busy && (
|
||||
<a href="#" className="mobile-only" onClick={(e) => (e.preventDefault(), (e.currentTarget.closest("details") as HTMLDetailsElement).open = false, forkSession())}>
|
||||
<Icon name="fork" /> {t("chat.fork")}
|
||||
</a>
|
||||
)}
|
||||
{!busy && (
|
||||
<a href="#" className="mobile-only" onClick={(e) => (e.preventDefault(), (e.currentTarget.closest("details") as HTMLDetailsElement).open = false, post(`/sessions/${sessionId}/compact`).catch((err) => toast(err.message)))}>
|
||||
<Icon name="compact" /> {t("command.compact")}
|
||||
</a>
|
||||
)}
|
||||
<a href="#" className="mobile-only danger" onClick={(e) => (e.preventDefault(), (e.currentTarget.closest("details") as HTMLDetailsElement).open = false, remove())}>
|
||||
<Icon name="trash" /> {t("chat.delete")}
|
||||
</a>
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
@@ -714,6 +893,33 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
>
|
||||
<Icon name="edit" /> {t("instructions.title")}
|
||||
</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 })} />
|
||||
<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")}>
|
||||
<Icon name="clock" /> {t("job.plan")}
|
||||
</a>
|
||||
<a href="#" title={t("projectDefaults.hint")} onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), void saveDefaults(false))}>
|
||||
<Icon name="template" /> {t("projectDefaults.save")}
|
||||
</a>
|
||||
<a href="#" onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), void saveDefaults(true))}>
|
||||
<Icon name="undo" /> {t("projectDefaults.remove")}
|
||||
</a>
|
||||
<a href="#" onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), void editCheck())}>
|
||||
<Icon name="check" /> {t("check.menu")}
|
||||
</a>
|
||||
<a href="#" onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), setShowApprovals(true))}>
|
||||
<Icon name="lock" /> {t("permProject.menu")}
|
||||
</a>
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
@@ -763,10 +969,10 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
<button className="small ghost" onClick={() => post(`/sessions/${sessionId}/compact`).catch((e) => toast(e.message))} disabled={busy} title={t("command.compact")}>
|
||||
<button className="small ghost hide-mobile" onClick={() => post(`/sessions/${sessionId}/compact`).catch((e) => toast(e.message))} disabled={busy} title={t("command.compact")}>
|
||||
<Icon name="compact" />
|
||||
</button>
|
||||
<button className="small ghost danger" onClick={remove} title={t("chat.delete")}>
|
||||
<button className="small ghost danger hide-mobile" onClick={remove} title={t("chat.delete")}>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</>
|
||||
@@ -790,7 +996,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
{searching && <ChatSearch sessionId={sessionId} onPick={(id) => void jumpTo(id)} onClose={() => setSearching(false)} />}
|
||||
<ChatTabBar state={tabs} />
|
||||
<ChatTabPanes state={tabs} />
|
||||
<div className="chat-pane" hidden={tabs.tab !== "chat"}>
|
||||
<div className="chat-pane" data-color={session.color} data-session-id={sessionId} hidden={tabs.tab !== "chat"}>
|
||||
{session.agent === "craft" && !session.parent_id && <PhaseBar phase={session.phase} deep={session.clean_room === false} />}
|
||||
<WorkBar active={busy && permissions.length === 0 && questions.length === 0} />
|
||||
<div
|
||||
@@ -805,6 +1011,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
// … scrolling back to the very end resumes it.
|
||||
else if (fromBottom < 4 && !stick.current && el.scrollTop > last.top) follow(true);
|
||||
lastScroll.current = { top: el.scrollTop, height: el.scrollHeight };
|
||||
setScrolled(el.scrollTop > 240);
|
||||
}}
|
||||
onWheel={(e) => {
|
||||
if (e.deltaY < 0 && stick.current) follow(false);
|
||||
@@ -825,6 +1032,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
baseDir={session.cwd}
|
||||
onRewind={onRewind}
|
||||
highlight={highlight}
|
||||
currency={stats?.currency ?? "USD"}
|
||||
/>
|
||||
{win?.newer && (
|
||||
<button className="back-to-latest" onClick={() => void showLatest()}>
|
||||
@@ -832,7 +1040,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
</button>
|
||||
)}
|
||||
{draft && (
|
||||
<div className="msg">
|
||||
<div className={`msg ${draft.parts.some((p) => p.type === "text" && p.text.trim()) ? "bubble agent" : ""}`}>
|
||||
<AssistantParts parts={draft.parts} results={results} running={busy} live baseDir={session.cwd} />
|
||||
</div>
|
||||
)}
|
||||
@@ -883,18 +1091,26 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!following && (
|
||||
{(!following || scrolled) && (
|
||||
<div className="jump-latest">
|
||||
<button className="primary" onClick={jumpToLatest} title={t("chat.jumpLatest")} aria-label={t("chat.jumpLatest")}>
|
||||
<Icon name="arrow-down" />
|
||||
<button onClick={jumpPrevOwn} title={t("chat.jumpPrevOwn")} aria-label={t("chat.jumpPrevOwn")}>
|
||||
<Icon name="arrow-up" />
|
||||
</button>
|
||||
{!following && <button className="primary" onClick={jumpToLatest} title={t("chat.jumpLatest")} aria-label={t("chat.jumpLatest")}>
|
||||
<Icon name="arrow-down" />
|
||||
</button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{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)} />}
|
||||
{editingTitle && <RenameDialog sessionId={sessionId} title={session.title} onClose={() => setEditingTitle(false)} />}
|
||||
{sharing && <ShareDialog sessionId={sessionId} onClose={() => setSharing(false)} />}
|
||||
{rewinding && <RewindDialog sessionId={sessionId} messageId={rewinding.id} onDone={rewindDone} onClose={() => setRewinding(undefined)} />}
|
||||
{!readOnly && isDraftChat(session.cwd) && <DraftBar sessionId={sessionId} />}
|
||||
{!readOnly && isIssueChat(session.cwd) && <IssueBar sessionId={sessionId} />}
|
||||
{!readOnly && <OutboxBar sessionId={sessionId} />}
|
||||
{!readOnly && <QueueList sessionId={sessionId} busy={busy} />}
|
||||
{readOnly ? (
|
||||
<div className="readonly-bar">{t("chat.readOnlyHint")}</div>
|
||||
@@ -910,7 +1126,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
</ChatCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useT, type Key } from "../i18n";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
/** Colour tags of chats: names, drawn in the colours of the active theme (see `[data-color]` in styles.css). */
|
||||
export const SESSION_COLORS = ["red", "orange", "yellow", "green", "aqua", "blue", "purple", "pink"] as const;
|
||||
|
||||
/** Icons a chat can get (must match SESSION_ICONS on the server). */
|
||||
export const SESSION_ICONS = [
|
||||
"robot", "brain", "terminal", "wrench", "gear", "chart", "shield", "image", "music", "cube", "file-text", "folder", "search", "sparkle", "clock", "lock",
|
||||
"users", "toolbox", "plug", "scroll", "eye", "template",
|
||||
"gamepad", "computer", "food", "coffee", "home", "book", "code", "camera", "cart", "heart", "star", "globe", "calendar", "car", "plane", "bulb", "money", "palette",
|
||||
] as const;
|
||||
|
||||
/** Row of colour dots; the selected one is ringed, a second click removes the tag. */
|
||||
export function ColorSwatches({ value, onChange }: { value?: string; onChange: (color: string) => void }) {
|
||||
const t = useT();
|
||||
return (
|
||||
<div className="color-swatches" role="radiogroup" aria-label={t("color.label")}>
|
||||
{SESSION_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={value === c}
|
||||
className={`swatch ${value === c ? "on" : ""}`}
|
||||
data-color={c}
|
||||
title={t(`color.${c}` as Key)}
|
||||
aria-label={t(`color.${c}` as Key)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onChange(value === c ? "" : c);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Grid of icons for a chat (in the colour of the chat); a second click removes the icon. */
|
||||
export function IconPicker({ value, color, onChange }: { value?: string; color?: string; onChange: (icon: string) => void }) {
|
||||
const t = useT();
|
||||
return (
|
||||
<div className="icon-picker" role="radiogroup" aria-label={t("icon.label")} data-color={color}>
|
||||
{SESSION_ICONS.map((i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={value === i}
|
||||
className={`icon-choice ${value === i ? "on" : ""}`}
|
||||
title={i}
|
||||
aria-label={i}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onChange(value === i ? "" : i);
|
||||
}}
|
||||
>
|
||||
<Icon name={i} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { TemplatePicker } from "./TemplatePicker";
|
||||
import { Icon } from "./Icon";
|
||||
import { formatSize, imageSrc } from "./FileFigure";
|
||||
import { uploadFile } from "../api";
|
||||
import { uploadBatch } from "../uploads";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAgents, useFetch, useModels } from "../hooks";
|
||||
import { useT, type Key } from "../i18n";
|
||||
@@ -10,6 +10,7 @@ import { ModelSelect } from "./ModelSelect";
|
||||
import { EffortSelect } from "./Regenerate";
|
||||
import { VoiceButton } from "./Voice";
|
||||
import { Markdown } from "./Markdown";
|
||||
import { COMPOSE_EVENT, type ComposeDetail } from "../compose";
|
||||
import { confirmDialog, promptDialog, toast } from "../dialogs";
|
||||
|
||||
interface Suggestion {
|
||||
@@ -19,6 +20,7 @@ interface Suggestion {
|
||||
|
||||
const BUILTIN: { name: string; key: Key }[] = [
|
||||
{ name: "compact", key: "command.compact" },
|
||||
{ name: "clear", key: "command.clear" },
|
||||
{ name: "new", key: "command.new" },
|
||||
];
|
||||
|
||||
@@ -77,6 +79,7 @@ export function Composer({
|
||||
const [mention, setMention] = useState<{ start: number; end: number; q: string }>();
|
||||
const [mentionHits, setMentionHits] = useState<{ rel: string; is_dir: boolean }[]>([]);
|
||||
const agents = useAgents(session.cwd).filter((a) => a.mode === "primary");
|
||||
const snippets = useFetch<{ id: string; name: string; text: string }[]>("/account/snippets").data;
|
||||
const cmdData = useFetch<{ commands: Suggestion[] }>(`/commands?cwd=${encodeURIComponent(session.cwd)}`).data;
|
||||
|
||||
// Auto-grow.
|
||||
@@ -133,11 +136,14 @@ export function Composer({
|
||||
...BUILTIN.map((b) => ({ name: b.name, description: t(b.key) })),
|
||||
...(cmdData?.commands ?? []),
|
||||
];
|
||||
return all
|
||||
const mine = (snippets ?? [])
|
||||
.filter((s) => s.name.toLowerCase().startsWith(m[1].toLowerCase()))
|
||||
.map((s) => ({ key: `snip:${s.id}`, label: `/${s.name}`, description: s.text.replace(/\s+/g, " ").slice(0, 80), apply: () => (setText(s.text), requestAnimationFrame(() => ref.current?.focus())) }));
|
||||
const cmds = all
|
||||
.filter((c) => c.name.startsWith(m[1]))
|
||||
.slice(0, 12)
|
||||
.map((c) => ({ key: c.name, label: `/${c.name}`, description: c.description, apply: () => setText(`/${c.name} `) }));
|
||||
}, [text, cmdData, t, mention, mentionHits]);
|
||||
return [...mine, ...cmds].slice(0, 12);
|
||||
}, [text, cmdData, snippets, t, mention, mentionHits]);
|
||||
|
||||
const send = () => {
|
||||
if ((!text.trim() && images.length === 0 && files.length === 0) || uploading > 0) return;
|
||||
@@ -195,9 +201,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 }) });
|
||||
// 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 uploadFile(path, f).catch((e) => {
|
||||
throw new Error(`${f.name}: ${e.message}`);
|
||||
});
|
||||
const sent = await uploadBatch([{ file: f, path }]);
|
||||
if (!sent.length) throw new Error(f.name);
|
||||
setFiles((cur) => [...cur, { name: f.name, path, size: f.size }]);
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? String(e));
|
||||
@@ -207,6 +212,27 @@ export function Composer({
|
||||
}
|
||||
};
|
||||
|
||||
// Content sent from elsewhere (quote a message, image viewer): latest closures via refs.
|
||||
const live = useRef({ text, addFiles, setText });
|
||||
live.current = { text, addFiles, setText };
|
||||
useEffect(() => {
|
||||
const on = (e: Event) => {
|
||||
const d = (e as CustomEvent<ComposeDetail>).detail;
|
||||
if (d.sessionId !== session.id) return;
|
||||
if (d.text) live.current.setText(live.current.text.trim() ? `${live.current.text.replace(/\s+$/, "")}\n\n${d.text}` : d.text);
|
||||
if (d.files?.length) void live.current.addFiles(d.files);
|
||||
requestAnimationFrame(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
setPreview(false);
|
||||
el.focus();
|
||||
el.setSelectionRange(el.value.length, el.value.length);
|
||||
});
|
||||
};
|
||||
window.addEventListener(COMPOSE_EVENT, on);
|
||||
return () => window.removeEventListener(COMPOSE_EVENT, on);
|
||||
}, [session.id]);
|
||||
|
||||
const removeFile = (path: string) => {
|
||||
setFiles((cur) => cur.filter((f) => f.path !== path));
|
||||
void fetch(`/api/files/delete?path=${encodeURIComponent(path)}`, { method: "DELETE", credentials: "same-origin" });
|
||||
|
||||
@@ -0,0 +1,961 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { get, post, put } from "../api";
|
||||
import { fmtCompact, fmtCost, fmtRelative, useT } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
import { choiceDialog, confirmDialog, promptDialog, toast } from "../dialogs";
|
||||
import { Icon } from "./Icon";
|
||||
import { Spinner } from "./Activity";
|
||||
import { ModelSelect } from "./ModelSelect";
|
||||
import { RecreateDialog } from "./FactoryDraft";
|
||||
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";
|
||||
const PHASES: Phase[] = ["review", "build", "qa"];
|
||||
|
||||
interface PhaseCfg {
|
||||
model: string;
|
||||
agent: string;
|
||||
permission_mode: string;
|
||||
timeout_minutes: number;
|
||||
max_attempts: number;
|
||||
extra_prompt: string;
|
||||
skills: string[];
|
||||
}
|
||||
interface RepoCfg {
|
||||
url: string;
|
||||
kind: string;
|
||||
connection: string;
|
||||
token: string;
|
||||
label: string;
|
||||
max_parallel: number;
|
||||
max_rework: number;
|
||||
allowed_users: string[];
|
||||
enabled: boolean;
|
||||
review: PhaseCfg;
|
||||
build: PhaseCfg;
|
||||
qa: PhaseCfg;
|
||||
}
|
||||
interface Connection {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: "gitea" | "github" | "gitlab";
|
||||
url: string;
|
||||
token: string;
|
||||
owner: string;
|
||||
}
|
||||
interface Defaults {
|
||||
spec_model: string;
|
||||
review: PhaseCfg;
|
||||
build: PhaseCfg;
|
||||
qa: PhaseCfg;
|
||||
}
|
||||
interface Settings {
|
||||
connections: Connection[];
|
||||
defaults: Defaults;
|
||||
repos: RepoCfg[];
|
||||
}
|
||||
interface Issue {
|
||||
repo: string;
|
||||
number: number;
|
||||
title: string;
|
||||
author: string;
|
||||
state: string;
|
||||
note: string;
|
||||
pr_url: string;
|
||||
branch: string;
|
||||
rounds: number;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
interface Run {
|
||||
id: string;
|
||||
repo: string;
|
||||
issue: number;
|
||||
phase: Phase;
|
||||
round: number;
|
||||
session_id: string;
|
||||
model: string;
|
||||
started_at: number;
|
||||
ended_at: number | null;
|
||||
status: string;
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
cost: number;
|
||||
}
|
||||
interface RepoInfo {
|
||||
url: string;
|
||||
kind: string;
|
||||
enabled: boolean;
|
||||
label: string;
|
||||
max_parallel: number;
|
||||
has_token: boolean;
|
||||
models: Record<Phase, string>;
|
||||
running: number;
|
||||
version?: string | null;
|
||||
}
|
||||
interface Overview {
|
||||
area: boolean;
|
||||
repos: RepoInfo[];
|
||||
issues: Issue[];
|
||||
runs: Run[];
|
||||
releases: ReleaseRow[];
|
||||
}
|
||||
|
||||
/** Board columns: a column collects one or more issue states. */
|
||||
const COLUMNS: { id: string; states: string[] }[] = [
|
||||
{ id: "review", states: ["new", "review"] },
|
||||
{ id: "question", states: ["question"] },
|
||||
{ id: "approved", states: ["approved"] },
|
||||
{ id: "build", states: ["building", "rework"] },
|
||||
{ id: "qa", states: ["qa", "testing"] },
|
||||
{ id: "failed", states: ["failed", "rejected"] },
|
||||
{ id: "done", states: ["done"] },
|
||||
];
|
||||
|
||||
const KIND_NAME: Record<string, string> = { gitea: "Gitea", github: "GitHub", gitlab: "GitLab" };
|
||||
const repoName = (url: string) => url.replace(/\.git$/, "").split("/").slice(-2).join("/");
|
||||
const issueUrl = (repo: string, n: number) => `${repo.replace(/\.git$/, "")}/issues/${n}`;
|
||||
|
||||
function fmtDuration(ms: number) {
|
||||
const s = Math.max(0, Math.round(ms / 1000));
|
||||
if (s < 60) return `${s} s`;
|
||||
const m = Math.floor(s / 60);
|
||||
return m < 60 ? `${m} min ${s % 60} s` : `${Math.floor(m / 60)} h ${m % 60} min`;
|
||||
}
|
||||
|
||||
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. */
|
||||
export function Factory({ onMenu }: { onMenu: () => void }) {
|
||||
const t = useT();
|
||||
const [tab, setTab] = useState<"overview" | "settings">("overview");
|
||||
return (
|
||||
<>
|
||||
<div className="topbar">
|
||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||
<Icon name="menu" />
|
||||
</button>
|
||||
<div className="grow">
|
||||
<h1>{t("factory.title")}</h1>
|
||||
</div>
|
||||
<div className="segmented">
|
||||
{(["overview", "settings"] as const).map((x) => (
|
||||
<button key={x} className={tab === x ? "active" : ""} onClick={() => setTab(x)}>
|
||||
{t(`factory.tab.${x}` as any)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="page">
|
||||
<div className="page-inner" style={{ maxWidth: 1280 }}>
|
||||
{tab === "overview" ? <FactoryOverview onSettings={() => setTab("settings")} /> : <FactorySettings />}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
const t = useT();
|
||||
const [data, setData] = useState<Overview>();
|
||||
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 [now, setNow] = useState(Date.now());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [recreate, setRecreate] = useState(false);
|
||||
|
||||
const reload = () =>
|
||||
get<Overview>("/factory/overview")
|
||||
.then(setData)
|
||||
.catch((e) => toast(e.message));
|
||||
useEffect(() => {
|
||||
void reload();
|
||||
const h = setInterval(() => {
|
||||
void reload();
|
||||
setNow(Date.now());
|
||||
}, 5000);
|
||||
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 () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const s = await post<{ id: string }>("/factory/drafts", {});
|
||||
navigate(`/s/${s.id}`);
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
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 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.repos.length === 0)
|
||||
return (
|
||||
<div className="empty">
|
||||
{recreate && <RecreateDialog onClose={() => setRecreate(false)} />}
|
||||
<p>{t("factory.empty")}</p>
|
||||
<div className="row" style={{ gap: 8, justifyContent: "center" }}>
|
||||
<button className="primary" onClick={newProject} disabled={busy}>
|
||||
<Icon name="plus" /> {t("factory.newProject")}
|
||||
</button>
|
||||
<button onClick={() => setRecreate(true)} disabled={busy}>
|
||||
<Icon name="search" /> {t("recreate.button")}
|
||||
</button>
|
||||
<button onClick={onSettings}>{t("factory.tab.settings")}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const sum = (f: (r: Run) => number) => runs.reduce((a, r) => a + f(r), 0);
|
||||
const finished = runs.filter((r) => r.ended_at);
|
||||
const running = runs.filter((r) => !r.ended_at);
|
||||
const done = issues.filter((i) => i.state === "done").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 shown = selected ? runsOf(selected) : runs.slice(0, 12);
|
||||
|
||||
const poll = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await post<{ errors: string[] }>("/factory/poll", {});
|
||||
if (r.errors.length) toast(r.errors.join("\n"));
|
||||
await reload();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
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 mergePr = async () => {
|
||||
if (!selected || !pr) return;
|
||||
if (!(await confirmDialog({ message: t("factory.mergeConfirm", { n: pr.number, method: t(`factory.merge.${prMethod}` as any) }) }))) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await post("/factory/issues/pr/merge", { repo: selected.repo, number: selected.number, pr: pr.number, method: prMethod });
|
||||
toast(t("factory.merged"));
|
||||
await loadPr();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
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);
|
||||
}
|
||||
};
|
||||
const closeIssue = async () => {
|
||||
if (!selected) return;
|
||||
const comment = await promptDialog({ title: t("factory.closeTitle"), message: t("factory.closeMsg", { n: selected.number }), defaultValue: t("factory.closeDefault"), confirmLabel: t("factory.close") });
|
||||
if (comment === null) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await post("/factory/issues/close", { repo: selected.repo, number: selected.number, comment });
|
||||
toast(t("factory.closed"), "success");
|
||||
setSel("");
|
||||
await reload();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const phaseRunning = !!selected && ["review", "building", "testing"].includes(selected.state);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!data.area && <div className="notice err">{t("factory.noArea")}</div>}
|
||||
<div className="kpis">
|
||||
<div className="kpi">
|
||||
<div className="k-label">{t("factory.kpi.running")}</div>
|
||||
<div className="k-value">{running.length}</div>
|
||||
<div className="k-sub">{t("factory.kpi.issues", { n: issues.length })}</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="k-label">{t("factory.kpi.done")}</div>
|
||||
<div className="k-value">{done}</div>
|
||||
<div className="k-sub">{t("factory.kpi.failed", { n: failed })}</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="k-label">{t("factory.kpi.tokens")}</div>
|
||||
<div className="k-value">{fmtCompact(sum((r) => r.input_tokens + r.output_tokens))}</div>
|
||||
<div className="k-sub">
|
||||
{fmtCompact(sum((r) => r.input_tokens))} {t("factory.in")} · {fmtCompact(sum((r) => r.output_tokens))} {t("factory.out")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="k-label">{t("factory.kpi.cost")}</div>
|
||||
<div className="k-value">{fmtCost(sum((r) => r.cost), "USD")}</div>
|
||||
<div className="k-sub">{t("factory.kpi.runs", { n: runs.length })}</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="k-label">{t("factory.kpi.time")}</div>
|
||||
<div className="k-value">{finished.length ? fmtDuration(sum((r) => runMs(r, now)) / finished.length) : "–"}</div>
|
||||
<div className="k-sub">{t("factory.kpi.perRun")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="factory-repos">
|
||||
<select className="factory-repo-select" value={repo} onChange={(e) => setRepo(e.target.value)} aria-label={t("factory.project")}>
|
||||
<option value="">
|
||||
{t("factory.allRepos")} ({data.issues.length})
|
||||
</option>
|
||||
{data.repos.map((r) => (
|
||||
<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 (
|
||||
<span className="factory-repo-info">
|
||||
<span className="chip">{KIND_NAME[r.kind] ?? r.kind}</span>
|
||||
{r.version && <span className="chip ok mono">v{r.version}</span>}
|
||||
<span className="hint">
|
||||
{r.running > 0 && <span className="factory-pulse" />}
|
||||
{t("factory.repoLine", { n: data.issues.filter((i) => i.repo === r.url).length, run: r.running })}
|
||||
</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>}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
<button className="small primary" onClick={newProject} disabled={busy}>
|
||||
<Icon name="plus" /> {t("factory.newProject")}
|
||||
</button>
|
||||
<button className="small" onClick={() => setRecreate(true)} disabled={busy} title={t("recreate.hint")}>
|
||||
<Icon name="search" /> {t("recreate.button")}
|
||||
</button>
|
||||
<button className="small" onClick={() => issueChat("feature")} disabled={busy} title={t("issues.featureHint")}>
|
||||
<Icon name="sparkle" /> {t("issues.feature")}
|
||||
</button>
|
||||
<button className="small" onClick={() => issueChat("slice")} disabled={busy} title={t("issues.sliceHint")}>
|
||||
<Icon name="sparkle" /> {t("issues.slice")}
|
||||
</button>
|
||||
<button className="small" onClick={startRelease} disabled={busy} title={t("release.hint")}>
|
||||
<Icon name="download" /> {t("release.button")}
|
||||
</button>
|
||||
<button className="small" onClick={poll} disabled={busy} title={t("factory.pollNow")}>
|
||||
<Icon name="refresh" /> {t("factory.pollNow")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="factory-board">
|
||||
{COLUMNS.map((c) => {
|
||||
const cards = issues.filter((i) => c.states.includes(i.state));
|
||||
return (
|
||||
<div key={c.id} className="factory-col">
|
||||
<h4>
|
||||
{t(`factory.col.${c.id}` as any)} <span className="chip">{cards.length}</span>
|
||||
</h4>
|
||||
{cards.map((i) => {
|
||||
const rs = runsOf(i);
|
||||
const active = rs.find((r) => !r.ended_at);
|
||||
const latest = active ?? rs[0];
|
||||
const tokens = rs.reduce((a, r) => a + r.input_tokens + r.output_tokens, 0);
|
||||
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}`)}>
|
||||
<span className="hint">
|
||||
{repoName(i.repo)} #{i.number}
|
||||
</span>
|
||||
<b>{i.title || `#${i.number}`}</b>
|
||||
{latest && (
|
||||
<span className="hint">
|
||||
{active && <span className="factory-pulse" />}
|
||||
{t(`factory.phase.${latest.phase}` as any)} · {(latest.model || "").split("/").pop()} · {fmtDuration(runMs(latest, now))}
|
||||
</span>
|
||||
)}
|
||||
{tokens > 0 && <span className="hint">{fmtCompact(tokens)} {t("factory.tokens")}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</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="row">
|
||||
<h3 style={{ margin: 0 }}>{selected ? `${repoName(selected.repo)} #${selected.number} – ${selected.title}` : t("factory.latestRuns")}</h3>
|
||||
<span className="spacer" />
|
||||
{selected && !phaseRunning && (
|
||||
<>
|
||||
<span className="hint">{t("factory.restartAt")}</span>
|
||||
<button className="small" onClick={() => restart("new")} disabled={busy}>
|
||||
{t("factory.col.review")}
|
||||
</button>
|
||||
<button className="small" onClick={() => restart("approved")} disabled={busy}>
|
||||
{t("factory.col.build")}
|
||||
</button>
|
||||
<button className="small" onClick={() => restart("qa")} disabled={busy || !selected.branch}>
|
||||
{t("factory.col.qa")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{selected && !["review", "building", "testing"].includes(selected.state) && (
|
||||
<button className="small" onClick={removeIssue} disabled={busy} title={t("factory.removeHint")}>
|
||||
<Icon name="trash" /> {t("factory.remove")}
|
||||
</button>
|
||||
)}
|
||||
{selected && selected.state === "done" && (
|
||||
<button className="small" onClick={closeIssue} disabled={busy}>
|
||||
<Icon name="check" /> {t("factory.close")}
|
||||
</button>
|
||||
)}
|
||||
{selected && (
|
||||
<>
|
||||
<a className="small ghost button-link" href={issueUrl(selected.repo, selected.number)} target="_blank" rel="noreferrer">
|
||||
<Icon name="external" /> Gitea
|
||||
</a>
|
||||
{selected.pr_url && (
|
||||
<a className="small ghost button-link" href={selected.pr_url} target="_blank" rel="noreferrer">
|
||||
<Icon name="external" /> {t("factory.pr")}
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</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" && (
|
||||
<>
|
||||
<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 className="small primary" 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="table-wrap">
|
||||
<table className="grid factory-runs">
|
||||
<thead>
|
||||
<tr>
|
||||
{!selected && <th>{t("factory.issue")}</th>}
|
||||
<th>{t("factory.phase")}</th>
|
||||
<th>{t("factory.model")}</th>
|
||||
<th>{t("factory.status")}</th>
|
||||
<th>{t("factory.started")}</th>
|
||||
<th>{t("factory.duration")}</th>
|
||||
<th>{t("factory.tokens")}</th>
|
||||
<th>{t("factory.cost")}</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{shown.map((r) => (
|
||||
<tr key={r.id}>
|
||||
{!selected && (
|
||||
<td>
|
||||
{repoName(r.repo)} #{r.issue}
|
||||
</td>
|
||||
)}
|
||||
<td>
|
||||
{t(`factory.phase.${r.phase}` as any)}
|
||||
{r.round > 0 && <span className="hint"> · {t("factory.round", { n: r.round })}</span>}
|
||||
</td>
|
||||
<td className="mono">{r.model}</td>
|
||||
<td>
|
||||
<span className={`chip ${r.status === "done" ? "ok" : r.status === "running" ? "" : "warn"}`}>
|
||||
{r.status === "running" && <span className="factory-pulse" />}
|
||||
{t(`factory.runStatus.${r.status}` as any) || r.status}
|
||||
</span>
|
||||
</td>
|
||||
<td>{fmtRelative(r.started_at)}</td>
|
||||
<td>{fmtDuration(runMs(r, now))}</td>
|
||||
<td title={`${r.input_tokens} / ${r.output_tokens}`}>
|
||||
{fmtCompact(r.input_tokens)} / {fmtCompact(r.output_tokens)}
|
||||
</td>
|
||||
<td>{fmtCost(r.cost, "USD")}</td>
|
||||
<td>
|
||||
<button className="small" onClick={() => navigate(`/s/${r.session_id}`)}>
|
||||
<Icon name="eye" /> {t("factory.openChat")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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, max_rework: 2, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() });
|
||||
const blankConn = (): Connection => ({ id: "", name: "", kind: "gitea", url: "", token: "", owner: "" });
|
||||
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 }) {
|
||||
const t = useT();
|
||||
return (
|
||||
<div className="factory-phase">
|
||||
<h4>{t(`factory.phase.${phase}` as any)}</h4>
|
||||
<label>
|
||||
<span>{t("factory.model")}</span>
|
||||
<ModelSelect value={value.model} onChange={(model) => onChange({ model })} emptyLabel={t("jobEditor.defaultModel")} />
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("factory.agent")}</span>
|
||||
<select value={value.agent} onChange={(e) => onChange({ agent: e.target.value })}>
|
||||
<option value="codecraft">CodeCraft</option>
|
||||
<option value="claude-code">Claude Code</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("factory.mode")}</span>
|
||||
<select value={value.permission_mode} onChange={(e) => onChange({ permission_mode: e.target.value })}>
|
||||
{MODES.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{t(`permissionMode.${m}` as any)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("factory.timeout")}</span>
|
||||
<input type="number" min={1} value={value.timeout_minutes} onChange={(e) => onChange({ timeout_minutes: Number(e.target.value) || 60 })} />
|
||||
</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>
|
||||
<span>{t("factory.extraPrompt")}</span>
|
||||
<textarea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const URL_PLACEHOLDER: Record<string, string> = { gitea: "https://git.example.org", github: "https://github.com", gitlab: "https://gitlab.com" };
|
||||
|
||||
function FactorySettings() {
|
||||
const t = useT();
|
||||
const [st, setSt] = useState<Settings>();
|
||||
const [busy, setBusy] = useState<string>();
|
||||
const [orgs, setOrgs] = useState<Record<string, string[]>>({});
|
||||
|
||||
useEffect(() => {
|
||||
get<Settings>("/account/factory")
|
||||
.then(setSt)
|
||||
.catch((e) => toast(e.message));
|
||||
}, []);
|
||||
if (!st) return <div className="empty"><Spinner /></div>;
|
||||
const { connections: conns, repos } = st;
|
||||
|
||||
const setConns = (connections: Connection[]) => setSt({ ...st, connections });
|
||||
const setRepos = (r: RepoCfg[]) => setSt({ ...st, repos: r });
|
||||
const upConn = (i: number, patch: Partial<Connection>) => setConns(conns.map((c, k) => (k === i ? { ...c, ...patch } : c)));
|
||||
const up = (i: number, patch: Partial<RepoCfg>) => setRepos(repos.map((r, k) => (k === i ? { ...r, ...patch } : r)));
|
||||
const upPhase = (i: number, p: Phase, patch: Partial<PhaseCfg>) => up(i, { [p]: { ...repos[i][p], ...patch } } as any);
|
||||
const upDefault = (p: Phase, patch: Partial<PhaseCfg>) => setSt({ ...st, defaults: { ...st.defaults, [p]: { ...st.defaults[p], ...patch } } });
|
||||
|
||||
const save = async () => {
|
||||
const s = await put<Settings>("/account/factory", st);
|
||||
setSt(s);
|
||||
return s;
|
||||
};
|
||||
const act = async (key: string, f: () => Promise<void>) => {
|
||||
setBusy(key);
|
||||
try {
|
||||
await f();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="notice">{t("factory.settingsHint")}</div>
|
||||
|
||||
<h3 className="factory-h">{t("factory.connections")}</h3>
|
||||
<div className="hint" style={{ marginBottom: 8 }}>{t("factory.connectionsHint")}</div>
|
||||
{conns.map((c, i) => (
|
||||
<div key={i} className="panel">
|
||||
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
|
||||
<h3 style={{ margin: 0 }}>{c.name || KIND_NAME[c.kind]}</h3>
|
||||
<span className="spacer" />
|
||||
<button
|
||||
className="small"
|
||||
disabled={busy !== undefined}
|
||||
onClick={() =>
|
||||
act(`c${i}`, async () => {
|
||||
const saved = await save();
|
||||
const id = saved.connections[i]?.id;
|
||||
const r = await post<{ login: string; orgs: string[] }>("/account/factory/connection/test", { id });
|
||||
setOrgs({ ...orgs, [id]: r.orgs });
|
||||
toast(t("factory.connOk", { login: r.login, n: r.orgs.length }), "success");
|
||||
})
|
||||
}
|
||||
>
|
||||
{busy === `c${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.testConn")}
|
||||
</button>
|
||||
<button
|
||||
className="small"
|
||||
title={t("common.delete")}
|
||||
aria-label={t("common.delete")}
|
||||
onClick={async () => {
|
||||
if (await confirmDialog({ message: t("factory.connDeleteConfirm", { name: c.name || KIND_NAME[c.kind] }), danger: true })) setConns(conns.filter((_, k) => k !== i));
|
||||
}}
|
||||
>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="factory-form">
|
||||
<label>
|
||||
<span>{t("factory.connName")}</span>
|
||||
<input value={c.name} onChange={(e) => upConn(i, { name: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("factory.kind")}</span>
|
||||
<select value={c.kind} onChange={(e) => upConn(i, { kind: e.target.value as Connection["kind"] })}>
|
||||
{Object.entries(KIND_NAME).map(([k, n]) => (
|
||||
<option key={k} value={k}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("factory.serviceUrl")}</span>
|
||||
<input value={c.url} placeholder={URL_PLACEHOLDER[c.kind]} onChange={(e) => upConn(i, { url: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
<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()} />
|
||||
<span className="hint">{c.token.startsWith("•") ? t("factory.tokenSet") : t(`factory.tokenHint.${c.kind}` as any)}</span>
|
||||
</label>
|
||||
<label>
|
||||
<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 })} />
|
||||
<datalist id={`orgs-${c.id}`}>
|
||||
{(orgs[c.id] ?? []).map((o) => (
|
||||
<option key={o} value={o} />
|
||||
))}
|
||||
</datalist>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button onClick={() => setConns([...conns, blankConn()])}>
|
||||
<Icon name="plus" /> {t("factory.addConn")}
|
||||
</button>
|
||||
|
||||
<h3 className="factory-h">{t("factory.defaults")}</h3>
|
||||
<div className="hint" style={{ marginBottom: 8 }}>{t("factory.defaultsHint")}</div>
|
||||
<div className="panel">
|
||||
<label className="factory-form" style={{ margin: 0 }}>
|
||||
<span style={{ fontSize: 12 }}>{t("factory.specModel")}</span>
|
||||
<ModelSelect value={st.defaults.spec_model} onChange={(spec_model) => setSt({ ...st, defaults: { ...st.defaults, spec_model } })} emptyLabel={t("jobEditor.defaultModel")} />
|
||||
</label>
|
||||
<div className="factory-phases" style={{ marginTop: 10 }}>
|
||||
{PHASES.map((p) => (
|
||||
<PhaseForm key={p} phase={p} value={st.defaults[p]} onChange={(patch) => upDefault(p, patch)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="factory-h">{t("factory.repos")}</h3>
|
||||
{repos.map((r, i) => (
|
||||
<div key={i} className="panel">
|
||||
<div className="row" style={{ flexWrap: "wrap", gap: 8 }}>
|
||||
<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="spacer" />
|
||||
<label className="switch">
|
||||
<input type="checkbox" checked={r.enabled} onChange={(e) => up(i, { enabled: e.target.checked })} />
|
||||
<span>{t(r.enabled ? "jobs.on" : "jobs.off")}</span>
|
||||
</label>
|
||||
<button
|
||||
className="small"
|
||||
disabled={busy !== undefined}
|
||||
onClick={() =>
|
||||
act(`t${i}`, async () => {
|
||||
await save();
|
||||
const res = await post<{ info: { login: string; repo: string; can_push: boolean }; labels_created: string[]; folder: string }>("/account/factory/test", { url: r.url });
|
||||
toast(t("factory.testOk", { login: res.info.login, repo: res.info.repo, n: res.labels_created.length }), "success");
|
||||
})
|
||||
}
|
||||
>
|
||||
{busy === `t${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.test")}
|
||||
</button>
|
||||
<button
|
||||
className="small"
|
||||
title={t("common.delete")}
|
||||
aria-label={t("common.delete")}
|
||||
onClick={async () => {
|
||||
if (await confirmDialog({ message: t("factory.deleteConfirm", { name: repoName(r.url) || "?" }), danger: true })) setRepos(repos.filter((_, k) => k !== i));
|
||||
}}
|
||||
>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="factory-form">
|
||||
<label>
|
||||
<span>{t("factory.connection")}</span>
|
||||
<select
|
||||
value={r.connection}
|
||||
onChange={(e) => up(i, { connection: e.target.value, kind: conns.find((c) => c.id === e.target.value)?.kind ?? r.kind })}
|
||||
>
|
||||
<option value="">{t("factory.noConnection")}</option>
|
||||
{conns
|
||||
.filter((c) => c.id)
|
||||
.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name || KIND_NAME[c.kind]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!r.connection && (
|
||||
<label>
|
||||
<span>{t("factory.kind")}</span>
|
||||
<select value={r.kind} onChange={(e) => up(i, { kind: e.target.value })}>
|
||||
{Object.entries(KIND_NAME).map(([k, n]) => (
|
||||
<option key={k} value={k}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
<span>{t("factory.url")}</span>
|
||||
<input value={r.url} placeholder="https://host/owner/repo.git" onChange={(e) => up(i, { url: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
<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()} />
|
||||
<span className="hint">{r.token.startsWith("•") ? t("factory.tokenSet") : t("factory.repoTokenHint")}</span>
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("factory.label")}</span>
|
||||
<input value={r.label} onChange={(e) => up(i, { label: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
<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 })} />
|
||||
</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>
|
||||
<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) })} />
|
||||
</label>
|
||||
</div>
|
||||
<div className="factory-phases">
|
||||
{PHASES.map((p) => (
|
||||
<PhaseForm key={p} phase={p} value={r[p]} onChange={(patch) => upPhase(i, p, patch)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<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")])}>
|
||||
<Icon name="plus" /> {t("factory.addRepo")}
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={busy !== undefined}
|
||||
onClick={() =>
|
||||
act("save", async () => {
|
||||
await save();
|
||||
toast(t("factory.saved"), "success");
|
||||
})
|
||||
}
|
||||
>
|
||||
{busy === "save" ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { get, post } from "../api";
|
||||
import { useT } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
import { toast } from "../dialogs";
|
||||
import { uploadBatch } from "../uploads";
|
||||
import { Icon } from "./Icon";
|
||||
import { Spinner } from "./Activity";
|
||||
|
||||
interface Draft {
|
||||
spec: string;
|
||||
setup?: string | null;
|
||||
proposal: { name?: string; slug?: string; description?: string } | null;
|
||||
connections: { id: string; name: string; kind: string; owner: string }[];
|
||||
recreate?: boolean;
|
||||
}
|
||||
|
||||
export const isDraftChat = (cwd: string) => /\/_drafts\/[^/]+$/.test(cwd);
|
||||
|
||||
const slugify = (s: string) =>
|
||||
s
|
||||
.toLowerCase()
|
||||
.replace(/ä/g, "ae")
|
||||
.replace(/ö/g, "oe")
|
||||
.replace(/ü/g, "ue")
|
||||
.replace(/ß/g, "ss")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 60);
|
||||
|
||||
/** Bar above the composer of a spec chat: file the spec as a new repository and start the workflow. */
|
||||
export function DraftBar({ sessionId }: { sessionId: string }) {
|
||||
const t = useT();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<div className="draft-bar">
|
||||
<Icon name="scroll" />
|
||||
<span>{t("draft.hint")}</span>
|
||||
<span className="spacer" />
|
||||
<button className="small primary" onClick={() => setOpen(true)}>
|
||||
<Icon name="check" /> {t("draft.create")}
|
||||
</button>
|
||||
</div>
|
||||
{open && <CreateProjectDialog sessionId={sessionId} onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClose: () => void }) {
|
||||
const t = useT();
|
||||
const [draft, setDraft] = useState<Draft>();
|
||||
const [name, setName] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [slugTouched, setSlugTouched] = useState(false);
|
||||
const [description, setDescription] = useState("");
|
||||
const [connection, setConnection] = useState("");
|
||||
const [owner, setOwner] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
get<Draft>(`/factory/drafts/${sessionId}`)
|
||||
.then((d) => {
|
||||
setDraft(d);
|
||||
setName(d.proposal?.name ?? "");
|
||||
setSlug(d.proposal?.slug ? slugify(d.proposal.slug) : "");
|
||||
setSlugTouched(!!d.proposal?.slug);
|
||||
setDescription(d.proposal?.description ?? "");
|
||||
setConnection(d.connections[0]?.id ?? "");
|
||||
setOwner(d.connections[0]?.owner ?? "");
|
||||
})
|
||||
.catch((e) => {
|
||||
toast(e.message);
|
||||
onClose();
|
||||
});
|
||||
}, [sessionId]);
|
||||
|
||||
if (!draft)
|
||||
return (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal">
|
||||
<Spinner />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const conn = draft.connections.find((c) => c.id === connection);
|
||||
const ready = draft.spec.trim() && name.trim() && slug.length >= 2 && connection;
|
||||
|
||||
const create = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await post<{ repo: string; issue: number | null }>(`/factory/drafts/${sessionId}/create`, { connection, name, slug, description, owner });
|
||||
await post("/factory/poll", {}).catch(() => undefined);
|
||||
toast(r.issue == null ? t("draft.createdRecreate", { repo: r.repo }) : t("draft.created", { repo: r.repo, n: r.issue }), "success");
|
||||
onClose();
|
||||
navigate("/factory");
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("draft.create")} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>{t("draft.create")}</h3>
|
||||
{draft.connections.length === 0 ? (
|
||||
<div className="notice err">
|
||||
{t("draft.noConnection")}{" "}
|
||||
<button className="link-btn" onClick={() => navigate("/factory")}>
|
||||
{t("factory.tab.settings")}
|
||||
</button>
|
||||
</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">
|
||||
<label>
|
||||
<span>{t("draft.name")}</span>
|
||||
<input
|
||||
autoFocus
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
if (!slugTouched) setSlug(slugify(e.target.value));
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("draft.slug")}</span>
|
||||
<input
|
||||
value={slug}
|
||||
className="mono"
|
||||
onChange={(e) => {
|
||||
setSlug(slugify(e.target.value));
|
||||
setSlugTouched(true);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label style={{ gridColumn: "1 / -1" }}>
|
||||
<span>{t("draft.description")}</span>
|
||||
<input value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("draft.connection")}</span>
|
||||
<select
|
||||
value={connection}
|
||||
onChange={(e) => {
|
||||
setConnection(e.target.value);
|
||||
setOwner(draft.connections.find((c) => c.id === e.target.value)?.owner ?? "");
|
||||
}}
|
||||
>
|
||||
{draft.connections.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name || c.kind} ({c.kind})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{t("draft.owner")}</span>
|
||||
<input value={owner} placeholder={t("draft.ownerPlaceholder")} onChange={(e) => setOwner(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<div className="hint" style={{ margin: "6px 0" }}>
|
||||
{t("draft.private", { conn: conn?.name || "" })}
|
||||
</div>
|
||||
<details>
|
||||
<summary>{t("draft.specPreview")}</summary>
|
||||
<pre className="draft-spec">{draft.spec || "–"}</pre>
|
||||
</details>
|
||||
</>
|
||||
)}
|
||||
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
|
||||
<button onClick={onClose} disabled={busy}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button className="primary" onClick={create} disabled={!ready || busy}>
|
||||
{busy ? <Spinner small /> : <Icon name="check" />} {t("draft.createGo")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 className="small primary" onClick={() => setOpen(true)}>
|
||||
<Icon name="check" /> {t("issues.create")}
|
||||
</button>
|
||||
</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 (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal">
|
||||
<Spinner />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
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 (
|
||||
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("issues.create")} onClick={(e) => e.stopPropagation()}>
|
||||
<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">
|
||||
<label className="row" style={{ gap: 8 }}>
|
||||
<input type="checkbox" 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 })} />
|
||||
</label>
|
||||
<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>
|
||||
<textarea rows={4} value={i.description} onChange={(e) => set(k, { description: e.target.value })} />
|
||||
</details>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<label className="row" style={{ gap: 8, marginTop: 8 }}>
|
||||
<input type="checkbox" checked={start} onChange={(e) => setStart(e.target.checked)} />
|
||||
<span>{t("issues.start")}</span>
|
||||
</label>
|
||||
<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 className="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>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("recreate.title")} onClick={(e) => e.stopPropagation()}>
|
||||
<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>
|
||||
<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 className="primary" onClick={start} disabled={busy || (!source.trim() && files.length === 0)}>
|
||||
{busy ? <Spinner small /> : <Icon name="search" />} {t("recreate.go")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
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 (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal">
|
||||
<Spinner />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
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 (
|
||||
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("release.title")} onClick={(e) => e.stopPropagation()}>
|
||||
<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 className="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>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 { uploadBatch } from "../uploads";
|
||||
import { Icon } from "./Icon";
|
||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { del, get, post, put } from "../api";
|
||||
@@ -223,10 +224,7 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
|
||||
|
||||
const upload = async (files: FileList | File[]) => {
|
||||
if (!listing) return;
|
||||
for (const f of [...files]) {
|
||||
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 uploadBatch([...files].map((f) => ({ file: f, path: `${listing.path}/${f.name}` })));
|
||||
await load(listing.path);
|
||||
void refreshGit();
|
||||
};
|
||||
|
||||
@@ -207,6 +207,13 @@ export function GitPanel({
|
||||
<input type="checkbox" checked={amend} onChange={(e) => setAmend(e.target.checked)} /> {t("git.amend")}
|
||||
</label>
|
||||
<span className="spacer" />
|
||||
<button
|
||||
disabled={!!busy || staged.length === 0}
|
||||
title={t("git.suggestHint")}
|
||||
onClick={() => run("suggest", async () => setMessage((await call<{ message: string }>("suggest")).message))}
|
||||
>
|
||||
{busy === "suggest" ? <Spinner small /> : t("git.suggest")}
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={!!busy || (!amend && (!message.trim() || staged.length === 0))}
|
||||
|
||||
@@ -34,6 +34,98 @@ const P: Record<string, ReactNode> = {
|
||||
download: <path d="M12 4v11M7 10l5 5 5-5M5 20h14" />,
|
||||
compact: <path d="M8 4l4 4 4-4M8 20l4-4 4 4M4 12h16" />,
|
||||
trash: <path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6" />,
|
||||
gamepad: (
|
||||
<>
|
||||
<path d="M7 8h10a4 4 0 0 1 4 4.2l-.6 3.8a2.4 2.4 0 0 1-4.1 1.3L14 15h-4l-2.3 2.3a2.4 2.4 0 0 1-4.1-1.3L3 12.2A4 4 0 0 1 7 8Z" />
|
||||
<path d="M8 10.5v3M6.5 12h3M15.5 11h.01M17.5 13h.01" />
|
||||
</>
|
||||
),
|
||||
computer: (
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="12" rx="2" />
|
||||
<path d="M8 20h8M12 16v4" />
|
||||
</>
|
||||
),
|
||||
food: (
|
||||
<>
|
||||
<path d="M5 3v6a2 2 0 0 0 4 0V3M7 11v10" />
|
||||
<path d="M17 21V3c-2.6 1.4-3.5 4.2-3.5 7.5H17" />
|
||||
</>
|
||||
),
|
||||
home: (
|
||||
<>
|
||||
<path d="M4 11.5 12 4l8 7.5V20H4Z" />
|
||||
<path d="M10 20v-5h4v5" />
|
||||
</>
|
||||
),
|
||||
book: (
|
||||
<>
|
||||
<path d="M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3Z" />
|
||||
<path d="M5 17a3 3 0 0 1 3-3h11" />
|
||||
</>
|
||||
),
|
||||
code: <path d="m8 7-5 5 5 5M16 7l5 5-5 5M14 5l-4 14" />,
|
||||
camera: (
|
||||
<>
|
||||
<path d="M4 8h3l1.5-2h7L17 8h3v11H4Z" />
|
||||
<circle cx="12" cy="13" r="3.5" />
|
||||
</>
|
||||
),
|
||||
cart: (
|
||||
<>
|
||||
<path d="M3 4h2.5l2 11h10l2-8H7" />
|
||||
<circle cx="9" cy="19" r="1.4" />
|
||||
<circle cx="17" cy="19" r="1.4" />
|
||||
</>
|
||||
),
|
||||
heart: <path d="M12 20s-8-4.6-8-10.5A4.5 4.5 0 0 1 12 7a4.5 4.5 0 0 1 8 2.5C20 15.4 12 20 12 20Z" />,
|
||||
star: <path d="m12 3.5 2.6 5.4 5.9.8-4.3 4.1 1 5.9L12 16.9l-5.2 2.8 1-5.9-4.3-4.1 5.9-.8Z" />,
|
||||
globe: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="8.5" />
|
||||
<path d="M3.5 12h17M12 3.5c3 3 3 14 0 17M12 3.5c-3 3-3 14 0 17" />
|
||||
</>
|
||||
),
|
||||
calendar: (
|
||||
<>
|
||||
<rect x="4" y="5" width="16" height="15" rx="2" />
|
||||
<path d="M4 10h16M8 3v4M16 3v4" />
|
||||
</>
|
||||
),
|
||||
coffee: (
|
||||
<>
|
||||
<path d="M5 9h11v5a5 5 0 0 1-5 5H10a5 5 0 0 1-5-5Z" />
|
||||
<path d="M16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 3v3M12 3v3" />
|
||||
</>
|
||||
),
|
||||
car: (
|
||||
<>
|
||||
<path d="M3.5 16v-4l2-5h13l2 5v4Z" />
|
||||
<path d="M3.5 12h17" />
|
||||
<circle cx="7.5" cy="16" r="1.5" />
|
||||
<circle cx="16.5" cy="16" r="1.5" />
|
||||
</>
|
||||
),
|
||||
plane: (
|
||||
<>
|
||||
<path d="M21 3 3 10.5l6.5 2.5L12 20Z" />
|
||||
<path d="M9.5 13 21 3" />
|
||||
</>
|
||||
),
|
||||
bulb: <path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-3.5 10.9c.6.5 1 1.3 1 2.1h5c0-.8.4-1.6 1-2.1A6 6 0 0 0 12 3Z" />,
|
||||
money: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="8.5" />
|
||||
<path d="M14.5 9.2c-.5-.8-1.4-1.2-2.5-1.2-1.5 0-2.5.8-2.5 1.9 0 2.7 5 1.2 5 4 0 1.1-1 2-2.5 2-1.1 0-2.1-.5-2.6-1.4M12 6.5V8M12 16v1.5" />
|
||||
</>
|
||||
),
|
||||
palette: (
|
||||
<>
|
||||
<path d="M12 3.5a8.5 8.5 0 1 0 0 17c1.3 0 1.8-1 1.3-2-.6-1.2.2-2.5 1.6-2.5H17a3.5 3.5 0 0 0 3.5-3.5C20.5 7 16.8 3.5 12 3.5Z" />
|
||||
<path d="M7.5 11h.01M9.5 7.5h.01M14 7.5h.01" />
|
||||
</>
|
||||
),
|
||||
reply: <path d="M9 7 4 12l5 5M4 12h9a7 7 0 0 1 7 7" />,
|
||||
edit: <path d="M4 20h4L19 9l-4-4L4 16v4ZM13.5 6.5l4 4" />,
|
||||
undo: <path d="M9 14 4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3" />,
|
||||
clip: <path d="m20 11-8.5 8.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-8.5 8.5a2 2 0 0 1-3-3L14 7" />,
|
||||
@@ -168,6 +260,12 @@ const P: Record<string, ReactNode> = {
|
||||
<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: (
|
||||
<>
|
||||
<rect x="3" y="8" width="18" height="11" rx="2" />
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useT } from "../i18n";
|
||||
import { toast } from "../dialogs";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
type Tool = "pen" | "arrow" | "rect";
|
||||
interface Shape {
|
||||
tool: Tool;
|
||||
color: string;
|
||||
/** pen: all points; arrow/rect: start and end. */
|
||||
pts: { x: number; y: number }[];
|
||||
}
|
||||
|
||||
const COLORS = ["#ff3b30", "#ffcc00", "#34c759", "#0a84ff", "#ffffff", "#000000"];
|
||||
const MAX_SIDE = 2000;
|
||||
|
||||
function paint(ctx: CanvasRenderingContext2D, shapes: Shape[], w: number) {
|
||||
const lw = Math.max(3, Math.round(w / 280));
|
||||
for (const s of shapes) {
|
||||
ctx.strokeStyle = s.color;
|
||||
ctx.fillStyle = s.color;
|
||||
ctx.lineWidth = lw;
|
||||
ctx.lineCap = "round";
|
||||
ctx.lineJoin = "round";
|
||||
const a = s.pts[0];
|
||||
const b = s.pts[s.pts.length - 1];
|
||||
ctx.beginPath();
|
||||
if (s.tool === "pen") {
|
||||
ctx.moveTo(a.x, a.y);
|
||||
for (const p of s.pts.slice(1)) ctx.lineTo(p.x, p.y);
|
||||
if (s.pts.length === 1) ctx.lineTo(a.x + 0.1, a.y);
|
||||
ctx.stroke();
|
||||
} else if (s.tool === "rect") {
|
||||
ctx.strokeRect(a.x, a.y, b.x - a.x, b.y - a.y);
|
||||
} else {
|
||||
// Arrow: line with a filled head at the end.
|
||||
const ang = Math.atan2(b.y - a.y, b.x - a.x);
|
||||
const head = lw * 5;
|
||||
ctx.moveTo(a.x, a.y);
|
||||
ctx.lineTo(b.x - Math.cos(ang) * head * 0.6, b.y - Math.sin(ang) * head * 0.6);
|
||||
ctx.stroke();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(b.x, b.y);
|
||||
ctx.lineTo(b.x - head * Math.cos(ang - 0.45), b.y - head * Math.sin(ang - 0.45));
|
||||
ctx.lineTo(b.x - head * Math.cos(ang + 0.45), b.y - head * Math.sin(ang + 0.45));
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Draw on an image (pen, arrow, rectangle) and hand the result back as a PNG file. */
|
||||
export function ImageAnnotator({ src, name, onDone, onCancel }: { src: string; name: string; onDone: (file: File) => void; onCancel: () => void }) {
|
||||
const t = useT();
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const bitmap = useRef<HTMLImageElement | undefined>(undefined);
|
||||
const [shapes, setShapes] = useState<Shape[]>([]);
|
||||
const [tool, setTool] = useState<Tool>("pen");
|
||||
const [color, setColor] = useState(COLORS[0]);
|
||||
const [ready, setReady] = useState(false);
|
||||
const drawing = useRef<Shape | null>(null);
|
||||
|
||||
const redraw = (extra?: Shape | null) => {
|
||||
const c = canvas.current;
|
||||
const img = bitmap.current;
|
||||
if (!c || !img) return;
|
||||
const ctx = c.getContext("2d")!;
|
||||
ctx.clearRect(0, 0, c.width, c.height);
|
||||
ctx.drawImage(img, 0, 0, c.width, c.height);
|
||||
paint(ctx, extra ? [...shapes, extra] : shapes, c.width);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const img = new Image();
|
||||
img.crossOrigin = "anonymous";
|
||||
img.onload = () => {
|
||||
const c = canvas.current;
|
||||
if (!c) return;
|
||||
const scale = Math.min(1, MAX_SIDE / Math.max(img.naturalWidth || 1, img.naturalHeight || 1));
|
||||
c.width = Math.max(1, Math.round((img.naturalWidth || 300) * scale));
|
||||
c.height = Math.max(1, Math.round((img.naturalHeight || 200) * scale));
|
||||
bitmap.current = img;
|
||||
setReady(true);
|
||||
};
|
||||
img.onerror = () => {
|
||||
toast(t("viewer.annotateFailed"));
|
||||
onCancel();
|
||||
};
|
||||
img.src = src;
|
||||
}, [src]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => redraw(), [shapes, ready]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const point = (e: React.PointerEvent) => {
|
||||
const c = canvas.current!;
|
||||
const r = c.getBoundingClientRect();
|
||||
return { x: ((e.clientX - r.left) / r.width) * c.width, y: ((e.clientY - r.top) / r.height) * c.height };
|
||||
};
|
||||
|
||||
const finish = () => {
|
||||
const c = canvas.current;
|
||||
if (!c) return;
|
||||
c.toBlob((blob) => {
|
||||
if (!blob) return toast(t("viewer.annotateFailed"));
|
||||
const base = name.replace(/\.[a-z0-9]{1,5}$/i, "") || "image";
|
||||
onDone(new File([blob], `${base}-marked.png`, { type: "image/png" }));
|
||||
}, "image/png");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="annotator" onClick={(e) => e.stopPropagation()} onWheel={(e) => e.stopPropagation()}>
|
||||
<canvas
|
||||
ref={canvas}
|
||||
style={{ visibility: ready ? "visible" : "hidden" }}
|
||||
onPointerDown={(e) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
drawing.current = { tool, color, pts: [point(e)] };
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
const d = drawing.current;
|
||||
if (!d) return;
|
||||
const p = point(e);
|
||||
d.pts = d.tool === "pen" ? [...d.pts, p] : [d.pts[0], p];
|
||||
redraw(d);
|
||||
}}
|
||||
onPointerUp={() => {
|
||||
const d = drawing.current;
|
||||
drawing.current = null;
|
||||
if (d) setShapes((s) => [...s, d]);
|
||||
}}
|
||||
onPointerCancel={() => {
|
||||
drawing.current = null;
|
||||
redraw();
|
||||
}}
|
||||
/>
|
||||
<div className="annotator-tools" role="toolbar" aria-label={t("viewer.annotate")}>
|
||||
{(["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)}>
|
||||
<Icon name={k === "pen" ? "edit" : k === "arrow" ? "arrow-right" : "box-off"} />
|
||||
</button>
|
||||
))}
|
||||
<span className="annotator-colors">
|
||||
{COLORS.map((c) => (
|
||||
<button key={c} className={`swatch ${c === color ? "on" : ""}`} style={{ background: c }} onClick={() => setColor(c)} aria-label={c} aria-pressed={c === color} />
|
||||
))}
|
||||
</span>
|
||||
<button className="small ghost" onClick={() => setShapes((s) => s.slice(0, -1))} disabled={!shapes.length} title={t("viewer.undo")} aria-label={t("viewer.undo")}>
|
||||
<Icon name="undo" />
|
||||
</button>
|
||||
<span className="grow" />
|
||||
<button className="small" onClick={onCancel}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button className="small primary" onClick={finish} disabled={!ready}>
|
||||
<Icon name="clip" /> {t("viewer.attach")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Icon } from "./Icon";
|
||||
import { ImageAnnotator } from "./ImageAnnotator";
|
||||
import { compose } from "../compose";
|
||||
import { toast } from "../dialogs";
|
||||
import { useT } from "../i18n";
|
||||
|
||||
/** Images that open in the viewer: everything in the app, except UI chrome. */
|
||||
const SKIP = ".viewer-overlay, .sidebar, .topbar, button, .modal-backdrop .viewer, .model-viewer, .media-stage, .composer, .brand, .login";
|
||||
|
||||
interface Item {
|
||||
src: string;
|
||||
alt: string;
|
||||
}
|
||||
|
||||
const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));
|
||||
|
||||
/**
|
||||
* Popup image viewer: a click on any image of the app opens it fullscreen.
|
||||
* Pinch / wheel / double tap to zoom, drag to pan, arrows or swipe for the other
|
||||
* images of the same chat, Esc to close. Mounted once; listens for clicks globally.
|
||||
*/
|
||||
export function ImageViewer() {
|
||||
const t = useT();
|
||||
const [list, setList] = useState<Item[]>([]);
|
||||
const [idx, setIdx] = useState(0);
|
||||
const [open, setOpen] = useState(false);
|
||||
// Chat the image belongs to (for "use in message"); drawing mode.
|
||||
const [sessionId, setSessionId] = useState<string>();
|
||||
const [marking, setMarking] = useState(false);
|
||||
const [view, setView] = useState({ x: 0, y: 0, s: 1 });
|
||||
const pointers = useRef(new Map<number, { x: number; y: number }>());
|
||||
const gesture = useRef<{ d: number; s: number } | null>(null);
|
||||
const moved = useRef(false);
|
||||
const lastTap = useRef(0);
|
||||
const swipe = useRef<{ x: number; y: number } | null>(null);
|
||||
|
||||
const reset = useCallback(() => setView({ x: 0, y: 0, s: 1 }), []);
|
||||
const close = useCallback(() => setOpen(false), []);
|
||||
const go = useCallback(
|
||||
(d: number) => {
|
||||
setIdx((i) => clamp(i + d, 0, list.length - 1));
|
||||
reset();
|
||||
},
|
||||
[list.length, reset],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onClick = (e: MouseEvent) => {
|
||||
const img = (e.target as HTMLElement | null)?.closest?.("img");
|
||||
if (!img || img.closest(SKIP) || e.defaultPrevented || e.button !== 0) return;
|
||||
if (img.naturalWidth && img.naturalWidth < 24) return; // icons
|
||||
e.preventDefault(); // the surrounding link would open a new tab
|
||||
e.stopPropagation();
|
||||
const scope = img.closest(".chat, .files-main, .gallery, .main") ?? document;
|
||||
const all = [...scope.querySelectorAll("img")].filter((i) => !i.closest(SKIP) && i.src && (i.naturalWidth === 0 || i.naturalWidth >= 24));
|
||||
const seen = new Set<string>();
|
||||
const items: Item[] = [];
|
||||
let start = 0;
|
||||
for (const i of all) {
|
||||
if (seen.has(i.currentSrc || i.src)) {
|
||||
if (i === img) start = items.findIndex((x) => x.src === (i.currentSrc || i.src));
|
||||
continue;
|
||||
}
|
||||
seen.add(i.currentSrc || i.src);
|
||||
if (i === img) start = items.length;
|
||||
items.push({ src: i.currentSrc || i.src, alt: i.alt });
|
||||
}
|
||||
setSessionId((img.closest("[data-session-id]") as HTMLElement | null)?.dataset.sessionId);
|
||||
setMarking(false);
|
||||
setList(items.length ? items : [{ src: img.currentSrc || img.src, alt: img.alt }]);
|
||||
setIdx(Math.max(0, start));
|
||||
reset();
|
||||
setOpen(true);
|
||||
};
|
||||
// Capture phase: before the link around a thumbnail navigates.
|
||||
document.addEventListener("click", onClick, true);
|
||||
return () => document.removeEventListener("click", onClick, true);
|
||||
}, [reset]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (marking) return;
|
||||
if (e.key === "Escape") close();
|
||||
else if (e.key === "ArrowLeft") go(-1);
|
||||
else if (e.key === "ArrowRight") go(1);
|
||||
else if (e.key === "+" || e.key === "=") setView((v) => ({ ...v, s: clamp(v.s * 1.25, 1, 8) }));
|
||||
else if (e.key === "-") setView((v) => ({ ...v, s: clamp(v.s / 1.25, 1, 8), ...(v.s / 1.25 <= 1 ? { x: 0, y: 0 } : {}) }));
|
||||
else return;
|
||||
e.preventDefault();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
document.body.style.overflow = prev;
|
||||
};
|
||||
}, [open, close, go, marking]);
|
||||
|
||||
if (!open || !list[idx]) return null;
|
||||
const cur = list[idx];
|
||||
|
||||
/** The image as a file for the composer (variants, questions about it, …). */
|
||||
async function useInChat() {
|
||||
try {
|
||||
const blob = await (await fetch(cur.src, { credentials: "same-origin" })).blob();
|
||||
const ext = blob.type.split("/")[1]?.split("+")[0] || "png";
|
||||
compose({ sessionId: sessionId!, files: [new File([blob], `image.${ext}`, { type: blob.type || "image/png" })] });
|
||||
toast(t("viewer.attached"), "success");
|
||||
close();
|
||||
} catch {
|
||||
toast(t("viewer.annotateFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
const dist = () => {
|
||||
const [a, b] = [...pointers.current.values()];
|
||||
return Math.hypot(a.x - b.x, a.y - b.y);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="viewer-overlay"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("viewer.title")}
|
||||
onClick={() => {
|
||||
if (!moved.current) close();
|
||||
}}
|
||||
onWheel={(e) => setView((v) => {
|
||||
const s = clamp(v.s * (e.deltaY < 0 ? 1.15 : 1 / 1.15), 1, 8);
|
||||
return s === 1 ? { x: 0, y: 0, s } : { ...v, s };
|
||||
})}
|
||||
>
|
||||
<div className="viewer-bar" onClick={(e) => e.stopPropagation()}>
|
||||
<span className="viewer-count">{list.length > 1 ? `${idx + 1} / ${list.length}` : ""}</span>
|
||||
<span className="viewer-name">{cur.alt && !/^(image|SVG)$/i.test(cur.alt) ? cur.alt : ""}</span>
|
||||
{sessionId && (
|
||||
<>
|
||||
<button className="small ghost" onClick={() => setMarking(true)} title={t("viewer.annotate")} aria-label={t("viewer.annotate")}>
|
||||
<Icon name="edit" />
|
||||
</button>
|
||||
<button className="small ghost" onClick={() => void useInChat()} title={t("viewer.useInChat")} aria-label={t("viewer.useInChat")}>
|
||||
<Icon name="reply" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<a className="button small ghost" href={cur.src} target="_blank" rel="noreferrer" title={t("viewer.open")} aria-label={t("viewer.open")}>
|
||||
<Icon name="share" />
|
||||
</a>
|
||||
<a className="button small ghost" href={cur.src} download title={t("viewer.download")} aria-label={t("viewer.download")}>
|
||||
<Icon name="download" />
|
||||
</a>
|
||||
<button className="small ghost" onClick={close} aria-label={t("common.close")}>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
{marking && (
|
||||
<ImageAnnotator
|
||||
src={cur.src}
|
||||
name={cur.alt || "image"}
|
||||
onCancel={() => setMarking(false)}
|
||||
onDone={(file) => {
|
||||
compose({ sessionId: sessionId!, files: [file] });
|
||||
toast(t("viewer.attached"), "success");
|
||||
close();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!marking && idx > 0 && (
|
||||
<button className="viewer-nav prev" onClick={(e) => (e.stopPropagation(), go(-1))} aria-label={t("media.prev")}>
|
||||
<Icon name="arrow-left" />
|
||||
</button>
|
||||
)}
|
||||
{!marking && idx < list.length - 1 && (
|
||||
<button className="viewer-nav next" onClick={(e) => (e.stopPropagation(), go(1))} aria-label={t("media.next")}>
|
||||
<Icon name="arrow-right" />
|
||||
</button>
|
||||
)}
|
||||
{!marking && <img
|
||||
key={cur.src}
|
||||
className="viewer-img"
|
||||
src={cur.src}
|
||||
alt={cur.alt}
|
||||
draggable={false}
|
||||
style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.s})`, cursor: view.s > 1 ? "grab" : "zoom-in" }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={(e) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
moved.current = false;
|
||||
if (pointers.current.size === 2) gesture.current = { d: dist(), s: view.s };
|
||||
else swipe.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
const p = pointers.current.get(e.pointerId);
|
||||
if (!p) return;
|
||||
const dx = e.clientX - p.x;
|
||||
const dy = e.clientY - p.y;
|
||||
pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (pointers.current.size === 2 && gesture.current) {
|
||||
moved.current = true;
|
||||
const s = clamp((gesture.current.s * dist()) / gesture.current.d, 1, 8);
|
||||
setView((v) => (s === 1 ? { x: 0, y: 0, s } : { ...v, s }));
|
||||
} else if (view.s > 1) {
|
||||
if (Math.abs(dx) + Math.abs(dy) > 1) moved.current = true;
|
||||
setView((v) => ({ ...v, x: v.x + dx, y: v.y + dy }));
|
||||
}
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
pointers.current.delete(e.pointerId);
|
||||
gesture.current = null;
|
||||
const s0 = swipe.current;
|
||||
swipe.current = null;
|
||||
if (s0 && view.s === 1) {
|
||||
const dx = e.clientX - s0.x;
|
||||
const dy = e.clientY - s0.y;
|
||||
if (Math.abs(dx) > 60 && Math.abs(dx) > Math.abs(dy) * 1.5) {
|
||||
moved.current = true;
|
||||
go(dx < 0 ? 1 : -1);
|
||||
} else if (dy > 90 && Math.abs(dy) > Math.abs(dx) * 1.5) {
|
||||
moved.current = true;
|
||||
close();
|
||||
}
|
||||
}
|
||||
// Double tap / double click: zoom in or back.
|
||||
if (!moved.current) {
|
||||
const now = Date.now();
|
||||
if (now - lastTap.current < 300) setView((v) => (v.s > 1 ? { x: 0, y: 0, s: 1 } : { ...v, s: 2.5 }));
|
||||
lastTap.current = now;
|
||||
}
|
||||
}}
|
||||
onPointerCancel={(e) => {
|
||||
pointers.current.delete(e.pointerId);
|
||||
gesture.current = null;
|
||||
}}
|
||||
/>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Icon } from "./Icon";
|
||||
import { useState } from "react";
|
||||
import { post } from "../api";
|
||||
import { useT } from "../i18n";
|
||||
import { getLang, useT } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import type { PermissionRequest, QuestionRequest } from "../types";
|
||||
@@ -31,7 +31,24 @@ export function PermissionCard({ req, currentId }: { req: PermissionRequest; cur
|
||||
const chosen = selected.filter(Boolean).length;
|
||||
const partial = hunkCount > 1 && chosen < hunkCount;
|
||||
|
||||
const reply = async (r: "once" | "always" | "reject") => {
|
||||
const [explaining, setExplaining] = useState(false);
|
||||
const [explanation, setExplanation] = useState<string>();
|
||||
const [explainError, setExplainError] = useState<string>();
|
||||
/** The small model explains in plain words what the action does (approving on a phone without reading code). */
|
||||
const explain = async () => {
|
||||
setExplaining(true);
|
||||
setExplainError(undefined);
|
||||
try {
|
||||
const r = await post<{ text: string }>(`/permissions/${req.id}/explain`, { lang: getLang() });
|
||||
setExplanation(r.text);
|
||||
} catch (e: any) {
|
||||
setExplainError(e.message);
|
||||
} finally {
|
||||
setExplaining(false);
|
||||
}
|
||||
};
|
||||
|
||||
const reply = async (r: "once" | "always" | "project" | "reject") => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const hunks = r === "once" && partial ? selected.flatMap((on, i) => (on ? [i] : [])) : undefined;
|
||||
@@ -47,6 +64,10 @@ export function PermissionCard({ req, currentId }: { req: PermissionRequest; cur
|
||||
? t("permission.alwaysCommand", { prefix: (command ?? "").split(/\s+/).slice(0, 2).join(" ") })
|
||||
: t("permission.alwaysTool", { tool: req.tool });
|
||||
|
||||
// Dangerous commands are only ever allowed for the session (the server decides; this hides the button).
|
||||
const dangerous = !!command && /\b(rm\s+-[a-zA-Z]*[rRf]|sudo|su|git\s+(push|reset|clean|rebase|checkout|restore)|docker|docker-compose|systemctl|chmod\s+-R|chown\s+-R|dd|mkfs|shutdown|reboot|kill|pkill|killall|crontab)\b|\|\s*(ba)?sh\b|publish/.test(command);
|
||||
const projectLabel = req.tool === "bash" ? t("permission.projectCommand", { prefix: (command ?? "").split(/\s+/).slice(0, 2).join(" ") }) : t("permission.projectTool", { tool: req.tool });
|
||||
|
||||
return (
|
||||
<div className="card" role="alertdialog" aria-label={t("permission.title")}>
|
||||
<h3>
|
||||
@@ -72,6 +93,16 @@ export function PermissionCard({ req, currentId }: { req: PermissionRequest; cur
|
||||
</details>
|
||||
)
|
||||
)}
|
||||
{explanation ? (
|
||||
<div className="explain" role="note">
|
||||
<Icon name="sparkle" className="tiny" /> {explanation}
|
||||
</div>
|
||||
) : (
|
||||
<button className="small ghost explain-btn" disabled={explaining} onClick={explain}>
|
||||
<Icon name="sparkle" /> {explaining ? t("permission.explaining") : t("permission.explain")}
|
||||
</button>
|
||||
)}
|
||||
{explainError && <div className="hint">{explainError}</div>}
|
||||
<input
|
||||
style={{ width: "100%", marginTop: 8 }}
|
||||
placeholder={t("permission.feedback")}
|
||||
@@ -86,6 +117,11 @@ export function PermissionCard({ req, currentId }: { req: PermissionRequest; cur
|
||||
<button disabled={busy || partial} onClick={() => reply("always")}>
|
||||
{alwaysLabel}
|
||||
</button>
|
||||
{!dangerous && (
|
||||
<button disabled={busy || partial} onClick={() => reply("project")} title={t("permission.projectHint")}>
|
||||
{projectLabel}
|
||||
</button>
|
||||
)}
|
||||
<button className="danger" disabled={busy} onClick={() => reply("reject")}>
|
||||
{feedback ? t("permission.rejectWithFeedback") : t("permission.reject")}
|
||||
</button>
|
||||
|
||||
@@ -20,6 +20,7 @@ interface Settings {
|
||||
model: string;
|
||||
permission_mode: string;
|
||||
timeout_minutes: number;
|
||||
notify: boolean;
|
||||
}
|
||||
|
||||
const settingsOf = (j: JobInfo): Settings => ({
|
||||
@@ -29,6 +30,7 @@ const settingsOf = (j: JobInfo): Settings => ({
|
||||
model: j.spec?.model ?? "",
|
||||
permission_mode: j.spec?.permission_mode ?? "auto",
|
||||
timeout_minutes: j.spec?.timeout_minutes ?? 60,
|
||||
notify: j.spec?.notify ?? true,
|
||||
});
|
||||
|
||||
type Tab = "prompt" | "settings" | "assistant";
|
||||
@@ -254,6 +256,10 @@ export function JobEditor({ id, onMenu }: { id: string; onMenu: () => void }) {
|
||||
<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>
|
||||
</div>
|
||||
<label className="row" style={{ gap: 6, alignItems: "center", marginTop: 6 }}>
|
||||
<input type="checkbox" checked={settings.notify} onChange={(e) => up({ notify: e.target.checked })} />
|
||||
{t("jobEditor.notify")}
|
||||
</label>
|
||||
{settings.permission_mode !== "bypass" && <div className="hint">{t("jobEditor.bypassHint")}</div>}
|
||||
</section>
|
||||
<section className="job-editor-prompt">
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface JobInfo {
|
||||
next_run?: number | null;
|
||||
error?: string;
|
||||
webhook?: boolean;
|
||||
spec?: { name: string; schedule: string; agent: string; model?: string | null; permission_mode: string; timeout_minutes: number; prompt: string; assistant_session?: string | null };
|
||||
spec?: { name: string; schedule: string; agent: string; model?: string | null; permission_mode: string; timeout_minutes: number; notify?: boolean; prompt: string; assistant_session?: string | null };
|
||||
}
|
||||
|
||||
const fmtDate = (ms?: number | null) => (ms ? new Date(ms).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }) : "–");
|
||||
|
||||
@@ -3,14 +3,24 @@ import { get } from "../api";
|
||||
import { useT, type Key } from "../i18n";
|
||||
import { Spinner } from "./Activity";
|
||||
import { Icon } from "./Icon";
|
||||
import { navigate } from "../router";
|
||||
|
||||
/** Open a 3D model in the 3D view of the file manager. */
|
||||
const open3d = (path: string) => {
|
||||
sessionStorage.setItem("codecraft.openFile", path);
|
||||
navigate("/files");
|
||||
};
|
||||
|
||||
interface MediaItem {
|
||||
kind: "image" | "video" | "audio";
|
||||
kind: "image" | "video" | "audio" | "model";
|
||||
url: string;
|
||||
name: string;
|
||||
source: "generated" | "tool" | "written" | "answer" | "upload";
|
||||
created_at: number;
|
||||
message_id?: string;
|
||||
/** 3D models: file (opened in the 3D view) and preview image. */
|
||||
path?: string;
|
||||
preview?: string;
|
||||
}
|
||||
|
||||
type Filter = "all" | MediaItem["kind"];
|
||||
@@ -55,7 +65,7 @@ export function MediaGallery({ sessionId, onClose, onJump }: { sessionId: string
|
||||
<Icon name="image" /> {t("media.title")}
|
||||
</h3>
|
||||
<div className="media-filters" role="radiogroup">
|
||||
{(["all", "image", "video", "audio"] 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"}>
|
||||
{t(`media.filter.${k}` as Key)} {items && <small>{count(k)}</small>}
|
||||
</button>
|
||||
@@ -78,6 +88,16 @@ export function MediaGallery({ sessionId, onClose, onJump }: { sessionId: string
|
||||
{current.kind === "image" && <img src={current.url} alt={current.name} />}
|
||||
{current.kind === "video" && <video src={current.url} controls autoPlay />}
|
||||
{current.kind === "audio" && <audio src={current.url} controls autoPlay />}
|
||||
{current.kind === "model" && (
|
||||
<div className="media-model">
|
||||
{current.preview ? <img src={current.preview} alt={current.name} /> : <Icon name="cube" />}
|
||||
{current.path && (
|
||||
<button className="primary" onClick={() => open3d(current.path!)}>
|
||||
<Icon name="cube" /> {t("tool.open3d")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="media-bar">
|
||||
<button className="small ghost" disabled={open === 0} onClick={() => setOpen((o) => (o ?? 1) - 1)} aria-label={t("media.prev")}>
|
||||
@@ -115,6 +135,16 @@ export function MediaGallery({ sessionId, onClose, onJump }: { sessionId: string
|
||||
</span>
|
||||
)}
|
||||
{m.kind === "video" && <Icon name="play" className="media-play" />}
|
||||
{m.kind === "model" &&
|
||||
(m.preview ? (
|
||||
<img src={m.preview} alt="" loading="lazy" decoding="async" />
|
||||
) : (
|
||||
<span className="media-audio">
|
||||
<Icon name="cube" />
|
||||
<span>{m.name}</span>
|
||||
</span>
|
||||
))}
|
||||
{m.kind === "model" && <span className="media-badge">3D</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import { post } from "../api";
|
||||
import { asQuote, compose } from "../compose";
|
||||
import { useT } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
import { loadSessions } from "../store";
|
||||
import { toast } from "../dialogs";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
/** What the message menus of one chat need to know. */
|
||||
export const ChatCtx = createContext<{ sessionId: string; canFork: boolean; canReply: boolean }>({ sessionId: "", canFork: false, canReply: false });
|
||||
|
||||
/**
|
||||
* Actions of one message: copy, quote into the reply, fork the chat from here and
|
||||
* (for own messages) edit and resend. Hover on desktop, always faintly visible on touch.
|
||||
*/
|
||||
export function MessageMenu({ messageId, text, forkable, onRewind }: { messageId: string; text: string; forkable: boolean; onRewind?: () => void }) {
|
||||
const t = useT();
|
||||
const { sessionId, canFork, canReply } = useContext(ChatCtx);
|
||||
const close = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
(e.currentTarget.closest("details") as HTMLDetailsElement).open = false;
|
||||
};
|
||||
if (!text.trim() && !onRewind) return null;
|
||||
return (
|
||||
<details className="menu-pop msg-menu">
|
||||
<summary className="small ghost" title={t("msg.actions")} aria-label={t("msg.actions")}>
|
||||
<Icon name="more" />
|
||||
</summary>
|
||||
<div className="menu-pop-body">
|
||||
{text.trim() && (
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
close(e);
|
||||
const done = () => toast(t("msg.copied"), "success");
|
||||
if (navigator.clipboard?.writeText) void navigator.clipboard.writeText(text).then(done, () => toast(t("msg.copyFailed")));
|
||||
else toast(t("msg.copyFailed"));
|
||||
}}
|
||||
>
|
||||
<Icon name="copy" /> {t("msg.copy")}
|
||||
</a>
|
||||
)}
|
||||
{text.trim() && canReply && (
|
||||
<a href="#" onClick={(e) => (close(e), compose({ sessionId, text: asQuote(text) }))}>
|
||||
<Icon name="reply" /> {t("msg.quote")}
|
||||
</a>
|
||||
)}
|
||||
{onRewind && (
|
||||
<a href="#" onClick={(e) => (close(e), onRewind())}>
|
||||
<Icon name="edit" /> {t("chat.rewind")}
|
||||
</a>
|
||||
)}
|
||||
{forkable && canFork && (
|
||||
<a
|
||||
href="#"
|
||||
onClick={async (e) => {
|
||||
close(e);
|
||||
try {
|
||||
const fork = await post<{ id: string }>(`/sessions/${sessionId}/fork`, { message_id: messageId });
|
||||
await loadSessions();
|
||||
toast(t("chat.forked"));
|
||||
navigate(`/s/${fork.id}`);
|
||||
} catch (err: any) {
|
||||
toast(err.message);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon name="fork" /> {t("msg.forkHere")}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Icon } from "./Icon";
|
||||
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 { useAgents, useFetch } from "../hooks";
|
||||
import { useT, type Key } from "../i18n";
|
||||
@@ -193,7 +194,7 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
||||
if (!model && config?.default_model) setModel(config.default_model);
|
||||
}, [config, model]);
|
||||
useEffect(() => {
|
||||
if (!rootPath && roots.length) setRootPath(roots[roots.length - 1].path);
|
||||
if (!rootPath && roots.length) setRootPath(roots[0].path);
|
||||
}, [roots, rootPath]);
|
||||
// Old software is analysed in deep mode; websites default to clean room.
|
||||
useEffect(() => {
|
||||
@@ -313,12 +314,14 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
||||
const send = async (list: File[], dir: string) => {
|
||||
if (!list.length) return;
|
||||
await mkdirs(dir);
|
||||
for (const f of list) {
|
||||
const jobs = list.map((f) => {
|
||||
const name = f.name.replace(/[\\/]/g, "_");
|
||||
setCreating(`${t("wizard.uploading")} ${name}`);
|
||||
await uploadFile(`${cwd}/${dir}/${name}`, f, (x) => setProgress((p) => ({ ...p, [f.name]: x })));
|
||||
uploaded.push(`${dir}/${name}`);
|
||||
}
|
||||
return { file: f, path: `${cwd}/${dir}/${name}`, name, onProgress: (x: number) => setProgress((p) => ({ ...p, [f.name]: x })) };
|
||||
});
|
||||
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/.
|
||||
await send(originals, "original");
|
||||
@@ -328,7 +331,8 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
|
||||
const isCraft = task === "craft";
|
||||
const s = await post<{ id: string }>("/sessions", {
|
||||
cwd,
|
||||
model: model || undefined,
|
||||
// The server default is not sent, so the project's own default model can apply.
|
||||
model: model && model !== config?.default_model ? model : undefined,
|
||||
agent: task === "cad" ? "build" : task,
|
||||
clean_room: isCraft ? !deep : undefined,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useEffect } from "react";
|
||||
import { useT } from "../i18n";
|
||||
import { flushOutbox, removeFromOutbox, useOutbox } from "../outbox";
|
||||
import { useStore } from "../store";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
/** Messages waiting for a connection: sent automatically once the server is reachable again. */
|
||||
export function OutboxBar({ sessionId }: { sessionId: string }) {
|
||||
const t = useT();
|
||||
const items = useOutbox(sessionId);
|
||||
const connected = useStore((s) => s.connected);
|
||||
useEffect(() => {
|
||||
if (!items.length) return;
|
||||
const go = () => void flushOutbox(sessionId);
|
||||
if (connected && navigator.onLine) go();
|
||||
window.addEventListener("online", go);
|
||||
return () => window.removeEventListener("online", go);
|
||||
}, [sessionId, connected, items.length]);
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<div className="outbox" role="status">
|
||||
<div className="outbox-head">
|
||||
<Icon name="clock" className="tiny" /> {t("outbox.waiting", { n: items.length })}
|
||||
<span className="grow" />
|
||||
<button className="small" onClick={() => void flushOutbox(sessionId)}>
|
||||
{t("outbox.sendNow")}
|
||||
</button>
|
||||
</div>
|
||||
{items.map((i) => (
|
||||
<div key={i.id} className="outbox-item">
|
||||
<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")}>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useMemo } from "react";
|
||||
import { useFetch } from "../hooks";
|
||||
import { fmtCost, fmtDate, fmtRelative, useT, type Key } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import type { Session } from "../types";
|
||||
import { Icon } from "./Icon";
|
||||
import { basename } from "./FileFigure";
|
||||
|
||||
interface Overview {
|
||||
sessions: Record<string, { files: number; check: string | null; checks_failed: number; cost: number }>;
|
||||
check: { command: string; enabled: boolean } | null;
|
||||
defaults: { model?: string; agent?: string; permission_mode?: string; color?: string; instructions?: string; folder?: string } | null;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
const day = (ms: number) => new Date(ms).toDateString();
|
||||
|
||||
/** One project folder: its chats as a timeline (newest first) with what each one did. */
|
||||
export function ProjectPage({ cwd, onMenu }: { cwd: string; onMenu: () => void }) {
|
||||
const t = useT();
|
||||
const all = useStore((s) => s.sessions);
|
||||
const { data } = useFetch<Overview>(`/projects/overview?cwd=${encodeURIComponent(cwd)}`);
|
||||
const sessions = useMemo(() => all.filter((s) => s.cwd === cwd && !s.archived).sort((a, b) => b.updated_at - a.updated_at), [all, cwd]);
|
||||
const archived = all.filter((s) => s.cwd === cwd && s.archived).length;
|
||||
|
||||
// Day groups: "Today", "Yesterday", date.
|
||||
const groups = useMemo(() => {
|
||||
const out: { label: string; items: Session[] }[] = [];
|
||||
const today = day(Date.now());
|
||||
const yesterday = day(Date.now() - 86_400_000);
|
||||
for (const s of sessions) {
|
||||
const d = day(s.updated_at);
|
||||
const label = d === today ? t("project.today") : d === yesterday ? t("project.yesterday") : fmtDate(s.updated_at, false);
|
||||
const last = out[out.length - 1];
|
||||
if (last?.label === label) last.items.push(s);
|
||||
else out.push({ label, items: [s] });
|
||||
}
|
||||
return out;
|
||||
}, [sessions, t]);
|
||||
|
||||
const totalCost = sessions.reduce((n, s) => n + (data?.sessions[s.id]?.cost ?? 0), 0);
|
||||
const totalFiles = sessions.reduce((n, s) => n + (data?.sessions[s.id]?.files ?? 0), 0);
|
||||
|
||||
const newChat = () => {
|
||||
try {
|
||||
localStorage.setItem("codecraft.lastDir", cwd);
|
||||
} catch {
|
||||
// Without storage the wizard starts at its usual folder.
|
||||
}
|
||||
navigate("/new");
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="topbar">
|
||||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||||
<Icon name="menu" />
|
||||
</button>
|
||||
<div className="grow">
|
||||
<h1>
|
||||
<Icon name="folder" /> {basename(cwd) || "/"}
|
||||
</h1>
|
||||
<div className="path mono">{cwd}</div>
|
||||
</div>
|
||||
<button className="small primary" onClick={newChat}>
|
||||
<Icon name="plus" /> {t("project.newChat")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="chat-scroll">
|
||||
<div className="chat project-page">
|
||||
<div className="project-summary">
|
||||
<span className="chip">{t("project.chats", { n: sessions.length })}</span>
|
||||
{totalFiles > 0 && <span className="chip">{t("project.files", { n: totalFiles })}</span>}
|
||||
{data && totalCost > 0 && <span className="chip">{fmtCost(totalCost, data.currency)}</span>}
|
||||
{data?.check?.enabled && (
|
||||
<span className="chip mono" title={t("check.title")}>
|
||||
<Icon name="check" className="tiny" /> {data.check.command}
|
||||
</span>
|
||||
)}
|
||||
{data?.defaults?.model && (
|
||||
<span className="chip" title={t("projectDefaults.hint")}>
|
||||
<Icon name="template" className="tiny" /> {data.defaults.model.split("/").pop()}
|
||||
</span>
|
||||
)}
|
||||
{archived > 0 && <span className="hint">{t("project.archived", { n: archived })}</span>}
|
||||
</div>
|
||||
{sessions.length === 0 && <div className="empty">{t("project.empty")}</div>}
|
||||
{groups.map((g) => (
|
||||
<section key={g.label} className="timeline-day">
|
||||
<h3>{g.label}</h3>
|
||||
<ol className="timeline">
|
||||
{g.items.map((s) => {
|
||||
const info = data?.sessions[s.id];
|
||||
return (
|
||||
<li key={s.id} data-color={s.color} className={s.color ? "tagged" : ""}>
|
||||
<a href={`#/s/${s.id}`} onClick={(e) => (e.preventDefault(), navigate(`/s/${s.id}`))}>
|
||||
<div className="tl-title">
|
||||
<span className={s.color ? "color-badge" : undefined}>
|
||||
{s.icon && <Icon name={s.icon} className="tiny chat-icon" />}
|
||||
{s.title || t("session.untitled")}
|
||||
</span>
|
||||
<span className="tl-when" title={fmtDate(s.updated_at)}>
|
||||
{fmtRelative(s.updated_at)}
|
||||
</span>
|
||||
</div>
|
||||
{s.summary && <div className="tl-summary">{s.summary}</div>}
|
||||
<div className="tl-meta">
|
||||
<span>{s.agent}</span>
|
||||
<span>{s.model.split("/").pop()}</span>
|
||||
{!!info?.files && <span>{t("project.files", { n: info.files })}</span>}
|
||||
{info?.check && (
|
||||
<span className={`check-${info.check}`}>
|
||||
<Icon name={info.check === "passed" ? "check" : info.check === "running" ? "clock" : "x-mark"} className="tiny" /> {t(`check.${info.check}` as Key)}
|
||||
</span>
|
||||
)}
|
||||
{!!info?.checks_failed && <span className="check-failed">{t("project.checksFailed", { n: info.checks_failed })}</span>}
|
||||
{!!info?.cost && data && <span>{fmtCost(info.cost, data.currency)}</span>}
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, get } from "../api";
|
||||
import { useT } from "../i18n";
|
||||
import { toast } from "../dialogs";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
/** "bash:git status" → "git status"; tool names stay. */
|
||||
const label = (key: string) => (key.startsWith("bash:") ? `$ ${key.slice(5)}` : key);
|
||||
|
||||
/** What the user allowed "for this project" (all chats of the folder) – with a way to revoke it. */
|
||||
export function ProjectPermissions({ sessionId, cwd, onClose }: { sessionId: string; cwd: string; onClose: () => void }) {
|
||||
const t = useT();
|
||||
const [keys, setKeys] = useState<string[]>();
|
||||
useEffect(() => {
|
||||
get<string[]>(`/sessions/${sessionId}/approvals`).then(setKeys, (e) => (toast(e.message), setKeys([])));
|
||||
}, [sessionId]);
|
||||
const revoke = async (key: string) => {
|
||||
try {
|
||||
await api(`/sessions/${sessionId}/approvals`, { method: "DELETE", json: { key } });
|
||||
setKeys((k) => k?.filter((x) => x !== key));
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal" role="dialog" aria-label={t("permProject.title")} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>
|
||||
<Icon name="lock" /> {t("permProject.title")}
|
||||
</h3>
|
||||
<p style={{ fontSize: 13, color: "var(--fg3)", marginBottom: 4 }}>{t("permProject.intro")}</p>
|
||||
<div className="path mono" style={{ marginBottom: 8 }}>{cwd}</div>
|
||||
{keys === undefined ? (
|
||||
<div className="empty">…</div>
|
||||
) : keys.length === 0 ? (
|
||||
<p style={{ fontSize: 13 }}>{t("permProject.empty")}</p>
|
||||
) : (
|
||||
<ul className="rewind-files">
|
||||
{keys.map((k) => (
|
||||
<li key={k} className="row" style={{ justifyContent: "space-between" }}>
|
||||
<code>{label(k)}</code>
|
||||
<button className="small danger" onClick={() => void revoke(k)}>
|
||||
{t("permProject.revoke")}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="row" style={{ justifyContent: "flex-end", marginTop: 10 }}>
|
||||
<button onClick={onClose}>{t("common.close")}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { get } from "../api";
|
||||
import { fmtMsgTime, useT } from "../i18n";
|
||||
import { Markdown } from "./Markdown";
|
||||
|
||||
interface Shared {
|
||||
title: string;
|
||||
messages: { id: string; role: "user" | "assistant"; text: string; created_at: number }[];
|
||||
}
|
||||
|
||||
/** A chat opened through a read-only link (no account needed). */
|
||||
export function PublicChat({ token }: { token: string }) {
|
||||
const t = useT();
|
||||
const [chat, setChat] = useState<Shared>();
|
||||
const [error, setError] = useState<string>();
|
||||
useEffect(() => {
|
||||
get<Shared>(`/public/chat/${encodeURIComponent(token)}`)
|
||||
.then((c) => (setChat(c), (document.title = `${c.title || "Chat"} – CodeCraft`)))
|
||||
.catch((e) => setError(e.message));
|
||||
}, [token]);
|
||||
if (error) return <div className="empty">{error}</div>;
|
||||
if (!chat) return <div className="empty">{t("common.loading")}</div>;
|
||||
return (
|
||||
<div className="public-chat">
|
||||
<header>
|
||||
<h1>{chat.title || "Chat"}</h1>
|
||||
<div className="hint">{t("link.readOnly")}</div>
|
||||
</header>
|
||||
<div className="chat-scroll">
|
||||
{chat.messages.map((m) => (
|
||||
<div key={m.id} className={m.role === "user" ? "bubble user-msg" : "bubble agent"}>
|
||||
<Markdown text={m.text} />
|
||||
<div className="msg-foot">
|
||||
<span className="hint">{fmtMsgTime(m.created_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { Folders } from "./settings/Folders";
|
||||
import { Users } from "./settings/Users";
|
||||
import { Audit } from "./settings/Audit";
|
||||
import { Tools } from "./settings/Tools";
|
||||
import { Skills } from "./settings/Skills";
|
||||
import { confirmDialog, promptDialog, toast } from "../dialogs";
|
||||
|
||||
type Json = any;
|
||||
@@ -146,8 +147,11 @@ function VersionInfo() {
|
||||
function DigestToggle() {
|
||||
const t = useT();
|
||||
const [on, setOn] = useState<boolean>();
|
||||
const [weekly, setWeekly] = useState(false);
|
||||
useEffect(() => {
|
||||
get<{ enabled: boolean }>("/push/digest").then((r) => setOn(r.enabled)).catch(() => {});
|
||||
get<{ enabled: boolean; weekly?: boolean }>("/push/digest")
|
||||
.then((r) => (setOn(r.enabled), setWeekly(!!r.weekly)))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
if (on === undefined) return null;
|
||||
return (
|
||||
@@ -164,6 +168,30 @@ function DigestToggle() {
|
||||
/>
|
||||
{t("settings.digest")}
|
||||
</label>
|
||||
<label className="row" style={{ gap: 6, alignItems: "center" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={weekly}
|
||||
onChange={(e) => {
|
||||
const v = e.target.checked;
|
||||
setWeekly(v);
|
||||
put("/push/digest", { weekly: v }).catch((err) => (setWeekly(!v), toast(err.message)));
|
||||
}}
|
||||
/>
|
||||
{t("settings.weeklyDigest")}
|
||||
</label>
|
||||
{weekly && (
|
||||
<button
|
||||
className="small ghost"
|
||||
onClick={() =>
|
||||
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"))
|
||||
.catch((e) => toast(e.message))
|
||||
}
|
||||
>
|
||||
{t("settings.digestNow")}
|
||||
</button>
|
||||
)}
|
||||
{on && (
|
||||
<button
|
||||
className="small ghost"
|
||||
@@ -246,8 +274,11 @@ function General({ cfg, reload }: { cfg: ConfigResponse; reload: () => void }) {
|
||||
const [form, setForm] = useState({
|
||||
default_model: s.default_model ?? "",
|
||||
small_model: s.small_model ?? "",
|
||||
plan_model: ((cfg.config as any).agents?.plan?.model ?? "") as string,
|
||||
transcribe_model: ((s as any).transcribe_model ?? "") as string,
|
||||
currency: s.currency ?? "USD",
|
||||
auto_compact_threshold: s.auto_compact_threshold ?? 0.85,
|
||||
commit_trailer: ((s as any).commit_trailer ?? "Co-Authored-By: {model} ({provider}) via CodeCraft") as string,
|
||||
max_parallel_subagents: s.max_parallel_subagents ?? 4,
|
||||
monthly_budget: s.monthly_budget ?? 0,
|
||||
budget_warning: s.budget_warning ?? 0.8,
|
||||
@@ -269,8 +300,11 @@ function General({ cfg, reload }: { cfg: ConfigResponse; reload: () => void }) {
|
||||
savePatches([
|
||||
{ path: ["server", "default_model"], value: form.default_model },
|
||||
{ path: ["server", "small_model"], value: form.small_model },
|
||||
{ path: ["agents", "plan", "model"], value: form.plan_model || null },
|
||||
{ path: ["server", "transcribe_model"], value: form.transcribe_model.trim() },
|
||||
{ path: ["server", "currency"], value: form.currency },
|
||||
{ path: ["server", "auto_compact_threshold"], value: Number(form.auto_compact_threshold) },
|
||||
{ path: ["server", "commit_trailer"], value: form.commit_trailer.trim() },
|
||||
{ path: ["server", "max_parallel_subagents"], value: Number(form.max_parallel_subagents) },
|
||||
{ path: ["server", "monthly_budget"], value: Number(form.monthly_budget) || 0 },
|
||||
{ path: ["server", "budget_warning"], value: Number(form.budget_warning) || 0.8 },
|
||||
@@ -300,11 +334,20 @@ function General({ cfg, reload }: { cfg: ConfigResponse; reload: () => void }) {
|
||||
<label>{t("settings.smallModel")}</label>
|
||||
<ModelSelect value={form.small_model} onChange={(v) => setForm({ ...form, small_model: v })} />
|
||||
<div className="hint">{t("settings.smallModelHint")}</div>
|
||||
<label>{t("settings.planModel")}</label>
|
||||
<ModelSelect value={form.plan_model} emptyLabel={t("settings.sameAsChat")} onChange={(v) => setForm({ ...form, plan_model: v })} />
|
||||
<div className="hint">{t("settings.planModelHint")}</div>
|
||||
<label>{t("settings.transcribeModel")}</label>
|
||||
<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>
|
||||
<label>{t("settings.currency")}</label>
|
||||
<input value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value.toUpperCase() })} maxLength={3} />
|
||||
<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 })} />
|
||||
<div className="hint">{t("settings.autoCompactHint")}</div>
|
||||
<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 })} />
|
||||
<div className="hint">{t("settings.commitTrailerHint")}</div>
|
||||
<label>{t("settings.monthlyBudgetTotal")}</label>
|
||||
<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>
|
||||
@@ -1046,8 +1089,8 @@ function Raw({ reload }: { reload: () => void }) {
|
||||
|
||||
// --- page -------------------------------------------------------------------
|
||||
|
||||
const ADMIN_TABS = ["general", "providers", "agents", "mcp", "permissions", "users", "folders", "tools", "audit", "templates", "modes", "account", "raw"] as const;
|
||||
const USER_TABS = ["general", "templates", "modes", "account"] 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", "skills", "account"] as const;
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
general: "gear",
|
||||
providers: "brain",
|
||||
@@ -1060,6 +1103,7 @@ const TAB_ICONS: Record<string, string> = {
|
||||
audit: "scroll",
|
||||
templates: "template",
|
||||
modes: "sparkle",
|
||||
skills: "scroll",
|
||||
account: "user",
|
||||
raw: "file-text",
|
||||
};
|
||||
@@ -1097,6 +1141,7 @@ export function Settings({ tab, onMenu }: { tab?: string; onMenu: () => void })
|
||||
{active === "account" && <Account />}
|
||||
{active === "templates" && <Templates />}
|
||||
{active === "modes" && <PersonalModes />}
|
||||
{active === "skills" && <Skills />}
|
||||
{cfg && active === "users" && <Users />}
|
||||
{cfg && active === "folders" && <Folders />}
|
||||
{cfg && active === "audit" && <Audit />}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { get, put } from "../api";
|
||||
import { del, get, post, put } from "../api";
|
||||
import { useT } from "../i18n";
|
||||
import { useStore } from "../store";
|
||||
import { toast } from "../dialogs";
|
||||
import { fmtDate } from "../i18n";
|
||||
|
||||
interface DirUser {
|
||||
id: string;
|
||||
@@ -9,6 +11,54 @@ interface DirUser {
|
||||
display_name: string;
|
||||
}
|
||||
|
||||
interface Link {
|
||||
token: string;
|
||||
url: string;
|
||||
expires_at: number;
|
||||
}
|
||||
|
||||
/** Read-only links for people without an account. */
|
||||
function Links({ sessionId }: { sessionId: string }) {
|
||||
const t = useT();
|
||||
const [links, setLinks] = useState<Link[]>([]);
|
||||
const [days, setDays] = useState(7);
|
||||
const load = () => get<Link[]>(`/sessions/${sessionId}/links`).then(setLinks).catch(() => undefined);
|
||||
useEffect(() => void load(), [sessionId]);
|
||||
const create = async () => {
|
||||
try {
|
||||
const l = await post<Link>(`/sessions/${sessionId}/links`, { days });
|
||||
await navigator.clipboard?.writeText(l.url).then(() => toast(t("link.copied"), "success"), () => undefined);
|
||||
void load();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="share-links">
|
||||
<h4>{t("link.title")}</h4>
|
||||
<div className="hint">{t("link.hint")}</div>
|
||||
{links.map((l) => (
|
||||
<div key={l.token} className="row share-link">
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
))}
|
||||
<div className="row" style={{ marginTop: 6 }}>
|
||||
<select value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label={t("link.validity")}>
|
||||
{[1, 7, 30, 90].map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{t("link.days", { n: d })}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button onClick={create}>{t("link.create")}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Choose users a session is shared with (read-only for them). */
|
||||
export function ShareDialog({ sessionId, onClose }: { sessionId: string; onClose: () => void }) {
|
||||
const t = useT();
|
||||
@@ -59,6 +109,7 @@ export function ShareDialog({ sessionId, onClose }: { sessionId: string; onClose
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Links sessionId={sessionId} />
|
||||
{error && <div className="notice err">{error}</div>}
|
||||
<div className="row" style={{ marginTop: 12, justifyContent: "flex-end" }}>
|
||||
<button onClick={onClose}>{t("common.cancel")}</button>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { deleteChat } from "../chatActions";
|
||||
import { Icon } from "./Icon";
|
||||
import { StatusLeds } from "./StatusLeds";
|
||||
import { cycleThemeMode, getThemeMode, onThemeChange } from "../theme";
|
||||
@@ -25,7 +26,7 @@ function groupKey(ms: number): Key {
|
||||
const GROUP_BY = "codecraft.sidebarGroupBy";
|
||||
const COLLAPSED = "codecraft.sidebarCollapsed";
|
||||
|
||||
const organise = (id: string, body: Partial<Pick<Session, "pinned" | "archived">> & { folder?: string }) => patch(`/sessions/${id}`, body).catch((e) => toast(e.message));
|
||||
const organise = (id: string, body: Partial<Pick<Session, "pinned" | "archived">> & { folder?: string; color?: string; icon?: string }) => patch(`/sessions/${id}`, body).catch((e) => toast(e.message));
|
||||
|
||||
/** One session in the list, with a menu to pin, file or archive it. */
|
||||
function SessionRow({ s, active, attention, busy, folders }: { s: Session; active: boolean; attention: boolean; busy: boolean; folders: string[] }) {
|
||||
@@ -53,11 +54,15 @@ function SessionRow({ s, active, attention, busy, folders }: { s: Session; activ
|
||||
};
|
||||
return (
|
||||
<div className={`session-row ${menu ? "menu-open" : ""}`}>
|
||||
<button className={`session-item ${active ? "active" : ""}`} onClick={() => navigate(`/s/${s.id}`)}>
|
||||
<button className={`session-item ${active ? "active" : ""}`} data-color={s.color} onClick={() => navigate(`/s/${s.id}`)}>
|
||||
<div className="title">
|
||||
{attention ? <i className="attn-dot" title={t("sidebar.needsInput")} /> : busy && <i className="busy-ring" title={t("activity.working")} />}
|
||||
<span>{s.title || t("session.untitled")}</span>
|
||||
<span className={s.color ? "color-badge" : undefined}>
|
||||
{s.icon && <Icon name={s.icon} className="tiny chat-icon" />}
|
||||
{s.title || t("session.untitled")}
|
||||
</span>
|
||||
</div>
|
||||
{s.summary && <div className="summary" title={s.summary}>{s.summary}</div>}
|
||||
<div className="sub">
|
||||
{s.shared && <span title={t("sidebar.shared")}><Icon name="share" className="tiny" /> </span>}
|
||||
{basename(s.cwd)} · {s.agent} · {fmtRelative(s.updated_at)}
|
||||
@@ -96,6 +101,18 @@ function SessionRow({ s, active, attention, busy, folders }: { s: Session; activ
|
||||
<button role="menuitem" onClick={() => (setMenu(false), organise(s.id, { archived: !s.archived }))}>
|
||||
<Icon name="archive" /> {t(s.archived ? "sidebar.unarchive" : "sidebar.archiveOne")}
|
||||
</button>
|
||||
{!s.shared && (
|
||||
<button
|
||||
role="menuitem"
|
||||
className="danger"
|
||||
onClick={async () => {
|
||||
setMenu(false);
|
||||
if ((await deleteChat(s)) && active) navigate("/new");
|
||||
}}
|
||||
>
|
||||
<Icon name="trash" /> {t("chat.delete")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -194,6 +211,11 @@ function GroupHeader({
|
||||
)}
|
||||
{menu && (
|
||||
<div className="session-menu" role="menu" onClick={(e) => e.stopPropagation()}>
|
||||
{g.id.startsWith("project:") && (
|
||||
<button role="menuitem" onClick={() => (setMenu(false), navigate(`/p/${encodeURIComponent(g.id.slice("project:".length))}`))}>
|
||||
<Icon name="clock" /> {t("project.open")}
|
||||
</button>
|
||||
)}
|
||||
<button role="menuitem" onClick={() => (setMenu(false), onPin?.())}>
|
||||
<Icon name="pin" /> {t(pinned ? "sidebar.groupUnpin" : "sidebar.groupPin")}
|
||||
</button>
|
||||
@@ -469,6 +491,10 @@ export function Sidebar({ open, activeIds, section }: { open: boolean; activeIds
|
||||
<Icon name="clock" className="nav-icon" />
|
||||
{t("nav.jobs")}
|
||||
</button>
|
||||
<button className={`ghost ${section === "factory" ? "active" : ""}`} onClick={() => navigate("/factory")}>
|
||||
<Icon name="factory" className="nav-icon" />
|
||||
{t("nav.factory")}
|
||||
</button>
|
||||
<button className={`ghost ${section === "stats" ? "active" : ""}`} onClick={() => navigate("/stats")}>
|
||||
<Icon name="chart" className="nav-icon" />
|
||||
{t("nav.stats")}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Icon } from "./Icon";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
||||
import { useFetch } from "../hooks";
|
||||
import { fmtCompact, fmtCost, fmtDate, fmtNumber, fmtPercent, getLang, useT, type Key } from "../i18n";
|
||||
import { navigate } from "../router";
|
||||
@@ -15,6 +15,9 @@ interface StatsData {
|
||||
total: Aggregate;
|
||||
by_day: Row<"day">[];
|
||||
by_day_model: { day: string; model: string; cost: number; input_tokens: number; output_tokens: number }[];
|
||||
by_month: Row<"month">[];
|
||||
/** First recorded request (any range): the years to choose from. */
|
||||
first_ts: number | null;
|
||||
by_model: Row<"model">[];
|
||||
by_provider: Row<"provider">[];
|
||||
by_agent: Row<"agent">[];
|
||||
@@ -37,6 +40,16 @@ const RANGES: { key: string; days: number; label: Key }[] = [
|
||||
|
||||
type HeatMetric = "requests" | "tokens" | "cost";
|
||||
|
||||
/** All months (YYYY-MM, local time) from the month of `fromMs` to the month of `toMs`. */
|
||||
function monthRange(fromMs: number, toMs: number): string[] {
|
||||
const out: string[] = [];
|
||||
const d = new Date(fromMs);
|
||||
d.setDate(1);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
for (; d.getTime() <= toMs && out.length < 600; d.setMonth(d.getMonth() + 1)) out.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
function dayKey(ms: number) {
|
||||
const d = new Date(ms);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
@@ -51,6 +64,44 @@ function dayRange(fromMs: number, toMs: number, firstDataDay?: string): string[]
|
||||
return out;
|
||||
}
|
||||
|
||||
const FOLD_KEY = "codecraft.statsFolded";
|
||||
|
||||
function foldedSet(): Set<string> {
|
||||
try {
|
||||
return new Set(JSON.parse(localStorage.getItem(FOLD_KEY) ?? "[]"));
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
/** Panel with a title that folds the content; the state is remembered per device. */
|
||||
function Fold({ id, title, children }: { id: string; title: React.ReactNode; children: React.ReactNode }) {
|
||||
const [closed, setClosed] = useState(() => foldedSet().has(id));
|
||||
const toggle = () => {
|
||||
const next = !closed;
|
||||
setClosed(next);
|
||||
try {
|
||||
const set = foldedSet();
|
||||
if (next) set.add(id);
|
||||
else set.delete(id);
|
||||
localStorage.setItem(FOLD_KEY, JSON.stringify([...set]));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className={`panel fold${closed ? " closed" : ""}`}>
|
||||
<h3>
|
||||
<button className="fold-toggle" aria-expanded={!closed} onClick={toggle}>
|
||||
<span className="fold-caret" aria-hidden="true" />
|
||||
{title}
|
||||
</button>
|
||||
</h3>
|
||||
{!closed && children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Kpi({ label, value, sub }: { label: string; value: string; sub?: string }) {
|
||||
return (
|
||||
<div className="kpi">
|
||||
@@ -67,8 +118,39 @@ function perMillion(r: Aggregate, currency: string) {
|
||||
return tokens > 0 && r.cost > 0 ? fmtCost((r.cost / tokens) * 1_000_000, currency) : "–";
|
||||
}
|
||||
|
||||
function AggTable({ rows, keyName, label, currency, link }: { rows: (Aggregate & Record<string, any>)[]; keyName: string; label: string; currency: string; link?: (r: any) => void }) {
|
||||
function AggTable({
|
||||
rows,
|
||||
keyName,
|
||||
label,
|
||||
currency,
|
||||
link,
|
||||
group,
|
||||
}: {
|
||||
rows: (Aggregate & Record<string, any>)[];
|
||||
keyName: string;
|
||||
label: string;
|
||||
currency: string;
|
||||
link?: (r: any) => void;
|
||||
/** Group key of a row (e.g. the provider of a model): groups fold. */
|
||||
group?: (r: any) => string;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [shut, setShut] = useState<Set<string>>(new Set());
|
||||
const groups = group ? [...new Set(rows.map(group))] : [];
|
||||
const row = (r: (typeof rows)[number]) => (
|
||||
<tr key={r[keyName]}>
|
||||
<td className={group ? "fold-indent" : undefined}>{link ? <a href="#" onClick={(e) => (e.preventDefault(), link(r))}>{r[keyName]}</a> : r[keyName]}</td>
|
||||
<td className="num">{fmtNumber(r.requests)}</td>
|
||||
<td className="num">{fmtCompact(r.input_tokens + r.cache_write_tokens)}</td>
|
||||
<td className="num">{fmtCompact(r.cache_read_tokens)}</td>
|
||||
<td className="num">{fmtCompact(r.output_tokens)}</td>
|
||||
<td className="num">{fmtNumber(r.avg_ttft_ms)} ms</td>
|
||||
<td className="num">{fmtNumber(r.output_tps, 1)}</td>
|
||||
<td className="num">{fmtNumber(r.prefill_tps)}</td>
|
||||
<td className="num">{fmtCost(r.cost, currency)}</td>
|
||||
<td className="num">{perMillion(r, currency)}</td>
|
||||
</tr>
|
||||
);
|
||||
return (
|
||||
<div style={{ overflowX: "auto" }}>
|
||||
<table className="grid">
|
||||
@@ -87,20 +169,33 @@ function AggTable({ rows, keyName, label, currency, link }: { rows: (Aggregate &
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r[keyName]}>
|
||||
<td>{link ? <a href="#" onClick={(e) => (e.preventDefault(), link(r))}>{r[keyName]}</a> : r[keyName]}</td>
|
||||
<td className="num">{fmtNumber(r.requests)}</td>
|
||||
<td className="num">{fmtCompact(r.input_tokens + r.cache_write_tokens)}</td>
|
||||
<td className="num">{fmtCompact(r.cache_read_tokens)}</td>
|
||||
<td className="num">{fmtCompact(r.output_tokens)}</td>
|
||||
<td className="num">{fmtNumber(r.avg_ttft_ms)} ms</td>
|
||||
<td className="num">{fmtNumber(r.output_tps, 1)}</td>
|
||||
<td className="num">{fmtNumber(r.prefill_tps)}</td>
|
||||
<td className="num">{fmtCost(r.cost, currency)}</td>
|
||||
<td className="num">{perMillion(r, currency)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{group
|
||||
? groups.map((g) => {
|
||||
const members = rows.filter((r) => group(r) === g);
|
||||
const open = !shut.has(g);
|
||||
return (
|
||||
<Fragment key={g}>
|
||||
<tr className="fold-group">
|
||||
<td>
|
||||
<button
|
||||
className="fold-toggle"
|
||||
aria-expanded={open}
|
||||
onClick={() => setShut((x) => (x.has(g) ? new Set([...x].filter((k) => k !== g)) : new Set(x).add(g)))}
|
||||
>
|
||||
<span className="fold-caret" aria-hidden="true" />
|
||||
{g} <span className="hint">({members.length})</span>
|
||||
</button>
|
||||
</td>
|
||||
<td className="num">{fmtNumber(members.reduce((a, r) => a + r.requests, 0))}</td>
|
||||
<td colSpan={6} />
|
||||
<td className="num">{fmtCost(members.reduce((a, r) => a + r.cost, 0), currency)}</td>
|
||||
<td />
|
||||
</tr>
|
||||
{open && members.map(row)}
|
||||
</Fragment>
|
||||
);
|
||||
})
|
||||
: rows.map(row)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -117,16 +212,40 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
const isAdmin = useStore((s) => s.me?.role === "admin");
|
||||
const users = useFetch<User[]>(isAdmin ? "/users" : null).data ?? [];
|
||||
const [userFilter, setUserFilter] = useState("");
|
||||
const days = RANGES.find((r) => r.key === range)!.days;
|
||||
const tz = -new Date().getTimezoneOffset();
|
||||
// Stable per range: rounded to the minute so the URL doesn't change on every render.
|
||||
const now = Math.floor(Date.now() / 60000) * 60000 + 60000;
|
||||
const from = days ? now - days * 86400000 : 0;
|
||||
const { data, error } = useFetch<StatsData>(`/stats?from=${from}&to=${now}&tz=${tz}${userFilter ? `&user=${userFilter}` : ""}`);
|
||||
// "y2025": that calendar year (local time); otherwise a rolling window.
|
||||
const year = /^y(\d{4})$/.test(range) ? Number(range.slice(1)) : 0;
|
||||
const days = RANGES.find((r) => r.key === range)?.days ?? 0;
|
||||
const from = year ? new Date(year, 0, 1).getTime() : days ? now - days * 86400000 : 0;
|
||||
const to = year ? Math.min(now, new Date(year + 1, 0, 1).getTime()) : now;
|
||||
const { data, error } = useFetch<StatsData>(`/stats?from=${from}&to=${to}&tz=${tz}${userFilter ? `&user=${userFilter}` : ""}`);
|
||||
/** Download of what is shown: all tables as XLSX, or one table as CSV. */
|
||||
const exportAs = (what: string) => {
|
||||
if (!what) return;
|
||||
const q = `from=${from}&to=${to}&tz=${tz}&lang=${getLang()}${userFilter ? `&user=${userFilter}` : ""}`;
|
||||
const a = document.createElement("a");
|
||||
a.href = `/api/stats/export?${q}&format=${what === "xlsx" ? "xlsx" : "csv&table=" + what.slice(4)}`;
|
||||
a.download = "";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
};
|
||||
// Years since the first recorded request (the data survives indefinitely).
|
||||
const [firstYear, setFirstYear] = useState(new Date().getFullYear());
|
||||
useEffect(() => {
|
||||
if (data?.first_ts) setFirstYear(new Date(data.first_ts).getFullYear());
|
||||
}, [data?.first_ts]);
|
||||
const years = Array.from({ length: new Date().getFullYear() - firstYear + 1 }, (_, i) => new Date().getFullYear() - i);
|
||||
const spanDays = ((data?.to ?? now) - (data?.from || data?.first_ts || now)) / 86400000;
|
||||
// Long ranges: one bar per month instead of one per day.
|
||||
const monthly = spanDays > 120;
|
||||
|
||||
const view = useMemo(() => {
|
||||
if (!data) return undefined;
|
||||
const cats = dayRange(data.from, data.to, data.by_day[0]?.day);
|
||||
const bucket = (day: string) => (monthly ? day.slice(0, 7) : day);
|
||||
const cats = monthly ? monthRange(data.from || data.first_ts || data.to, data.to) : dayRange(data.from, data.to, data.by_day[0]?.day);
|
||||
// Up to 7 models by cost get their own color; the rest fold into "Other".
|
||||
const ranked = [...data.by_model].sort((a, b) => b.cost - a.cost || b.requests - a.requests);
|
||||
const named = ranked.slice(0, ranked.length > 8 ? 7 : 8).map((m) => m.model);
|
||||
@@ -135,7 +254,7 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
const costByDay = cats.map(() => ({}) as Record<string, number>);
|
||||
const idx = new Map(cats.map((c, i) => [c, i]));
|
||||
for (const r of data.by_day_model) {
|
||||
const i = idx.get(r.day);
|
||||
const i = idx.get(bucket(r.day));
|
||||
if (i === undefined) continue;
|
||||
const key = named.includes(r.model) ? r.model : other;
|
||||
costByDay[i][key] = (costByDay[i][key] ?? 0) + r.cost;
|
||||
@@ -146,7 +265,7 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
{ key: "output", label: t("stats.output"), color: SERIES[2] },
|
||||
];
|
||||
const tokensByDay = cats.map((c): Record<string, number> => {
|
||||
const d = data.by_day.find((x) => x.day === c);
|
||||
const d = monthly ? data.by_month.find((x) => x.month === c) : data.by_day.find((x) => x.day === c);
|
||||
return d ? { input: d.input_tokens + d.cache_write_tokens, cache: d.cache_read_tokens, output: d.output_tokens } : {};
|
||||
});
|
||||
// Rolling window: the last 14 days, today at the bottom.
|
||||
@@ -174,10 +293,12 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
return { label: `${wd.format(date)} ${dm.format(date)}`, title: full.format(date) };
|
||||
});
|
||||
return { cats, modelSeries, costByDay, tokenSeries, tokensByDay, cells, heatRows };
|
||||
}, [data, heat, t]);
|
||||
}, [data, heat, t, monthly]);
|
||||
|
||||
const dayLabel = (d: string) =>
|
||||
new Intl.DateTimeFormat(getLang(), { day: "numeric", month: "short" }).format(new Date(`${d}T00:00:00`));
|
||||
monthly
|
||||
? new Intl.DateTimeFormat(getLang(), { month: "short", year: "2-digit" }).format(new Date(`${d}-01T00:00:00`))
|
||||
: new Intl.DateTimeFormat(getLang(), { day: "numeric", month: "short" }).format(new Date(`${d}T00:00:00`));
|
||||
const cur = data?.currency ?? "USD";
|
||||
const tot = data?.total;
|
||||
const heatFormat = (v: number) => (heat === "cost" ? fmtCost(v, cur) : fmtCompact(v));
|
||||
@@ -203,6 +324,16 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{years.length > 1 && (
|
||||
<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>
|
||||
{years.map((y) => (
|
||||
<option key={y} value={`y${y}`}>
|
||||
{y}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<select value={userFilter} onChange={(e) => setUserFilter(e.target.value)} aria-label={t("stats.user")}>
|
||||
<option value="">{t("stats.allUsers")}</option>
|
||||
@@ -213,6 +344,15 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<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="xlsx">{t("stats.exportXlsx")}</option>
|
||||
{(["day", "month", "model", "provider", "agent", "user", "session"] as const).map((k) => (
|
||||
<option key={k} value={`csv:${k}`}>
|
||||
{t("stats.exportCsv", { table: t(`stats.table.${k}` as Key) })}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="small" onClick={() => setTableView(!tableView)}>
|
||||
{tableView ? t("stats.chartView") : t("stats.tableView")}
|
||||
</button>
|
||||
@@ -238,61 +378,51 @@ export function Stats({ onMenu }: { onMenu: () => void }) {
|
||||
{tot.requests === 0 ? (
|
||||
<div className="empty">{t("stats.noData")}</div>
|
||||
) : tableView ? (
|
||||
<div className="panel">
|
||||
<h3>{t("stats.perDay")}</h3>
|
||||
<Fold id="perDay" title={t("stats.perDay")}>
|
||||
<AggTable rows={data.by_day} keyName="day" label={t("stats.day")} currency={cur} />
|
||||
</div>
|
||||
</Fold>
|
||||
) : (
|
||||
<>
|
||||
<div className="panel">
|
||||
<h3>{t("stats.costPerDay")}</h3>
|
||||
<Fold id="costPerDay" title={t(monthly ? "stats.costPerMonth" : "stats.costPerDay")}>
|
||||
<Legend series={view.modelSeries} />
|
||||
<StackedBars categories={view.cats} categoryLabel={dayLabel} series={view.modelSeries} values={view.costByDay} format={(v) => fmtCost(v, cur)} />
|
||||
</div>
|
||||
<div className="panel">
|
||||
<h3>{t("stats.tokensPerDay")}</h3>
|
||||
</Fold>
|
||||
<Fold id="tokensPerDay" title={t(monthly ? "stats.tokensPerMonth" : "stats.tokensPerDay")}>
|
||||
<Legend series={view.tokenSeries} />
|
||||
<StackedBars categories={view.cats} categoryLabel={dayLabel} series={view.tokenSeries} values={view.tokensByDay} format={fmtCompact} />
|
||||
</div>
|
||||
<div className="panel">
|
||||
<h3>
|
||||
{t("stats.heatmap")}
|
||||
<span className="spacer" />
|
||||
<select value={heat} onChange={(e) => setHeat(e.target.value as HeatMetric)}>
|
||||
</Fold>
|
||||
<Fold id="heatmap" title={t("stats.heatmap")}>
|
||||
<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")}>
|
||||
<option value="requests">{t("stats.requests")}</option>
|
||||
<option value="tokens">{t("stats.tokens")}</option>
|
||||
<option value="cost">{t("stats.cost")}</option>
|
||||
</select>
|
||||
</h3>
|
||||
</div>
|
||||
<Heatmap cells={view.cells} rows={view.heatRows} format={heatFormat} />
|
||||
</div>
|
||||
</Fold>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tot.requests > 0 && (
|
||||
<>
|
||||
<div className="panel">
|
||||
<h3>{t("stats.byModel")}</h3>
|
||||
<AggTable rows={data.by_model} keyName="model" label={t("stats.model")} currency={cur} />
|
||||
</div>
|
||||
<div className="panel">
|
||||
<h3>{t("stats.byProvider")}</h3>
|
||||
<Fold id="byModel" title={t("stats.byModel")}>
|
||||
<AggTable rows={data.by_model} keyName="model" label={t("stats.model")} currency={cur} group={(r) => String(r.model).split("/")[0]} />
|
||||
</Fold>
|
||||
<Fold id="byProvider" title={t("stats.byProvider")}>
|
||||
<AggTable rows={data.by_provider} keyName="provider" label={t("stats.provider")} currency={cur} />
|
||||
</div>
|
||||
<div className="panel">
|
||||
<h3>{t("stats.byAgent")}</h3>
|
||||
</Fold>
|
||||
<Fold id="byAgent" title={t("stats.byAgent")}>
|
||||
<AggTable rows={data.by_agent} keyName="agent" label={t("stats.agent")} currency={cur} />
|
||||
</div>
|
||||
</Fold>
|
||||
{isAdmin && !userFilter && data.by_user.length > 1 && (
|
||||
<div className="panel">
|
||||
<h3>{t("stats.byUser")}</h3>
|
||||
<Fold id="byUser" title={t("stats.byUser")}>
|
||||
<AggTable rows={data.by_user} keyName="user" label={t("stats.user")} currency={cur} />
|
||||
</div>
|
||||
</Fold>
|
||||
)}
|
||||
<div className="panel">
|
||||
<h3>{t("stats.topSessions")}</h3>
|
||||
<Fold id="topSessions" title={t("stats.topSessions")}>
|
||||
<AggTable rows={data.top_sessions} keyName="title" label={t("stats.session")} currency={cur} link={(r) => !r.session_id.startsWith("cli:") && navigate(`/s/${r.session_id}`)} />
|
||||
</div>
|
||||
</Fold>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -121,7 +121,7 @@ export function ToolCard({ call, result, running, baseDir }: { call: ToolCall; r
|
||||
const diffLines = typeof meta?.diff === "string" ? meta.diff.split("\n").length : 0;
|
||||
const openByDefault =
|
||||
(status === "err" && !!result) ||
|
||||
(!!result && !result.is_error && ((diffLines > 0 && diffLines <= 40) || call.name === "generate_image"));
|
||||
(!!result && !result.is_error && ((diffLines > 0 && diffLines <= 40) || (result.images?.length ?? 0) > 0 || call.name === "generate_image" || call.name === "generate_3d"));
|
||||
const open = toggled ?? openByDefault;
|
||||
|
||||
return (
|
||||
@@ -164,6 +164,18 @@ export function ToolCard({ call, result, running, baseDir }: { call: ToolCall; r
|
||||
<pre className="mono">{result.content}</pre>
|
||||
</>
|
||||
)}
|
||||
{typeof meta?.model_file === "string" && (
|
||||
<button
|
||||
className="small"
|
||||
style={{ marginBottom: 8 }}
|
||||
onClick={() => {
|
||||
sessionStorage.setItem("codecraft.openFile", meta.model_file);
|
||||
navigate("/files");
|
||||
}}
|
||||
>
|
||||
<Icon name="cube" /> {t("tool.open3d")}
|
||||
</button>
|
||||
)}
|
||||
{Array.isArray(meta?.image_ids) ? (
|
||||
<div className="gallery small">
|
||||
{meta.image_ids.map((id: string, i: number) => {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useState } from "react";
|
||||
import { get } from "../api";
|
||||
import { useT } from "../i18n";
|
||||
import type { Message } from "../types";
|
||||
import { Diff } from "./Diff";
|
||||
import { Icon } from "./Icon";
|
||||
import { basename } from "./FileFigure";
|
||||
|
||||
interface Change {
|
||||
path: string;
|
||||
created: boolean;
|
||||
deleted?: boolean;
|
||||
diff?: string;
|
||||
truncated?: boolean;
|
||||
}
|
||||
|
||||
const count = (diff: string | undefined, sign: "+" | "-") => (diff ?? "").split("\n").filter((l) => l.startsWith(sign) && !l.startsWith(sign.repeat(3))).length;
|
||||
|
||||
/**
|
||||
* What one turn changed: files with their diffs (from the checkpoints the agent leaves before
|
||||
* every write/edit) and a button to roll the chat and the files back to before the turn.
|
||||
*/
|
||||
export function TurnChanges({
|
||||
sessionId,
|
||||
fromId,
|
||||
untilId,
|
||||
fileCount,
|
||||
userMessage,
|
||||
onRewind,
|
||||
}: {
|
||||
sessionId: string;
|
||||
fromId: string;
|
||||
untilId?: string;
|
||||
fileCount: number;
|
||||
userMessage?: Message;
|
||||
onRewind?: (m: Message) => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [changes, setChanges] = useState<Change[]>();
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const toggle = () => {
|
||||
const next = !open;
|
||||
setOpen(next);
|
||||
if (next && !changes) {
|
||||
const q = `since_message=${encodeURIComponent(fromId)}&diff=true${untilId ? `&until_message=${encodeURIComponent(untilId)}` : ""}`;
|
||||
get<Change[]>(`/sessions/${sessionId}/changes?${q}`).then(setChanges, (e) => setError(e.message));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="turn-changes">
|
||||
<button className="small ghost" onClick={toggle} aria-expanded={open}>
|
||||
<Icon name={open ? "chevron-down" : "chevron-right"} className="tiny" /> {t("turn.changes", { n: fileCount })}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="turn-changes-body">
|
||||
{error && <div className="notice err">{error}</div>}
|
||||
{!changes && !error && <div className="hint">…</div>}
|
||||
{changes?.length === 0 && <div className="hint">{t("turn.noChanges")}</div>}
|
||||
{changes?.map((c) => (
|
||||
<details key={c.path} className="turn-file">
|
||||
<summary title={c.path}>
|
||||
<span className="mono">{basename(c.path)}</span>
|
||||
{c.created && <span className="chip">{t("turn.new")}</span>}
|
||||
{c.deleted && <span className="chip warn">{t("turn.deleted")}</span>}
|
||||
<span className="turn-stat">
|
||||
<span className="add">+{count(c.diff, "+")}</span> <span className="del">−{count(c.diff, "-")}</span>
|
||||
</span>
|
||||
</summary>
|
||||
{c.diff ? <Diff diff={c.diff} /> : <div className="hint">{t("turn.noDiff")}</div>}
|
||||
{c.truncated && <div className="hint">{t("turn.truncated")}</div>}
|
||||
</details>
|
||||
))}
|
||||
{userMessage && onRewind && changes && changes.length > 0 && (
|
||||
<button className="small" onClick={() => onRewind(userMessage)}>
|
||||
<Icon name="undo" /> {t("turn.rollback")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useState } from "react";
|
||||
import { post } from "../api";
|
||||
import { toast } from "../dialogs";
|
||||
import { useT } from "../i18n";
|
||||
import { useStore } from "../store";
|
||||
import { Spinner } from "./Activity";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
/** Green/red badge of the project's check (tests, build …) for one turn; output and "let the agent fix it" on click. */
|
||||
export function TurnCheck({ sessionId, messageId, canSend }: { sessionId: string; messageId: string; canSend: boolean }) {
|
||||
const t = useT();
|
||||
const check = useStore((s) => s.checks[sessionId]?.[messageId]);
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!check) return null;
|
||||
const seconds = check.duration_ms >= 1000 ? ` · ${(check.duration_ms / 1000).toFixed(check.duration_ms >= 10_000 ? 0 : 1)} s` : "";
|
||||
const label =
|
||||
check.status === "running" ? t("check.running") : check.status === "passed" ? t("check.passed") : check.status === "timeout" ? t("check.timeout") : t("check.failed");
|
||||
const fix = async () => {
|
||||
try {
|
||||
await post(`/sessions/${sessionId}/prompt`, { text: `${t("check.fixPrompt")}\n\n\`\`\`\n${check.output}\n\`\`\`` });
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="turn-check">
|
||||
<button className={`chip check-${check.status}`} onClick={() => setOpen(!open)} aria-expanded={open} disabled={check.status === "running"}>
|
||||
{check.status === "running" ? <Spinner small /> : <Icon name={check.status === "passed" ? "check" : "x-mark"} className="tiny" />} {label}
|
||||
{seconds}
|
||||
</button>
|
||||
{open && check.status !== "running" && (
|
||||
<div className="turn-check-body">
|
||||
<pre className="mono">{check.output || t("check.noOutput")}</pre>
|
||||
{check.status !== "passed" && canSend && (
|
||||
<button className="small primary" onClick={fix}>
|
||||
<Icon name="sparkle" /> {t("check.fix")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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 className="small ghost" 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,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { getLang, useT } from "../i18n";
|
||||
import { toast } from "../dialogs";
|
||||
import { get } from "../api";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
/* Web Speech API (Chrome/Edge/Safari; Firefox has none). */
|
||||
@@ -18,10 +19,86 @@ const Impl: (new () => Recognition) | undefined = (window as any).SpeechRecognit
|
||||
|
||||
export const voiceSupported = () => !!Impl;
|
||||
|
||||
/** Server-side transcription is on (server.transcribe_model) – for browsers without dictation. */
|
||||
function useServerSpeech(): boolean {
|
||||
const [on, setOn] = useState(false);
|
||||
useEffect(() => {
|
||||
if (Impl) return;
|
||||
get<{ transcribe?: boolean }>("/config")
|
||||
.then((c) => setOn(!!c.transcribe))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
return on;
|
||||
}
|
||||
|
||||
/** Record with the microphone; the audio is transcribed by the server. */
|
||||
function RecorderButton({ onText, onInterim }: { onText: (text: string) => void; onInterim: (text: string) => void }) {
|
||||
const t = useT();
|
||||
const [state, setState] = useState<"idle" | "recording" | "sending">("idle");
|
||||
const rec = useRef<MediaRecorder | null>(null);
|
||||
useEffect(() => () => rec.current?.stream.getTracks().forEach((x) => x.stop()), []);
|
||||
|
||||
const toggle = async () => {
|
||||
if (state === "recording") {
|
||||
rec.current?.stop();
|
||||
return;
|
||||
}
|
||||
if (state === "sending") return;
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
const r = new MediaRecorder(stream);
|
||||
const chunks: Blob[] = [];
|
||||
r.ondataavailable = (e) => e.data.size && chunks.push(e.data);
|
||||
r.onstop = async () => {
|
||||
stream.getTracks().forEach((x) => x.stop());
|
||||
setState("sending");
|
||||
onInterim(t("voice.transcribing"));
|
||||
try {
|
||||
const blob = new Blob(chunks, { type: r.mimeType || "audio/webm" });
|
||||
const res = await fetch(`/api/transcribe?lang=${getLang()}`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": blob.type }, body: blob });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error ?? data.message ?? `HTTP ${res.status}`);
|
||||
if (data.text) onText(String(data.text));
|
||||
} catch (e: any) {
|
||||
toast(`${t("voice.error")}: ${e.message}`);
|
||||
} finally {
|
||||
onInterim("");
|
||||
setState("idle");
|
||||
}
|
||||
};
|
||||
rec.current = r;
|
||||
r.start();
|
||||
setState("recording");
|
||||
} catch {
|
||||
toast(t("voice.denied"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`ghost small voice-btn ${state === "recording" ? "on" : ""}`}
|
||||
disabled={state === "sending"}
|
||||
onClick={() => void toggle()}
|
||||
title={t(state === "recording" ? "voice.stop" : "voice.start")}
|
||||
aria-label={t(state === "recording" ? "voice.stop" : "voice.start")}
|
||||
aria-pressed={state === "recording"}
|
||||
>
|
||||
<Icon name="mic" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const LOCALES: Record<string, string> = { de: "de-DE", en: "en-US" };
|
||||
|
||||
/** Microphone button: dictated text is appended to the message. */
|
||||
export function VoiceButton({ onText, onInterim }: { onText: (text: string) => void; onInterim: (text: string) => void }) {
|
||||
export function VoiceButton(props: { onText: (text: string) => void; onInterim: (text: string) => void }) {
|
||||
const server = useServerSpeech();
|
||||
if (!Impl) return server ? <RecorderButton {...props} /> : null;
|
||||
return <BrowserVoiceButton {...props} />;
|
||||
}
|
||||
|
||||
function BrowserVoiceButton({ onText, onInterim }: { onText: (text: string) => void; onInterim: (text: string) => void }) {
|
||||
const t = useT();
|
||||
const [listening, setListening] = useState(false);
|
||||
const rec = useRef<Recognition | null>(null);
|
||||
|
||||
@@ -3,9 +3,12 @@ import { post } from "../../api";
|
||||
import { useT } from "../../i18n";
|
||||
import { useStore } from "../../store";
|
||||
import { GitAccount } from "./GitAccount";
|
||||
import { SshKeys } from "./SshKeys";
|
||||
import { ApiTokens } from "./ApiTokens";
|
||||
import { CliInstall } from "./CliInstall";
|
||||
import { Memory } from "./Memory";
|
||||
import { Snippets } from "./Snippets";
|
||||
import { ClaudeCode } from "./ClaudeCode";
|
||||
import { Telegram } from "./Telegram";
|
||||
|
||||
export function Account() {
|
||||
@@ -50,8 +53,11 @@ export function Account() {
|
||||
<div style={{ fontSize: 12, color: "var(--muted)", marginTop: 8 }}>{t("account.hint")}</div>
|
||||
</div>
|
||||
<Memory />
|
||||
<Snippets />
|
||||
<GitAccount />
|
||||
<SshKeys />
|
||||
<CliInstall />
|
||||
<ClaudeCode />
|
||||
<Telegram />
|
||||
<ApiTokens />
|
||||
</>
|
||||
|
||||
@@ -62,6 +62,7 @@ function AgentRow({ a, raw, tools, onSaved }: { a: AgentInfo; raw: any; tools: T
|
||||
refine_model: raw?.refine?.model ?? "",
|
||||
refine_criteria: raw?.refine?.criteria ?? "",
|
||||
refine_after_todos: (raw?.refine?.after_todos ?? a.refine?.after_todos ?? true) as boolean,
|
||||
reverse_tools: !!(raw?.reverse_tools ?? a.reverse),
|
||||
});
|
||||
const builtin = a.source === "builtin" || (a.source === "config" && !raw?.prompt && ["build", "plan", "craft", "chat", "general", "explore"].includes(a.name));
|
||||
|
||||
@@ -78,6 +79,7 @@ function AgentRow({ a, raw, tools, onSaved }: { a: AgentInfo; raw: any; tools: T
|
||||
value: rounds || form.refine_model || form.refine_criteria ? { rounds, model: form.refine_model || null, criteria: form.refine_criteria || null, after_todos: form.refine_after_todos } : null,
|
||||
});
|
||||
}
|
||||
if (a.name !== "craft") patches.push({ path: [...base, "reverse_tools"], value: form.reverse_tools || null });
|
||||
if (!builtin || form.description) patches.push({ path: [...base, "description"], value: form.description || null });
|
||||
if (!builtin) {
|
||||
patches.push({ path: [...base, "mode"], value: form.mode });
|
||||
@@ -166,6 +168,15 @@ function AgentRow({ a, raw, tools, onSaved }: { a: AgentInfo; raw: any; tools: T
|
||||
<div className="hint">{t("agents.refineAfterTodosHint")}</div>
|
||||
</>
|
||||
)}
|
||||
{a.name !== "craft" && (
|
||||
<>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={form.reverse_tools} onChange={(e) => setForm({ ...form, reverse_tools: e.target.checked })} />
|
||||
{t("agents.reverseTools")}
|
||||
</label>
|
||||
<div className="hint">{t("agents.reverseToolsHint")}</div>
|
||||
</>
|
||||
)}
|
||||
<label>{t("agents.description")}</label>
|
||||
<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>}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { uploadBatch } from "../../uploads";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { api, get, patch, post } from "../../api";
|
||||
import { confirmDialog, toast } from "../../dialogs";
|
||||
@@ -100,7 +101,11 @@ export function Backups() {
|
||||
setRestoring(true);
|
||||
try {
|
||||
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");
|
||||
// Wait until the server is gone and back, then reload with the restored data.
|
||||
await new Promise((r) => setTimeout(r, 2500));
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, get, post } from "../../api";
|
||||
import { confirmDialog, toast } from "../../dialogs";
|
||||
import { useT } from "../../i18n";
|
||||
import { Icon } from "../Icon";
|
||||
import { Spinner } from "../Activity";
|
||||
import { useStore } from "../../store";
|
||||
|
||||
interface Status {
|
||||
installed: boolean;
|
||||
logged_in?: boolean;
|
||||
method?: string;
|
||||
email?: string;
|
||||
org?: string;
|
||||
expires?: string;
|
||||
login_in_progress?: boolean;
|
||||
error?: string;
|
||||
version?: string | null;
|
||||
latest?: string | null;
|
||||
update_available?: boolean;
|
||||
output?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude Code: sign in from the browser. The CLI prints a sign-in URL; the Anthropic page shows
|
||||
* a code after login that is pasted here and handed back to the CLI on the server.
|
||||
*/
|
||||
export function ClaudeCode() {
|
||||
const t = useT();
|
||||
const [status, setStatus] = useState<Status>();
|
||||
const [url, setUrl] = useState<string>();
|
||||
const [code, setCode] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [console_, setConsole] = useState(false);
|
||||
const isAdmin = useStore((s) => s.me?.role === "admin");
|
||||
const [updating, setUpdating] = useState(false);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [updateLog, setUpdateLog] = useState<string>();
|
||||
|
||||
const check = async () => {
|
||||
setChecking(true);
|
||||
try {
|
||||
setStatus(await get<Status>("/claude/status?refresh=true"));
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
};
|
||||
const update = async () => {
|
||||
setUpdating(true);
|
||||
setUpdateLog(undefined);
|
||||
try {
|
||||
const r = await post<Status>("/claude/update", {});
|
||||
setStatus(r);
|
||||
setUpdateLog(r.output);
|
||||
toast(t("claude.updated", { version: r.version ?? "" }), "success");
|
||||
} catch (e: any) {
|
||||
setUpdateLog(e.message);
|
||||
toast(t("claude.updateFailed"));
|
||||
} finally {
|
||||
setUpdating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const load = () => get<Status>("/claude/status").then(setStatus, (e) => setStatus({ installed: false, error: e.message }));
|
||||
useEffect(() => void load(), []);
|
||||
|
||||
const start = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await post<{ url: string }>("/claude/login", { console: console_ });
|
||||
setUrl(r.url);
|
||||
setCode("");
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setStatus(await post<Status>("/claude/login/code", { code }));
|
||||
setUrl(undefined);
|
||||
setCode("");
|
||||
toast(t("claude.signedIn"), "success");
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const cancel = async () => {
|
||||
await api("/claude/login", { method: "DELETE" }).catch(() => undefined);
|
||||
setUrl(undefined);
|
||||
setCode("");
|
||||
};
|
||||
const logout = async () => {
|
||||
if (!(await confirmDialog({ message: t("claude.logoutConfirm"), danger: true, confirmLabel: t("claude.logout") }))) return;
|
||||
try {
|
||||
setStatus(await post<Status>("/claude/logout", {}));
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>
|
||||
<Icon name="robot" /> {t("claude.title")}
|
||||
<span className="spacer" />
|
||||
{status?.logged_in && (
|
||||
<button className="small ghost danger" onClick={logout}>
|
||||
{t("claude.logout")}
|
||||
</button>
|
||||
)}
|
||||
</h3>
|
||||
<div className="hint" style={{ marginBottom: 10 }}>{t("claude.intro")}</div>
|
||||
{!status && <Spinner />}
|
||||
{status && !status.installed && <div className="notice err">{status.error ?? t("claude.notInstalled")}</div>}
|
||||
{status?.installed && (
|
||||
<div className="row" style={{ gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
|
||||
<span className="chip mono">{t("claude.version", { version: status.version ?? "?" })}</span>
|
||||
{status.update_available ? (
|
||||
<>
|
||||
<span className="chip warn">{t("claude.updateAvailable", { version: status.latest ?? "" })}</span>
|
||||
{isAdmin ? (
|
||||
<button className="small primary" disabled={updating} onClick={update}>
|
||||
{updating ? <Spinner small /> : <Icon name="download" />} {updating ? t("claude.updating") : t("claude.update")}
|
||||
</button>
|
||||
) : (
|
||||
<span className="hint">{t("claude.updateAdmin")}</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")}>
|
||||
{checking ? <Spinner small /> : <Icon name="refresh" />}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{updateLog && (
|
||||
<details style={{ marginBottom: 10 }}>
|
||||
<summary className="hint" style={{ cursor: "pointer" }}>{t("claude.updateLog")}</summary>
|
||||
<pre className="mono" style={{ whiteSpace: "pre-wrap", maxHeight: 200, overflow: "auto" }}>{updateLog}</pre>
|
||||
</details>
|
||||
)}
|
||||
{status?.installed && status.logged_in && (
|
||||
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
|
||||
<span className="chip">
|
||||
<Icon name="check" className="tiny" /> {t("claude.signedInAs", { who: status.email || status.org || status.method || "" })}
|
||||
</span>
|
||||
{status.method && <span className="chip">{status.method}</span>}
|
||||
{status.expires && <span className="hint">{t("claude.expires", { date: new Date(status.expires).toLocaleDateString() })}</span>}
|
||||
</div>
|
||||
)}
|
||||
{status?.installed && !status.logged_in && !url && (
|
||||
<>
|
||||
<label className="row" style={{ marginBottom: 8 }}>
|
||||
<input type="checkbox" checked={console_} onChange={(e) => setConsole(e.target.checked)} /> {t("claude.console")}
|
||||
</label>
|
||||
<button className="primary" disabled={busy} onClick={start}>
|
||||
{busy ? <Spinner small /> : <Icon name="lock" />} {t("claude.signIn")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{url && (
|
||||
<ol className="cli-steps">
|
||||
<li>
|
||||
<a className="button" href={url} target="_blank" rel="noreferrer">
|
||||
<Icon name="external" /> {t("claude.openLogin")}
|
||||
</a>
|
||||
<div className="hint">{t("claude.step1")}</div>
|
||||
</li>
|
||||
<li>
|
||||
{t("claude.step2")}
|
||||
<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()} />
|
||||
<button className="primary" disabled={busy || !code.trim()} onClick={submit}>
|
||||
{busy ? <Spinner small /> : <Icon name="check" />} {t("claude.confirm")}
|
||||
</button>
|
||||
<button onClick={cancel}>{t("common.cancel")}</button>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import { useState } from "react";
|
||||
import { del, get, post, put } from "../../api";
|
||||
import { confirmDialog, promptDialog, toast } from "../../dialogs";
|
||||
import { useFetch } from "../../hooks";
|
||||
import { useT } from "../../i18n";
|
||||
import { Icon } from "../Icon";
|
||||
import { Spinner } from "../Activity";
|
||||
|
||||
interface SkillInfo {
|
||||
name: string;
|
||||
description: string;
|
||||
files: string[];
|
||||
}
|
||||
interface SkillFile {
|
||||
path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
const TEMPLATE = `---
|
||||
name: my-skill
|
||||
description: When to use this skill, in one or two sentences
|
||||
---
|
||||
|
||||
# Instructions
|
||||
|
||||
Describe what the agent should do.
|
||||
`;
|
||||
|
||||
/** The user's own skills: SKILL.md plus further files; created here or imported from GitHub. */
|
||||
export function Skills() {
|
||||
const t = useT();
|
||||
const { data, reload } = useFetch<{ skills: SkillInfo[] }>("/skills");
|
||||
const [editing, setEditing] = useState<{ name: string; isNew: boolean }>();
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [filter, setFilter] = useState("");
|
||||
const list = (data?.skills ?? []).filter((s) => !filter.trim() || `${s.name} ${s.description}`.toLowerCase().includes(filter.trim().toLowerCase()));
|
||||
|
||||
const remove = async (s: SkillInfo) => {
|
||||
if (!(await confirmDialog({ message: t("skills.confirmDelete", { name: s.name }), danger: true }))) return;
|
||||
try {
|
||||
await del(`/skills/${s.name}`);
|
||||
reload();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>
|
||||
<Icon name="sparkle" /> {t("skills.title")}
|
||||
</h3>
|
||||
<div className="hint" style={{ marginBottom: 8 }}>
|
||||
{t("skills.hint")}
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6, marginBottom: 8 }}>
|
||||
<button className="primary" onClick={() => setEditing({ name: "", isNew: true })}>
|
||||
<Icon name="plus" /> {t("skills.new")}
|
||||
</button>
|
||||
<button onClick={() => setImporting(true)}>
|
||||
<Icon name="git" /> {t("skills.import")}
|
||||
</button>
|
||||
<span className="spacer" />
|
||||
{(data?.skills.length ?? 0) > 8 && <input placeholder={t("skills.filter")} value={filter} onChange={(e) => setFilter(e.target.value)} />}
|
||||
</div>
|
||||
{!data ? (
|
||||
<Spinner />
|
||||
) : list.length === 0 ? (
|
||||
<div className="empty">{t("skills.empty")}</div>
|
||||
) : (
|
||||
list.map((s) => (
|
||||
<div key={s.name} className="row" style={{ gap: 8, padding: "6px 0", borderBottom: "1px solid var(--border)" }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<code>{s.name}</code>
|
||||
{s.files.length > 0 && <span className="chip" style={{ marginLeft: 6 }}>{t("skills.files", { n: s.files.length })}</span>}
|
||||
<div className="hint" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
|
||||
{s.description}
|
||||
</div>
|
||||
</div>
|
||||
<button className="small" onClick={() => setEditing({ name: s.name, isNew: false })}>
|
||||
<Icon name="edit" /> {t("common.edit")}
|
||||
</button>
|
||||
<button className="small danger" onClick={() => void remove(s)} aria-label={t("common.delete")}>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{editing && (
|
||||
<SkillEditor
|
||||
name={editing.name}
|
||||
isNew={editing.isNew}
|
||||
onClose={(saved) => {
|
||||
setEditing(undefined);
|
||||
if (saved) reload();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{importing && (
|
||||
<ImportDialog
|
||||
onClose={(done) => {
|
||||
setImporting(false);
|
||||
if (done) reload();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SkillEditor({ name: initial, isNew, onClose }: { name: string; isNew: boolean; onClose: (saved: boolean) => void }) {
|
||||
const t = useT();
|
||||
const [name, setName] = useState(initial);
|
||||
const [files, setFiles] = useState<SkillFile[]>(isNew ? [{ path: "SKILL.md", content: TEMPLATE }] : []);
|
||||
const [loaded, setLoaded] = useState(isNew);
|
||||
const [current, setCurrent] = useState("SKILL.md");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useState(() => {
|
||||
if (!isNew)
|
||||
get<{ files: SkillFile[] }>(`/skills/${initial}`)
|
||||
.then((d) => (setFiles(d.files), setLoaded(true)))
|
||||
.catch((e) => (setError(e.message), setLoaded(true)));
|
||||
});
|
||||
|
||||
const file = files.find((f) => f.path === current) ?? files[0];
|
||||
const setContent = (content: string) => setFiles(files.map((f) => (f.path === file?.path ? { ...f, content } : f)));
|
||||
const addFile = async () => {
|
||||
const p = await promptDialog({ message: t("skills.addFile"), placeholder: "references/guide.md", confirmLabel: t("common.add") });
|
||||
const path = p?.trim().replace(/^\/+/, "");
|
||||
if (!path) return;
|
||||
if (files.some((f) => f.path === path)) return setCurrent(path);
|
||||
setFiles([...files, { path, content: "" }]);
|
||||
setCurrent(path);
|
||||
};
|
||||
const removeFile = () => {
|
||||
if (!file || file.path === "SKILL.md") return;
|
||||
setFiles(files.filter((f) => f.path !== file.path));
|
||||
setCurrent("SKILL.md");
|
||||
};
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
try {
|
||||
await put(`/skills/${name.trim()}`, { files });
|
||||
onClose(true);
|
||||
} catch (e: any) {
|
||||
setError(e.message);
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("skills.edit")}>
|
||||
<h3>{isNew ? t("skills.new") : t("skills.edit")}</h3>
|
||||
{!loaded ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<>
|
||||
<label style={{ display: "block", marginBottom: 8 }}>
|
||||
<span className="hint">{t("skills.name")}</span>
|
||||
<input className="mono" style={{ width: "100%" }} value={name} disabled={!isNew} placeholder="frontend" onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, "-"))} />
|
||||
</label>
|
||||
<div className="row" style={{ gap: 4, flexWrap: "wrap", marginBottom: 6 }}>
|
||||
{files.map((f) => (
|
||||
<button key={f.path} className={`small ${f.path === file?.path ? "primary" : ""}`} onClick={() => setCurrent(f.path)}>
|
||||
{f.path}
|
||||
</button>
|
||||
))}
|
||||
<button className="small ghost" onClick={() => void addFile()}>
|
||||
<Icon name="plus" /> {t("skills.file")}
|
||||
</button>
|
||||
{file && file.path !== "SKILL.md" && (
|
||||
<button className="small danger" onClick={removeFile} aria-label={t("common.delete")}>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<textarea className="mono" rows={18} style={{ width: "100%" }} value={file?.content ?? ""} onChange={(e) => setContent(e.target.value)} spellCheck={false} />
|
||||
<div className="hint">{t("skills.fileHint")}</div>
|
||||
</>
|
||||
)}
|
||||
{error && <div className="notice err">{error}</div>}
|
||||
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
|
||||
<button onClick={() => onClose(false)} disabled={busy}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button className="primary" onClick={() => void save()} disabled={busy || !loaded || !name.trim() || !files.some((f) => f.path === "SKILL.md")}>
|
||||
{busy ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Found {
|
||||
path: string;
|
||||
name: string;
|
||||
files: number;
|
||||
}
|
||||
|
||||
function ImportDialog({ onClose }: { onClose: (done: boolean) => void }) {
|
||||
const t = useT();
|
||||
const [url, setUrl] = useState("");
|
||||
const [found, setFound] = useState<Found[]>();
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||
const [filter, setFilter] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const scan = async () => {
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
try {
|
||||
const r = await post<{ skills: Found[] }>("/skills/github/scan", { url: url.trim() });
|
||||
setFound(r.skills);
|
||||
setPicked(new Set());
|
||||
if (r.skills.length === 0) setError(t("skills.noneFound"));
|
||||
} catch (e: any) {
|
||||
setError(e.message);
|
||||
}
|
||||
setBusy(false);
|
||||
};
|
||||
const shown = (found ?? []).filter((s) => !filter.trim() || s.path.toLowerCase().includes(filter.trim().toLowerCase()));
|
||||
const toggle = (p: string) => setPicked((s) => (s.has(p) ? new Set([...s].filter((x) => x !== p)) : new Set(s).add(p)));
|
||||
const run = async () => {
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
try {
|
||||
const r = await post<{ saved: unknown[]; skipped: { path: string; why: string }[] }>("/skills/github/import", { url: url.trim(), paths: [...picked] });
|
||||
toast(t("skills.imported", { n: r.saved.length }) + (r.skipped.length ? ` (${r.skipped.length} ${t("skills.skipped")})` : ""), "success");
|
||||
onClose(true);
|
||||
} catch (e: any) {
|
||||
setError(e.message);
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal draft-modal" role="dialog" aria-label={t("skills.import")}>
|
||||
<h3>{t("skills.import")}</h3>
|
||||
<div className="hint" style={{ marginBottom: 8 }}>
|
||||
{t("skills.importHint")}
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6 }}>
|
||||
<input className="mono" style={{ flex: 1 }} value={url} placeholder="https://github.com/owner/repo/tree/main/skills" onChange={(e) => setUrl(e.target.value)} onKeyDown={(e) => e.key === "Enter" && url.trim() && !busy && void scan()} />
|
||||
<button onClick={() => void scan()} disabled={busy || !url.trim()}>
|
||||
{busy && !found ? <Spinner small /> : <Icon name="search" />} {t("skills.scan")}
|
||||
</button>
|
||||
</div>
|
||||
{found && found.length > 0 && (
|
||||
<>
|
||||
<div className="row" style={{ gap: 6, margin: "8px 0" }}>
|
||||
<input style={{ flex: 1 }} placeholder={t("skills.filter")} value={filter} onChange={(e) => setFilter(e.target.value)} />
|
||||
<button className="small" onClick={() => setPicked(new Set([...picked, ...shown.map((s) => s.path)]))}>
|
||||
{t("skills.selectShown", { n: shown.length })}
|
||||
</button>
|
||||
<button className="small ghost" onClick={() => setPicked(new Set())}>
|
||||
{t("skills.selectNone")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="issue-list">
|
||||
{shown.map((s) => (
|
||||
<label key={s.path} className="row" style={{ gap: 8, padding: "2px 0" }}>
|
||||
<input type="checkbox" checked={picked.has(s.path)} onChange={() => toggle(s.path)} />
|
||||
<span>
|
||||
<code>{s.name}</code> <span className="hint">{s.path} · {t("skills.files", { n: s.files })}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{error && <div className="notice err">{error}</div>}
|
||||
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
|
||||
<button onClick={() => onClose(false)} disabled={busy}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button className="primary" onClick={() => void run()} disabled={busy || picked.size === 0}>
|
||||
{busy && found ? <Spinner small /> : <Icon name="check" />} {t("skills.importN", { n: picked.size })}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { get, put } from "../../api";
|
||||
import { useT } from "../../i18n";
|
||||
import { toast } from "../../dialogs";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
export interface Snippet {
|
||||
id?: string;
|
||||
name: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** Personal prompt snippets: typed as `/name` in the composer. */
|
||||
export function Snippets() {
|
||||
const t = useT();
|
||||
const [items, setItems] = useState<Snippet[]>();
|
||||
useEffect(() => {
|
||||
get<Snippet[]>("/account/snippets")
|
||||
.then(setItems)
|
||||
.catch((e) => toast(e.message));
|
||||
}, []);
|
||||
if (!items) return null;
|
||||
const set = (i: number, patch: Partial<Snippet>) => setItems(items.map((s, j) => (j === i ? { ...s, ...patch } : s)));
|
||||
const save = () => {
|
||||
const clean = items.filter((s) => s.name.trim() || s.text.trim()).map((s) => ({ ...s, name: s.name.trim().replace(/^\/+/, "").replace(/\s+/g, "-") }));
|
||||
put<Snippet[]>("/account/snippets", clean)
|
||||
.then((r) => (setItems(r), toast(t("settings.saved"), "success")))
|
||||
.catch((e) => toast(e.message));
|
||||
};
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>
|
||||
<Icon name="sparkle" /> {t("snippets.title")}
|
||||
</h3>
|
||||
<div className="hint" style={{ marginBottom: 8 }}>
|
||||
{t("snippets.hint")}
|
||||
</div>
|
||||
{items.map((s, i) => (
|
||||
<div key={s.id ?? i} className="snippet-row">
|
||||
<div className="row">
|
||||
<span className="snippet-slash">/</span>
|
||||
<input value={s.name} placeholder={t("snippets.name")} maxLength={40} onChange={(e) => set(i, { name: e.target.value })} aria-label={t("snippets.name")} />
|
||||
<button title={t("common.delete")} aria-label={t("common.delete")} onClick={() => setItems(items.filter((_, j) => j !== i))}>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</div>
|
||||
<textarea rows={2} value={s.text} placeholder={t("snippets.text")} onChange={(e) => set(i, { text: e.target.value })} aria-label={t("snippets.text")} />
|
||||
</div>
|
||||
))}
|
||||
<div className="row" style={{ marginTop: 8 }}>
|
||||
<button onClick={() => setItems([...items, { name: "", text: "" }])}>
|
||||
<Icon name="plus" /> {t("snippets.add")}
|
||||
</button>
|
||||
<span className="grow" />
|
||||
<button className="primary" onClick={save}>
|
||||
{t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { del, get, post } from "../../api";
|
||||
import { useT } from "../../i18n";
|
||||
import { confirmDialog, toast } from "../../dialogs";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
interface Key {
|
||||
id: string;
|
||||
name: string;
|
||||
public: string;
|
||||
fingerprint: string;
|
||||
}
|
||||
|
||||
/** SSH keys of the user: used by agents, the terminal and the git panel to reach other servers. */
|
||||
export function SshKeys() {
|
||||
const t = useT();
|
||||
const [keys, setKeys] = useState<Key[]>();
|
||||
const [name, setName] = useState("");
|
||||
const [priv, setPriv] = useState("");
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
get<Key[]>("/account/ssh")
|
||||
.then(setKeys)
|
||||
.catch((e) => toast(e.message));
|
||||
}, []);
|
||||
if (!keys) return null;
|
||||
|
||||
const add = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setKeys(await post<Key[]>("/account/ssh", { name, private: importing ? priv : undefined }));
|
||||
setName("");
|
||||
setPriv("");
|
||||
toast(t("ssh.added"), "success");
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copy = (text: string) => navigator.clipboard?.writeText(text).then(() => toast(t("ssh.copied"), "success"), () => toast(t("ssh.copyFailed")));
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>
|
||||
<Icon name="lock" /> {t("ssh.title")}
|
||||
</h3>
|
||||
<div className="hint" style={{ marginBottom: 10 }}>
|
||||
{t("ssh.hint")}
|
||||
</div>
|
||||
{keys.length === 0 && <div className="hint">{t("ssh.none")}</div>}
|
||||
{keys.map((k) => (
|
||||
<div key={k.id} className="ssh-key">
|
||||
<div className="row">
|
||||
<b>{k.name}</b>
|
||||
<span className="hint mono">{k.fingerprint}</span>
|
||||
<span className="spacer" />
|
||||
<button className="small" onClick={() => copy(k.public)}>
|
||||
<Icon name="copy" /> {t("ssh.copyPublic")}
|
||||
</button>
|
||||
<button
|
||||
className="small"
|
||||
title={t("common.delete")}
|
||||
aria-label={t("common.delete")}
|
||||
onClick={async () => {
|
||||
if (await confirmDialog({ message: t("ssh.deleteConfirm", { name: k.name }), danger: true })) {
|
||||
del<Key[]>(`/account/ssh/${k.id}`).then(setKeys).catch((e) => toast(e.message));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</div>
|
||||
<input readOnly value={k.public} onFocus={(e) => e.currentTarget.select()} aria-label={t("ssh.public")} className="mono" />
|
||||
</div>
|
||||
))}
|
||||
<div className="row" style={{ marginTop: 10, flexWrap: "wrap" }}>
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} placeholder={t("ssh.name")} maxLength={60} aria-label={t("ssh.name")} style={{ flex: "1 1 160px" }} />
|
||||
<button className="primary" disabled={busy || !name.trim() || (importing && !priv.trim())} onClick={add}>
|
||||
{importing ? t("ssh.import") : t("ssh.generate")}
|
||||
</button>
|
||||
<label className="row" style={{ gap: 6 }}>
|
||||
<input type="checkbox" checked={importing} onChange={(e) => setImporting(e.target.checked)} />
|
||||
{t("ssh.importExisting")}
|
||||
</label>
|
||||
</div>
|
||||
{importing && (
|
||||
<>
|
||||
<textarea rows={5} className="mono" value={priv} onChange={(e) => setPriv(e.target.value)} placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" aria-label={t("ssh.private")} style={{ width: "100%", marginTop: 8 }} spellCheck={false} autoComplete="off" />
|
||||
<div className="hint">{t("ssh.importHint")}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,12 @@ interface Status {
|
||||
pair_code: string;
|
||||
running: boolean;
|
||||
error?: string | null;
|
||||
factory_alerts: boolean;
|
||||
quiet: boolean;
|
||||
quiet_from: string;
|
||||
quiet_to: string;
|
||||
quiet_now: boolean;
|
||||
server_time: string;
|
||||
}
|
||||
|
||||
/** Connect a personal Telegram bot as a chat interface. */
|
||||
@@ -33,6 +39,14 @@ export function Telegram() {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const savePrefs = async (patch: Partial<Pick<Status, "factory_alerts" | "quiet" | "quiet_from" | "quiet_to">>) => {
|
||||
try {
|
||||
await put("/account/telegram/prefs", patch);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e);
|
||||
}
|
||||
};
|
||||
const disconnect = async () => {
|
||||
if (!(await confirmDialog({ message: t("telegram.disconnectConfirm"), danger: true, confirmLabel: t("telegram.disconnect") }))) return;
|
||||
await del("/account/telegram").catch((e) => toast(e));
|
||||
@@ -97,6 +111,22 @@ export function Telegram() {
|
||||
)}
|
||||
{data.error && <div className="notice err" style={{ marginTop: 10 }}>{data.error}</div>}
|
||||
{data.paired && <div className="hint" style={{ marginTop: 10 }}>{t("telegram.commands")}</div>}
|
||||
<h4 style={{ margin: "16px 0 6px" }}>{t("telegram.notify")}</h4>
|
||||
<label className="row" style={{ gap: 8, alignItems: "center" }}>
|
||||
<input type="checkbox" checked={data.factory_alerts} onChange={(e) => void savePrefs({ factory_alerts: e.target.checked })} />
|
||||
<span>{t("telegram.factoryAlerts")}</span>
|
||||
</label>
|
||||
<label className="row" style={{ gap: 8, alignItems: "center", marginTop: 6 }}>
|
||||
<input type="checkbox" checked={data.quiet} onChange={(e) => void savePrefs({ quiet: e.target.checked })} />
|
||||
<span>{t("telegram.quiet")}</span>
|
||||
</label>
|
||||
<div className="row" style={{ gap: 8, alignItems: "center", marginTop: 6, marginLeft: 24, flexWrap: "wrap", opacity: data.quiet ? 1 : 0.5 }}>
|
||||
<input type="time" value={data.quiet_from} disabled={!data.quiet} onChange={(e) => e.target.value && void savePrefs({ quiet_from: e.target.value })} />
|
||||
<span>–</span>
|
||||
<input type="time" value={data.quiet_to} disabled={!data.quiet} onChange={(e) => e.target.value && void savePrefs({ quiet_to: e.target.value })} />
|
||||
<span className="hint">{t("telegram.serverTime", { time: data.server_time })}{data.quiet_now ? ` · ${t("telegram.quietNow")}` : ""}</span>
|
||||
</div>
|
||||
<div className="hint" style={{ marginTop: 6 }}>{t("telegram.quietHint")}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Put content into the composer of a chat from anywhere in the app (quote, image viewer, …). */
|
||||
export interface ComposeDetail {
|
||||
sessionId: string;
|
||||
/** Appended to the text field (a blank line before it if there is text already). */
|
||||
text?: string;
|
||||
/** Attached like dropped files (images stay images). */
|
||||
files?: File[];
|
||||
}
|
||||
|
||||
export const COMPOSE_EVENT = "codecraft:compose";
|
||||
|
||||
export function compose(detail: ComposeDetail) {
|
||||
window.dispatchEvent(new CustomEvent<ComposeDetail>(COMPOSE_EVENT, { detail }));
|
||||
}
|
||||
|
||||
/** "> quoted\n> lines\n\n" for the composer. */
|
||||
export function asQuote(text: string) {
|
||||
const lines = text.trim().split("\n").map((l) => `> ${l}`.trimEnd());
|
||||
return `${lines.join("\n")}\n\n`;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { UploadPanel } from "./components/UploadPanel";
|
||||
import { Icon } from "./components/Icon";
|
||||
// In-app dialogs and toasts instead of the browser's alert/confirm/prompt.
|
||||
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
|
||||
@@ -20,8 +21,15 @@ interface PromptOpts {
|
||||
confirmLabel?: string;
|
||||
}
|
||||
|
||||
interface ChoiceOpts {
|
||||
title?: string;
|
||||
message: string;
|
||||
choices: { value: string; label: string; danger?: boolean }[];
|
||||
}
|
||||
|
||||
type Dialog =
|
||||
| ({ kind: "confirm"; id: number; resolve: (v: boolean) => void } & ConfirmOpts)
|
||||
| ({ kind: "choice"; id: number; resolve: (v: string | null) => void } & ChoiceOpts)
|
||||
| ({ kind: "prompt"; id: number; resolve: (v: string | null) => void } & PromptOpts);
|
||||
|
||||
interface Toast {
|
||||
@@ -45,6 +53,14 @@ export function confirmDialog(opts: ConfirmOpts | string): Promise<boolean> {
|
||||
});
|
||||
}
|
||||
|
||||
/** Several actions to choose from (plus Cancel): resolves to the chosen value, or null. */
|
||||
export function choiceDialog(opts: ChoiceOpts): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
dialogs = [...dialogs, { kind: "choice", id: ++seq, resolve, ...opts }];
|
||||
emit();
|
||||
});
|
||||
}
|
||||
|
||||
export function promptDialog(opts: PromptOpts | string): Promise<string | null> {
|
||||
const o = typeof opts === "string" ? { message: opts } : opts;
|
||||
return new Promise((resolve) => {
|
||||
@@ -108,14 +124,27 @@ function DialogView({ d }: { d: Dialog }) {
|
||||
style={{ width: "100%" }}
|
||||
/>
|
||||
)}
|
||||
<div className="row dialog-actions">
|
||||
<button type="button" onClick={() => close(d, cancelValue)}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button ref={ok} type="submit" className={d.kind === "confirm" && d.danger ? "danger-solid" : "primary"}>
|
||||
{d.confirmLabel ?? t("common.ok")}
|
||||
</button>
|
||||
</div>
|
||||
{d.kind === "choice" ? (
|
||||
<div className="row dialog-actions dialog-choices">
|
||||
<button type="button" onClick={() => close(d, null)}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
{d.choices.map((c, i) => (
|
||||
<button key={c.value} ref={i === d.choices.length - 1 ? ok : undefined} type="button" className={c.danger ? "danger-solid" : i === d.choices.length - 1 ? "primary" : undefined} onClick={() => close(d, c.value)}>
|
||||
{c.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="row dialog-actions">
|
||||
<button type="button" onClick={() => close(d, cancelValue)}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button ref={ok} type="submit" className={d.kind === "confirm" && d.danger ? "danger-solid" : "primary"}>
|
||||
{d.confirmLabel ?? t("common.ok")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
@@ -130,6 +159,7 @@ export function DialogHost() {
|
||||
{state.map((d) => (
|
||||
<DialogView key={d.id} d={d} />
|
||||
))}
|
||||
<UploadPanel />
|
||||
<div className="toasts" role="status" aria-live="polite">
|
||||
{ts.map((x) => (
|
||||
<div key={x.id} className={`toast ${x.kind}`} onClick={() => ((toasts = toasts.filter((y) => y.id !== x.id)), emit())}>
|
||||
|
||||
@@ -79,6 +79,8 @@ export const de: Messages = {
|
||||
"files.search": "Dateien suchen…",
|
||||
"files.newFile": "Neue Datei",
|
||||
"files.newFolder": "Neuer Ordner",
|
||||
"upload.running": "Lade hoch {done}/{n} …",
|
||||
"upload.finished": "{n} Datei(en) hochgeladen",
|
||||
"files.upload": "Hochladen",
|
||||
"files.showHidden": "Versteckte Dateien zeigen",
|
||||
"files.newFileName": "Dateiname:",
|
||||
@@ -189,7 +191,7 @@ export const de: Messages = {
|
||||
"tools.install": "Ghidra installieren",
|
||||
"tools.reinstall": "Installation prüfen / reparieren",
|
||||
"tools.installing": "Installiere (Download ca. 800 MB, auf ARM wird der Dekompiler kompiliert – das dauert einige Minuten)…",
|
||||
"tools.ghidraHint": "Mit Ghidra können Agenten im Craft-Deep-Modus Programme dekompilieren (Windows .exe/.dll, Linux, DOS …), um zu verstehen, wie sie funktionieren. Wird samt eigenem JDK ins Daten-Volume installiert.",
|
||||
"tools.ghidraHint": "Mit Ghidra können Agenten Programme und Firmware dekompilieren (Windows .exe/.dll, Linux, DOS …), um zu verstehen, wie sie funktionieren – im Craft-Deep-Modus und in Modi mit Reverse-Engineering-Werkzeugen (Einstellungen → Agenten & Befehle). Wird samt eigenem JDK ins Daten-Volume installiert.",
|
||||
"rewind.intro": "Die Unterhaltung wird auf den Stand vor dieser Nachricht zurückgesetzt; du kannst sie bearbeiten und neu senden.",
|
||||
"rewind.noFiles": "Der Agent hat seitdem keine Dateien geändert.",
|
||||
"rewind.restore": "Auch die {n} vom Agenten geänderte(n) Datei(en) zurücksetzen",
|
||||
@@ -336,6 +338,8 @@ export const de: Messages = {
|
||||
"activity.reviewing": "Ergebnis wird geprüft (Runde {round})…",
|
||||
"chat.reviewPassed": "Review bestanden:",
|
||||
"chat.todoReminder": "Weiterarbeiten – {n} offene Todos:",
|
||||
"agents.reverseTools": "Reverse-Engineering-Werkzeuge (binary_info, decompile mit Ghidra)",
|
||||
"agents.reverseToolsHint": "Der Agent kann in diesem Modus Programme und Firmware untersuchen und dekompilieren (Ghidra muss unter Einstellungen → Werkzeuge installiert sein). Craft hat sie im Deep-Modus ohnehin.",
|
||||
"agents.refineAfterTodos": "Jedes erledigte Todo prüfen und bis zum Ende der Liste arbeiten",
|
||||
"agents.refineAfterTodosHint": "Jedes Todo, das der Agent als erledigt markiert, wird geprüft; bei Befunden wird es wieder geöffnet. Beendet er den Turn mit offenen Todos, arbeitet er weiter (für unbeaufsichtigte Läufe, z. B. über Nacht). Aus: nur ein Review am Ende des Turns.",
|
||||
"chat.workSteps": "{n} Schritte",
|
||||
@@ -354,6 +358,7 @@ export const de: Messages = {
|
||||
"media.filter.all": "Alle",
|
||||
"media.filter.image": "Bilder",
|
||||
"media.filter.video": "Videos",
|
||||
"media.filter.model": "3D",
|
||||
"media.filter.audio": "Audio",
|
||||
"media.source.generated": "generiert",
|
||||
"media.source.tool": "Tool-Ausgabe",
|
||||
@@ -363,8 +368,103 @@ export const de: Messages = {
|
||||
"media.showInChat": "Im Chat zeigen",
|
||||
"media.open": "Öffnen",
|
||||
"media.prev": "Vorheriges",
|
||||
"msg.actions": "Nachrichtenaktionen",
|
||||
"msg.copy": "Text kopieren",
|
||||
"msg.copied": "Kopiert",
|
||||
"msg.copyFailed": "Kopieren ist hier nicht möglich",
|
||||
"msg.quote": "In Antwort zitieren",
|
||||
"msg.forkHere": "Ab hier abzweigen",
|
||||
"chat.jumpPrevOwn": "Vorherige eigene Nachricht",
|
||||
"viewer.annotate": "Markieren",
|
||||
"viewer.annotateFailed": "Dieses Bild lässt sich nicht bearbeiten",
|
||||
"viewer.attach": "An Nachricht anhängen",
|
||||
"viewer.undo": "Rückgängig",
|
||||
"viewer.tool.pen": "Stift",
|
||||
"viewer.tool.arrow": "Pfeil",
|
||||
"viewer.tool.rect": "Rechteck",
|
||||
"viewer.useInChat": "In Nachricht verwenden",
|
||||
"viewer.attached": "Bild an die Nachricht angehängt",
|
||||
"turn.changes": "{n} Datei(en) geändert",
|
||||
"turn.noChanges": "Für diesen Schritt wurden keine Dateiänderungen gefunden.",
|
||||
"turn.noDiff": "Kein Text-Diff verfügbar.",
|
||||
"turn.truncated": "Der Diff ist gekürzt.",
|
||||
"turn.new": "neu",
|
||||
"turn.deleted": "gelöscht",
|
||||
"turn.rollback": "Auf den Stand vor diesem Schritt zurücksetzen",
|
||||
"job.plan": "Als Automatisierung planen",
|
||||
"job.planHint": "Macht aus diesem Chat Anweisungen für eine wiederkehrende Automatisierung (aus, bis du den Zeitplan setzt)",
|
||||
"job.drafting": "Automatisierung wird aus diesem Chat entworfen …",
|
||||
"color.label": "Farbe dieses Chats",
|
||||
"color.red": "Rot",
|
||||
"color.orange": "Orange",
|
||||
"color.yellow": "Gelb",
|
||||
"color.green": "Grün",
|
||||
"color.aqua": "Türkis",
|
||||
"color.blue": "Blau",
|
||||
"color.purple": "Violett",
|
||||
"color.pink": "Pink",
|
||||
"icon.label": "Symbol dieses Chats",
|
||||
"claude.title": "Claude Code",
|
||||
"claude.intro": "Chats mit einem „Claude Code“-Modell führt die Claude-Code-CLI auf dem Server aus – mit deinem Claude-Abo oder Anthropic-Console-Konto. Einmal hier anmelden; Freigaben, Push und Sandbox funktionieren wie gewohnt.",
|
||||
"claude.notInstalled": "Claude Code ist auf dem Server nicht installiert.",
|
||||
"claude.console": "Anthropic Console (API-Abrechnung) statt Claude-Abo",
|
||||
"claude.signIn": "Anmelden",
|
||||
"claude.openLogin": "Anmeldeseite öffnen",
|
||||
"claude.step1": "Bei Anthropic in einem beliebigen Browser (auch auf einem anderen Gerät) anmelden und den Zugriff erlauben.",
|
||||
"claude.step2": "Den Code einfügen, den die Seite danach anzeigt:",
|
||||
"claude.codePlaceholder": "Code von der Anmeldeseite",
|
||||
"claude.confirm": "Bestätigen",
|
||||
"claude.signedIn": "Bei Claude Code angemeldet",
|
||||
"claude.signedInAs": "Angemeldet: {who}",
|
||||
"claude.expires": "gültig bis {date}",
|
||||
"claude.logout": "Abmelden",
|
||||
"claude.logoutConfirm": "Auf dem Server von Claude Code abmelden?",
|
||||
"claude.version": "CLI {version}",
|
||||
"claude.updateAvailable": "Update verfügbar: {version}",
|
||||
"claude.upToDate": "aktuell",
|
||||
"claude.update": "Update installieren",
|
||||
"claude.updating": "Installiere …",
|
||||
"claude.updated": "Claude Code auf {version} aktualisiert",
|
||||
"claude.updateFailed": "Das Update ist fehlgeschlagen (Details unten)",
|
||||
"claude.updateAdmin": "Ein Administrator kann es installieren.",
|
||||
"claude.checkNow": "Nach Updates suchen",
|
||||
"claude.updateLog": "Ausgabe des Updates",
|
||||
"check.menu": "Prüfung nach jedem Schritt …",
|
||||
"check.title": "Prüfung nach jedem Schritt",
|
||||
"check.hint": "Befehl, der in {project} nach jedem Schritt mit Dateiänderungen läuft (z. B. cargo test, npm test). Das Ergebnis erscheint als Badge am Schritt. Leer = aus.",
|
||||
"check.saved": "Prüfung gespeichert",
|
||||
"check.removed": "Prüfung entfernt",
|
||||
"check.running": "Prüfung läuft …",
|
||||
"check.passed": "Prüfung bestanden",
|
||||
"check.failed": "Prüfung fehlgeschlagen",
|
||||
"check.timeout": "Prüfung: Zeitüberschreitung",
|
||||
"check.noOutput": "(keine Ausgabe)",
|
||||
"check.fix": "Vom Agenten beheben lassen",
|
||||
"check.fixPrompt": "Die Prüfung des Projekts ist nach deiner letzten Änderung fehlgeschlagen. Bitte beheben und erneut ausführen. Ausgabe:",
|
||||
"projectDefaults.save": "Als Projekt-Standard verwenden",
|
||||
"projectDefaults.remove": "Projekt-Standard entfernen",
|
||||
"projectDefaults.hint": "Neue Chats in diesem Projektordner starten mit Modell, Modus, Farbe, Anweisungen und Ordner dieses Chats",
|
||||
"projectDefaults.saved": "Neue Chats in diesem Projekt starten wie dieser",
|
||||
"projectDefaults.removed": "Projekt-Standard entfernt",
|
||||
"outbox.waiting": "{n} Nachricht(en) warten auf eine Verbindung",
|
||||
"outbox.sendNow": "Jetzt senden",
|
||||
"outbox.discard": "Verwerfen",
|
||||
"outbox.saved": "Keine Verbindung – die Nachricht ist gespeichert und wird gesendet, sobald du wieder online bist",
|
||||
"project.open": "Projektübersicht",
|
||||
"project.newChat": "Neuer Chat",
|
||||
"project.today": "Heute",
|
||||
"project.yesterday": "Gestern",
|
||||
"project.chats": "{n} Chat(s)",
|
||||
"project.files": "{n} Datei(en) geändert",
|
||||
"project.archived": "{n} archiviert",
|
||||
"project.checksFailed": "{n} Prüfung(en) fehlgeschlagen",
|
||||
"project.empty": "In diesem Ordner gibt es noch keine Chats.",
|
||||
"viewer.title": "Bildbetrachter",
|
||||
"viewer.open": "In neuem Tab öffnen",
|
||||
"viewer.download": "Herunterladen",
|
||||
"media.next": "Nächstes",
|
||||
"media.back": "Zurück zur Übersicht",
|
||||
"chat.turnUsageHint": "Alle {n} Anfragen dieser Antwort (Tokens gesendet/empfangen, Kosten)",
|
||||
"chat.reviewRound": "Review {round}: Änderungen nötig",
|
||||
"agents.refine": "Review-Schleife",
|
||||
"agents.refineRounds": "Review-Runden pro Aufgabe",
|
||||
@@ -439,6 +539,12 @@ export const de: Messages = {
|
||||
"telegram.intro": "CodeCraft über Telegram mit deinem eigenen Bot nutzen: Nachrichten gehen an deine aktuelle Sitzung, Befehle wechseln Sitzungen, Modi und Modelle, Freigaben und Rückfragen kommen mit Knöpfen. Nur dein Telegram-Konto kann den Bot nutzen.",
|
||||
"telegram.step1": "In Telegram @BotFather öffnen, /newbot senden und den Schritten folgen.",
|
||||
"telegram.step2": "Das Token von BotFather hier einfügen.",
|
||||
"telegram.notify": "Benachrichtigungen",
|
||||
"telegram.factoryAlerts": "Factory: Nachricht, wenn ein Issue eine Frage hat oder fehlschlägt",
|
||||
"telegram.quiet": "Nachtmodus: keine ungefragten Nachrichten",
|
||||
"telegram.serverTime": "Serverzeit {time}",
|
||||
"telegram.quietNow": "gerade ruhig",
|
||||
"telegram.quietHint": "Im Nachtmodus wird nichts von sich aus gesendet: keine Factory-Meldungen, keine Freigaben oder Fragen aus anderen Chats. Der Chat, in dem du gerade per Telegram schreibst, antwortet weiter. Zurückgehaltene Nachrichten werden nicht nachgeholt – sie bleiben in der Weboberfläche sichtbar.",
|
||||
"telegram.connect": "Verbinden",
|
||||
"telegram.checking": "Prüfe…",
|
||||
"telegram.running": "läuft",
|
||||
@@ -558,6 +664,7 @@ export const de: Messages = {
|
||||
"backup.restoring": "Wird wiederhergestellt…",
|
||||
"backup.restoreTitle": "Backup wiederherstellen?",
|
||||
"backup.restoreConfirm": "Datenbank und Konfiguration durch {file} ersetzen? Alle Sitzungen, Benutzer, Statistiken und Einstellungen werden durch den Stand im Backup ersetzt; Dateien im Workspace bleiben unverändert. Der aktuelle Stand wird vorher gesichert. CodeCraft startet neu – laufende Agents werden beendet.",
|
||||
"backup.uploadFailed": "Das Backup konnte nicht hochgeladen werden.",
|
||||
"backup.restarting": "Backup übernommen – CodeCraft startet neu…",
|
||||
"backup.notBack": "Der Server ist nicht zurückgekommen. Er braucht eine Restart-Policy (Docker: restart: unless-stopped) – bitte von Hand starten.",
|
||||
"backup.now": "Jetzt sichern",
|
||||
@@ -676,6 +783,32 @@ export const de: Messages = {
|
||||
"instructions.hint": "Gelten für jede Nachricht in diesem Chat, zusätzlich zum Modus – z. B. Sprache, Ton, Regeln oder der Teil des Projekts, um den es geht.",
|
||||
"instructions.placeholder": "z. B. Antworte immer auf Englisch. Ändere nur Dateien unter api/. Frag, bevor du Abhängigkeiten hinzufügst.",
|
||||
"instructions.clear": "Entfernen",
|
||||
"settings.tab.skills": "Skills",
|
||||
"skills.title": "Skills",
|
||||
"skills.hint": "Ein Skill ist ein Ordner mit SKILL.md (Anweisungen) und weiteren Dateien. Skills schaltest du pro Chat ein (Menü ⋯ → Skills); ihre Anweisungen gelten dann in jeder Runde, alle anderen kosten keinen Kontext. Agenten können außerdem alle Skills per Stichwort suchen und bei Bedarf laden.",
|
||||
"skills.new": "Neuer Skill",
|
||||
"skills.edit": "Skill bearbeiten",
|
||||
"skills.import": "Von GitHub importieren",
|
||||
"skills.importHint": "URL eines Repositorys oder eines Ordners darin einfügen. Jeder Ordner mit SKILL.md wird angeboten; die Textdateien des Skills werden mit importiert. Bei großen Repositorys die URL auf einen Ordner eingrenzen (…/tree/main/engineering).",
|
||||
"skills.scan": "Suchen",
|
||||
"skills.noneFound": "Unter dieser Adresse wurde keine SKILL.md gefunden.",
|
||||
"skills.selectShown": "Angezeigte wählen ({n})",
|
||||
"skills.selectNone": "Keine wählen",
|
||||
"skills.importN": "{n} importieren",
|
||||
"skills.imported": "{n} Skills importiert",
|
||||
"skills.skipped": "übersprungen",
|
||||
"skills.filter": "Filtern…",
|
||||
"skills.empty": "Noch keine Skills.",
|
||||
"skills.files": "Dateien: {n}",
|
||||
"skills.name": "Name (Ordner, Kleinbuchstaben)",
|
||||
"skills.file": "Datei",
|
||||
"skills.addFile": "Pfad der neuen Datei",
|
||||
"skills.fileHint": "SKILL.md beginnt mit einem Kopfblock (name, description); die Beschreibung sagt dem Agenten, wann der Skill passt.",
|
||||
"skills.confirmDelete": "Skill {name} löschen?",
|
||||
"skills.chatTitle": "Skills für diesen Chat",
|
||||
"skills.chatHint": "Eingeschaltete Skills gelten für jede Nachricht dieses Chats. Schalte nur ein, was du brauchst – jeder belegt Kontext.",
|
||||
"skills.manyActive": "Viele aktive Skills belegen viel Kontext.",
|
||||
"skills.chip": "Skills: {n}",
|
||||
"instructions.chip": "Anweisungen",
|
||||
"chat.compacted": "Unterhaltung komprimiert – Zusammenfassung",
|
||||
"chat.context": "Kontext",
|
||||
@@ -710,6 +843,7 @@ export const de: Messages = {
|
||||
"plan.implementPrompt": "Setze den Plan um.",
|
||||
|
||||
"tool.input": "Eingabe",
|
||||
"tool.open3d": "In 3D-Ansicht öffnen",
|
||||
"tool.output": "Ausgabe",
|
||||
"tool.todosUpdated": "Aufgaben aktualisiert ({done}/{total} erledigt)",
|
||||
"tool.todos": "Aufgaben",
|
||||
@@ -719,6 +853,16 @@ export const de: Messages = {
|
||||
|
||||
"permission.title": "Freigabe erforderlich",
|
||||
"permission.allowOnce": "Einmal erlauben",
|
||||
"permission.projectCommand": "„{prefix}“ in diesem Projekt immer erlauben",
|
||||
"permission.projectTool": "{tool} in diesem Projekt immer erlauben",
|
||||
"permission.projectHint": "Wird für diesen Projektordner gemerkt: in allen Chats, auch nach einem Neustart. Widerrufen im ⋯-Menü.",
|
||||
"permission.explain": "Was macht das?",
|
||||
"permission.explaining": "Erkläre …",
|
||||
"permProject.title": "Projekt-Freigaben",
|
||||
"permProject.intro": "In diesem Projektordner ohne Rückfrage erlaubt (alle Chats):",
|
||||
"permProject.empty": "Für dieses Projekt ist noch nichts freigegeben. Der Knopf „… in diesem Projekt immer erlauben“ bei einer Freigabe-Anfrage legt hier Einträge an.",
|
||||
"permProject.revoke": "Widerrufen",
|
||||
"permProject.menu": "Projekt-Freigaben",
|
||||
"permission.alwaysTool": "{tool} in dieser Session immer erlauben",
|
||||
"permission.alwaysCommand": "„{prefix}“ in dieser Session immer erlauben",
|
||||
"permission.reject": "Ablehnen",
|
||||
@@ -768,6 +912,9 @@ export const de: Messages = {
|
||||
"settings.smallModelHint": "Für Session-Titel. Die Komprimierung nutzt das Session-Modell.",
|
||||
"settings.currency": "Währung",
|
||||
"settings.autoCompact": "Auto-Komprimierung bei",
|
||||
"settings.commitTrailer": "Commit-Vermerk der Agenten",
|
||||
"settings.commitTrailerOff": "aus",
|
||||
"settings.commitTrailerHint": "Wird als Trailer an jeden Git-Commit eines Agenten angehängt. {model} = Modellname, {provider} = Anbieter, {model_id} = Modell-ID. Leer = aus. Deine eigenen Commits bleiben unverändert.",
|
||||
"settings.autoCompactHint": "Anteil des Kontextfensters (0 = aus).",
|
||||
"settings.craft": "Craft-Modus",
|
||||
"settings.cleanRoom": "Clean Room",
|
||||
@@ -989,4 +1136,252 @@ export const de: Messages = {
|
||||
"stats.user": "Benutzer",
|
||||
"stats.allUsers": "Alle Benutzer",
|
||||
"stats.byUser": "Nach Benutzer",
|
||||
"snippets.title": "Prompt-Bausteine",
|
||||
"snippets.hint": "Eigene Textbausteine. Tippe / im Nachrichtenfeld und wähle einen Baustein, um ihn einzufügen (z. B. /tests → \"Schreibe Tests zu dieser Änderung\").",
|
||||
"snippets.name": "Name",
|
||||
"snippets.text": "Einzufügender Text",
|
||||
"snippets.add": "Baustein hinzufügen",
|
||||
"snippets.insert": "Baustein",
|
||||
"link.title": "Nur-Lese-Link",
|
||||
"link.hint": "Wer den Link hat, kann den Gesprächstext lesen (keine Tool-Ausgaben, keine Dateien) – ohne Konto.",
|
||||
"link.create": "Link erstellen",
|
||||
"link.copy": "Kopieren",
|
||||
"link.copied": "Link kopiert",
|
||||
"link.revoke": "Widerrufen",
|
||||
"link.validity": "Gültigkeit",
|
||||
"link.days": "{n} Tage",
|
||||
"link.until": "bis {date}",
|
||||
"link.readOnly": "Schreibgeschützt geteilt",
|
||||
"git.suggest": "Nachricht vorschlagen",
|
||||
"git.suggestHint": "Das kleine Modell schreibt eine Commit-Nachricht für die vorgemerkten Änderungen",
|
||||
"settings.weeklyDigest": "Wochenrückblick montags um 8:00 (Chats, Checks, Kosten)",
|
||||
"settings.transcribeModel": "Spracherkennungs-Modell",
|
||||
"settings.transcribeHint": "provider/modell eines OpenAI-kompatiblen Transkriptions-Endpunkts (z. B. openai/whisper-1). Schaltet den Mikrofon-Knopf in Browsern ohne eigene Diktierfunktion frei, etwa Firefox.",
|
||||
"voice.transcribing": "Wird transkribiert …",
|
||||
"offline.banner": "Keine Verbindung – gespeicherte Kopien. Geschriebene Nachrichten warten im Postausgang.",
|
||||
"settings.planModel": "Planungsmodell",
|
||||
"settings.planModelHint": "Der Plan-Modus nutzt immer dieses Modell (z. B. ein starkes); alle anderen Modi das im Chat gewählte (z. B. ein günstigeres). Leer = Modell des Chats.",
|
||||
"settings.sameAsChat": "(Modell des Chats)",
|
||||
"jobEditor.notify": "Bericht als Push-Nachricht senden, wenn ein Lauf endet",
|
||||
"stats.year": "Jahr",
|
||||
"stats.month": "Monat",
|
||||
"stats.perMonth": "Pro Monat",
|
||||
"stats.costPerMonth": "Kosten pro Monat",
|
||||
"stats.tokensPerMonth": "Tokens pro Monat",
|
||||
"stats.export": "Export",
|
||||
"stats.exportHint": "Die Werte des gewählten Zeitraums herunterladen",
|
||||
"stats.exportXlsx": "Excel (.xlsx) – alle Tabellen",
|
||||
"stats.exportCsv": "CSV – {table}",
|
||||
"stats.table.day": "pro Tag",
|
||||
"stats.table.month": "pro Monat",
|
||||
"stats.table.model": "nach Modell",
|
||||
"stats.table.provider": "nach Anbieter",
|
||||
"stats.table.agent": "nach Modus",
|
||||
"stats.table.user": "nach Benutzer",
|
||||
"stats.table.session": "teuerste Chats",
|
||||
"command.clear": "Bisheriges Gespräch vergessen (der Chat bleibt sichtbar)",
|
||||
"chat.cleared": "Kontext geleert – das Modell sieht die Nachrichten darüber nicht mehr",
|
||||
"ssh.title": "SSH-Schlüssel",
|
||||
"ssh.hint": "Schlüssel, mit denen Agenten, Terminal und Git-Panel andere Server erreichen (ssh, scp, rsync, Git über ssh). Sie werden automatisch genutzt; Hosts werden beim ersten Kontakt akzeptiert. Den öffentlichen Schlüssel trägst du in die authorized_keys des Servers ein.",
|
||||
"ssh.none": "Noch keine Schlüssel.",
|
||||
"ssh.name": "Name (z. B. Laptop, Build-Server)",
|
||||
"ssh.generate": "Neuen Schlüssel erzeugen",
|
||||
"ssh.import": "Schlüssel importieren",
|
||||
"ssh.importExisting": "Vorhandenen Schlüssel importieren",
|
||||
"ssh.importHint": "Nur private Schlüssel ohne Passphrase. Der Schlüssel wird für dein Konto auf dem Server gespeichert.",
|
||||
"ssh.private": "Privater Schlüssel",
|
||||
"ssh.public": "Öffentlicher Schlüssel",
|
||||
"ssh.copyPublic": "Öffentlichen Schlüssel kopieren",
|
||||
"ssh.copied": "Öffentlicher Schlüssel kopiert",
|
||||
"ssh.copyFailed": "Kopieren nicht möglich – Text von Hand markieren",
|
||||
"ssh.added": "Schlüssel hinzugefügt",
|
||||
"ssh.deleteConfirm": "Schlüssel \"{name}\" löschen? Server, die ihm vertrauen, akzeptieren dich von hier aus nicht mehr.",
|
||||
"chat.deleteTitle": "Chat löschen",
|
||||
"chat.deleteWithFolder": "Dieser Chat hat einen eigenen Ordner:\n{path}\n({size})\n\nSoll der Ordner mit dem Chat gelöscht werden?",
|
||||
"chat.deleteOnlyChat": "Nur Chat löschen",
|
||||
"chat.deleteChatAndFolder": "Chat und Ordner löschen",
|
||||
"chat.folderFiles": "{n} Dateien",
|
||||
"chat.folderHasGit": "Der Ordner enthält ein Git-Repository – nicht gepushte Commits und Branches gehen verloren.",
|
||||
"chat.folderDeleted": "Chat und Ordner gelöscht",
|
||||
"nav.factory": "Factory",
|
||||
"factory.title": "Software-Factory",
|
||||
"factory.tab.overview": "Übersicht",
|
||||
"factory.tab.settings": "Einstellungen",
|
||||
"factory.empty": "Noch kein Repository verbunden. Füge in den Einstellungen eines hinzu: Issues mit dem Factory-Label werden dann von Agenten geprüft, gebaut und abgenommen.",
|
||||
"factory.addRepo": "Repository hinzufügen",
|
||||
"factory.newRepo": "Neues Repository",
|
||||
"factory.noArea": "Der Factory-Bereich ist nicht eingebunden (FACTORY_DIR → /factory). Repositories können nicht geklont werden.",
|
||||
"factory.kpi.running": "Läuft gerade",
|
||||
"factory.kpi.issues": "{n} Issues",
|
||||
"factory.kpi.done": "Fertig",
|
||||
"factory.kpi.failed": "{n} fehlgeschlagen oder abgelehnt",
|
||||
"factory.kpi.tokens": "Tokens",
|
||||
"factory.kpi.cost": "Kosten",
|
||||
"factory.kpi.runs": "{n} Läufe",
|
||||
"factory.kpi.time": "Ø Laufzeit",
|
||||
"factory.kpi.perRun": "pro beendetem Lauf",
|
||||
"factory.in": "ein",
|
||||
"factory.out": "aus",
|
||||
"factory.allRepos": "Alle Projekte",
|
||||
"factory.repoLine": "{n} Issues · {run} laufen",
|
||||
"factory.noToken": "kein Token",
|
||||
"factory.pollNow": "Jetzt prüfen",
|
||||
"factory.col.review": "Prüfung",
|
||||
"factory.col.question": "Rückfragen",
|
||||
"factory.col.approved": "Freigegeben",
|
||||
"factory.col.build": "Bau",
|
||||
"factory.col.qa": "Abnahme",
|
||||
"factory.col.done": "Fertig",
|
||||
"factory.col.failed": "Fehlgeschlagen / abgelehnt",
|
||||
"factory.phase": "Phase",
|
||||
"factory.phase.review": "Prüfung",
|
||||
"factory.phase.build": "Bau",
|
||||
"factory.phase.qa": "Abnahme",
|
||||
"factory.latestRuns": "Letzte Läufe",
|
||||
"factory.noRuns": "Noch keine Läufe.",
|
||||
"factory.issue": "Issue",
|
||||
"factory.model": "Modell",
|
||||
"factory.status": "Status",
|
||||
"factory.started": "Gestartet",
|
||||
"factory.duration": "Dauer",
|
||||
"factory.tokens": "Tokens",
|
||||
"factory.cost": "Kosten",
|
||||
"factory.restartAt": "Neu starten bei:",
|
||||
"factory.restarted": "Issue ist wieder im Ablauf",
|
||||
"factory.mergeBtn": "Freigeben und mergen",
|
||||
"factory.mergeConfirm": "Pull Request #{n} mergen ({method})? Die Factory merged nie selbst – das ist deine Freigabe.",
|
||||
"factory.merged": "Pull Request gemergt",
|
||||
"factory.merge.merge": "Merge-Commit",
|
||||
"factory.merge.squash": "Squash",
|
||||
"factory.merge.rebase": "Rebase",
|
||||
"factory.pr.open": "offen",
|
||||
"factory.pr.merged": "gemergt",
|
||||
"factory.pr.closed": "geschlossen",
|
||||
"factory.pr.conflict": "Konflikt mit dem Zielbranch",
|
||||
"factory.pr.files": "{n} Dateien",
|
||||
"issues.hint": "Wenn der Plan steht, die Issues im Repository anlegen.",
|
||||
"issues.create": "Issues anlegen",
|
||||
"issues.createGo": "{n} Issues anlegen",
|
||||
"issues.created": "{n} Issues angelegt",
|
||||
"issues.noProposal": "Das Modell hat noch keine Issue-Liste vorgeschlagen. Sag ihm, dass der Plan fertig ist; es schließt dann mit der Liste ab.",
|
||||
"issues.spec": "Spec-Datei im Repository",
|
||||
"issues.depends": "Voraussetzung: {d}",
|
||||
"issues.description": "Beschreibung",
|
||||
"issues.start": "Sofort starten (Label factory setzen)",
|
||||
"issues.startHint": "Standardmäßig aus: die Issues werden nur angelegt, das Label setzt du selbst nacheinander – spätere bauen auf den gemergten früheren auf.",
|
||||
"issues.pickRepo": "Für welches Repository?",
|
||||
"issues.sliceWhich": "Welcher Meilenstein soll in Deliverables zerlegt werden?",
|
||||
"issues.sliceGo": "Starten",
|
||||
"issues.feature": "Feature planen",
|
||||
"issues.featureHint": "Ein neues Feature mit einem Modell ausarbeiten und daraus Issues anlegen",
|
||||
"issues.slice": "Meilenstein zerlegen",
|
||||
"issues.sliceHint": "Ein Modell zerlegt einen Meilenstein in nummerierte Deliverables und legt die Issues an",
|
||||
"factory.attempts": "Versuche",
|
||||
"factory.attemptsHint": "Wie oft diese Phase bei technischem Scheitern (Zeitüberschreitung, kein Ergebnis, keine Änderungen) versucht wird, bevor das Issue als fehlgeschlagen gilt",
|
||||
"factory.rework": "Nachbesserungsrunden",
|
||||
"factory.reworkHint": "Wie oft eine durchgefallene Abnahme das Issue zurück an den Build schickt (0 = nie, das Issue scheitert sofort)",
|
||||
"release.button": "Release",
|
||||
"release.hint": "Release erstellen: Tag, Docker-Image und Downloads",
|
||||
"release.title": "Release",
|
||||
"release.current": "Aktuelle Version: v{v}",
|
||||
"release.version": "Neue Version",
|
||||
"release.what": "Die Factory schreibt VERSION, baut, was das Rezept beschreibt, pusht den Tag und erstellt das Release auf der Forge mit Quell-ZIP und den Dateien des Rezepts. Das Docker-Image geht in die Registry des Image-Namens.",
|
||||
"release.recipe": "Release-Rezept (.factory/release.json)",
|
||||
"release.trust": "Die Befehle in diesem Rezept laufen auf dem Server mit Docker-Zugriff außerhalb der Sandbox. Starte das Release nur, wenn du sie gelesen hast und ihnen vertraust.",
|
||||
"release.noRecipe": "Keine .factory/release.json auf dem Default-Branch: es werden nur Tag, Release und Quell-ZIP erstellt, kein Docker-Image.",
|
||||
"release.running": "Für dieses Repository läuft bereits ein Release.",
|
||||
"release.go": "Release v{v}",
|
||||
"release.started": "Release v{v} gestartet",
|
||||
"release.list": "Releases",
|
||||
"release.state.running": "läuft",
|
||||
"release.state.done": "fertig",
|
||||
"release.state.failed": "fehlgeschlagen",
|
||||
"factory.close": "Issue schließen",
|
||||
"factory.closeTitle": "Issue schließen",
|
||||
"factory.closeMsg": "Kommentar zum Schließen von Issue #{n}. Er wird im Issue veröffentlicht, danach wird das Issue geschlossen.",
|
||||
"factory.closeDefault": "Erledigt und abgenommen.",
|
||||
"factory.remove": "Vom Board entfernen",
|
||||
"factory.removeHint": "Nimmt das Issue vom Factory-Board; das Issue im Forge bleibt unberührt. Gelöschte Issues verschwinden von selbst.",
|
||||
"factory.removeConfirm": "#{n} vom Factory-Board entfernen? Das Issue im Forge bleibt unverändert.",
|
||||
"factory.closed": "Issue geschlossen",
|
||||
"factory.skills": "Skills",
|
||||
"factory.skillAdd": "Skill hinzufügen…",
|
||||
"factory.skillRemove": "Entfernen",
|
||||
"factory.skillsHint": "Für jeden Chat dieser Phase eingeschaltet (CodeCraft-Agent). Jeder belegt Kontext – wenige wählen.",
|
||||
"factory.pr": "Pull Request",
|
||||
"factory.round": "Runde {n}",
|
||||
"factory.openChat": "Chat öffnen",
|
||||
"factory.runStatus.running": "läuft",
|
||||
"factory.runStatus.done": "fertig",
|
||||
"factory.runStatus.timeout": "Zeitlimit",
|
||||
"factory.runStatus.error": "Fehler",
|
||||
"factory.runStatus.no-result": "kein Ergebnis",
|
||||
"factory.runStatus.interrupted": "unterbrochen",
|
||||
"factory.settingsHint": "Specs kommen als Gitea-Issues mit dem Factory-Label (\"Spec: <Pfad>\" im Text). Jede Phase läuft als eigener Chat in der Sandbox mit eigenem Modell. Repositories werden in den separaten Factory-Bereich geklont, nicht in den Workspace; die Agenten sehen den API-Token nie.",
|
||||
"factory.url": "Repository-URL",
|
||||
"factory.token": "Gitea-API-Token",
|
||||
"factory.tokenPlaceholder": "Token mit Rechten für Issues und Pull Requests",
|
||||
"factory.tokenSet": "Ein Token ist gespeichert. Gib einen neuen ein, um ihn zu ersetzen.",
|
||||
"factory.label": "Issue-Label",
|
||||
"factory.parallel": "Parallele Läufe",
|
||||
"factory.allowed": "Erlaubte Issue-Autoren",
|
||||
"factory.allowedPlaceholder": "leer = nur der Token-Besitzer",
|
||||
"factory.agent": "Agent",
|
||||
"factory.mode": "Berechtigungsmodus",
|
||||
"factory.timeout": "Zeitlimit (Minuten)",
|
||||
"factory.extraPrompt": "Zusätzliche Anweisungen",
|
||||
"factory.test": "Verbindung testen",
|
||||
"factory.testOk": "Verbunden als {login} mit {repo}; {n} Labels angelegt, Repository geklont.",
|
||||
"factory.deleteConfirm": "{name} aus der Factory entfernen? Issues und Chats bleiben.",
|
||||
"factory.project": "Projekt",
|
||||
"factory.newProject": "Neues Projekt",
|
||||
"factory.connections": "Verbindungen",
|
||||
"factory.connectionsHint": "Deine Konten bei Gitea, GitHub oder GitLab. Jeder Nutzer richtet seine eigenen ein; Repositories nutzen den Token ihrer Verbindung, sofern sie keinen eigenen haben.",
|
||||
"factory.connName": "Name",
|
||||
"factory.kind": "Dienst",
|
||||
"factory.serviceUrl": "Adresse des Dienstes",
|
||||
"factory.defaultOwner": "Standard-Besitzer für neue Repositories",
|
||||
"factory.addConn": "Verbindung hinzufügen",
|
||||
"factory.testConn": "Testen",
|
||||
"factory.connOk": "Angemeldet als {login}; {n} Organisationen oder Gruppen gefunden.",
|
||||
"factory.connDeleteConfirm": "Verbindung {name} entfernen? Repositories funktionieren danach nur mit eigenem Token.",
|
||||
"factory.tokenHint.gitea": "Scopes: write:repository, write:issue, read:user – zum Anlegen von Repositories zusätzlich write:user (oder write:organization).",
|
||||
"factory.tokenHint.github": "Classic-Token mit Scope \"repo\" oder fein abgestufter Token mit Contents, Issues und Pull requests (Lesen/Schreiben).",
|
||||
"factory.tokenHint.gitlab": "Persönlicher oder Projekt-Zugriffstoken mit Scope \"api\".",
|
||||
"factory.defaults": "Standard für neue Projekte",
|
||||
"factory.defaultsHint": "Modelle und Grenzen, mit denen ein Projekt startet; du kannst sie danach pro Projekt ändern.",
|
||||
"factory.specModel": "Modell des Spec-Chats",
|
||||
"factory.repos": "Repositories",
|
||||
"factory.connection": "Verbindung",
|
||||
"factory.noConnection": "– keine (eigener Token) –",
|
||||
"factory.repoToken": "Eigener Token (optional)",
|
||||
"factory.repoTokenPlaceholder": "leer = Token der Verbindung",
|
||||
"factory.repoTokenHint": "Nur nötig, wenn dieses Repository einen anderen Token nutzen soll.",
|
||||
"recreate.button": "Software nachbauen",
|
||||
"recreate.title": "Bestehende Software nachbauen",
|
||||
"recreate.hint": "Cleanroom-Modus: Das Original wird bis ins Detail analysiert (Entpacken, Dekompilieren, Formate, Verhalten), danach entsteht eine Spezifikation mit Meilensteinen. Die Bau-Agenten sehen nur diese Spezifikation, nie das Original.",
|
||||
"recreate.source": "Quelle (Git- oder Download-URL, optional)",
|
||||
"recreate.files": "Dateien des Originals (Programm, Installer, Archive)",
|
||||
"recreate.notes": "Hinweise",
|
||||
"recreate.notesPlaceholder": "Was soll die neue Version anders oder besser machen? Zielplattform, bevorzugte Technik, besonders wichtige Teile …",
|
||||
"recreate.uploadFailed": "Nicht alle Dateien konnten hochgeladen werden – siehe Upload-Anzeige.",
|
||||
"recreate.go": "Analyse starten",
|
||||
"recreate.firstMessage": "Starte jetzt die Analyse. Das Original liegt in original/, recreate.txt nennt Quelle und meine Hinweise.",
|
||||
"draft.createdRecreate": "{repo} mit der Spezifikation angelegt. Schneide als Nächstes die Meilensteine in Issues (Factory → „Meilenstein zerlegen“).",
|
||||
"draft.hint": "Spec-Chat: Wenn die Spec fertig ist, lege sie als neues Repository ab.",
|
||||
"draft.create": "Projekt anlegen",
|
||||
"draft.createGo": "Repository anlegen und starten",
|
||||
"draft.name": "Projektname",
|
||||
"draft.slug": "Repository-Name",
|
||||
"draft.description": "Kurzbeschreibung",
|
||||
"draft.connection": "Verbindung",
|
||||
"draft.owner": "Besitzer",
|
||||
"draft.ownerPlaceholder": "leer = dein eigenes Konto",
|
||||
"draft.private": "Das Repository wird privat angelegt. Die Spec wird als docs/specs/<name>.md committet und ein Issue startet den Workflow.",
|
||||
"draft.noSetup": "Noch keine setup.json – bitte das Modell sie schreiben lassen, sonst muss die Abnahme raten, wie die App startet.",
|
||||
"draft.specPreview": "Spec anzeigen",
|
||||
"draft.noSpec": "In diesem Chat gibt es noch keine spec.md – lass sie zuerst vom Modell schreiben.",
|
||||
"draft.noConnection": "Richte zuerst eine Verbindung (Gitea, GitHub oder GitLab) ein:",
|
||||
"draft.created": "{repo} angelegt, Issue #{n} eröffnet – die Prüfung startet gleich.",
|
||||
"factory.saved": "Gespeichert",
|
||||
};
|
||||