77 Commits
Author SHA1 Message Date
WHCandCursor ea38247161 feat: Hermit 1.1.0 — HERMIT_* env, Tauri desktop shell
ci / tcc-check (push) Failing after 42s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Wire hermit_getenv across the engine, rebrand WebUI/systemd/docs, and
add apps/desktop (Tauri 2 + React) with a DeepSeek-Harness-like UI.
Qt app/ is frozen; full libcstcore FFI is scaffolded behind --features engine.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-30 13:15:47 +08:00
WHCandCursor 15c6c4a02a fix: align topbar/sidebar so the top-right is not a dead hole
ci / tcc-check (push) Failing after 39s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Topbar spans the full width; seat deck starts under it. Compact badge
and a seat chip on the right of the chrome. Hermit 1.0.2.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 22:08:58 +08:00
WHCandCursor f29c1000b6 fix: ship hermit-update (and hermit-service) as 1.0.1
ci / tcc-check (push) Failing after 39s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Install hermit-update / hermit-service from make install and bootstrap;
keep cst-agent-* as compat symlinks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 22:00:07 +08:00
WHCandCursor 41f4cf85ee release: Hermit 1.0.0 — home layout, icon font, install
ci / tcc-check (push) Failing after 41s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Compact the home parliament chip, animate crab states like the HTML kit,
ship hermit-icons.ttf (sbix) + frames, and install the font from make/
bootstrap/package paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 21:57:46 +08:00
WHCandCursor 8fcbd886c3 docs: final CST-agent → Hermit migration notice (0.10.1)
ci / tcc-check (push) Failing after 40s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Point readers at WHC/Hermit as canonical; add MIGRATION.md and
migrate_remote_to_hermit.sh so existing checkouts can retarget origin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 21:46:23 +08:00
WHCandCursor f30b4ede48 feat: rebrand as Hermit — TUI palette, dual glyphs, binary 0.10.0
ci / tcc-check (push) Failing after 41s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Ship hermit binary (cst-agent symlink), ~/.config/hermit with legacy fallback,
Hermit color theme and mini crab frames, plus SVG→PUA font build pipeline.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 21:42:45 +08:00
WHCandCursor 2602806aea docs: product-facing README; archive CST theory notes (0.9.34)
ci / tcc-check (push) Failing after 43s
ci / linux (aarch64, 0) (push) Skipped
ci / linux (x86, 1) (push) Skipped
ci / linux (x86_64, 1) (push) Skipped
ci / windows (push) Skipped
Rewrite the homepage for day-to-day use, move paper/eval drafts under
docs/archive, and add a docs index so theory no longer leads the project.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 20:00:22 +08:00
WHCandCursor 814a31c9c8 feat: restore CI/release, prompt contracts, faster install (0.9.33)
Bring back Gitea CI + auto-publish; share release helpers; strengthen multi-turn
tool/job prompts with a unit contract; ccache/make help and --release bootstrap.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:56:42 +08:00
WHCandCursor f00aad9e3e feat: solo default, job completion reports, tools wave-1 (0.9.32)
Password Realm no longer auto-enables parliament (keeps task/worker tools);
finished jobs fan out to agent notes + TUI; raise PAR_MAX/grep caps and tag truncations.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:48:02 +08:00
WHCandCursor 5917c48bd0 feat: TUI completeness — identity, Seat Deck empty states, lean chrome (0.9.31)
Sanitize session titles, stamp CST on the topbar, fill work/sync/keys so
the sidebar never looks unfinished, drop duplicate ctx from the foot, and
tone down the scroll banner plus composer mode line.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:35:21 +08:00
WHCandCursor 2ccad623e4 fix: drop stranded topbar chair chip; blend chrome into panel (0.9.30)
Seat role already lives in the Seat Deck. Remove the lonely right-edge
chip and paint the session strip on panel ground so it no longer reads
as a raised bar with a hairline seam.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:18:55 +08:00
WHCandCursor 67b9d6683f fix: keep stream write-head on tip glyph, not next-line col0 (0.9.29)
Appending the scanning caret after trailing newlines parked a lonely
block at the left margin. Overlay the tip character instead and let the
decode crest sweep through the wake.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:15:01 +08:00
WHCandCursor 6d2e106e26 feat: decode-wave stream glitch — plasma tip, braille wake, caret (0.9.28)
Replace noisy glyph spam with a layered frontier: bright cyan plasma at
the tip, a traveling braille wake that ghosts the real text, a lock flash
as glyphs settle, and a scanning write-head caret.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:08:09 +08:00
WHCandCursor 1b0f14533a feat: adaptive drip buffer for stream reveal (0.9.27)
Network tokens fill md_live immediately; the UI reveals md_shown at a
non-linear rate (slow at the tip, accelerates with backlog) so glitch
and text stay readable without lagging far behind a fast model.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:05:20 +08:00
WHCandCursor 7d183d5bba fix: park cursor in composer; glitch stream frontier (0.9.26)
leaveok on chrome panes and always redraw input after side/log motion
so the caret no longer sticks on the Seat Deck version line. Live
assistant text briefly scrambles at the tip then settles to plaintext.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:02:05 +08:00
WHCandCursor 6e09f79666 feat: Seat Deck sidebar with parliament telemetry and motion (0.9.25)
Replace the OpenCode-style inspector with a seat/fleet/ctx/work telemetry
rail, default-on for wide sessions, driven by 80ms ASCII micro-motion.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 18:50:36 +08:00
WHCandCursor 00288108cd feat: TUI chrome refresh — steel theme, home card, session topbar (0.9.24)
Cooler brand palette, compact CST-agent home with tagline and framed
composer, session topbar (model + chair chip), sidebar off by default.
Screenshot pipeline in tools/tui_shot.py; docs/screenshots for before/after.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 18:27:06 +08:00
WHCandCursor c329db504d perf: accept thread + dial backoff; join/peers.json (0.9.23)
Run inbound peer handling on its own thread so outbound dials cannot starve
:9100. Failed peers cool down exponentially. Also land --join (member seat)
and realm/peers.json seed discovery for Tailscale meshes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 18:16:46 +08:00
WHCandCursor de2eaf87f7 fix: stop parliament accept starvation on outbound dial (0.9.22)
Peer dial used per-step read timeouts so a stuck handshake could block the
single-threaded daemon for tens of seconds; inbound hellos piled up unread
(CLOSE-WAIT). Use a wall-clock dial budget, drain accepts before each dial,
skip self, and only one side initiates idle polls.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 13:19:03 +08:00
WHCandCursor 2f96b050d6 perf: faster builds, leaner daemon, smoother install/run (0.9.20)
Reuse libcstcore.a for tests with -MMD incremental deps; idle-backoff the
parliament seat loop; defer curl init and cache settings; add systemd helper.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 11:41:16 +08:00
WHCandCursor 812e3ee265 feat: parliament seat collaboration loop (0.9.19)
Seats publish via parliament_note, sync pushes on write, member join without
stealing the chair, and worker tools are hard-gated when parliament is active.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 11:29:38 +08:00
WHCandCursor 1605d74f17 fix: sealed peer sync smoke + clearer approval denials (0.9.18)
CLI/Docker assert AEAD sync; status shows sealed channel; headless denials no longer pretend the user refused.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 11:18:04 +08:00
WHCandCursor 5900b53642 feat: seal peer sync with X25519 + XChaCha20-Poly1305 (0.9.17)
Encrypt parliament context sync after Realm mutual auth without pulling in OpenSSL.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 11:16:26 +08:00
WHCandCursor a3e115539e feat: /realm in TUI, daemon instance takeover (0.9.16)
Pidfile records instance+port; login restarts the service when the seat
changes. TUI /realm status|login|stop; prompts discourage filler chatter.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 11:00:34 +08:00
WHCandCursor e610d70c30 fix: interactive Realm password, recoverable worker budget (0.9.15)
Prompt for Realm password when CST_REALM_PASSWORD is unset; map worker
request-gate exhaustion to a clear budget error with partial progress;
hard-skip identical tool failures after 3 tries. Add docs/parliament.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 10:53:36 +08:00
WHCandCursor 9c6257fc96 fix: parliament UX, prompt alignment, execution nudges (0.9.14)
Inject shared parliament context into the agent environment, switch
prompts away from in-process workers when parliament is active, clear
login tickets on chair sync/new-project, and surface realm/chair/service
in /status. Tighten empty-reply handling and prefer-tool principles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 10:22:31 +08:00
WHCandCursor be8d021480 fix: Alpine parliament Docker build (musl clean rebuild)
Ignore/clean host objects, add linux-headers, and include sys/time.h
so discover builds under musl. Docker chair↔member handshake now passes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 10:14:15 +08:00
WHCandCursor e853abac5e feat: parliament daemon, login gate, peer context sync (0.9.13)
Login claims the chair, writes a session ticket, and starts a background
service for discovery plus revision-based context sync. Password Realm
opens require --login (or CST_REALM_PASSWORD); --service/--service-stop
manage the resident agent.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 23:11:23 +08:00
WHCandCursor de9ee28773 feat: password Realm, single-chair login, shared parliament context (0.9.12)
Derive Realm keys from a user password (Argon2id, no private key on disk).
Login claims the sole chair with handover; peers share parliament context;
--new-project clears it. CLI peer/discover helpers and Docker alpine recipe
included; headless empty-answer retries raised for unattended runs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 23:06:51 +08:00
WHCandCursor 08ca613a0e feat: mutual Realm peer handshake over TCP (0.9.11)
Exchange enrolled certificates and Ed25519 challenge signatures so
same-Realm instances can authenticate each other after discovery.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 22:49:33 +08:00
WHCandCursor 5ee82f126d feat: same-Realm peer discovery via UDP and local registry (0.9.10)
Advertise instances with a multicast beacon and a config-dir registry so
same-machine and LAN peers that share a Realm fingerprint can find each
other without TOFU pairing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 22:48:04 +08:00
WHCandCursor dade4072cf feat: add Realm Ed25519 keys and instance enrollment (0.9.9)
Introduce a user Realm keypair (Monocypher) that signs instance
certificates so same-domain peers can later auto-discover and connect.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 22:43:54 +08:00
WHCandCursor acd6f1d998 fix: keep task completion, cancel, pause, and undo honest
Pending earlier-revision jobs no longer skip completion repair; late
cancels preserve real exits; begin clears pause; partial undo keeps
snapshots; permissions and worktree failure paths are hardened.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 22:09:47 +08:00
WHC d971cb02b0 feat: add v2 task control and asynchronous isolated workers 2026-10-20 14:46:57 +08:00
WHC 143dba203b feat: add persistent multi-model workers and orchestration budgets 2026-10-19 11:29:26 +08:00
WHC 235652604d feat: add Kimi Code and web APIs 2026-10-19 10:41:00 +08:00
WHC 60047ca5ce the session readers use getline(3), which a Windows CRT does not have
Building the Windows TUI by hand -- the first local build since the CI file
went away -- stopped in src/tools/session_tools.c: `getline` was an implicit
declaration there, which this GCC treats as an error. src/session.c had a
private fgetc() shim for exactly that; the session-list scan is newer and used
the POSIX call directly, and only the Windows build notices.

The shim moves to os_compat as os_getline(): getline(3) itself on Unix, the
fgetc() loop on Windows, one prototype in the header so a caller reads the same
everywhere. src/session.c drops its copy and calls it; the scan does too (its
`ssize_t` becomes `long long`, which Windows has).

make check is green on Linux, the Windows cross build now finishes and
packages (dist/cst-agent-0.9.7-windows-x86_64.zip plus the NSIS setup), and the
static Linux tarball was rebuilt with it.
2026-10-11 21:54:32 +08:00
WHC b7034baec4 build: no CI; the packages are made here
The release files are built on this machine from now on, so the workflow that
did the same steps on a runner -- TinyCC build and unit tests, the static musl
Linux tarballs, the mingw Windows zip, the Gitea release upload -- is gone.
.gitea/ held nothing else.

Everything the workflow called stays and is runnable by hand exactly as it ran
there: scripts/ci_linux_toolchain.sh is what package_linux.sh uses to pick its
musl toolchain, scripts/ci_tcc.sh builds the second compiler the test job used,
scripts/ci_windows_cross.sh and scripts/bootstrap_windows.sh are the mingw
build, and scripts/release.sh is the upload (GITEA_TOKEN=... scripts/release.sh
FILE...).
2026-10-11 21:52:08 +08:00
WHC db8cdd7dd1 the back key: one C++ path, so a dialog closes too
A phone's back key did not close the settings dialog. A window-level QML
Shortcut never sees the key while a modal popup is up, and a desktop run says
so plainly: with the dialog open, Back left backLayer() at "settings", while
invokeMethod(win, "stepBack") closed it on the spot and Escape -- the popup's
own CloseOnEscape -- closed it too. So the key reaches the popup and never
reaches the shortcut map, which is why the drawer (no popup) closed fine and
hid the problem on a phone.

A Keys handler on the window's root item is no help either: nothing reached
it, the focused TextField keeps the key. So the key is read in C++, on the
application object but only for this window's events -- a filter installed on
the window itself was never called once, while the same key closed the drawer
through the shortcut, hence the application object.

With a layer open, the window's own backLayer() names it and stepBack() closes
it, press and release both taken; with nothing open the key is passed on
untouched, which is what leaves the window on a phone and does nothing on a
desktop. Main.qml keeps only those two functions: the Shortcut and
backHasLayer are gone, --uitest installs the same handler main() does, and the
back checks now drive the code the phone runs instead of a shortcut only the
test had.

The last check asks the phone's own question and can end the run without the
closing line -- the activity leaving takes the process with it, and every line
is flushed as it is written.

Desktop: 106 ok, 0 FAIL. Phone: 104 ok, 0 FAIL (two clipboard checks are
skipped on Android), and "after the last back: window visible 0".
2026-10-11 21:44:33 +08:00
WHC 81aeee7d1e uitest: scroll a card into view before clicking it
Open and Share failed on the phone for a reason that was in the harness,
not in the app: the card was where isVisible() says yes, but the transcript
clips it away -- the run's own note says it found contentY at -14 with the
card's row below the visible part -- so the click (and the tap after it)
landed on whatever was at that point instead, and the header stayed empty.

The run now stops the view following its tail (ChatView.stickBottom, which
the replay sets), scrolls the card's row into view with the numbers in a
note, and only then clicks. ChatView gets an objectName for that.

The checks also say what the card hands the engine (the name the store
keeps the file under, from the strip's own model) and what the card itself
answers -- which is what turned "it did nothing" into this answer:

  note the card is out of the viewport (contentY -14, card at 433 of 615):
       scrolling to it
  ok   Open hands the file to the system (opened report.md (test mode);
       cards hold 'img-...png, art-....md', on screen, card says '')
  ok   Share names the file (shared report.md (test mode); card says '')

The whole device run is green now: 97 ok, 0 FAIL (it was 88/17 when this
session's work started, and every one of those was real).
2026-10-11 21:14:54 +08:00
WHC a99f78134a uitest: no clipboard on Android, and say which event got through
The two clipboard-image checks failed on the phone for a reason that is not
a defect: Android's clipboard carries text and URIs, not images -- setImage
does nothing there -- so they are skipped on Android with a note saying so,
instead of reporting a phone that is broken because it is a phone.

Open and Share still fail on the device, and now say how far they got:
neither the synthesized mouse click nor a touch tap leaves a line on the
card's buttons, while the same click reaches the header and the sidebar.
The engine's own path is fine (openArtifact() called directly answers as it
should), and the only way for the header to stay empty is openArtifact()'s
early return for a name it cannot resolve -- so what is left to look at is
the name the card hands over (the model's `rel`) and whether the card is
inside the visible part of the scrolled transcript at that moment, since
QQuickItem::isVisible() does not account for clipping.

Device run after this: 95 ok, 2 FAIL (was 17 before this session's fixes).
2026-10-11 21:05:21 +08:00
WHC 8e5bdd0c9d the header is a Rectangle, and the phone puts it where it is
A Controls ToolBar hands its children to a style-owned contentItem, and on
the NX789J that item sat 35 px below the bar itself: the header was at y 0
h 42 while its own gear was at y 56 -- drawn on top of the sidebar's first
lines, and clicked there too, so the settings dialog could not be opened
from the gear at all (eleven checks that follow it failed with it). A
desktop never showed it: same style (Basic), same numbers, gear at y 21.

A plain Rectangle has no such indirection -- its children are where it is.
Nothing else changed; the background and the border line are the same.

--uitest prints what it sees at that point now (style, window, header,
gear, safe area), which is how this was found:

  note style Basic, window 1280x853, header y 0 h 42, gear centre y 21

Before: gear centre y 56, `FAIL the gear opens the settings dialog`, 17
failures on the device. After: 95 ok, 4 FAIL (Open/Share and the two
clipboard-image checks, which Android has no answer for).
2026-10-11 21:00:11 +08:00
WHC f8030ec201 a device run can be looked at: --shots, and Qt's messages in the log
The settings dialog check failed only on the phone, with no QML error and
nothing to read: this build's Qt messages never reach logcat (verified: a
plain qInfo from the app is not in the buffer). Two ways in, then:

- --uitest installs a message handler that writes Qt's own warnings into
  uitest.log, next to the checks. What the phone did say, it says there.
- --uitest --shots saves window grabs at the interesting points into the
  workspace. A device run cannot be handed CST_APP_SHOT (an app started
  from adb gets no environment), so what a desktop run asks for with an
  environment variable has to be an argument here. main.cpp takes it, so
  `--uitest --workspace DIR --shots` works from adb.

What they said about the phone (NX789J, 1280x853):

  ok ... the gear is reachable, centre 1191,56 of 1280x853
  ok ... and openSettings() opens it when called directly

so the button is there and the handler works: the synthesized click is what
does not open the dialog. The run's own picture of that moment shows why --
the header is drawn over the sidebar, so the click lands on what is drawn
above the gear. On a desktop the same window has the header above the
sidebar and the click lands. Not fixed yet (nor the Open/Share checks on the
device, which are the other two failures that are not about the dialog).

The settings checks now go on either way, so a phone run reports the dialog
instead of eleven lines of "not there".
2026-10-11 20:53:16 +08:00
WHC a34c74e453 the tool card counts, and a device run leaves a log
A tool that takes minutes -- a build, a wide search, a command nobody can
predict -- read as a window that had hung: the card said "running" and
nothing else, forever. The chip now counts from the point the card starts
running (from five seconds on, before that it is noise), which is where a
person looks when a call seems stuck; the status line and the Stop button
were already there. A card that appears already running (a replayed
transcript) starts its clock too.

--uitest: two checks for it (a card four minutes eighteen in says
"running · 4:18"; a finished one stops counting).

And the run now writes uitest.log in its workspace, every line and the
verdict. That is the only way to read a run *on a phone*: stdout reaches
nobody there, an app started from adb cannot be handed CST_APP_SHOT or any
other environment (so the shots a desktop run can take are out), and logcat
does not carry this build's Qt messages at all -- checked: a plain
`qInfo` from the app is not in the buffer.

First device run (NX789J, 105 checks): 88 ok, 17 FAIL, every failure
pre-existing and unrelated to this work -- the settings dialog does not
open from the gear (so nothing in it is reachable: the five dialog checks,
the two provider-form ones and the four clicks that follow), Open/Share
leave no status line on the device, and the clipboard-image checks have no
clipboard. All the md_to_pdf and card checks pass on the phone, including
"black ink on paper (darkest pixel 0)" from 4c69ef3.
2026-10-11 20:41:58 +08:00
WHC 9d7ad9433e android: the arguments arrive as a String[], not an ArrayList
The hook added in da04913 asked for getStringArrayListExtra, but `am
start --esa applicationArguments "--uitest,--workspace,/sdcard/x"`
stores a String[] -- that call answers null for an array, so the window
still started with no arguments at all. Ask for the array first, then
the list (Qt's own loader, putStringArrayListExtra), then the single
comma-separated string.

With this the uitest runs from adb on the NX789J: the fixtures and
selftest.pdf land in --workspace, which is how a device round trip is
possible without touch injection (adb cannot tap this window).
2026-10-11 20:35:41 +08:00
WHC 4c69ef39ab pdf: text that names no colour comes out black, not the palette
A QTextDocument takes its default text colour from the application
palette, and markdown names no colour at all: in a window running a dark
palette -- which is what a phone in dark mode hands Qt -- every plain
paragraph was laid out #eeeeee on a white page. Printed, that is a blank
document; on screen it reads as "the font is oddly faint". The first
PDFs off the phone were exactly that.

- PdfTools: paperDocument() sets the default stylesheet (body colour
  #000000) before setHtml, and writePdf() lays that out. A colour the
  document does name still wins, so an .html handed to the tool keeps its
  own -- checked with a #cc0000 document under both palettes.
- --uitest: draws that document on a white image under a dark palette and
  looks for ink (238 before the fix, 0 after).

Verified on the NX789J: md_to_pdf on the device now writes CID TrueType
NotoSansCJKHK-Regular/-Bold text whose page renders at min=0.
2026-10-11 20:35:41 +08:00
WHC da04913071 android: read the activity's own arguments, since Qt does not deliver them
`am start -n <pkg>/org.qtproject.qt.android.bindings.QtActivity --esa
applicationArguments "--workspace,/sdcard/x"` left the window on its default
workspace on the NX789J (the plain-string extra too), so the extra is read
from the intent directly. That is what makes `cst-agent-app --uitest
--workspace DIR` reachable on a device with no keyboard -- and adb cannot
inject touch into this window either (tap, touchscreen tap, mouse tap and
motionevent all do nothing; key events do work), so it is the only way in.

Everything degrades to "no arguments": an invalid object, a missing method or
a context that is not an activity all come back empty.
2026-10-11 20:22:50 +08:00
WHC 7b2e7a3dbd fix: the window's approval switch never reached the engine
needs_confirm() (src/agent_loop.c) decides whether a tool asks by reading
cfg->confirm_shell / confirm_write / confirm_net; the approval mode only
relaxes those. The CLI fills them in (main.c: parse_confirm), the TUI and the
WebUI do too -- the Qt window never did: AgentCore::open() memset the whole
config and cst_agent_create() keeps what it is given, so every tool ran
without asking while the sidebar said "ask". That is why nothing was ever
asked on the phone (or on a desktop).

- AgentCore: one mapping, applyApproval(), used by open() and setApproval();
  the mode is remembered like the TUI's /approval and read back on start
  (else "ask", the only mode where the window's consent dialog is reached).
- --uitest: two checks that the mode reaches the engine as those flags.

Version 0.9.7 (local).
2026-10-11 20:22:50 +08:00
WHC 4e990c8e35 docs/android.md: what a turn does when nobody answers, and md_to_pdf
The SAF picker is not 'still to come' any more (v0.9.6 did it): the list keeps
the back gesture and the icon glyphs. In its place, what v0.9.7 changed on the
phone -- a consent question refused in the background and bounded in the
foreground, the bounded GUI hop, the phase in the header, and the window's own
md_to_pdf.
2026-10-11 20:04:24 +08:00
WHC dae51e06c7 fix the session-list scan's line count, and pin both new paths with tests
The rewritten cst_agent_store_info() counted a transcript line that ran past a
whole 64 KiB read block a second time, when the newline ending its tail
arrived: a session with one very long line (a tool that read a file back)
reported one message too many -- exactly what the sidebar shows the person.

- src/agent_store.c: the tail's newline ends a line that was already counted.
- tests/test_store.c: test_info_scan() holds the scan down -- a 70 KiB line is
  one line, the first user message comes from the head of the file, and a user
  line past the window is not called the first one.
- tests/test_tools_ext.c: a byte budget stops the session_search walk, says so
  in the result, and never reports a match it did not reach; the same query
  without a budget finds it.

make check and make asan are green.
2026-10-11 20:03:39 +08:00
WHC 042d7f6999 v0.9.7: a turn that cannot hang, a session list that reads nothing twice, and PDFs
- consent: on_permission / on_ask_user wait at most two / five minutes, and in
  the background (a phone off screen, a window that is gone) the answer is
  refused at once with a reason -- a dialog nobody can see blocked the worker
  for good, which is what "the app hangs while the agent works" looked like.
- finishTurn() no longer joins the thread it is called from; the event loop
  reaps the Turn instead.
- AndroidTools: the hop to the GUI thread pings first and gives up after 3 s
  instead of waiting forever on a busy GUI thread.
- the session list stopped reading every transcript: cst_agent_store_info()
  counts newlines in 64 KiB blocks (first_user only within the first 256 KiB),
  and AgentCore::sessions() reuses a row while (mtime, size) is unchanged.
- session_search gets a budget (max_bytes 32 MB, max_seconds 5 s), skips lines
  over 64 KiB, and says when the budget stopped the walk.
- the header shows the phase ("shell: make -j8"), so a long turn no longer
  looks like a stuck one.
- md_to_pdf: the front end's own Qt tool (owner app:qt, every platform):
  markdown or a workspace .md/.html becomes an A4 PDF with 15 mm margins,
  paginated by hand, written into the workspace and delivered as a file card.
  No PrintSupport, so the phone gets it too.
- --uitest runs md_to_pdf through the registry with Chinese text and checks the
  bytes are a PDF; app/CMakeLists.txt no longer drops src/web_md.c from the
  standalone engine build, which the window needs to render markdown.

Version 0.9.7.
2026-10-11 19:26:36 +08:00
WHC 2ffe74b37c desktop: the window installs itself (launcher entry, icon, default.nix)
app/linux/cst-agent-app.{desktop,svg} plus one CMake component ("app") in
app/CMakeLists.txt: `cmake --install --component app` puts the binary in bin/,
the entry in share/applications/ and the icon in hicolor/scalable/apps/. The
entry's file name stays the app_id Qt sets (QGuiApplication::applicationName),
or the launcher draws a generic icon; only the front end installs, the CLI
keeps coming from scripts/bootstrap_linux.sh.

default.nix is that install for nix users: nixpkgs' Qt 6 (qtwayland for a
Wayland session, qtsvg for Breeze's SVG icons), wrapQtAppsHook so the plugins
and QML modules resolve outside a nix-shell and survive nix-collect-garbage,
a filtered src (third_party/ and the build directories are gigabytes this
build never reads), and the version read from include/cst_version.h. doCheck
runs ctest minus test_sandbox, whose Landlock assertion cannot hold inside the
nix build sandbox (the other 40 pass there; make check runs all 41).

Verified: nix-build, nix profile add --file ., then --selftest and --uitest in
a clean environment (no nix-shell, no XDG_* from the session).
2026-10-11 18:44:31 +08:00
WHC 580d533656 v0.9.6: documents, downloads, PDFs and the phone's own files
ci / tcc-check (push) Successful in 1m9s
ci / linux (aarch64, 0) (push) Failing after 1h0m2s
ci / linux (x86, 1) (push) Failing after 1h0m2s
ci / linux (x86_64, 1) (push) Failing after 1h0m2s
ci / windows (push) Failing after 10m4s
Four tools and a document writer, plus the storage half of the phone: until
now the picker's answer (a content:// URI) reached the engine as a path, and
it said "cannot read" -- the app had no way to hand a phone's file over.

- md_to_html (new, src/tools/web.c + cst_web_md_document()): markdown in, one
  self-contained HTML document out -- doctype, utf-8, viewport, escaped
  title, a small stylesheet; no script, no external request. It is written
  into the workspace and delivered as a file card (for_user, so it never
  enters a request), the way deliver_file does. The default name comes from
  the source file's stem or, for pasted markdown, from the title with what a
  path cannot carry turned into '-'. It has a preview, so an approval prompt
  says "render x -> y.html" before anything is written.
- download (src/tools/web.c): an http(s) URL into a file in the workspace,
  streamed with a 128 MB ceiling; a redirect chain, the same CA handling and
  the same refusals as web_fetch, but the bytes stay on disk (a half file is
  removed on any failure, including HTTP >= 400). The name comes from the URL
  when the caller names only a directory.
- read_pdf (src/tools/fs_tools.c): the text layer and page count of a PDF,
  which read_file refuses because the bytes are binary -- and a PDF is
  exactly what arrives from a phone. Same extractor an attachment uses, its
  own 4 MiB input ceiling, 256 KiB of text by default with a note when cut.
- session_search (new, src/tools/session_tools.c): every stored session --
  this one and all the ones before it -- searched for a substring, reporting
  the session's id, message count and title, then the matching lines with
  their number and role. Case-insensitive by default, capped at 20 matches.
- device_info (same file, perm_name "device"): version, system/arch/CPU
  count, workspace, sandbox, model and permissions, config/temp/program
  directories, pid -- so the model stops guessing where it runs.
- Tools 3 and 4 come with tests/test_tools_ext.c (also in both build files):
  the document is a whole page, a script tag and a javascript: link do not
  survive, a hostile title stays text and cannot write outside the workspace,
  the preview names the file, read_pdf/download refuse what they must (no
  network in a test), session_search finds a fixture session and says so when
  nothing matches, device_info names the workspace. README's tool table grew
  five rows.

- Android storage: the picker (SAF) answers with a content:// URI, and the
  engine opens files by path, so the app now copies what it points at into
  its own directory first -- app/android/src/xyz/whcself/cstagent/
  AttachFile.java, called through a new app::materializeAttachment()
  (ToolProvider.h: one API for every platform; a desktop strips file:// and
  refuses content:// with a reason). The copy needs no permission at all: the
  grant travels with the URI.
- "All files access" (MANAGE_EXTERNAL_STORAGE) is the other half: it is what
  lets the engine read a path in shared storage that a task names rather than
  picks. Android has no runtime dialog for it, so main.cpp opens the one
  Settings screen once (AttachFile.java's requestAllFilesAccess, with the
  all-apps screen as a fallback) and never insists: without it everything
  works, one picked file at a time. On the NX789J the screen came up, the
  app-op reads back "allow", and a relaunch no longer asks.
- Composer.qml hands a content:// URI through untouched (it is not a path,
  and decoding it would corrupt it); AgentCore::attachFile() turns whatever
  the picker gave into a path first.

Desktop: build clean, make check 36/36 (the new test included, also under
ASan), --uitest all green, --selftest and cst-app-selftest OK.
The APK builds and installs (86 MB, release-signed) with the new Java class
in its dex.

Version 0.9.6.
2026-10-11 18:33:41 +08:00
WHC 08008a5a4c v0.9.5: a session owns a directory, and the store hands out uuids
A session's transcript lived beside its attachments, both named after an id
that was a timestamp. Two things fell out of that: on a workspace two
machines share, a timestamp is not an id (the same second on both is enough
to hand out the same name), and "delete this conversation" had to chase the
jsonl, the title and a directory in a shared attachments/ tree, guessing what
belonged to whom. A phone's app data has nobody to tidy it by hand.

Now one session is one directory:

  <workspace>/.agent/sessions/
    <uuid>/session.jsonl     the transcript
    <uuid>/title             the window title, one line
    <uuid>/attachments/      images and delivered files (img-…, art-…)
    <uuid>/sub-1.jsonl       an agent role's own transcript
    CURRENT                  the id the next run opens

- src/agent_store.c: new_id() makes a uuid v4 (16 bytes from /dev/urandom,
  clock+pid only as a fallback), dir_for_id/flat_for_id/nested_for_id/
  shape_of_id decide which shape an id has, so every reader takes either.
  An id is a directory name, so it is checked as one (no "/", no "..",
  nothing starting with ".", not CURRENT or attachments). path_for_id() keeps
  the shape a session already has and makes the directory for a new id, so
  nothing had to change in the callers. store_list() lists the directories
  that hold a transcript plus the flat files, newest first. delete() is one
  rm_tree of the session's directory, plus the old shared attachments/<id>
  and CURRENT when it pointed there.
- cst_agent_store_migrate() (--migrate-store, or plain cst-agent for a
  session): moves a flat store in — <id>.jsonl to <id>/session.jsonl,
  <id>.title in, the shared attachments/<id>/ to <id>/attachments/. rename
  first, copy when the filesystem says no, and counts what it moved, so a
  second run is a no-op that says "nothing to move". On the real workspace:
  6 sessions moved, the shared directory gone, --list-sessions reads them
  back unchanged, a second run moved 0.
- cst_agent_store_id_of_path(): the id of a session path. This is the bug the
  whole change had been hiding: cst_agent_session_id() took the id from the
  file name, and the new file name is session.jsonl -- every session would
  have called itself "session" (the sidebar, CURRENT, undo, an agent role's
  directory, and the metrics file, which now also goes through the helper).
- src/attach.c: a session that owns its directory keeps its payloads inside
  it (<id>/attachments/); only the flat layout needs the shared directory and
  the id stem. Attachments behave exactly as before otherwise.
- tests/test_store.c: uuid shape and uniqueness, a small buffer refused, a
  new session's path and directory, write/list/info/title read back, the
  payload landing in <id>/attachments/, delete taking the directory with it;
  then an old-layout store: readable before the move, moved byte for byte,
  its payload readable through the new path, listed once, a second migration
  a no-op, deletion covering the migrated payload. Also in the Makefile and
  CMakeLists test lists.
- app/src/ui/UiTest.cpp: the image directory check wanted "/attachments/",
  which the new layout has no trailing slash for.

Desktop: build clean, make check 35/35, --uitest all green, --selftest and
cst-app-selftest OK, and --selftest opens a session of the migrated workspace.

Version 0.9.5.
2026-10-11 17:39:00 +08:00
WHC 7299f39245 v0.9.4: a turn keeps running when the app is not on screen
A phone freezes an app it cannot see, and the front end had nothing holding
it: a turn that took minutes -- a long shell command, a provider that thinks,
a build -- stopped quietly the moment the user pressed home, and the answer
was only there if the window happened to come back. The engine's own /attach
flow made this visible: an APK turn survived, a pocket did not.

- app/android/src/xyz/whcself/cstagent/CstService.java: a foreground service
  started with an explicit component (nothing outside the app can reach it,
  no intent filter) for as long as a turn runs. Being a foreground service
  makes the process one Android neither freezes nor kills; a partial wake
  lock (30 min ceiling) keeps the CPU awake with the screen off. Its ongoing
  notification says what is running -- "CST-agent is working" plus the first
  line of the prompt -- on the same cst-agent channel the notification_send
  tool uses, and taps back into the app. A phone that refuses the foreground
  start (Android 12+ does, from the background) loses the protection, not the
  turn: the failure is caught and the service stops itself.
- Manifest: FOREGROUND_SERVICE, FOREGROUND_SERVICE_DATA_SYNC (API 34+ wants
  the typed one) and WAKE_LOCK, plus the <service> with
  foregroundServiceType="dataSync". The first build of this failed with
  "Expected '>', but got ' '" -- a manifest comment cannot contain "--".
- Front end: app::holdForeground(text) / app::releaseForeground() in
  ToolProvider.h, one call for every platform -- Android starts and stops the
  service through JNI, a desktop has nothing to hold (its window is the app).
  AgentCore::send() calls it when the turn starts (firstLine() of the prompt
  is what the notification says) and finishTurn() releases it, so the
  notification exists exactly as long as the work does. CST_APP_NO_SERVICE=1
  keeps a test run from touching the phone.
- On the NX789J, with the app sent home and the screen off: the service read
  back isForeground=true with its notification, the wake lock cst-agent:turn
  was taken at the start of the turn and dropped at its end, run_shell
  "sleep 60" finished with the screen dark, and the service was gone after.

Desktop: build clean, --uitest all green, --selftest and cst-app-selftest OK
(the hold is a no-op there, so nothing about the Qt side changed).

Version 0.9.4.
2026-10-11 16:51:39 +08:00
WHC d4f65b17cf v0.9.3: notification_send posts on the phone, and Java helpers have a home
The tool was the last Android one that never worked on the NX789J: it would
fail with "Notification.Builder.build() failed: no exception detail" and the
shade stayed empty. The detail was the whole story -- Qt clears a Java
exception before C++ gets to look at it, so a build() that throws and a
build() that returns null look exactly the same from here, and the only way
to catch the difference is to let Java catch it.

- app/android/src/xyz/whcself/cstagent/Notifier.java: the builder, the
  PendingIntent, build() and notify() in one try/catch that returns "" or
  the throwable's class and message. androiddeployqt copies app/android/ with
  the rest of the package source and Qt's Gradle template puts its src/ on
  java.srcDirs, so a class dropped there needs no build-script change (the
  first one is this; the foreground service of the next step goes there too).
- AndroidTools.cpp keeps what it can see from C++ (the context, the channel
  on API 26+, the small icon looked up by name, the launch intent) and calls
  Notifier.post(); the result line now carries the Java failure when there is
  one. The javaErrorText() helper of the previous attempt is gone: reading a
  pending exception from C++ is exactly what does not work here.
- On the device: the tool answers "notification sent", the system holds the
  record (channel cst-agent, importance 3, the framework small icon, the tap
  intent back into the app). Earlier attempts in the same session are in the
  transcript next to it: four failures from the old path, then this one.

Docs: docs/android.md gets the Java-helper mechanism (and why the tool has to
be wrapped in Java at all) and no longer lists notification_send as missing;
app/README.md's platform table and the Android note say where a Java class
goes.

Version 0.9.3.
2026-10-11 16:40:51 +08:00
WHC 60cbce3c5c v0.9.2: files the agent delivers come back as cards, and the saved key is used
A turn could write a report and say "here it is" -- and there was nothing to
open. The engine had no way to hand a finished file to the person, and the
front end had no way to show one. This release adds the whole path: a tool to
deliver, a store that keeps the copy, a card in the transcript, and open /
share through the platform. It also fixes two bugs the phone exposed while it
was being tried there.

deliver_file (engine)
- cst_attachment_t.for_user marks a copy that belongs to the person, not to
  the model; cst_attach_import_artifact() stores any bytes up to
  CST_ARTIFACT_MAX_BYTES (64 MB) with the mime taken from the name's
  extension. Attachments are unchanged (content decides the type, 16 MB).
- It is a read-policy engine tool: path resolves inside the workspace, a
  directory is refused, title (optional) is the display name.
- The wire is what keeps it out of the conversation: parts_add_attachments()
  skips for_user entries without even a "not sent" note, and a turn that only
  delivered a file no longer invents an empty user message. tests/test_artifacts.c
  pins that down end to end, including a session-file round trip.

The card (Qt front end)
- filesText() replaced imagesText(): one line per file -- kind, stored name,
  name, origin, mime, bytes, pixels -- decoded by ImageStrip.qml. A for_user
  entry is a file card (extension badge, name, type and size, Open, Share);
  a picture stays a thumbnail and opens on tap. Both shapes are read, so
  sessions written by an older version still draw.
- AgentCore::openArtifact() / shareArtifact() accept a name only when one of
  the session's own messages carries it, and hand the display name to the
  platform layer for the status line.
- Android opens through the app's FileProvider (content:// + ACTION_VIEW,
  resolveActivity() checked, read permission granted) and shares through the
  share sheet; a desktop uses QDesktopServices / the clipboard.
  CST_APP_NO_OPEN=1 makes --uitest run without opening anything.

Two bugs the device found
- The session writer had its own copy of the attachment JSON and forgot
  `for_user`: the file survived the file, but came back as an attachment --
  no card, and put back in front of the model. It now uses the one writer
  (cst_attachments_to_json()), with the round trip covered by a test.
- engineToolImages() looked the card up with findTool(), which only finds a
  card that is still running -- and the engine reports the result *before*
  the files, so the card was already complete and the files were dropped.
  A live turn therefore showed no card while a replay of the same session
  did. It now matches on the call id.
- A tap that could not work said nothing: ImageStrip.qml's errorText was
  never drawn. The card now carries the reason ("no app on the phone opens
  report.md").

Also
- The saved provider key reaches the engine on every start: AgentCore::open()
  was handed an empty key and the engine never resolves credentials itself
  (only the CLI did), so every start asked for it again. It resolves the same
  order main.c uses (saved key, provider environment, CST_API_KEY) and wipes
  the copy it made; --selftest checks it against a scratch credentials file.
- Android: notification_send reads the Java exception text into its result,
  and keeps failing on the NX789J -- the build() returns null and Qt clears
  the exception before C++ can read it, so the call has to be wrapped in Java
  next (docs/android.md says so).
- --uitest grew the delivered-file case (card, Open, Share, a forged name
  refused), the live order of result-then-files, and the startup row count.

Version 0.9.2.
2026-10-11 16:34:47 +08:00
WHC 84f9585588 v0.9.1: the window opens on the session the engine already has open
A workspace is never empty on the second run: cst_agent_open() resumes the
last session of the store, so the engine holds a transcript before the window
exists. The window only filled its view on a session *switch*, and a start is
not a switch -- the pane came up empty next to a sidebar pointing at the very
session it belonged to (on the phone: "hello, 6 messages" highlighted, no
transcript under it).

- Main.qml: Component.onCompleted reloads the session list and replays the
  open session, the same call the sessionChanged handler makes.
- AgentCore::switchSession(): a click on the row of the session that is
  already open emits sessionChanged instead of returning quietly, so the row
  redraws its transcript rather than being a dead spot.
- --uitest: the window is now created over a seeded session (a fixture is
  written and switched to before the QML loads, which is what a restart looks
  like) and the check "the open session is on screen at startup" pins it --
  it failed with 0 rows before the fix. Two qWaits in the settings-dialog
  section, whose clicks were racing the dialog's layout: the extra startup
  work made that visible (5 failures that had nothing to do with sessions).

Verified: --uitest 79/79 (the new check among them), cst-app-selftest OK, and
on the phone -- the APK rebuilt and installed, a restart of the app draws the
whole stored session (messages, tool cards, thinking blocks, copy icons).

Version 0.9.1.

mode = coding
2026-10-11 15:26:32 +08:00
WHC c2320f946b v0.9.0: the Qt front end as an Android APK, images in the transcript
Two strands land together: the window draws pictures now, and the whole front
end builds, installs and runs on the phone with the engine linked in-process.

Images (the "make a picture actually show up" part)
- Engine, additively: cst_agent_hooks_t.on_tool_images(call, list, n, ud) fires
  when a call left attachments behind, and cst_agent_pending_rel() /
  cst_agent_pending_is_image() read that list without the app touching the
  store. tests/test_attach.c::test_agent_pending pins the three cases (an
  image, a stored name that passes cst_attach_rel_ok, out-of-range NULL).
- App: image://cstattach/<stored name> (app/src/ui/SessionImages.cpp) serves
  only the current session's attachment directory, checked with
  cst_attach_rel_ok, decodes down to the requested sourceSize and never
  upscales, and holds a mutex because requestImage() runs on the render
  thread while the directory can change underneath it. AgentCore gained
  attachmentDir(), pendingImages(), the toolImages()/promptImages() signals
  and hookToolImages(); history() gives replayed rows their images too.
- QML: ImageStrip.qml (a thumb strip, <=150 px tall, shaped by the picture,
  tooltip with name/size/origin, the file's name when it went missing),
  wired into MessageCard and ToolCard. Qt 6's ListModel cannot hold a
  list-valued role (append() reads back undefined, setProperty drops it), so
  a row carries one image per line as <stored>|<name>|<origin>|<w>x<h> and
  ImageStrip decodes that.

Android (the engine is already in the APK; this is the front end)
- app/src/main.cpp: on Android the workspace, config, tmp and HOME go under
  the app's own data directory before the engine opens anything, because
  QDir::currentPath() is "/" there and /tmp is not writable.
- app/android/: the manifest (QtApplication/QtActivity, INTERNET and
  POST_NOTIFICATIONS, adjustResize, no storage permission -- the picker will
  be the system one), strings, a vector icon; minSdk 24 and targetSdk 35 come
  from app/CMakeLists.txt through QT_ANDROID_MIN/TARGET_SDK_VERSION.
- app/src/platform/android/AndroidTools.cpp: the Android file behind
  PlatformInit(), owner "app:android" (notification, clipboard, share sheet,
  file picker are stubs for now, so the tool list does not lie about them).
- app/tools/selftest.c decides its scratch workspace with os_temp_dir(), so
  the C smoke test runs on the device too.
- scripts/build_apk_android.sh: sources to installed APK in one command
  (environment checks, qt-cmake configure, --target apk, adb install), and
  the host-side plumbing the NixOS + qt.io combination needs -- the NDK
  sysroot include dirs for Qt's FindGLESv2/FindEGL (they only look under
  <sysroot>/include), -L$PREFIX/lib on the shared/module link lines as well
  as the executables', the Android debug keystore created on first use with
  QT_ANDROID_SIGN_APK + QT_ANDROID_KEYSTORE_* (androiddeployqt copies the
  unsigned gradle output and signs it itself), and the #!/bin/bash shebang of
  the build-tools wrappers, which NixOS does not have.
- scripts/gradle-android-init.gradle (installed into ~/.gradle/init.d/): the
  release lint task is switched off -- lintVitalAnalyzeRelease resolves its
  own tool jars straight from dl.google.com, bypassing every repository the
  build configures, and fails the build after all the real work is done.
- Icons: app/icons/*.svg (Breeze's 24@3x files, the 19 names the window asks
  for) are compiled in as :/cst-icons and ThemeIcons.cpp falls back to them
  when the platform has no icon theme. On the phone the Qt theme lookup found
  nothing and the QML glyph fallback was an empty box in the phone's fonts.
- docs/android.md: "The APK (Qt front end)" -- the SDK assembled without
  sdkmanager, the host Qt's missing libraries on NixOS, the Gradle mirrors,
  lint, signing -- and a Status that says what runs where. app/README.md
  gains the images and APK lines, and stops claiming Android platform tools
  that are still stubs.

Verified: engine `make check` green; desktop `cst-app-selftest: OK` and
--uitest all checks pass; phone (NX789J, Android 16, arm64-v8a) -- the APK
installs, starts on the workspace under /data/user/0/xyz.whcself.cstagent/
files/, a turn reaches a configured provider over HTTPS from inside the ART
process and renders the reply, rotation keeps the session and docks the
sidebar, and the toolbar/card icons draw.

Version 0.9.0.

mode = coding
2026-10-11 15:22:10 +08:00
WHC 82dee65942 v0.8.15: custom providers and model parameters under Advanced options
The settings dialog could pick a preset, a model and a key and nothing else.
Two things were missing: a provider the presets do not know, and what the
model is asked to do while it answers. Both live under "Advanced options"
now, next to the entry they belong to.

Custom providers (engine)
- cst_models_user_set_provider() / cst_models_user_drop_provider() write the
  engine's own user layer, <config>/cst-agent/models.json:
  {"providers": {"myllm": {"api_base": ..., "key_env": ...,
                           "default_model": ..., "models": [...]}}}
  and reload the registry, so the provider is at once in the provider list,
  in the wire models[] and in the CLI's /provider -- the file a hand-written
  override would go into is the same one, so the GUI and an editor agree.
  The name is checked (1-31 of letters, digits, '.', '_', '-'), a preset's
  name overrides that preset (a self-hosted endpoint, a proxy), everything
  else in the file (model rules) is kept, and a file that is not a JSON
  object is never overwritten. Dropping only removes the user's own entry.
- AgentCore::providers() gained "custom" (source == "user"), and
  addProvider() / removeProvider() drive the two calls above.

Model parameters (engine + wire)
- cst_agent_config_t and cst_llm_request_t carry temperature, top_p and
  max_tokens. 0 means the field is not sent at all -- an absent field is the
  provider's own default, which "temperature": 0 is not (deterministic
  decoding is a real choice), so cst_llm_build_body() only adds what was set.
  tests/test_llm_body.c:test_gen_params pins both halves.
- settings.json keeps them per provider ("params": {...}) via
  cst_settings_remember_params(); cst_settings_remember() carries them along
  with the provider choice, and cst_agent_create() reads them, so a CLI or
  TUI run sends what the window was set to. An all-zero config (the CLI)
  leaves what the GUI saved alone.
- AgentCore::genParams() / setGenParams(), and useProvider() applies both the
  remembered parameters of the provider it lands on and a base URL that was
  edited in the dialog.

The dialog
- Rewritten around one scrolling body with a fixed footer: a long model list
  used to push the key field and the buttons out of the dialog. The model
  chips are filtered (a filter field appears past twelve) and capped at 40
  with "... +N more", which is what a router with hundreds of models needs.
- "Advanced options" folds out the provider entry (name, base URL, key
  variable, default model, models; Save provider / Remove from models.json)
  and the model parameters (temperature, top-p, max tokens; empty = not
  sent). The fields follow the picked provider and are what gets saved, so a
  hand-typed edit is never lost to a stale property.

Verified: --uitest 67/67 (15 new checks: parameters round-trip through the
engine, a provider added through the form and removed again, a bad name
refused, a preset not removable), --selftest, ctest cst-app-selftest, and
make check with the new body test.

Version 0.8.15.

mode = coding
2026-10-11 13:26:02 +08:00
WHC 3fd039cb51 v0.8.14: icons from the desktop's theme (Breeze), readable text, composer frame
The window drew its icons with unicode glyphs -- a clip emoji for attach, a
gear, a hamburger, a chevron, a multiplication sign for delete. Those render
in whichever font happens to cover them (colour emoji in a grey toolbar) and
are a box on a machine without that glyph. They now come from the icon theme,
the way every other desktop app gets them.

Icons
- app/src/ui/ThemeIcons.{h,cpp}: a QQuickImageProvider for
  image://csttheme/<name>?color=%23rrggbb -- QIcon::fromTheme() in the
  desktop's theme (whatever the platform theme set, else breeze-dark, breeze,
  hicolor), tinted with QPainter's SourceIn and rasterised at the requested
  size and the screen's device pixel ratio. Qt only builds its theme search
  paths from XDG once a theme name is set, so the provider fills them itself
  (GenericDataLocation/icons, ~/.icons and, on NixOS,
  /run/current-system/sw/share/icons, for a shell started outside the desktop
  session). An unknown name yields a null image, which QML reports as
  Image.Error.
- app/qml/ThemeIcon.qml: the one component that asks for an icon. Every use
  still names the old character as `glyph:`, so a host with no icon theme
  degrades to exactly what the window looked like before instead of going
  blank. installThemeIcons() is called by main() and by --uitest, so the test
  loads the same icons the app does.
- Replaced: nav (application-menu), settings (settings-configure), attach
  (mail-attachment), copy (edit-copy), session delete (edit-delete), new
  session (list-add), expand/collapse (arrow-right/arrow-down), jump to the end
  (go-down), the plan checklist (task-complete/box). A tool card also shows
  what kind of tool ran -- Theme.toolIcon(): pencil for patch/write, text page
  for read, folder for list/glob, magnifier for grep, braces for a shell,
  globe for web, list for a plan. Toolbar icons are 22 px (Breeze's toolbar
  size), card and row icons 14-16 px.

Colours (the "some text is unreadable" part)
- textFaint #6d757b -> #8d959c: ~3.4:1 -> ~5:1 on the card fill. It carries
  hints, provider URLs, session metadata and placeholders, so it is text, not
  decoration.
- A selected provider row and the open session row write on the accent fill;
  they now use accentText / accentTextDim / okOnAccent instead of faint grey
  and green on blue (named "accentText", not "onAccent": QML reads any `onFoo`
  property as a signal handler and refuses the assignment).
- The filled buttons (Send, Use this) take their ink from Theme.accentInk.

Composer
- The frame is one Theme.pad around its column on every side (anchors.fill,
  implicitHeight + 2*pad). With the top margin alone the last row -- the clip
  and Send -- hung over the lower border, which is what put the clip on the
  frame instead of inside it.

app/README.md gains an "Icons, colors" section (the provider, why the theme
search paths are filled by hand, the qtsvg requirement for rasterising Breeze,
the tool map, and the contrast rules).

Verified: --uitest 52/52, --selftest OK, and the 0.8.14 window relaunched in
the Plasma session (no QML warnings).

Version 0.8.14.

mode = coding
2026-10-11 12:53:49 +08:00
WHC 8694afca94 v0.8.13: tool cards paired by call id, markdown rendered while it streams
Two things the window got wrong once a real turn ran through it, plus the
switch that was invisible on a dark theme.

Tool cards (app/src/core/AgentCore.*, app/qml/Main.qml, ToolCard.qml):
- A turn that called the same tool twice left the first card on "running"
  forever and gave its result to the second card: both were paired by name.
  cst_agent_hooks_t hands the call (ctl_tool_call_t) to every callback, so the
  id travels with the signals now (toolEvent(phase, id, name, detail),
  toolResult(id, name, exitCode, output)) and findTool() matches on it, in the
  same way AgentCore::history() fills it from tool_call_id / tool_calls_json
  for a replayed session. Only a call without an id -- an old text-protocol
  session -- still falls back to the name.
- Nothing may keep spinning after a turn: closeAllRows() runs when the turn
  ends and settles every open row; a call that never came back shows "no
  result" (state "unfinished") and no longer claims an exit code.

Streaming text (app/qml/Main.qml, ChatView.qml):
- The answer was plain text while it streamed and turned into markdown only
  when the turn ended. A 120 ms timer now re-renders the open answer with the
  engine's own renderer (AgentCore::renderMarkdown -> cst_web_md_html), so a
  list, a table or a code fence fills in formatted as it arrives. A row keeps
  its own "html" field; a replayed session renders once, where its rows are
  built.

QML details:
- the Plan mode Switch got a drawn indicator: the Basic style's pill is a dark
  pill with a dark knob on this theme, which made the control look disabled.
- Every engine signal handler is a plain window function now
  (engineToolEvent, engineToolResult, engineTurnFinished, engineAssistant,
  ...), which is also what lets --uitest drive the exact path; rowJson(i)
  returns a transcript row as JSON for it (an object would not survive
  QMetaObject::invokeMethod).

Tests: 6 more checks -- a call opens a card, two calls of one tool are two
cards, the result lands on the card of its own call, the other card is
untouched, the turn end settles an open call, a delta opens a streaming answer
and markdown is rendered while it still streams. 52/52 pass, --selftest,
ctest cst-app-selftest.

Version 0.8.13.
2026-10-11 12:44:20 +08:00
WHC cbd71b83c7 v0.8.12: attachments in the composer, picker + drop + paste
A prompt can carry files now, and they come in the three ways a desktop user
expects: the 📎 button in the composer (QtQuick.Dialogs' FileDialog), files
dropped anywhere on the window (a DropArea over it, with an accent border and
"drop to attach" while something is dragged), and an image on the clipboard
(Ctrl+V). Text keeps the editor's own paste: the composer asks
AgentCore::clipboardHasImage() first and only takes the keystroke when there is
an image.

AgentCore (app/src/core/AgentCore.*):
- pending is a property now (QStringList) fed by cst_agent_pending_describe();
  attachFile() and attachClipboard() wrap cst_agent_attach_file() /
  cst_agent_attach_bytes(), clearPending() wraps cst_agent_pending_clear(), and
  seesImages() reports whether the model is shown images at all.
- the engine's description says what the model gets ("png 12.0 KB"), not where
  it came from, so the window remembers the names it attached and puts them in
  front: "note.txt — text 21 B".
- pendingChanged() fires on attach, on clear and when a turn ends (the prompt
  consumed the list), which is what makes the chips move.

Engine (src/attach.c):
- cst_attach_describe() printed every sub-megabyte size as "%.0f KB": a 21-byte
  text file came out as "text 0 KB". It is "B", "KB" with one decimal or "MB"
  now, and test_attach still passes.

QML: the composer shows one chip per pending file with "clear all"; the hint
line mentions 📎/Ctrl+V and says when the model is text-only (images then
travel as notes); Main.qml owns the DropArea and the drag feedback.

Verified: 44/44 UI checks (8 new: attach ok, one pending, the name is shown, a
missing file is refused, one chip in the composer, clear all empties it, the
clipboard image is seen and attached), --selftest, make check rc=0 (test_attach
included), and screenshots of the chip row.

Version 0.8.12.
2026-10-11 12:35:22 +08:00
WHC be4025e276 v0.8.11: theme the settings dialog's fields and buttons
The Basic style paints its own controls: the two text fields came out as white
boxes on the dark panel and the buttons looked nothing like the rest of the
window. Both fields now carry the surface, border and focus colors the chat
cards use (same shape as AskDialog's field), and the buttons follow the
composer: Close is a quiet bordered button, Use this is the accent one.

No behavior change; 36/36 UI checks still pass and the dialog was looked at
again through CST_APP_SHOT.

Version 0.8.11.
2026-10-11 12:27:44 +08:00
WHC 69842edf16 v0.8.10: settings dialog (provider, model, key), window starts on a provider
The window could be started, but it could not be pointed anywhere: a provider,
a model and a key only came in on the command line. The gear in the header now
opens a dialog that changes all three on the engine's live config.

AgentCore (app/src/core/AgentCore.*):
- providers(): the engine's preset table (cst_provider_count/at), with base
  URL, the remembered or preset model, whether a key exists and where it comes
  from (cst_creds_resolve: "saved", or the environment variable), the preset's
  key variable and the source ("built-in" / "user"). A key is read into a local
  buffer only to answer "is there one"; it never leaves the C++ side.
- modelChoices(provider): the provider's own list (cst_provider_models), the
  fetched cache (cst_ps_cached -- which writes through its out-parameters, so
  it takes a real int, not NULL: passing one cost a segfault) and the
  remembered pick. No network. modelInfo() is cst_model_info + its "200K ·
  text only" label; usage() is cst_agent_usage for the session and the turn.
- useProvider(provider, model, key) -> "" or a reason: a different provider
  goes through cst_ps_switch_provider() (the key is verified against /models
  before it is saved; offline it is kept unverified and the header says so),
  a key for the current one through cst_ps_set_key(), and the model is
  remembered in settings.json. syncConfig() takes the engine's config back
  over the app's copy, so provider/model/approval read correctly afterwards.
  The engine's session is never touched by a switch.
- open() no longer starts with an empty provider: it takes the one the engine
  used last (settings.json), else the built-in default, plus that provider's
  base URL and model. Without this the first turn could not be sent at all and
  no entry in the dialog was "in use".

QML (app/qml/SettingsDialog.qml, Main.qml):
- a modal dialog with the themed surface the other dialogs use (the Basic
  style's light panel washes out the dark theme), the provider list with its
  key state, a model field with the info label and clickable candidates, a
  password field for a new key, the session's token counters, and a note that
  reports what the last "Use this" answered.

Tests: 8 more checks -- the presets are readable, an unknown provider is
refused, the counters are readable, the gear opens the panel, the rows exist, a
model typed into the field reaches the engine, the note says so, Close puts the
dialog away. 36 checks pass. --uitest also points XDG_CONFIG_HOME at its
scratch directory now, so a run cannot rewrite the user's settings.json or
credentials, and CST_APP_SHOT writes shot.png at the end plus
shot-settings.png while the dialog is open (that is how the dialog above was
reviewed on a machine without a screen).

Verified: 36/36 UI checks, --selftest, ctest cst-app-selftest, make check rc=0,
and a screenshot of the dialog.

Version 0.8.10.
2026-10-11 12:25:33 +08:00
WHC f5d340bd2a v0.8.9: sessions in the Qt front end, transcript replay, UI test helpers
A conversation is now something the window can pick. The sidebar lists the
workspace's stored sessions and switching replays one into the view.

Sessions (app/src/core/AgentCore.*, app/qml/SessionRow.qml, Sidebar.qml):
- AgentCore::open() resolves the workspace's current session through
  cst_agent_store_resolve_default() before the engine starts. Without it the
  engine opened session.jsonl in the process's working directory, next to a
  session list that stayed empty.
- sessionId property; sessions() (id, title, firstUser, messages, mtime in ms,
  current); newSession(), switchSession(), deleteSession() (moves the engine
  off a session it has open first), renameSession(); sessionChanged and
  sessionListChanged signals. No mutation runs during a turn.
- history() turns the open session back into the rows the live signals build
  (kind/role/text/name/state/detail/output/exitCode/complete): system prompt
  skipped, notes and attachments shown, assistant reasoning as a think row,
  tool_calls_json as one card per call, and each result paired with its call
  the way findTool() pairs the live stream. A call with no result keeps state
  "unfinished" ("no result"), so a replay never shows a spinner that cannot
  stop. Main.qml replays on sessionChanged.
- SessionRow.qml is a file of its own: as an inline component it would not see
  the Repeater's modelData. Session controls are disabled while a turn runs.

Tests (app/src/ui/UiTest.cpp, app/src/main.cpp):
- the fixture session is written through the store's own API (a tool call with
  its result), then the checks click its row, assert the five replayed rows and
  the paired result, start two new sessions (the view empties), delete one by
  its button (the open one stays), and switch back. 28 checks in total.
- item() falls back to the visual tree: delegates a model owns are not always
  in the window's QObject tree, which is why the rows were invisible to
  findChild even though they were on screen.
- --uitest drives a scratch workspace unless --workspace is given; it creates
  and deletes sessions. CST_APP_SHOT=file saves the window as a PNG when the
  run ends and CST_APP_DUMP=1 prints the session rows seen; both are how the
  layout gets looked at on a machine without a screen.

QML: ThinkBlock's click target is a TapHandler on its row (a MouseArea anchored
inside a layout is undefined behavior and Qt said so).

Verified: 28/28 UI checks, --selftest, ctest cst-app-selftest, make check rc=0,
and a screenshot of a replayed session (cards, tool card with its result, the
think block, the sidebar list).

Version 0.8.9.
2026-10-11 12:14:59 +08:00
WHC da812cc7e8 v0.8.8: Qt front end redesign, responsive shell, UI input tests
The window is no longer one file pretending to be a chat box. The transcript,
the run panel, the composer and the two consent dialogs are their own QML
components over one Theme singleton, and the shell around them adapts to the
screen: docked and scrollable on a desktop, a slide-out drawer on a phone.

QML (app/qml/, new except Main.qml):
- Theme.qml: single QML singleton, dark Breeze-flavoured tokens (surface,
  border, accent, text/textDim/textFaint, radius, pad, gap, sizes, monospace);
  diffLineColor() for unified-diff rows, compactBreakpoint 880, touchTarget
  34, segmentHeight 30, headerHeight 42.
- ChatView.qml: a row-type dispatcher over the transcript model (message,
  thought, tool, note), follow-the-tail scrolling with a "jump to latest"
  button once the user scrolls up, and an empty state that says where the
  agent runs and what it can do.
- MessageCard.qml, ThinkBlock.qml, NoteLine.qml, ToolCard.qml (status pill,
  arguments, collapsible output, 500-line cut, diff colouring, spinner while
  the call runs), TodoPanel.qml.
- Sidebar.qml: workspace/provider/status, mode and approval segmented rows,
  plan switch, the engine's todo list, version footer; scrolls, so a short
  window still reaches every control.
- Composer.qml: auto-growing field, Enter sends / Shift+Enter newlines,
  red Stop while a turn runs, autocorrect hints off, finger-sized targets.
- ConsentDialog.qml (Deny / Once / Always -> CST_PERM_*) and AskDialog.qml
  (the model's options become buttons, free text stays possible).
- Main.qml: shell with header, draggable sidebar splitter (hover feedback,
  200-560 px, double-click resets), transcript, composer, the two dialogs,
  Esc to cancel and Ctrl+L to clear. Under 880 px the sidebar becomes a
  drawer with a scrim instead of squeezing the chat away.

AgentCore / main.cpp:
- provider, model, approval and planMode are properties now; approval and
  plan mode write back into the engine's config, and renderMarkdown() calls
  cst_web_md_html(), so a table or a code fence looks like the WebUI's.
- the todo hook writes m_todo on the GUI thread (it was written from the
  worker thread before: a data race on a QString member).
- --size WxH for the window (the layout tests drive it), and the Basic style
  is chosen by default: the Breeze Quick style registers its types with
  relative URLs, which floods the log and breaks the composer.

UI tests (app/src/ui/):
- --uitest drives the real window with synthesized input and exits with the
  number of failures: 15 checks over docking/drawer transitions, mouse clicks
  and touch taps reaching the engine's mode, the plan switch, the composer
  arming the send button, and a 460x900 -> 1200x820 resize round trip.
- every control the tests touch carries an objectName; the sidebar's
  implicitHeight binding loop is gone.

Tests: cst-app-selftest and --uitest pass in the standalone app build,
ctest cst-app-selftest passes in the repo build (38/38 on the host).

Version 0.8.8.
2026-10-11 11:58:23 +08:00
WHC 5ba215b36c v0.8.7: tool capability metadata, in-process engine, Qt app, Android engine
The engine can be embedded now instead of only driven from a terminal: the
same objects link into a Qt front end (app/) that owns a cst_agent_t inside
its own process -- no port, no token, no second process -- and that front end
now runs on the desktop and, engine-side, on the phone.

Capability metadata (include/cst_tools.h, src/tools/registry.c):
- cst_tool_def_t gains perm_name, platforms and available (a probe that
  returns a reason), so a permission is addressable by name and a tool can
  say why it cannot run here.
- cst_platform_name(), cst_tool_platform_ok(), cst_tool_available(),
  cst_tool_meta_reload(), cst_tool_perm_name() and CST_PLAT_DESKTOP[].
- cst_tool_register() may take over a built-in name that is not runnable on
  this platform, so a front end replaces it with its own implementation.
- the registry entries carry their class (delete_file -> "delete"), the
  desktop clipboard tools carry a clipboard probe; find/active/run gate on it.
- /api/settings.tools[] exposes perm_name, platforms, available, why and the
  declared parameters.

Engine as a library (Makefile, CMakeLists.txt):
- libcstcore.a from the CORE_OBJ set, and a CMake cstcore target shared by
  the CLI and by app/ (-DCST_BUILD_APP=ON): the engine is compiled once.
- Android branch for the vendored sashidown: a per-ABI archive built with the
  NDK's aarch64-linux-android24-clang wrapper, because CMake's compiler is
  plain clang and keeps --target/--sysroot in its own variables.

Qt front end (app/, new):
- AgentCore wraps one cst_agent_t: turns run on a worker thread, every
  cst_agent_hooks_t callback becomes a Qt signal, and the two hooks that need
  an answer (on_permission, on_ask_user) block the worker until the GUI
  replies; mode, approval and plan mode go through the engine's config.
- ToolProvider hands the front end's tools to the engine (owner "app:*"); the
  Linux one is notification_send with a probe for notify-send/D-Bus.
- Main.qml: transcript, tool blocks, consent dialog (Deny/Once/Always ->
  CST_PERM_*), ask_user, mode switch, Esc to cancel; --selftest stays
  headless and runs the embedding checks without QML.

Android (scripts/, docs/android.md, new):
- scripts/build_third_party_android.sh builds static mbedTLS + libcurl for an
  ABI (CA path /system/etc/security/cacerts); build_android.sh builds
  cst-agent, libcstcore.a and the test binaries for the phone, can push them
  and run the whole suite there.
- sandbox_exec.c keeps the plain exec path on Android: the seccomp supervisor
  compiled in and the probe reported "seccomp", but writes outside the
  workspace were not denied on the device -- claiming a sandbox that does not
  hold is worse than reporting none.
- tests/test_diff.c compares layouts only against real GNU diffutils: toybox's
  diff prints the same hunk header with its own hunk/context rules.

Tests: test_tool_meta (metadata, platform gate, probe reasons, takeover of a
built-in name) and test_embed (in-process embedding contract) are new; the
existing registry/llm_body assertions now follow availability. 38 test
binaries pass on the host, 36/36 on arm64-v8a Android 16, cst-app-selftest
passes in both the standalone app/ build and the repo build.

Version 0.8.7.
2026-10-11 11:42:04 +08:00
WHC e0b0eddf3a v0.8.6: general mode, clipboard text, PDF text extraction
ci / tcc-check (push) Successful in 59s
ci / linux (aarch64, 0) (push) Successful in 19m11s
ci / linux (x86, 1) (push) Successful in 11m31s
ci / linux (x86_64, 1) (push) Successful in 11m11s
ci / windows (push) Successful in 9m24s
Working mode: --mode coding|general (CST_MODE, settings.json, /mode,
WebUI run settings). general swaps the default framing for a general
assistant one -- workflow, safety notes, tool wording (run_shell, the
subagents) -- and /status shows it; minimal (the paper profile) stays
byte-frozen. The prompt state carries the mode so a switch leaves a
system note in history.

Clipboard: clipboard_read / clipboard_write tools (16 MiB cap read,
default 64 KiB window; writing is a WRITE permission with a preview) on
pbcopy / wl-copy / xclip / pbpaste / wl-paste / xclip and the Win32
clipboard. In the TUI, /attach paste falls back to clipboard text when
there is no image on it.

PDF: a dependency-free text extractor (src/pdf_text.c): inflate,
Flate/ASCIIHex/ASCII85, PNG/TIFF predictors, layout-independent object
scan, object streams, page tree walk with inherited resources, content
lexer (Tj/TJ/'/" and the Td/TD/T*/Tm spacing heuristics), per-font
ToUnicode CMaps and inline images skipped. Encrypted files and pages
with no text layer are refused with the reason.

Attachments: /attach (a path or files dropped on the terminal) now take
images, PDFs and text. A PDF is stored as its text layer with the mime
still saying application/pdf and its page count; anything else has to be
UTF-8 text. Documents travel inline as text parts, so CST_NO_IMAGES and
text-only models no longer drop them, while images keep their old path.

Tests: test_pdf_text (plain, bare and zlib-framed Flate, inline image,
CID + ToUnicode, object stream, error paths), documents in test_attach,
inlined documents in test_llm_body, mode in test_config.
2026-10-11 11:09:39 +08:00
WHC 50abcf1a91 build: finish cross-platform release tooling
ci / tcc-check (push) Successful in 1m9s
ci / linux (aarch64, 0) (push) Failing after 58m44s
ci / linux (x86, 1) (push) Successful in 13m47s
ci / linux (x86_64, 1) (push) Failing after 1h0m2s
ci / windows (push) Successful in 10m46s
2026-10-10 16:21:00 +08:00
WHC 9bf7707912 v0.8.5: WebUI process timeline, Gemini-style images, aligned layout
ci / linux (clang) (push) Successful in 6m15s
ci / linux (gcc) (push) Successful in 7m14s
ci / musl (push) Successful in 7m14s
ci / windows-cross (push) Successful in 11m4s
Process timeline: a run of consecutive thinking and tool calls is one
block that folds to a single line ("思考 4 次 · 工具 6 次"; while running
it shows the current action) and opens into a compact timeline, one row
per thought or call. Visible text, a note or the next prompt closes the
block; history and the live stream follow the same rule. show_thinking
now also applies while streaming instead of forcing thoughts open.

Layout: the avatar gutter and the flex-wrap that dropped it under long
answers are gone, so answer, process blocks, notes and composer share one
left edge. The text column and composer are both 720px (--content); the
rail and run panel grow with clamp() on wide screens. A rebuild after
each turn no longer replays every entrance animation, and the turn time
survives it. Message actions are icon buttons and only appear under text.

Images: a prompt's images sit above the bubble, right-aligned (one keeps
its shape, several are 152px rounded tiles) and open in a lightbox (Esc,
arrow keys). Images uploaded from the page show as thumbnails over the
composer and appear on the prompt as soon as it is sent.

Also: ?theme= is no longer overridden by app.js, the user bubble is
visible in the light theme, and the narrow top bar no longer wraps.
2026-10-10 14:54:36 +08:00
WHC 7e1dbd9afa v0.8.4: WebUI sessions, diff, settings, slash commands and extensions
ci / linux (clang) (push) Successful in 6m13s
ci / musl (push) Canceled after 0s
ci / windows-cross (push) Canceled after 0s
ci / linux (gcc) (push) Canceled after 6m33s
Sessions: rename, delete and search; /api/retry regenerates the last
answer, editing a prompt resends from there; /api/export downloads the
transcript as Markdown (cst_session_export_md). Session messages carry
note/tool_result markers, so a reload rebuilds the tool steps with
their arguments, output and exit status; subagent progress is shown.

Diff and settings: /api/diff shows the real diff; /api/settings covers
protocol, max_steps, tool switches and confirm; /api/permissions edits
the rules; sandbox status is reported. Session rename no longer reads
past a short title.

Commands: slash commands with completion in the composer (/model,
/provider, /new, /retry, /undo, /compact, /export, /diff, /init,
/skill and more), a Ctrl+P palette, Shift+Tab cycles the approval
mode, F1 or ? shows the keys. "Thinking expanded" is saved in the
settings (show_thinking), "expand all tool output" in the browser.

Extensions: GET /api/extensions lists MCP servers, plugins, skills,
agent roles and subagent runs; POST /api/extensions/reload and
/api/extensions/trust; a workspace switch reloads them. /api/init and
/api/skill run on the server (cst_init_prompt shared with the TUI).

Errors, statuses and [cst] notes are shown in Chinese with a readable
reason instead of rc=; a failed turn's error survives the reload.

Tests: scripts/e2e_webui_sessions.py, e2e_webui_workspace.py and
e2e_webui_ext.py, run from e2e_webui.sh.
2026-10-10 13:57:17 +08:00
WHC 2d1052fd5f v0.8.3: WebUI models, providers and keys; garbled thinking fixed
ci / linux (clang) (push) Successful in 5m56s
ci / linux (gcc) (push) Successful in 8m38s
ci / musl (push) Successful in 7m22s
ci / windows-cross (push) Successful in 9m21s
Streaming: Chinese reasoning showed up garbled in the WebUI. The agent
loop now feeds visible/thinking text in runs instead of byte by byte,
and the WebUI holds an incomplete UTF-8 tail until the next chunk
(cst_utf8_hold_feed), so every think_delta/assistant_delta is whole.

src/provider_switch.c: model list fetch/cache, key verify-and-save and
provider switching moved out of tui.c and shared by TUI and WebUI.

WebUI API:
- GET /api/providers, GET /api/models[?refresh=1] (401 on a rejected
  key, still listing built-ins), POST /api/provider, POST /api/key
  (key checked against /v1/models, saved to credentials 0600, never
  echoed in replies, events or logs)
- /api/config validates everything before applying, persists model,
  effort and approval (not yolo), warns when effort does not apply;
  plan_mode no longer forces read-only
- state: turn_usage, api_base, key_set/key_from, model_info,
  effort_applies, sees_images, max_steps, tool_profile, perm_timeout;
  permission events carry their timeout

Frontend: searchable model picker with refresh and manual entry,
provider picker and key dialog, effort/vision hints, toasts instead of
silent failures, Chinese error text, real protocol in the settings and
usage panels, approval countdown from the server's timeout.

Tests: utf8 hold unit test, scripts/e2e_webui_settings.py (fake
/v1/models, wrong key, switching, persistence, Chinese thinking) run
from e2e_webui.sh, scripts/tui_keys/provider.py.
2026-10-09 15:54:53 +08:00
WHC e238f5f37d v0.8.2: build fixes, WebUI security and correctness
ci / linux (clang) (push) Successful in 5m45s
ci / linux (gcc) (push) Successful in 6m46s
ci / musl (push) Successful in 7m9s
ci / windows-cross (push) Successful in 11m52s
Build: <fcntl.h> in tui.c, format-truncation in http_srv.c and /web.

WebUI:
- refuse cross-site requests (Origin must be the page itself) in the
  default no-token mode: any page could POST approval=yolo and a prompt
- session/workspace/undo/compact/attach/model changes are 409 while a
  turn runs (use-after-free, messages landing in the wrong session)
- ask_user returned "dismissed" at once instead of waiting
- cancel and shutdown wake a turn parked on a permission or question;
  SIGTERM mid-turn no longer hangs or crashes
- a page opened while a question is pending still gets it;
  Last-Event-ID resumes the stream; event seq matches the SSE id
- token mode: page assets load without the token, images via cookie
- --web-open works, --web-port/--web-token are validated
- frontend: gate keys ignored while typing, clear-images button,
  reasoning no longer wiped while streaming

HTTP server: auth and size cap before reading the body, strict
Content-Length, NUL in url_decode, 413 on keep-alive, idle timeout,
absolute-form only without a leading '/', case-insensitive Connection,
header deadline, 400 for long request lines, unlink before close,
poll() instead of select(), SO_EXCLUSIVEADDRUSE on Windows.

Markdown sanitizer escapes quotes in attribute values.

/web: passes this session's provider/model/base/effort/approval (key
via the environment), keeps output off the TUI, shows the real URL and
keeps CURRENT on the TUI's session.

Tests: scripts/e2e_webui_ask.py, scripts/e2e_webui_http.py (run from
e2e_webui.sh), sanitizer quote test.
2026-10-09 13:51:34 +08:00
WHC adf3e9f024 v0.8.0: WebUI redesign, /web, workspace switch, 75% budget, no shell timeout
ci / linux (clang) (push) Failing after 31s
ci / linux (gcc) (push) Failing after 32s
ci / musl (push) Failing after 39s
ci / windows-cross (push) Canceled after 2m32s
The front end is rebuilt on the design tokens the desktop app ships (surfaces,
color-mix borders, alpha hovers, accent): a 30-icon inline SVG sprite, dark and
light themes, layout switches as deep links (?side=0, ?panel=0, ?theme=light)
resolved before the first paint. The empty page is one line and leaves with the
first turn; the right rail keeps three cards - todo, file changes (+N -M) and
context (tokens, prompt cache hit rate). Both rails animate in and out, and a
collapsed rail widens its grid track to 0 instead of being removed, so the
transcript never slides into a zero-width column.

- src/webui.c: POST /api/workspace - re-root the agent at another directory
  (permission rules, metrics, AGENTS.md follow) and start a session there, as
  sessions live per directory; state also reports cached/cache_miss tokens
- src/agent_loop.c: cst_agent_set_workspace(), rebuilt prompt and re-measured
  budget; the auto-compact threshold is 75% of the window (was 60%)
- src/tui.c: /web forks a WebUI next to the TUI - separate process and a new
  session, because cst_webui_run() blocks and two writers corrupt one session
- src/os_compat.c, src/os_win.c: run_shell runs without a time limit unless
  CST_SHELL_TIMEOUT asks for one, so builds and long clones finish
- src/main.c, include/cst_webui.h: one CST_WEBUI_DEFAULT_PORT for --help, the
  docs and /web; Termux opens the browser through termux-open-url
- README.md, docs/webui.md, docs/env_openai.md: /web, /api/workspace, the new
  state fields, the 75% threshold and the layout deep links

tests/e2e_webui.sh green (permission round-trip, token paths, --web-dev);
make check green.
2026-10-09 11:50:13 +08:00
WHC 6e81513e36 v0.7.8: WebUI (--web): HTTP/1.1 + SSE front end, engine API v1, tests
ci / linux (clang) (push) Successful in 5m25s
ci / linux (gcc) (push) Failing after 34s
ci / musl (push) Successful in 7m22s
ci / windows-cross (push) Successful in 10m41s
A second implementation of cst_agent_hooks_t next to the TUI: the turn runs on
a worker thread, the hooks publish events into a ring buffer that SSE clients
read, so the engine itself needs no changes.

- src/net.c, include/cst_net.h: POSIX/Winsock sockets, non-blocking connect
- src/http_srv.c, include/cst_http.h: HTTP/1.1, keep-alive, chunked streaming,
  body caps (413), Expect: 100-continue, connection cap, exact routing
- src/web_md.c, include/cst_web_md.h: streaming markdown -> sanitized HTML
  (tag/attribute allowlist, javascript: URLs and off-site images dropped)
- src/webui.c, include/cst_webui.h: event ring + SSE broadcast, all routes,
  token (Bearer/Cookie/query) and loopback Host checks, 3 s auto-deny when no
  client is attached
- src/webui_stub.c, CST_WEBUI=0 / CST_BUILD_WEBUI=OFF: build without the WebUI
- web/: no-build front end (transcript, approvals, todo, sessions, image
  upload, status bar)
- docs/webui.md: engine API v1 - events, requests, security model
- tests/test_webui.c, scripts/e2e_webui.sh: unit tests plus an end-to-end run
  driven by a recorded SSE stream (no API key needed)
- src/main.c: --web --web-port --web-host --web-token --web-dev --web-open
  and CST_WEB_PORT/HOST/TOKEN/ROOT

An empty POST body is now accepted without Content-Length (RFC 9112 6.3) so
curl-driven clients can reach cancel/undo/compact/quit; CMakeList's core tests
learned about sashidown and test_webui, and CST_WEBUI=0 defines CST_NO_WEBUI.
2026-10-09 10:20:09 +08:00
WHC c7b32c3fd6 v0.7.5: arrow keys, image request fix, deepseek-flash vision, musl CI
ci / linux (clang) (push) Successful in 4m42s
ci / linux (gcc) (push) Successful in 5m35s
ci / musl (push) Successful in 5m52s
ci / windows-cross (push) Successful in 12m51s
TUI keys: register both CSI and SS3 forms of the cursor/Home/End keys and
the xterm modifier sequences when terminfo lacks them, so an arrow sent in
the "other" form no longer turns into Esc + a typed letter. Up/Down move by
visual (soft-wrapped) row, and the draft survives a trip through history.
scripts/tui_keys drives the TUI in a pty to check all of this.

Images: text inside a multimodal content array is now a {"type":"text"}
part; DeepSeek rejected the bare string with HTTP 422. deepseek-flash
(and its deepseek-chat / deepseek-reasoner aliases) read images, so the
registry marks them vision; deepseek-v4-pro stays text only.

CI: models.c lost _DEFAULT_SOURCE in 0.7.0 and gmtime_r broke the musl
build; tests sleep with poll() instead of usleep for the same reason.
2026-10-08 22:35:34 +08:00
397 changed files with 62434 additions and 1641 deletions
+22
View File
@@ -0,0 +1,22 @@
.git
result
build/
build-*/
dist/
third_party/
backups/
reports/
**/*.o
**/*.a
**/cst-agent
tests/test_*
!tests/test_*.c
app/
.cursor/
*.apk
*.tar.gz
.gen/
vendor/sashidown/*.o
vendor/sashidown/*.a
vendor/cjson/*.o
vendor/monocypher/*.o
+120 -72
View File
@@ -11,13 +11,11 @@ concurrency:
cancel-in-progress: true
jobs:
linux:
# Verification: TinyCC builds and tests everything in seconds. tcc warns on
# `#pragma GCC`, so no -Werror here; the gcc release builds below carry it.
tcc-check:
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
cc: [gcc, clang]
steps:
- name: Checkout
env:
@@ -34,60 +32,38 @@ jobs:
$SUDO bash scripts/ci_pkg_mirror.sh
$SUDO apt-get update
$SUDO apt-get install -y --no-install-recommends \
build-essential clang cmake pkg-config python3 \
build-essential pkg-config python3 curl ca-certificates \
libcurl4-openssl-dev libncurses-dev
- name: Build (warnings are errors)
run: make CC=${{ matrix.cc }} CFLAGS="-std=c11 -Wall -Wextra -O2 -g -Werror" -j"$(nproc)"
- name: Build TinyCC
run: bash scripts/ci_tcc.sh
- name: Build
run: make CC=tcc AR=ar CFLAGS="-std=c11 -Wall -O2 -g" -j"$(nproc)" hermit
- name: Unit tests
run: |
# Same -Werror as the build step so undeclared libc helpers cannot
# silently return int and truncate pointers (see test_subagent).
make CC=${{ matrix.cc }} \
CFLAGS="-std=c11 -Wall -Wextra -O2 -g -Werror" check
- name: CMake build + ctest
run: |
cmake -B build -DCMAKE_C_COMPILER=${{ matrix.cc }} -DCST_BUILD_TUI=ON
cmake --build build -j"$(nproc)"
ctest --test-dir build --output-on-failure
run: make CC=tcc AR=ar CFLAGS="-std=c11 -Wall -O2 -g" check
- name: Smoke test
run: |
./cst-agent --help
./cst-agent --workspace "$PWD" --list-sessions
./cst-agent --demo-ctl --workspace .
./hermit --help
./hermit --workspace "$PWD" --list-sessions
./hermit --demo-ctl --workspace .
- name: WebUI end-to-end (recorded stream, no API key)
run: sh scripts/e2e_webui.sh
musl:
# Release: static musl binaries, gcc with -Werror.
# dist/cst-agent-VERSION-linux-ARCH.tar.gz
linux:
needs: tcc-check
runs-on: ubuntu-latest
timeout-minutes: 30
container: alpine:3.20
steps:
- name: Install tools + mirror
run: |
sed -i 's#https\?://dl-cdn.alpinelinux.org/alpine#https://mirrors.tuna.tsinghua.edu.cn/alpine#g' \
/etc/apk/repositories
apk add --no-cache curl git bash
- name: Checkout
env:
GITHUB_SERVER_URL: ${{ github.server_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_SHA: ${{ github.sha }}
run: |
curl -fsSL "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/raw/commit/$GITHUB_SHA/scripts/ci_checkout.sh" \
-o /tmp/ci_checkout.sh
bash /tmp/ci_checkout.sh
- name: Install build dependencies
run: |
# linux-headers provides linux/audit.h for the seccomp probe path
apk add --no-cache build-base pkgconf curl-dev ncurses-dev \
linux-headers git nodejs bash python3
- name: Build + unit tests
run: |
make CFLAGS="-std=c11 -Wall -Wextra -O2 -Werror" -j"$(nproc)"
make check
# MinGW-w64 UCRT cross build → dist/cst-agent-*-windows-x86_64.zip
windows-cross:
runs-on: ubuntu-latest
timeout-minutes: 120
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- arch: x86_64
check: 1
- arch: x86
check: 1
- arch: aarch64
check: 0
steps:
- name: Checkout
env:
@@ -103,20 +79,40 @@ jobs:
SUDO=$(command -v sudo || true)
$SUDO bash scripts/ci_pkg_mirror.sh
$SUDO apt-get update
# ncurses-bin/-term: tic, infocmp and the fallback terminal entries
$SUDO apt-get install -y --no-install-recommends \
ca-certificates curl git cmake ninja-build make pkg-config \
python3 zip unzip perl xz-utils
- name: Cross-build Windows zip
run: bash scripts/ci_windows_cross.sh
- name: Verify zip
build-essential cmake ninja-build pkg-config python3 perl \
curl ca-certificates xz-utils bzip2 file ncurses-bin ncurses-term
if [ "${{ matrix.arch }}" = aarch64 ]; then
$SUDO apt-get install -y --no-install-recommends qemu-user-static
fi
- name: Cache musl toolchain + third_party prefix
uses: actions/cache@v4
with:
path: |
${{ env.HOME }}/.local/toolchains
/opt/*musl*
third_party/prefix-linux-${{ matrix.arch }}
third_party/src
key: linux-${{ matrix.arch }}-tp-v1-${{ hashFiles('scripts/build_third_party_linux.sh', 'scripts/ci_linux_toolchain.sh') }}
restore-keys: |
linux-${{ matrix.arch }}-tp-v1-
- name: Build (static, -Werror)
env:
CST_LINUX_CHECK: ${{ matrix.check }}
run: bash scripts/package_linux.sh ${{ matrix.arch }}
- name: Smoke test
run: |
ls -lah dist/windows-x86_64/
ls -lah dist/cst-agent-*-windows-x86_64.zip
cat dist/cst-agent-*-windows-x86_64.zip.sha256
unzip -l dist/cst-agent-*-windows-x86_64.zip | head -20
# Auto-publish to Gitea Releases (v$CST_VERSION from include/cst_version.h).
# Prefer repo secret RELEASE_TOKEN (write:repository); fall back to the
# job token. Skipped on pull_request and when no token is available.
d=$(ls -d dist/hermit-*-linux-${{ matrix.arch }})
file "$d/hermit"
run=""
[ "${{ matrix.arch }}" = aarch64 ] && run=qemu-aarch64-static
$run "$d/hermit" --version
$run "$d/hermit" --help >/dev/null
$run "$d/hermit" --workspace "$PWD" --list-sessions
cat dist/hermit-*-linux-${{ matrix.arch }}.tar.gz.sha256
# Release vVERSION (from include/cst_version.h) on Gitea. Prefer repo
# secret RELEASE_TOKEN (write:repository); fall back to the job token.
- name: Publish Gitea Release
if: github.event_name == 'push'
env:
@@ -125,11 +121,63 @@ jobs:
CST_GITEA: ${{ github.server_url }}
CST_REPO: ${{ github.repository }}
GITHUB_REF: ${{ github.ref }}
CI: "true"
run: bash scripts/ci_publish.sh dist/hermit-*-linux-${{ matrix.arch }}.tar.gz dist/cst-agent-*-linux-${{ matrix.arch }}.tar.gz
# Release: mingw-w64 UCRT gcc (Debian trixie) with -Werror.
# dist/cst-agent-VERSION-windows-x86_64.zip and -setup.exe (NSIS)
windows:
needs: tcc-check
runs-on: ubuntu-latest
timeout-minutes: 120
container: debian:trixie
steps:
- name: Install tools
run: |
export GITEA_TOKEN="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}"
if [[ -z "${GITEA_TOKEN}" ]]; then
echo "::warning::no RELEASE_TOKEN / GITHUB_TOKEN; skip auto-release"
exit 0
fi
bash scripts/release_windows.sh
# No CA certificates in the image yet, so the mirror is plain http.
sed -i 's#https\?://deb.debian.org#http://mirrors.tuna.tsinghua.edu.cn#g' \
/etc/apt/sources.list.d/debian.sources
apt-get update
apt-get install -y --no-install-recommends \
ca-certificates curl git build-essential cmake ninja-build make \
pkg-config python3 perl zip unzip xz-utils patch file \
gcc-mingw-w64-ucrt64 binutils-mingw-w64-ucrt64 nsis
- name: Checkout
env:
GITHUB_SERVER_URL: ${{ github.server_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_SHA: ${{ github.sha }}
run: |
curl -fsSL "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/raw/commit/$GITHUB_SHA/scripts/ci_checkout.sh" \
-o /tmp/ci_checkout.sh
bash /tmp/ci_checkout.sh
- name: Cache mingw third_party
uses: actions/cache@v4
with:
path: |
third_party/prefix-mingw-x86_64
third_party/src
third_party/busybox
key: win-tp-v1-${{ hashFiles('scripts/build_third_party_mingw.sh', 'scripts/bootstrap_windows.sh') }}
restore-keys: |
win-tp-v1-
- name: Cross-build zip and installer
env:
CST_WIN_CFLAGS: -Wall -Wextra -Werror
run: bash scripts/ci_windows_cross.sh
- name: Verify
run: |
ls -lah dist/windows-x86_64/
file dist/windows-x86_64/cst-agent.exe dist/cst-agent-*-windows-x86_64-setup.exe
cat dist/cst-agent-*-windows-x86_64.zip.sha256 dist/cst-agent-*-windows-x86_64-setup.exe.sha256
unzip -l dist/cst-agent-*-windows-x86_64.zip
- name: Publish Gitea Release
if: github.event_name == 'push'
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CST_GITEA: ${{ github.server_url }}
CST_REPO: ${{ github.repository }}
GITHUB_REF: ${{ github.ref }}
run: |
bash scripts/ci_publish.sh dist/cst-agent-*-windows-x86_64.zip \
dist/cst-agent-*-windows-x86_64-setup.exe
+36 -1
View File
@@ -1,6 +1,8 @@
*.o
*.d
cst-agent
cst-agent.exe
libcstcore.a
tests/test_*
!tests/test_*.c
session.jsonl
@@ -26,8 +28,41 @@ third_party/ncurses-*.tar.gz
third_party/busybox-w32/
third_party/busybox-src/
third_party/prefix-mingw/
third_party/prefix-linux-*/
third_party/build-linux-*/
# the Windows app package (scripts/package_windows_app.sh): MSYS2's Qt and the
# host tools it is built with, both fetched/unpacked by the script
third_party/msys-qt6/
third_party/prefix-qt6-host
third_party/prefix-android-*/
third_party/build-android-*/
third_party/src/
vendor/sashidown/*.o
vendor/sashidown/src/*.o
vendor/sashidown/libsashidown.a
vendor/sashidown/libsashidown-*.a
vendor/sashidown/libsashidown-mingw.a
.gen/models_builtin.inc
.gen/
.build-tmp/
# Android APK builds (scripts/build_apk_android.sh) and what gradle leaves
build-apk-android/
*.apk
*.aab
app/android/.gradle/
app/android/build/
app/android/local.properties
# the engine as a static library (app/ links it; built by `make`)
libcstcore.a
# nix-build
result
hermit
.peer_probe.out
reports/
# Tauri desktop
apps/desktop/node_modules/
apps/desktop/dist/
apps/desktop/src-tauri/target/
+164 -25
View File
@@ -5,6 +5,8 @@ set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
option(CST_BUILD_TUI "Build ncurses/PDCurses TUI" ON)
option(CST_BUILD_WEBUI "Build the HTTP/SSE WebUI (--web)" ON)
option(CST_BUILD_APP "Build the Qt front end in app/ (in-process engine, no port)" OFF)
option(CST_NATIVE_ARCH "Pass -march=native to sashidown" OFF)
option(CST_BUNDLE_BUSYBOX "Install placeholder/scripts for busybox beside binary" ON)
@@ -63,6 +65,29 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
COMMAND ${CST_MAKE} -C "${SD_DIR}" clean
COMMENT "Building libsashidown for MinGW"
VERBATIM)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Android")
# The host archive has to stay host-built (the CLI, the tests and the
# Makefile link it), so the NDK build keeps its own copy, one per ABI.
# CMake's compiler is plain clang (the --target/--sysroot flags live in its
# own variables), so the vendor make gets the per-target wrapper instead:
# aarch64-linux-android24-clang carries both.
get_filename_component(_SD_CC_BIN "${CMAKE_C_COMPILER}" DIRECTORY)
string(REPLACE "-none" "" _SD_TRIPLE "${CMAKE_C_COMPILER_TARGET}")
set(_SD_CC "${_SD_CC_BIN}/${_SD_TRIPLE}-clang")
if(NOT EXISTS "${_SD_CC}")
set(_SD_CC "${CMAKE_C_COMPILER}")
endif()
set(SASHIDOWN_A "${SD_DIR}/libsashidown-${ANDROID_ABI}.a")
add_custom_command(
OUTPUT "${SASHIDOWN_A}"
COMMAND ${CST_MAKE} -C "${SD_DIR}" clean
COMMAND ${CST_MAKE} -C "${SD_DIR}" libsashidown.a
CC=${_SD_CC} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB}
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${SD_DIR}/libsashidown.a" "${SASHIDOWN_A}"
COMMAND ${CST_MAKE} -C "${SD_DIR}" clean
COMMENT "Building libsashidown for Android (${ANDROID_ABI})"
VERBATIM)
else()
set(SASHIDOWN_A "${SD_DIR}/libsashidown.a")
add_custom_command(
@@ -80,6 +105,8 @@ set(CJSON_DIR "${CMAKE_CURRENT_SOURCE_DIR}/vendor/cjson")
set(CST_CORE_SOURCES
vendor/cjson/cJSON.c
vendor/monocypher/monocypher.c
vendor/monocypher/monocypher-ed25519.c
src/util.c
src/ctl_parse.c
src/os_compat.c
@@ -92,8 +119,17 @@ set(CST_CORE_SOURCES
src/plugins.c
src/mcp.c
src/subagent.c
src/runtime.c
src/worktree.c
src/realm.c
src/discover.c
src/peer_auth.c
src/parliament.c
src/parliament_daemon.c
src/parliament_cli.c
src/attach.c
src/clipboard.c
src/pdf_text.c
src/session.c
src/tools/tools.c
src/tools/patch.c
@@ -101,6 +137,7 @@ set(CST_CORE_SOURCES
src/tools/fs_tools.c
src/tools/agent_tools.c
src/tools/web.c
src/tools/session_tools.c
src/tools/diff.c
src/undo.c
src/permissions.c
@@ -110,29 +147,109 @@ set(CST_CORE_SOURCES
src/agent_store.c
src/json_baseline.c
src/creds.c
src/provider_switch.c
src/mm_tool.c
src/models.c
src/model_registry.c
src/metrics.c
src/hermit_glyph.c
src/net.c
src/http_srv.c
src/web_md.c
)
# Built-in model data as a C byte list (included by model_registry.c).
set(CST_GEN_DIR "${CMAKE_CURRENT_BINARY_DIR}/gen")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/src/models_builtin.json")
# The WebUI shell (web/*) as C byte arrays, the same trick as the model data.
file(GLOB CST_WEB_ASSETS "${CMAKE_CURRENT_SOURCE_DIR}/web/*")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${CST_WEB_ASSETS})
set(_cst_web_inc "/* Generated by CMake from web/ - do not edit. */\n")
set(_cst_web_table "")
foreach(_f ${CST_WEB_ASSETS})
if(IS_DIRECTORY "${_f}")
continue()
endif()
get_filename_component(_name "${_f}" NAME)
string(REGEX REPLACE "[^A-Za-z0-9]" "_" _var "wui_asset_${_name}")
file(READ "${_f}" _hex HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," _hex "${_hex}")
set(_ctype "application/octet-stream")
if(_name MATCHES "\\.html$")
set(_ctype "text/html; charset=utf-8")
elseif(_name MATCHES "\\.js$")
set(_ctype "text/javascript; charset=utf-8")
elseif(_name MATCHES "\\.css$")
set(_ctype "text/css; charset=utf-8")
elseif(_name MATCHES "\\.svg$")
set(_ctype "image/svg+xml")
endif()
string(APPEND _cst_web_inc "static const unsigned char ${_var}[] = {${_hex}0x00};\n")
string(APPEND _cst_web_table " {\"${_name}\", \"${_ctype}\", ${_var}, sizeof(${_var}) - 1},\n")
endforeach()
string(APPEND _cst_web_inc "static const wui_asset_t wui_assets[] = {\n${_cst_web_table}};\n")
string(APPEND _cst_web_inc "static const int wui_asset_count = (int)(sizeof(wui_assets) / sizeof(wui_assets[0]));\n")
file(WRITE "${CST_GEN_DIR}/web_assets.inc" "${_cst_web_inc}")
if(NOT CST_BUILD_WEBUI)
list(APPEND CST_CORE_SOURCES src/webui_stub.c)
else()
list(APPEND CST_CORE_SOURCES src/webui.c)
endif()
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/models_builtin.json" _cst_models_hex HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," _cst_models_hex "${_cst_models_hex}")
file(WRITE "${CST_GEN_DIR}/models_builtin.inc" "${_cst_models_hex}\n")
include_directories("${CST_GEN_DIR}")
if(NOT CST_BUILD_WEBUI)
add_compile_definitions(CST_NO_WEBUI=1)
endif()
if(WIN32)
# MinGW has no <regex.h>: musl's TRE engine, UTF-8 aware (vendor/tre-regex)
include_directories(vendor/tre-regex)
list(APPEND CST_CORE_SOURCES
set(_CST_TRE_SOURCES
vendor/tre-regex/regcomp.c vendor/tre-regex/regexec.c
vendor/tre-regex/regerror.c vendor/tre-regex/tre-mem.c)
list(APPEND CST_CORE_SOURCES ${_CST_TRE_SOURCES})
# Upstream code, kept as is: CST_WIN_CFLAGS=-Werror must not apply to it.
set_source_files_properties(${_CST_TRE_SOURCES} PROPERTIES COMPILE_OPTIONS "-w")
endif()
set(CST_SOURCES ${CST_CORE_SOURCES} src/main.c)
# --- the engine as a library ---------------------------------------------
# cstcore is the core without main()/TUI: the CLI links it and the Qt front
# end in app/ (CST_BUILD_APP) embeds the very same objects in-process, so the
# engine is compiled once per build instead of once per front end.
add_library(cstcore STATIC ${CST_CORE_SOURCES})
add_dependencies(cstcore sashidown)
target_include_directories(cstcore PUBLIC
"${CMAKE_CURRENT_SOURCE_DIR}/include"
"${SD_DIR}/include"
"${CJSON_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/vendor/monocypher"
)
set_source_files_properties(
vendor/monocypher/monocypher.c
vendor/monocypher/monocypher-ed25519.c
PROPERTIES COMPILE_OPTIONS "-w")
target_compile_definitions(cstcore PRIVATE _GNU_SOURCE)
if(WIN32)
target_compile_definitions(cstcore PRIVATE _WIN32_WINNT=0x0A00)
target_link_libraries(cstcore PUBLIC
"${SASHIDOWN_A}" CURL::libcurl Threads::Threads
ws2_32 crypt32 secur32 bcrypt advapi32 user32)
else()
target_compile_definitions(cstcore PRIVATE _XOPEN_SOURCE_EXTENDED)
target_link_libraries(cstcore PUBLIC
"${SASHIDOWN_A}" CURL::libcurl Threads::Threads m)
endif()
if(CST_BUILD_APP)
add_subdirectory(app)
endif()
set(CST_SOURCES src/main.c)
if(CST_BUILD_TUI)
list(APPEND CST_SOURCES src/textsel.c src/tui.c)
@@ -141,6 +258,7 @@ else()
endif()
add_executable(cst-agent ${CST_SOURCES})
set_target_properties(cst-agent PROPERTIES OUTPUT_NAME hermit)
add_dependencies(cst-agent sashidown)
cst_win_exe(cst-agent)
@@ -155,14 +273,8 @@ if(NOT WIN32)
target_compile_definitions(cst-agent PRIVATE _XOPEN_SOURCE_EXTENDED)
endif()
target_link_libraries(cst-agent PRIVATE
"${SASHIDOWN_A}"
CURL::libcurl
Threads::Threads
)
if(NOT WIN32)
target_link_libraries(cst-agent PRIVATE m)
endif()
# cstcore carries sashidown, curl, threads and libm as usage requirements.
target_link_libraries(cst-agent PRIVATE cstcore)
set(CST_WIN_CURSES "ncurses" CACHE STRING "Windows TUI backend: ncurses or pdcurses")
set_property(CACHE CST_WIN_CURSES PROPERTY STRINGS ncurses pdcurses)
@@ -231,7 +343,7 @@ endif()
enable_testing()
set(_CST_SMALL_TESTS test_ctl_frontier test_ctl_heredoc test_json_baseline
test_replay_starvation test_replay_real test_mm_tool test_textsel
test_markdown)
test_pdf_text test_markdown)
foreach(t ${_CST_SMALL_TESTS})
if(t STREQUAL test_textsel)
add_executable(${t} tests/${t}.c src/textsel.c src/os_compat.c src/os_win.c
@@ -239,6 +351,12 @@ foreach(t ${_CST_SMALL_TESTS})
if(WIN32)
target_link_libraries(${t} PRIVATE advapi32 user32)
endif()
elseif(t STREQUAL test_pdf_text)
add_executable(${t} tests/${t}.c src/pdf_text.c src/os_compat.c src/os_win.c
src/util.c)
if(WIN32)
target_link_libraries(${t} PRIVATE advapi32 user32)
endif()
elseif(t STREQUAL test_markdown)
add_executable(${t} tests/${t}.c)
target_include_directories(${t} PRIVATE "${SD_DIR}/include")
@@ -262,27 +380,35 @@ foreach(t ${_CST_SMALL_TESTS})
target_include_directories(${t} PRIVATE include "${CJSON_DIR}")
target_compile_definitions(${t} PRIVATE _GNU_SOURCE)
if(NOT WIN32)
target_link_libraries(${t} PRIVATE m)
target_link_libraries(${t} PRIVATE m Threads::Threads)
endif()
cst_win_exe(${t})
add_test(NAME ${t} COMMAND ${t} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
endforeach()
# Tests that link the whole core (no TUI).
foreach(t test_llm_body test_prefix_stable test_sse_decode test_apply_patch
test_session_roundtrip test_attach
test_shell test_diff test_tools_fs test_registry
test_undo test_config test_models test_model_registry test_sandbox
test_keymap test_shell_compact test_skills
test_plugins test_mcp test_subagent test_lowil
test_win_utf8 test_os_dir test_tmpdir)
add_executable(${t} tests/${t}.c ${CST_CORE_SOURCES})
target_include_directories(${t} PRIVATE include "${CJSON_DIR}")
set(_CST_CORE_TESTS test_llm_body test_prefix_stable test_sse_decode
test_apply_patch test_session_roundtrip test_store test_attach
test_artifacts
test_shell test_diff test_tools_fs test_tools_ext test_registry
test_undo test_config test_models test_model_registry test_sandbox
test_keymap test_shell_compact test_skills
test_plugins test_mcp test_subagent test_runtime test_realm test_discover
test_peer_auth test_parliament test_lowil
test_win_utf8 test_os_dir test_tmpdir
test_tool_meta test_embed)
if(CST_BUILD_WEBUI)
# test_webui drives the real server; the stub has nothing to test.
list(APPEND _CST_CORE_TESTS test_webui)
endif()
foreach(t ${_CST_CORE_TESTS})
# Link the shared cstcore archive instead of recompiling every core .c.
add_executable(${t} tests/${t}.c)
target_include_directories(${t} PRIVATE include "${CJSON_DIR}" "${SD_DIR}/include")
target_compile_definitions(${t} PRIVATE _GNU_SOURCE)
target_link_libraries(${t} PRIVATE CURL::libcurl Threads::Threads)
if(NOT WIN32)
target_link_libraries(${t} PRIVATE m)
else()
target_link_libraries(${t} PRIVATE cstcore)
add_dependencies(${t} sashidown)
if(WIN32)
target_link_libraries(${t} PRIVATE ws2_32 crypt32 secur32 bcrypt advapi32 user32)
endif()
cst_win_exe(${t})
@@ -302,9 +428,22 @@ endif()
if(WIN32)
install(TARGETS cst-agent RUNTIME DESTINATION .)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-icons.ttf")
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-icons.ttf" DESTINATION .)
endif()
else()
include(GNUInstallDirs)
install(TARGETS cst-agent RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-icons.ttf")
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-icons.ttf"
DESTINATION ${CMAKE_INSTALL_DATADIR}/hermit)
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-icons.ttf"
DESTINATION ${CMAKE_INSTALL_DATADIR}/fonts/hermit)
endif()
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-frames")
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/res/hermit-frames/"
DESTINATION ${CMAKE_INSTALL_DATADIR}/hermit/frames)
endif()
endif()
message(STATUS "Compiler: ${CMAKE_C_COMPILER_ID} ${CMAKE_C_COMPILER}")
+104
View File
@@ -0,0 +1,104 @@
# 从 CST-Agent 迁移到 Hermit
**本仓库 `WHC/CST-agent` 保留为兼容入口。** 产品名与规范克隆地址已改为:
**https://git.whcself.xyz/WHC/Hermit**
二进制、配置与环境变量自 **0.10.0** 起以 Hermit 为准;`CST-agent` 仓库与旧包名仅作过渡。
---
## 1. 换源码远程(推荐)
已有检出:
```bash
# 一键(在仓库根目录)
./scripts/migrate_remote_to_hermit.sh
# 或手动
git remote set-url origin https://git.whcself.xyz/WHC/Hermit.git
git fetch origin
git branch -u origin/main
```
新克隆:
```bash
git clone https://git.whcself.xyz/WHC/Hermit.git
cd Hermit
make -j$(nproc) && make install PREFIX=$HOME/.local
```
旧地址仍可拉代码一段时间:
```bash
git clone https://git.whcself.xyz/WHC/CST-agent.git # 兼容;请改 origin 到 Hermit
```
---
## 2. 二进制与 PATH
| 旧 | 新 |
|---|---|
| `cst-agent` | `hermit`(安装时仍提供 `cst-agent` → `hermit` 软链) |
| `cst-agent-update` | → `hermit-update`(软链;议会助手 → `hermit-service`) |
| Release `cst-agent-VERSION-linux-*.tar.gz` | `hermit-VERSION-linux-*.tar.gz`(过渡期可能双发) |
```bash
hermit --version # hermit 1.0.x
hermit-update # 升级;兼容名 cst-agent-update
cst-agent --version # 同二进制(软链)
```
---
## 3. 配置目录
| 旧 | 新 |
|---|---|
| `~/.config/cst-agent/` | `~/.config/hermit/` |
| Windows `%APPDATA%\cst-agent` | `%APPDATA%\hermit` |
程序若发现 **仅有** 旧目录、尚无新目录,会继续读旧路径。建议主动迁移:
```bash
# Linux / macOS
mkdir -p ~/.config/hermit
# 若尚未迁过:
cp -a ~/.config/cst-agent/. ~/.config/hermit/ 2>/dev/null || true
```
工作区 `.agent/` 会话目录**不变**,无需改动。
---
## 4. 环境变量
`HERMIT_*` 优先;未设置时仍读 `CST_*`。
| 用途 | 新 | 旧(兼容) |
|---|---|---|
| Provider / Key / Model | `HERMIT_PROVIDER` 等 | `CST_PROVIDER` 等 |
| ASCII / Icons | `HERMIT_ASCII` / `HERMIT_ICONS` | `CST_ASCII` / `CST_ICONS` |
| 议会密码等 | `HERMIT_REALM_PASSWORD`(若已接双读) | `CST_REALM_PASSWORD` |
systemd:`EnvironmentFile` 已同时尝试 `~/.config/hermit/parliament.env` 与旧路径。
---
## 5. CI / 脚本 / 文档链接
- 安装脚本、bootstrap、文档中的规范 URL 改为 `…/WHC/Hermit`。
- 本文件与 README 顶栏是 **CST-agent 仓库上的最后一次迁移说明**;后续功能请在 **Hermit** 仓库跟进。
---
## 6. 核对清单
- [ ] `git remote -v` 指向 `WHC/Hermit.git`
- [ ] `hermit --version` 正常;PATH 上可选保留 `cst-agent` 软链
- [ ] `~/.config/hermit/` 有 credentials / settings(或确认仍在用旧目录回退)
- [ ] 书签 / 镜像 / CI 的 clone URL 已更新
- [ ](可选)归档或只读化 `CST-agent` 仓库说明,避免双主开发
+251 -51
View File
@@ -2,11 +2,23 @@ CC ?= gcc
CFLAGS ?= -std=c11 -Wall -Wextra -O2 -g
SD_DIR := vendor/sashidown
CJSON_DIR := vendor/cjson
MONO_DIR := vendor/monocypher
PKG_CONFIG ?= pkg-config
PREFIX ?= /usr/local
DESTDIR ?=
UNAME_S := $(shell uname -s 2>/dev/null)
UNAME_O := $(shell uname -o 2>/dev/null)
comma := ,
# Optional ccache: USE_CCACHE=1 forces it; USE_CCACHE=0 disables; else auto.
USE_CCACHE ?= auto
ifeq ($(USE_CCACHE),1)
CC := $(shell command -v ccache >/dev/null && echo "ccache $(CC)" || echo "$(CC)")
else ifeq ($(USE_CCACHE),auto)
ifneq ($(findstring ccache,$(CC)),ccache)
CC := $(shell command -v ccache >/dev/null && echo "ccache $(CC)" || echo "$(CC)")
endif
endif
# Android (Termux): pthreads live in libc.
PTHREAD_LIBS := -lpthread
@@ -26,6 +38,15 @@ CPPFLAGS += -D_DARWIN_C_SOURCE
endif
PKGC = $(PKG_ENV) $(PKG_CONFIG)
# STATIC=1: fully static link (the musl release builds).
STATIC ?= 0
LINK_STATIC :=
ifeq ($(STATIC),1)
PKGC += --static
LINK_STATIC := -static
endif
LDFLAGS += $(LINK_STATIC)
# Wide-character curses: ncursesw, else ncurses (macOS/BSD build it wide).
CURSES_PC := $(shell for p in ncursesw ncurses; do $(PKGC) --exists $$p 2>/dev/null && { echo $$p; exit 0; }; done)
ifneq ($(CURSES_PC),)
@@ -43,15 +64,47 @@ ifeq ($(strip $(CURL_LIBS)),)
CURL_LIBS := -lcurl
endif
# WebUI (HTTP + SSE front end): src/net.c src/http_srv.c src/web_md.c
# src/webui.c. CST_WEBUI=0 swaps in the stub (--web then prints a hint).
CST_WEBUI ?= 1
PKG_CFLAGS := $(CURL_CFLAGS) $(CURSES_CFLAGS)
PKG_LIBS := $(CURL_LIBS) $(CURSES_LIBS)
CPPFLAGS += -Iinclude -I.gen -I$(SD_DIR)/include -I$(CJSON_DIR) -D_XOPEN_SOURCE_EXTENDED $(PKG_CFLAGS)
# Upstream Monocypher: keep -Werror builds green without patching the vendor.
$(MONO_DIR)/monocypher.o $(MONO_DIR)/monocypher-ed25519.o: %.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -w -c -o $@ $<
# tcc writes no rpath of its own, so shared libs found via pkg-config -L
# (Nix store, /opt prefixes) would not load at run time.
RPATH_LIBS :=
ifneq ($(findstring tcc,$(notdir $(CC))),)
ifneq ($(STATIC),1)
RPATH_LIBS := $(patsubst -L%,-Wl$(comma)-rpath$(comma)%,$(filter -L%,$(PKG_LIBS)))
endif
endif
# Keep POSIX declarations visible for shared test helpers (notably symlink()).
CPPFLAGS += -Iinclude -I.gen -I$(SD_DIR)/include -I$(CJSON_DIR) -I$(MONO_DIR) \
-D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE_EXTENDED $(PKG_CFLAGS)
LDFLAGS += -L$(SD_DIR)
LDLIBS += -lsashidown -lm $(PKG_LIBS) $(PTHREAD_LIBS)
LDLIBS += -lsashidown -lm $(PKG_LIBS) $(PTHREAD_LIBS) $(RPATH_LIBS)
WEB_DIR := web
WEB_ASSETS := $(wildcard $(WEB_DIR)/*.html) $(wildcard $(WEB_DIR)/*.js) \
$(wildcard $(WEB_DIR)/*.css) $(wildcard $(WEB_DIR)/*.svg)
ifeq ($(CST_WEBUI),0)
WEB_SRC := src/net.c src/http_srv.c src/web_md.c src/webui_stub.c
# The stub body is guarded by this, so the switch has to define it too.
CPPFLAGS += -DCST_NO_WEBUI=1
else
WEB_SRC := src/net.c src/http_srv.c src/web_md.c src/webui.c
endif
CORE_SRC = \
$(CJSON_DIR)/cJSON.c \
$(MONO_DIR)/monocypher.c \
$(MONO_DIR)/monocypher-ed25519.c \
src/util.c \
src/ctl_parse.c \
src/os_compat.c \
@@ -61,13 +114,16 @@ CORE_SRC = \
src/keymap.c \
src/skills.c \
src/extensions.c src/plugins.c src/mcp.c src/subagent.c src/attach.c src/clipboard.c \
src/session.c \
src/pdf_text.c \
src/session.c src/runtime.c src/worktree.c src/realm.c src/discover.c \
src/peer_auth.c src/parliament.c src/parliament_daemon.c src/parliament_cli.c \
src/tools/tools.c \
src/tools/patch.c \
src/tools/registry.c \
src/tools/fs_tools.c \
src/tools/agent_tools.c \
src/tools/web.c \
src/tools/session_tools.c \
src/tools/diff.c \
src/undo.c \
src/permissions.c \
@@ -76,15 +132,22 @@ CORE_SRC = \
src/agent_loop.c \
src/agent_store.c \
src/json_baseline.c \
src/creds.c \
src/creds.c src/provider_switch.c \
src/mm_tool.c \
src/models.c src/model_registry.c \
src/metrics.c
src/metrics.c \
src/hermit_glyph.c \
$(WEB_SRC)
SRC = $(CORE_SRC) src/textsel.c src/tui.c src/main.c
OBJ = $(SRC:.c=.o)
HDRS = $(wildcard include/*.h) $(wildcard src/tools/*.h) $(CJSON_DIR)/cJSON.h \
.gen/models_builtin.inc
# The core as a static library: what the Qt app embeds in-process (app/), so
# the GUI links the same engine the CLI/TUI/WebUI run. No TUI, no main.
CORE_OBJ = $(CORE_SRC:.c=.o)
CST_CORE_LIB = libcstcore.a
# Generated embeds; per-file .d files (from -MMD) track the rest.
GEN_INCS = .gen/models_builtin.inc .gen/web_assets.inc
DEPFILES = $(OBJ:.o=.d)
TESTS = \
tests/test_ctl_frontier \
@@ -98,11 +161,17 @@ TESTS = \
tests/test_sse_decode \
tests/test_apply_patch \
tests/test_session_roundtrip \
tests/test_store \
tests/test_attach \
tests/test_artifacts \
tests/test_pdf_text \
tests/test_shell \
tests/test_diff \
tests/test_tools_fs \
tests/test_tools_ext \
tests/test_registry \
tests/test_tool_meta \
tests/test_embed \
tests/test_undo \
tests/test_config \
tests/test_models \
@@ -116,94 +185,225 @@ TESTS = \
tests/test_plugins \
tests/test_mcp \
tests/test_subagent \
tests/test_runtime \
tests/test_prompt_contract \
tests/test_realm \
tests/test_discover \
tests/test_peer_auth \
tests/test_parliament \
tests/test_lowil \
tests/test_win_utf8 \
tests/test_os_dir \
tests/test_tmpdir
# test_webui drives the real server; there is nothing to test with the stub.
ifneq ($(CST_WEBUI),0)
TESTS += tests/test_webui
endif
TEST_LIBS = -lm $(CURL_LIBS) $(PTHREAD_LIBS)
TEST_SYS_LIBS = -lm $(PTHREAD_LIBS) $(LINK_STATIC)
TEST_LIBS = -L$(SD_DIR) -lsashidown $(CURL_LIBS) $(RPATH_LIBS) $(TEST_SYS_LIBS)
# cst_test_util.h has static os_* helpers; gcc drops them when unused, tcc
# keeps them, so the small tests link the OS layer too.
TEST_OS_SRC = src/os_compat.c src/os_win.c src/util.c
# hermit_getenv is in os_compat.c (HERMIT_/CST_ dual env).
.PHONY: all clean check demo sashidown-lib FORCE cmake-gcc cmake-clang asan install uninstall
.PHONY: all clean check demo sashidown-lib cmake-gcc cmake-clang asan install \
uninstall install-service help hermit-font cst-agent
all: sashidown-lib cst-agent
all: sashidown-lib hermit $(CST_CORE_LIB)
# Compat alias: many scripts still say `make cst-agent`.
cst-agent: hermit
help:
@echo "Hermit build targets (prefer: make -j\$$(nproc))"
@echo " all / hermit incremental build (ccache auto if installed)"
@echo " check build + run unit tests"
@echo " asan AddressSanitizer rebuild + check"
@echo " hermit-font bake PNG frames + hermit-icons.ttf (Pillow+fonttools)"
@echo " install PREFIX=$(PREFIX); hermit + font + cst-agent symlink"
@echo " install-service systemd --user parliament unit"
@echo "Env: USE_CCACHE=0|1|auto STATIC=1 CST_WEBUI=0 CC=tcc"
@echo " HERMIT_ICONS=auto|mini|font HERMIT_*/CST_* env"
@echo "Release: scripts/package_linux.sh ARCH | scripts/ci_windows_cross.sh"
@echo "Fast install: scripts/bootstrap_linux.sh --release"
$(CST_CORE_LIB): $(CORE_OBJ)
rm -f $@
$(AR) rcs $@ $(CORE_OBJ)
cmake-gcc:
cmake -B build-gcc -DCMAKE_C_COMPILER=gcc -DCST_BUILD_TUI=ON
cmake --build build-gcc
ctest --test-dir build-gcc --output-on-failure
cmake --build build-gcc -j
ctest --test-dir build-gcc --output-on-failure -j
cmake-clang:
cmake -B build-clang -DCMAKE_C_COMPILER=clang -DCST_BUILD_TUI=ON
cmake --build build-clang
cmake --build build-clang -j
sashidown-lib: $(SD_DIR)/libsashidown.a
# The sub-make decides whether the archive is stale; FORCE only makes sure it
# is asked, and -j builds wait for it before linking.
$(SD_DIR)/libsashidown.a: FORCE
# Always ask the sub-make; it no-ops when libsashidown.a is current.
sashidown-lib:
$(MAKE) -C $(SD_DIR) libsashidown.a
FORCE:
cst-agent: $(OBJ) $(SD_DIR)/libsashidown.a
hermit: $(OBJ) sashidown-lib
$(CC) $(CFLAGS) -o $@ $(OBJ) $(LDFLAGS) $(LDLIBS)
@ln -sfr $@ cst-agent 2>/dev/null || ln -sf hermit cst-agent
hermit-font:
@python3 scripts/build_hermit_font.py || \
echo "hermit-font: skipped (need Pillow+fonttools; try: nix-shell -p python3Packages.pillow python3Packages.fonttools)"
# Built-in model data as a C byte list (included by model_registry.c).
.gen/models_builtin.inc: src/models_builtin.json
@mkdir -p .gen
od -An -v -tx1 $< | sed 's/\([0-9a-f][0-9a-f]\)/0x\1,/g' > $@.tmp && mv $@.tmp $@
%.o: %.c $(HDRS)
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
# The WebUI shell is embedded the same way, one array per file.
.gen/web_assets.inc: $(WEB_ASSETS) scripts/embed_web.sh
@mkdir -p .gen
@sh scripts/embed_web.sh $@ $(WEB_DIR)
src/tui.o: src/tui.c $(HDRS) $(SD_DIR)/include/sashidown.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
# Incremental rebuilds: -MMD tracks real includes instead of every header.
COMPILE_C = $(CC) $(CFLAGS) $(CPPFLAGS) -MMD -MP -c -o $@ $<
tests/test_ctl_frontier: tests/test_ctl_frontier.c src/ctl_parse.c include/ctl.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_frontier.c src/ctl_parse.c
%.o: %.c
$(COMPILE_C)
tests/test_ctl_heredoc: tests/test_ctl_heredoc.c src/ctl_parse.c include/ctl.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_heredoc.c src/ctl_parse.c
src/model_registry.o: .gen/models_builtin.inc
src/webui.o: .gen/web_assets.inc
src/tui.o: $(SD_DIR)/include/sashidown.h
tests/test_json_baseline: tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(HDRS)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c -lm
tests/test_ctl_frontier: tests/test_ctl_frontier.c src/ctl_parse.c include/ctl.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_frontier.c src/ctl_parse.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_replay_starvation: tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c -lm
tests/test_ctl_heredoc: tests/test_ctl_heredoc.c src/ctl_parse.c include/ctl.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_heredoc.c src/ctl_parse.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_replay_real: tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c -lm
tests/test_json_baseline: tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_json_baseline.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_mm_tool: tests/test_mm_tool.c src/mm_tool.c include/mm_tool.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_mm_tool.c src/mm_tool.c
tests/test_replay_starvation: tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_textsel: tests/test_textsel.c src/textsel.c src/os_compat.c src/os_win.c src/util.c include/cst_textsel.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_textsel.c src/textsel.c src/os_compat.c src/os_win.c src/util.c
tests/test_replay_real: tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_real.c src/ctl_parse.c src/json_baseline.c $(CJSON_DIR)/cJSON.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_mm_tool: tests/test_mm_tool.c src/mm_tool.c include/mm_tool.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_mm_tool.c src/mm_tool.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_textsel: tests/test_textsel.c src/textsel.c $(TEST_OS_SRC) include/cst_textsel.h
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_textsel.c src/textsel.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_pdf_text: tests/test_pdf_text.c src/pdf_text.c include/cst_pdf.h $(TEST_OS_SRC)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_pdf_text.c src/pdf_text.c $(TEST_OS_SRC) $(TEST_SYS_LIBS)
tests/test_markdown: tests/test_markdown.c $(SD_DIR)/libsashidown.a
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_markdown.c $(LDFLAGS) -lsashidown -lm
tests/test_%: tests/test_%.c $(CORE_SRC) $(HDRS)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $< $(CORE_SRC) $(TEST_LIBS)
# Core tests reuse libcstcore.a — avoid recompiling ~35 .c files per binary.
# Do not depend on the phony sashidown-lib target or every test relinks each check.
tests/test_%: tests/test_%.c $(CST_CORE_LIB) $(SD_DIR)/libsashidown.a
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $< $(CST_CORE_LIB) $(TEST_LIBS)
check: $(TESTS)
$(SD_DIR)/libsashidown.a: sashidown-lib
# Build test binaries with make -j; run them one-by-one for readable logs.
check: sashidown-lib $(TESTS)
@set -e; for t in $(TESTS); do echo "== $$t"; ./$$t; done
# AddressSanitizer + UBSan build of the agent and all tests.
# AddressSanitizer + UBSan rebuild (clears objects so sanitizer flags apply).
asan:
$(MAKE) clean
$(MAKE) sashidown-lib
$(MAKE) CFLAGS="-std=c11 -Wall -Wextra -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer" cst-agent check
$(MAKE) CFLAGS="-std=c11 -Wall -Wextra -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer" \
sashidown-lib hermit check
demo: cst-agent
./cst-agent --demo-ctl --workspace .
demo: hermit
./hermit --demo-ctl --workspace .
clean:
rm -f $(OBJ) cst-agent $(TESTS) .gen/models_builtin.inc
rm -f $(OBJ) $(DEPFILES) hermit cst-agent $(CST_CORE_LIB) $(TESTS) \
.gen/models_builtin.inc .gen/web_assets.inc
install: cst-agent
# Absolute checkout path for hermit-update (survives cd). Override with HERMIT_SRC.
HERMIT_SRC ?= $(abspath .)
install: hermit
install -d "$(DESTDIR)$(PREFIX)/bin"
install -m 0755 cst-agent "$(DESTDIR)$(PREFIX)/bin/cst-agent"
install -m 0755 hermit "$(DESTDIR)$(PREFIX)/bin/hermit"
ln -sfr "$(DESTDIR)$(PREFIX)/bin/hermit" "$(DESTDIR)$(PREFIX)/bin/cst-agent" 2>/dev/null || \
ln -sf hermit "$(DESTDIR)$(PREFIX)/bin/cst-agent"
@# hermit-update / hermit-service (cst-* compat symlinks)
@printf '%s\n' '#!/usr/bin/env bash' \
'export HERMIT_PREFIX="$${HERMIT_PREFIX:-$${CST_AGENT_PREFIX:-$(PREFIX)}}"' \
'export CST_AGENT_PREFIX="$$HERMIT_PREFIX"' \
'export HERMIT_DIR="$${HERMIT_DIR:-$${CST_AGENT_DIR:-$(HERMIT_SRC)}}"' \
'export CST_AGENT_DIR="$$HERMIT_DIR"' \
'exec bash "$$HERMIT_DIR/scripts/bootstrap_linux.sh" "$$HERMIT_DIR" "$$@"' \
> "$(DESTDIR)$(PREFIX)/bin/hermit-update"
@chmod 0755 "$(DESTDIR)$(PREFIX)/bin/hermit-update"
@ln -sfr "$(DESTDIR)$(PREFIX)/bin/hermit-update" "$(DESTDIR)$(PREFIX)/bin/cst-agent-update" 2>/dev/null || \
ln -sf hermit-update "$(DESTDIR)$(PREFIX)/bin/cst-agent-update"
@printf '%s\n' '#!/usr/bin/env bash' \
'set -euo pipefail' \
'BIN="$(PREFIX)/bin/hermit"' \
'cmd="$${1:-status}"' \
'case "$$cmd" in' \
'status) "$$BIN" --version; if command -v systemctl >/dev/null 2>&1 && systemctl --user is-active hermit-parliament.service >/dev/null 2>&1; then systemctl --user status hermit-parliament.service --no-pager; elif command -v systemctl >/dev/null 2>&1 && systemctl --user is-active cst-agent-parliament.service >/dev/null 2>&1; then systemctl --user status cst-agent-parliament.service --no-pager; else "$$BIN" --service-stop >/dev/null 2>&1 || true; echo "parliament service: not managed by systemd --user"; fi ;;' \
'install-unit) make -C "$(HERMIT_SRC)" install-service PREFIX="$(PREFIX)" ;;' \
'start) systemctl --user start hermit-parliament.service 2>/dev/null || systemctl --user start cst-agent-parliament.service ;;' \
'stop) systemctl --user stop hermit-parliament.service 2>/dev/null || true; systemctl --user stop cst-agent-parliament.service 2>/dev/null || true; "$$BIN" --service-stop || true ;;' \
'restart) systemctl --user restart hermit-parliament.service 2>/dev/null || systemctl --user restart cst-agent-parliament.service ;;' \
'*) echo "usage: hermit-service {status|install-unit|start|stop|restart}" >&2; exit 2 ;;' \
'esac' \
> "$(DESTDIR)$(PREFIX)/bin/hermit-service"
@chmod 0755 "$(DESTDIR)$(PREFIX)/bin/hermit-service"
@ln -sfr "$(DESTDIR)$(PREFIX)/bin/hermit-service" "$(DESTDIR)$(PREFIX)/bin/cst-agent-service" 2>/dev/null || \
ln -sf hermit-service "$(DESTDIR)$(PREFIX)/bin/cst-agent-service"
@if [ ! -f res/hermit-icons.ttf ]; then $(MAKE) hermit-font || true; fi
@if [ -f res/hermit-icons.ttf ]; then \
install -d "$(DESTDIR)$(PREFIX)/share/hermit"; \
install -d "$(DESTDIR)$(PREFIX)/share/fonts/hermit"; \
install -m 0644 res/hermit-icons.ttf "$(DESTDIR)$(PREFIX)/share/hermit/hermit-icons.ttf"; \
install -m 0644 res/hermit-icons.ttf "$(DESTDIR)$(PREFIX)/share/fonts/hermit/hermit-icons.ttf"; \
if [ -n "$(HOME)" ] && [ "$(DESTDIR)" = "" ]; then \
install -d "$(HOME)/.local/share/fonts"; \
install -m 0644 res/hermit-icons.ttf "$(HOME)/.local/share/fonts/hermit-icons.ttf"; \
command -v fc-cache >/dev/null 2>&1 && fc-cache -f "$(HOME)/.local/share/fonts" >/dev/null 2>&1 || true; \
fi; \
echo "installed Hermit Icons → $(PREFIX)/share/fonts/hermit/hermit-icons.ttf"; \
else \
echo "warning: res/hermit-icons.ttf missing (run: make hermit-font)" >&2; \
fi
@if [ -d res/hermit-frames ]; then \
install -d "$(DESTDIR)$(PREFIX)/share/hermit/frames"; \
cp -a res/hermit-frames/. "$(DESTDIR)$(PREFIX)/share/hermit/frames/"; \
fi
@echo "installed hermit-update → $(PREFIX)/bin/hermit-update"
# Optional systemd --user unit for the parliament seat service.
install-service: install
install -d "$(DESTDIR)$(HOME)/.config/systemd/user"
sed -e 's|@BIN@|$(PREFIX)/bin/hermit|g' \
scripts/hermit-parliament.service.in \
> "$(DESTDIR)$(HOME)/.config/systemd/user/hermit-parliament.service"
ln -sfr "$(DESTDIR)$(HOME)/.config/systemd/user/hermit-parliament.service" \
"$(DESTDIR)$(HOME)/.config/systemd/user/cst-agent-parliament.service" 2>/dev/null || \
ln -sf hermit-parliament.service \
"$(DESTDIR)$(HOME)/.config/systemd/user/cst-agent-parliament.service"
@echo "Installed user unit. Enable with:"
@echo " systemctl --user daemon-reload"
@echo " systemctl --user enable --now hermit-parliament.service"
@echo "(set HERMIT_/CST_ REALM_PASSWORD / INSTANCE_ID in the drop-in or environment)"
uninstall:
rm -f "$(DESTDIR)$(PREFIX)/bin/cst-agent"
rm -f "$(DESTDIR)$(PREFIX)/bin/hermit" "$(DESTDIR)$(PREFIX)/bin/cst-agent"
rm -f "$(DESTDIR)$(PREFIX)/bin/hermit-update" "$(DESTDIR)$(PREFIX)/bin/cst-agent-update"
rm -f "$(DESTDIR)$(PREFIX)/bin/hermit-service" "$(DESTDIR)$(PREFIX)/bin/cst-agent-service"
rm -f "$(DESTDIR)$(PREFIX)/share/hermit/hermit-icons.ttf"
rm -f "$(DESTDIR)$(PREFIX)/share/fonts/hermit/hermit-icons.ttf"
rm -rf "$(DESTDIR)$(PREFIX)/share/hermit/frames"
rm -f "$(HOME)/.local/share/fonts/hermit-icons.ttf"
rm -f "$(HOME)/.config/systemd/user/hermit-parliament.service"
rm -f "$(HOME)/.config/systemd/user/cst-agent-parliament.service"
-include $(DEPFILES)
+56 -403
View File
@@ -1,441 +1,94 @@
# CST-Agent
# Hermit
C11 OpenCode-like carrier that extends paper **CST** (confirmation frontier / irreversible emission) from Markdown→HTML to the **agent tool loop**.
> **仓库已更名。** 规范地址:[WHC/Hermit](https://git.whcself.xyz/WHC/Hermit)。
> 本仓库 `CST-agent` 仅作迁移兼容入口。换远程:`./scripts/migrate_remote_to_hermit.sh`
> 完整步骤:[MIGRATION.md](MIGRATION.md)。
See [docs/theory_tool_cst.md](docs/theory_tool_cst.md).
评测/反哺论文素材:[docs/eval_tool_cst.md](docs/eval_tool_cst.md)。
本地 coding agent(原 CST-Agent):终端 TUI、可选 WebUI / 桌面 GUI,在工作区里读改文件、跑命令、管会话。
C11 实现,OpenAI 兼容网关(DeepSeek / Kimi / MiniMax / OpenAI 等)。
## 能不能用来工作?
**适合**:有监督的本地改动与仓库探索(权限确认、diff、`/undo`、沙箱)。
**慎用**:完全无人值守的长任务;headless 默认自动批准。
**可以**:有监督的本地改动 / 探索仓库(TUI + 13 个内置工具 + 带 diff 的权限确认 + `/undo`)。
**不宜**:无人值守长任务或当 CI 主力(网关偶发空答;headless 模式默认自动批准)。
文档索引:[docs/README.md](docs/README.md)。
### 5 分钟试用
兼容:安装后提供 `cst-agent` → `hermit` 软链;环境变量 `HERMIT_*` 优先,仍接受 `CST_*`;配置目录优先 `~/.config/hermit`,若无则回退 `~/.config/cst-agent`。
---
## 安装
### Linux / WSL / macOS
```bash
# Linux / WSL / macOS 一键:克隆到 ~/CST-agent、编译、装到 ~/.local/bin
curl -fsSL https://git.whcself.xyz/WHC/CST-agent/raw/branch/main/scripts/bootstrap_linux.sh | bash
# 预编译包(快;失败则回退源码)— 规范仓库 Hermit
curl -fsSL https://git.whcself.xyz/WHC/Hermit/raw/branch/main/scripts/bootstrap_linux.sh | bash -s -- --release
# 已有仓库目录内(装到别处:CST_AGENT_PREFIX=/usr/local)
# 源码增量编译 → ~/.local/bin/hermit(+ cst-agent 软链)
curl -fsSL https://git.whcself.xyz/WHC/Hermit/raw/branch/main/scripts/bootstrap_linux.sh | bash
```
```bash
./scripts/bootstrap_linux.sh .
# 以后升级:拉取最新代码、重新编译并安装(本地有未提交改动时跳过 pull)
cst-agent-update
cst-agent --version
# 在项目目录里直接启动:首次会让你选 provider 并输入 API key(遮罩输入,按 provider 保存)
cd ~/my-project && cst-agent
hermit --version # hermit 1.0.x
hermit-update # 升级(源码或 --release);兼容 cst-agent-update
./scripts/migrate_remote_to_hermit.sh # 已有 CST-agent 检出时改 origin
```
Windows 10 1903+(PowerShell,不需要管理员):
[Release](https://git.whcself.xyz/WHC/Hermit/releases)(旧 [CST-agent releases](https://git.whcself.xyz/WHC/CST-agent/releases) 过渡期可能仍有镜像):`hermit-VERSION-linux-{x86_64,x86,aarch64}.tar.gz`。
```powershell
irm https://git.whcself.xyz/WHC/CST-agent/raw/branch/main/scripts/install_windows.ps1 | iex
# 新开终端后:cd 到项目目录运行 cst-agent;升级用 cst-agent-update
```
### Windows
详见 [docs/README-windows.md](docs/README-windows.md)。
见 [docs/README-windows.md](docs/README-windows.md)(产物名逐步改为 `hermit-…`;旧 `cst-agent-…` 包过渡期可能仍有)。
一键脚本可以重复运行:已有仓库会 `git pull --ff-only`,代码有更新时干净重编,然后重新安装;
同时装一个 `cst-agent-update` 命令(等同重跑脚本)。NixOS 上会自动进 `nix-shell` 编译。
之后再启动会沿用上次的 provider、模型和推理强度(low / medium / high / max),不需要任何参数或环境变量。
界面里用 `/provider` 切换(没保存过 key 的会当场询问),`/model`、`/effort` 切换模型和推理强度,`/key` 更换 key。
完整环境变量说明:[docs/env_openai.md](docs/env_openai.md)。
| 平台 | 一键脚本 |
|---|---|
| Linux | [`scripts/bootstrap_linux.sh`](scripts/bootstrap_linux.sh) |
| Termux | [`scripts/bootstrap_termux.sh`](scripts/bootstrap_termux.sh) |
| Windows 安装 / 升级 | [`scripts/install_windows.ps1`](scripts/install_windows.ps1)(从 Release 安装),之后 `cst-agent-update` |
| Windows 交叉构建(在 Linux 上) | [`scripts/bootstrap_windows.sh`](scripts/bootstrap_windows.sh) → `dist/windows-x86_64/` |
| Windows 原生构建(MSYS2 UCRT64) | [`scripts/bootstrap_msys2.sh`](scripts/bootstrap_msys2.sh) → `dist/windows-x86_64/` |
### 迷你验收工程(论文案例)
故意带 bug 的小计算器:[`fixtures/mini_calc/`](fixtures/mini_calc/)(任务书 `TASK.md`)。
### 第一次用
```bash
./scripts/e2e_mini_calc.sh --baseline-only # 无 API:证明初始测试 RED
./scripts/e2e_mini_calc.sh --provider deepseek --protocol ctl # 有 key
cd ~/my-project && hermit
```
更多夹具(每个都有 `TASK.md` + `check.sh`):`makefile_tab`(写含 TAB 的 Makefile)、
`big_file`(写 5000 字节文件)、`test_fix_test`(先跑测试→修→再跑测试)、
`multi_file_refactor`(跨文件改名 + 修 bug,适合 `edit_file` / `grep`)、
`ask_or_todo`(必须用 `todo_write` 规划并全部完成;无人回答 `ask_user`)。
后两个需要 `--tools default`(脚本默认 `minimal`,即论文用的 4 个工具)。
---
## 构建
```bash
scripts/e2e_fixture.sh makefile_tab --provider deepseek --protocol native-inc
scripts/e2e_fixture.sh multi_file_refactor --provider deepseek --tools default
# 批量实验:协议 x 模型 x 夹具 x N 次 → results.csv + summary.md
scripts/run_matrix.sh -p "native-eos native-inc ctl ctl-heredoc xml" \
-m "deepseek:deepseek-flash deepseek:deepseek-v4-pro" -n 3 -r
make -j$(nproc) # 产出 hermit(并链 cst-agent)
make -j$(nproc) check
make hermit-font # 烘焙 PNG 帧 + hermit-icons.ttf(Pillow + fonttools)
make install PREFIX=$HOME/.local # 同时安装字体到 share/fonts/hermit 与 ~/.local/share/fonts
```
口径:`pass` / `fail` / `agent_error` / `timeout` — 见 [docs/eval_tool_cst.md](docs/eval_tool_cst.md)。
桌面 GUI(Tauri 2 + React,DeepSeek Harness 风格布局):见 [`apps/desktop`](apps/desktop/) 与 [docs/desktop.md](docs/desktop.md)。旧 Qt App(`app/`)已冻结。
## Build
TUI 图标:`HERMIT_ICONS=auto|mini|font`(默认色块动画帧,状态与 `icons/agent-motion` HTML 套件一致;`font` 输出 PUA `U+E700+`,需终端加载已安装的 Hermit Icons)。环境变量 **`HERMIT_*` 优先,`CST_*` 仍接受**。
### Make(Linux 默认)
---
## 用法速览
```bash
cd CST-agent
make # 依赖 pkg-config 找 libcurl / ncursesw(找不到时退回 ncurses)
make check # 单元测试 + 截断实验(含真实录制流)
make asan # AddressSanitizer + UBSan 构建并跑全部测试
make install PREFIX=$HOME/.local # 或 sudo make install(默认 /usr/local)
hermit # TUI
hermit --web # http://127.0.0.1:8787/
hermit --headless --prompt '…'
```
NixOS:`nix-shell`(仓库自带 [`shell.nix`](shell.nix))后再 `make`。
macOS:`brew install curl ncurses pkg-config` 后直接 `make`(Makefile 会找 Homebrew 的 keg-only 库)。
各平台细节与验收清单见 [docs/compat.md](docs/compat.md)。
首页品牌 **HERMIT** + 寄居蟹色块动效;色板:brand `#277F94`、crab `#F68042`、eye `#9957AD`。
### CMake(推荐跨编译器 / 交叉)
更多:Provider / 工具 / 议会 / WebUI 见 [docs/](docs/)。
```bash
# GCC
cmake -B build-gcc -DCMAKE_C_COMPILER=gcc -DCST_BUILD_TUI=ON
cmake --build build-gcc && ctest --test-dir build-gcc
---
# Clang
cmake -B build-clang -DCMAKE_C_COMPILER=clang -DCST_BUILD_TUI=ON
cmake --build build-clang
## CI 与发布
# Headless only(无 ncurses)
cmake -B build-hd -DCST_BUILD_TUI=OFF && cmake --build build-hd
`.gitea/workflows/ci.yml`:TinyCC check → 打 Linux/Windows 包 → `scripts/ci_publish.sh`。
共用逻辑:[scripts/lib_release.sh](scripts/lib_release.sh)。
# Windows:用一键脚本(见下方“Windows 发行包”),会先编译静态依赖
./scripts/bootstrap_windows.sh
```
依赖:`gcc` 或 `clang`、`libcurl`、TUI 需 `ncursesw`(Windows 版用打过补丁的 ncurses 6.6,脚本自动编译)。
Sashidown(`vendor/sashidown`)与 cJSON(`vendor/cjson`,MIT)已随仓库提供。
API Key:TUI 里输入并按 provider 保存到配置目录的 `credentials`(权限 0600);`/key` 更换,`--ask-key` 在命令行输入。
`--api-key` 只用于本次进程、不落盘;`DEEPSEEK_API_KEY` 等环境变量和 `CST_API_KEY` 仅作为没有保存 key 时的兜底(方便 CI)。
## 平台支持矩阵
| OS | Arch | 编译器 | Headless | TUI | Shell |
|---|---|---|---|---|---|
| Linux(glibc / musl) | x86_64 / aarch64 | GCC, Clang | yes | ncursesw | `/bin/sh` 或旁路 `busybox` |
| WSL2 | x86_64 | 同 Linux | yes | ncursesw | `/bin/sh`(工作区建议放在 Linux 文件系统内) |
| macOS | arm64 / x86_64 | Apple Clang | yes | ncurses(Homebrew) | `/bin/sh` |
| Android Termux | aarch64 / … | Clang (Termux) | yes | ncurses(Termux 包) | `$PREFIX/bin/sh`;可旁路 busybox |
| Windows 10 1903+ | x86_64 | MinGW-w64 GCC(UCRT) | yes | ncurses 6.6(Windows 控制台) | **捆绑 busybox-w32** |
### Termux
```bash
# 一键:装依赖、克隆到 ~/CST-agent、编译、安装到 $PREFIX/bin
curl -fsSL https://git.whcself.xyz/WHC/CST-agent/raw/branch/main/scripts/bootstrap_termux.sh | bash
# 以后升级(重跑上面那条也一样)
cst-agent-update
# 或手动
pkg install git clang make pkg-config binutils libcurl ncurses
git clone https://git.whcself.xyz/WHC/CST-agent.git && cd CST-agent
make && make install # 装到 Termux 的 $PREFIX/bin,之后任意目录运行 cst-agent
# 可选:旁路 Unix busybox
# ./scripts/build_third_party_mingw.sh busybox-unix
```
环境:`PREFIX` 自动用于找 `sh`;`CST_EXE_DIR` / `argv[0]` 用于定位旁路 busybox(`/proc/self/exe` 受限时)。
临时目录:依次试 `$TMPDIR`、`$PREFIX/tmp`、`/tmp`、`/var/tmp`、`~/.cache/cst-agent/tmp`,用第一个真能建文件的,
并写回 `TMPDIR` 给 shell 子进程和沙箱用(Termux 的 `/tmp` 常常不存在或被 SELinux 拒绝)。
### Windows 发行包
见 [docs/README-windows.md](docs/README-windows.md)(安装、编码、沙箱、构建、已知限制)。
```bash
./scripts/bootstrap_windows.sh # Linux 交叉编译;Windows 上在 MSYS2 UCRT64 里用 scripts/bootstrap_msys2.sh
```
产物:`dist/windows-x86_64/`(静态链接的 `cst-agent.exe` + `busybox.exe`,无其他 DLL)和
`dist/cst-agent-VERSION-windows-x86_64.zip`。CI 在 `main` / `v*` tag 推送且交叉构建成功后会自动上传到
Gitea Release `vVERSION`(同名资源会被替换);仓库可设 `RELEASE_TOKEN`(`write:repository`),否则用任务自带 token。
本地:`GITEA_TOKEN=... scripts/release_windows.sh`。
环境变量:`CST_SHELL`、`CST_EXE_DIR`、`CST_AUTO_APPROVE` 等。
## Defaults (API)
`--provider`(或 `CST_PROVIDER`)选择预设;显式的 `--api-base` / `--model` / 环境变量优先。
| provider | API Base | 默认模型 | Key 变量 |
|---|---|---|---|
| `minimax`(默认) | `https://api.minimax.cn/v1` | `MiniMax-M2.7` | `MINIMAX_API_KEY` |
| `deepseek` | `https://api.deepseek.com/v1` | `deepseek-flash`(另有 `deepseek-v4-pro`) | `DEEPSEEK_API_KEY` |
| `openai` | `https://api.openai.com/v1` | `gpt-4.1-mini` | `OPENAI_API_KEY` |
| `teamorouter` | `https://api.teamorouter.com/v1` | 登录后自动取 `/models` 第一个(`/model` 可换) | `TEAMOROUTER_API_KEY` |
| 用途 | 来源(优先级从高到低) |
|---|---|
| Provider | `--provider` → `CST_PROVIDER` → 上次使用 → `minimax` |
| Key | `--api-key` → 已保存的 key(`credentials`)→ provider 的 Key 变量 → `CST_API_KEY` → TUI 询问 |
| Base(含 `/v1`) | `--api-base` → `CST_API_BASE` → `OPENAI_BASE_URL` → `OPENAI_API_BASE` → 预设 |
| Model | `--model` → `CST_MODEL` → `OPENAI_MODEL` → 该 provider 上次使用的模型 → 预设 |
| 推理强度 | `--effort` → `CST_EFFORT` → 上次使用 → `medium` |
“上次使用”记在配置目录的 `settings.json`(TUI 里切换时更新;headless 运行不改它)。
推理强度以 `reasoning_effort` 发送给 DeepSeek 和 OpenAI 推理模型(o 系列、gpt-5,`max` 映射为 `high`),其他模型不发送。
详见 [docs/env_openai.md](docs/env_openai.md)。
| 变量 | 作用(默认) |
|---|---|
| `CST_PROTOCOL` / `--protocol` | 工具调用协议(`native-eos`) |
| `CST_TOOLS` / `--tools` | 工具集:`default`(全部)/ `minimal`(论文 4 件套) |
| `CST_EFFORT` / `--effort` | 推理强度 `low` / `medium` / `high` / `max` |
| `CST_CONFIRM` / `--confirm` | 哪些类别要确认:`shell,write,net`(默认)或 `none` |
| `CST_MAX_STEPS` / `--max-steps` | 每个用户回合最多调用模型几次(30) |
| `CST_TOOL_OUT_CAP` | 单个工具输出发给模型的字节上限(16384,保留头 60% + 尾 40%) |
| `CST_CTX_WINDOW` | 发给模型的最近非 system 消息条数(80) |
| `CST_CTX_TOKENS` / `CST_AUTO_COMPACT=0` | 覆盖模型上下文窗口大小 / 关闭自动压缩(用到 80% 时自动 `/compact`) |
| `CST_NO_PROJECT_NOTES=1` | 不把工作区的 `AGENTS.md` 注入 system prompt |
| `NO_COLOR` / `CST_ASCII=1` | 关闭颜色 / 强制 ASCII 图形(非 UTF-8 终端自动退化) |
| `CST_SHELL_TIMEOUT` | `run_shell` 超时秒数(120),超时整组进程被杀,exit=124 |
| `CST_METRICS=0` / `CST_METRICS_PATH` | 关闭 / 指定计时埋点 JSONL(默认 `.agent/metrics/<session>.jsonl`) |
| `CST_RECORD_SSE=DIR` / `CST_REPLAY_SSE=DIR` | 录制 / 回放原始 SSE 流(`NNNN.sse` + `NNNN.req.json`) |
| `CST_APPROVAL=ask\|auto\|yolo` / `CST_SANDBOX=off\|landlock\|seccomp` | 审批模式 / 关闭沙箱(回落到只读白名单规则)或只用指定沙箱 |
| `CST_MODELS`、`CST_AUTO_APPROVE=1`、`CST_SHELL`、`CST_EXE_DIR` | 模型列表、自动批准(= yolo)、shell、旁路 busybox |
## Run
```bash
# TUI(工作目录 = 当前目录;Assistant Markdown 经 Sashidown CST 渲染)
cst-agent
# Local CTL demo (no API)
cst-agent --demo-ctl
# 在命令行输入并保存当前 provider 的 key(不回显)
cst-agent --ask-key --provider deepseek
# Headless(默认 auto-approve shell/写文件)
cst-agent --headless --prompt 'List files'
```
会话相关命令行参数:
| 参数 | 作用 |
|---|---|
| `-c` / `--continue` | 打开上次的会话(默认行为) |
| `-N` / `--new` | 开新会话 |
| `-R ID` / `--resume ID` | 打开指定会话(完整 id 或唯一前缀) |
| `-L` / `--list-sessions` | 列出会话(时间、条数、标题)后退出 |
| `-A MODE` / `--approval MODE` | 审批模式 `ask` / `auto`(默认)/ `yolo`,见下文 |
| `-y` / `--yolo` | 等同 `--approval yolo`,只对本次运行有效 |
| `-C LIST` / `--confirm LIST` | 需要确认的类别:`shell,write,net` 的任意组合或 `none` |
| `-T PROFILE` / `--tools PROFILE` | `default` 或 `minimal` |
| `-P NAME` / `-m NAME` / `-e LEVEL` | 本次使用的 provider / 模型 / 推理强度(不传则用上次的) |
| `-a` / `--ask-key` | 在命令行输入并保存当前 provider 的 key |
工作目录默认就是当前目录(`-w DIR` 可指定别的目录)。
会话落盘:`<workspace>/.agent/sessions/<id>.jsonl` + `CURRENT`;`.agent/` 自带 `.gitignore`,不会被误提交。
### 内置工具
| 工具 | 类别 | 说明 |
|---|---|---|
| `read_file` | 读 | 支持 `offset` / `limit` 分段读和行号 |
| `list_dir` | 读 | 目录树(`depth`),遵守 `.gitignore`,跳过 `.git` / `node_modules` 等 |
| `glob` | 读 | 按通配符找文件(支持 `**`) |
| `grep` | 读 | 正则搜索内容,可限定路径 / glob、忽略大小写、带上下文 |
| `write_file` | 写 | 整文件写入(自动建父目录) |
| `edit_file` | 写 | 精确片段替换(必须唯一,或 `replace_all`) |
| `apply_patch` | 写 | 应用 unified diff,多文件原子生效 |
| `delete_file` / `move_file` | 写 | 删除 / 移动(重命名)文件 |
| `run_shell` | shell | 非交互命令,超时整组进程被杀,Esc 可中断 |
| `web_fetch` | 网络 | 抓取 URL,HTML 转纯文本 |
| `todo_write` | 元 | 维护任务清单(TUI 右侧面板,Ctrl+T 开关) |
| `ask_user` | 询问 | 向用户提问(可给选项);headless 下返回错误让模型自行决定 |
| `skill` | 元 | 加载一个 skill 的说明(`SKILL.md`)或其中的文件;有 skill 时才出现 |
| `task` | 子 agent | 把独立任务交给子 agent(`general` / `explore` / `plan` / 自定义角色),只返回最终报告 |
插件工具和 MCP 工具(`mcp__<server>__<tool>`)在运行时注册,和内置工具走同一套审批与 `/tools` 开关。
同一步里的多个只读调用(读文件、搜索、只读子 agent)会并行执行(最多 4 个)。
`--tools minimal` 只保留 `read_file` / `run_shell` / `write_file` / `apply_patch`(论文实验口径)。
TUI 中 `/tools off NAME`、`/tools on NAME` 可临时开关单个工具。
### 权限、撤销与项目说明
- **审批模式**(Shift+Tab 循环切换,`/approval`,`--approval`,`CST_APPROVAL`):
| 模式 | 写文件 | run_shell | web_fetch |
|---|---|---|---|
| `ask` | 询问 | 询问 | 询问 |
| `auto`(默认) | 直接执行 | 有沙箱 → 在沙箱里直接执行;没有沙箱 → 只读白名单命令直接执行,其余询问 | 询问 |
| `yolo` | 直接执行 | 直接执行(不进沙箱) | 直接执行 |
已保存的规则(`a` / `p`)优先:匹配的命令不进沙箱直接运行。
`ask` / `auto` 的选择会记在 `settings.json`;`yolo` 只在本次运行有效。headless 行为不变(全部自动)。
- **沙箱**(C 实现,`src/sandbox_exec.c`):
- Linux:Landlock(内核 5.13+,直接 syscall,无需 libseccomp)。子进程只能写工作区、临时目录、`/dev/null`、`/dev/tty`;
读、执行和联网不受限。
- Linux 没有 Landlock 时(Android / Termux、WSL、老发行版;内核 5.5+,x86_64 / aarch64):seccomp user-notify
(界面显示 `auto · seccomp`)。子进程的写类系统调用(带写标志的 open、创建 / 删除 / 改名 / 链接 / chmod 等)先交给
agent 里的监督线程,按真实路径判断是否在工作区、临时目录或 `/dev/null` 等之内,不在就返回 `EACCES`。联网不受限。
读、执行和已打开文件的写入不检查。它防的是误操作而不是恶意程序:检查之后内核会再读一次路径,多线程程序可以趁机换掉。
探测还会确认能读直接子进程的内存;`ptrace_scope=2` 且无 `CAP_SYS_PTRACE` 时 seccomp 不会启用。
比 shell 活得久的后台进程:桌面发行版开着 Yama(`ptrace_scope` ≥ 1)时它们的受检写入会被拒;命令结束后一律失败。
- macOS:`sandbox_init` profile,同样只放行工作区和临时目录写入,不限制联网。
- Windows 10 1903+:Low 完整性级别的受限令牌 + Job Object(界面显示 `auto · lowil`)。第一次在工作区运行时
给它打上 Low 标签,之后子进程只能写工作区和沙箱临时目录,读不到凭据文件;不限制联网。
`/sandbox` 查看、`/sandbox reset-labels` 撤销标签,详见 [docs/README-windows.md](docs/README-windows.md)。
- 更老的内核:没有沙箱,自动回落到规则判断(界面显示 `auto · rules`)。
- `CST_SANDBOX=off` 强制关闭沙箱;`CST_SANDBOX=landlock` / `seccomp` / `lowil` 只用指定的那种。
- 沙箱里的命令如果像是被拦了(`Permission denied` / `权限不够` / `Read-only file system` 等),会弹窗问
“Rerun outside the sandbox?”:`y` 在沙箱外重跑一次 · `p` 保存命令前缀规则并重跑 · `n` 保留沙箱结果(模型会收到说明)。
- **只读白名单**(无沙箱时 `auto` 用):`ls cat head tail wc grep rg find pwd echo which file stat du tree`
和 `git status/diff/log/show/branch`;可以用 `|` `&&` `||` `;` 串联,但每段都必须在白名单里。
`find -exec/-delete`、`rg --pre`、`git branch NAME`、`>` 重定向(`2>&1`、`>/dev/null` 除外)、`$(…)`、反引号、
`<(…)`、`sudo`、`rm` 一律不算安全。
- **确认弹窗**会显示命令或写入的 diff:
`y` 允许一次 · `a` 本工具总是允许 · `p` 总是允许这个命令前缀(如 `make`、`git status`)· `n` / Esc 拒绝。
`a` / `p` 写入 `<workspace>/.agent/permissions.json`,`/permissions` 查看,`/permissions reset` 清空。
`sudo`、`rm`、解释器(`python3 -c …`)等危险前缀不会被建议成规则。
- **撤销**:每轮写文件前自动快照到 `.agent/undo/`,`/undo` 恢复上一轮改动的全部文件(新建的文件会被删除)。
- **AGENTS.md**:工作区根目录的 `AGENTS.md` 会注入 system prompt;`/init` 让 agent 自己生成一份。
- **自动压缩**:上一轮 prompt 用到模型上下文 80% 时,下一轮开始前自动总结历史(`CST_AUTO_COMPACT=0` 关闭)。
### 扩展:Skills、插件、MCP、子 agent
`--tools minimal` 下这些都不加载(论文口径保持不变)。配置写法与示例见 [docs/plugins.md](docs/plugins.md)。
- **Skills**:`<dir>/SKILL.md`(frontmatter `name` + `description`),放在工作区 `.agent/skills/`、`.claude/skills/`
或配置目录 `skills/`。system prompt 只放名字和一句描述,模型需要时调用 `skill(name)` 读全文;
`/skills` 浏览,`/skill NAME 任务` 直接带着某个 skill 开始一轮。
- **插件**:`plugins/<name>/plugin.json` 声明外部命令工具(参数以 JSON 写到 stdin,stdout 即结果,`perm` 决定审批,
默认 60 s 超时),也可以附带 skills 目录和 MCP 服务器。
- **MCP**:`mcp.json`(`{"mcpServers": {...}}`,与 Claude/Cursor 格式相同)里的 stdio 服务器在后台启动,
工具注册为 `mcp__<server>__<tool>`,默认按网络工具审批(`autoApprove` 可放行)。`/mcp` 看状态,侧栏显示连接数。
- **工作区信任**:工作区里的 `.agent/plugins/` 和 `.agent/mcp.json` 会执行命令,默认不加载;
`/plugins trust` 后才生效(记在 `settings.json`)。配置目录(`~/.config/cst-agent/`)下的始终加载。
- **子 agent**:`task(description, prompt, agent?)` 新开一个独立上下文跑完一轮,把最终报告交回主 agent。
内置 `general`(除 task 外全部工具)、`explore`(只读,可并行)、`plan`(只读,输出计划);
`.agent/agents/*.md` 或配置目录 `agents/*.md` 可自定义角色(frontmatter `name / description / model / tools /
max_steps / readonly`,正文是角色说明)。子 agent 不能再开子 agent;Esc 会一并取消;它的审批弹窗标 `[角色名]`;
文件改动并入当前轮,`/undo` 一起撤销。转录在 `.agent/sessions/<会话>/sub-N.jsonl`,`/agents` 查看。
### TUI 快捷键
默认 leader 是 **Ctrl+X**:先按 Ctrl+X,再按后面的字母。`/keys`(或 F1、Ctrl+X h)列出当前全部绑定。
| 按键 | 说明 |
|---|---|
| Enter | 发送;busy 时入队 |
| Ctrl+N / Alt+Enter | 换行(粘贴的多行文本保持原样,不会被当成发送) |
| Shift+Enter / Ctrl+Enter | 换行;需要支持 kitty 键盘协议的终端(kitty、WezTerm、foot、Ghostty、WHC Shell 等),启动时自动探测 |
| ← → Home End Ctrl+A/E Ctrl+B/F Alt+B/F Ctrl/Alt+← → | 移动光标(按字 / 按词,支持中文宽字符) |
| Ctrl+W / Alt+Backspace / Ctrl+Backspace / Ctrl+Delete | 向前删词 / 向后删词(Ctrl+Backspace 需要 kitty 键盘协议) |
| Ctrl+U / Ctrl+K / Delete | 删到行首 / 删到行尾 / 删后一个字符 |
| ↑ / ↓ | 提示历史(多行输入时先在行间移动) |
| Tab | 补全 `/命令` 和 `@文件`;没有可补全时切换 Build / Plan(Plan 只开放只读工具) |
| Shift+Tab | 循环切换审批模式 ask → auto → yolo |
| Ctrl+P | 命令面板(输入过滤,↑↓ / 鼠标选择) |
| Ctrl+O / Ctrl+R | 展开/折叠最近的 tool 输出 / 最近的 Thought |
| Ctrl+T / Ctrl+L | 开关任务面板 / 重绘 |
| PgUp / PgDn、Alt+↑ / Alt+↓、Ctrl+Home / Ctrl+End | 半页滚动、单行滚动、跳到开头 / 最新 |
| Ctrl+X n / l | 新会话 / 会话列表 |
| Ctrl+X m / p / e | 模型 / provider / 推理强度 |
| Ctrl+X u / r / c | 撤销上一轮改动 / 重问 / 压缩上下文 |
| Ctrl+X y / x | 复制上一条回复 / 导出记录 |
| Ctrl+X t / d / s | 全部 Thought 默认展开或折叠 / 全部 tool 输出 / 侧栏 |
| Ctrl+X a / k / g | 子 agent 面板 / skills / 插件 |
| Ctrl+X h、F1 / Ctrl+X q | 快捷键列表 / 退出 |
| 鼠标点击 | 展开/折叠 tool 卡片和 Thought、在输入框里定位光标、点模式行切换 Build/Plan、在选择框里选中 |
| 鼠标拖动 / 双击 / 三击 | 在对话区选中文字(按字符 / 词 / 行),松开即通过 OSC 52 复制到剪贴板;拖到上下边缘会自动滚动。Shift+拖动或 `/mouse` 关闭后用终端原生选择 |
| Esc | 取消当前 turn(不会退出) |
| Ctrl+C 两次 / 空输入 Ctrl+D | 退出 |
Thought(推理过程)默认折叠成一行“Thought · 3.2s”,生成中显示实时计时;`/thinking on` 改为默认展开。
**自定义按键**:`~/.config/cst-agent/keybinds.json`,键是动作名(`/keys` 里能看到),值是一个或多个按键,
`"none"` 解除绑定:
```json
{
"leader": "ctrl+x",
"new_session": ["<leader> n", "f2"],
"toggle_thought": "ctrl+g",
"todo": "none"
}
```
按键写法:`ctrl+x`、`alt+b`、`shift+tab`、`f1`…`f12`、`pgup`、`home`、`<leader> n`。
写错的条目会被跳过并在 `/keys` 里提示,其余照常生效。
### 斜杠命令
输入 `/` 弹出补全;唯一前缀即可(如 `/st` → `/status`)。标 * 的命令在模型运行中也能用。
| 命令 | 说明 |
|---|---|
| `/help` * | 命令与按键 |
| `/new`、`/session [id]`、`/rename <标题>` *、`/delete [id]` | 新建 / 选择切换 / 命名 / 删除会话 |
| `/provider [name]`、`/model [name]`、`/effort [level]` | 切换 provider(缺 key 时当场输入并用 `/models` 校验)、模型(列表优先显示 API 实际返回的模型,标 `(api)`)、推理强度;都会记住 |
| `/key` | 输入或更换当前 provider 的 API key(遮罩输入并保存) |
| `/protocol [name]` | 切换工具调用协议 |
| `/tools [on\|off NAME\|minimal\|default]` | 查看或开关工具 |
| `/approval [ask\|auto\|yolo]` *、`/yolo` * | 审批模式;本次开关 yolo |
| `/permissions [reset]` *、`/max-steps [N]` * | 权限规则、每轮步数 |
| `/sidebar` *、`/mouse` * | 开关右侧边栏(≥120 列时显示)、开关鼠标 |
| `/status` *、`/todo` * | 会话 / 模型 / 上下文占比 / 设置;任务清单 |
| `/undo`、`/retry` | 撤销上一轮文件改动;丢弃上一条回复重问 |
| `/diff [path]` * | `git status` + `git diff` |
| `/compact` | 手动压缩上下文 |
| `/export [file]` *、`/copy` * | 导出 Markdown 记录;复制上一条回复(OSC 52,需终端支持) |
| `/init` | 让 agent 写 `AGENTS.md` |
| `/details` *、`/thinking [on\|off]`、`/keys` * | 展开全部 tool 输出;Thought 默认展开/折叠;快捷键列表 |
| `/skills [reload\|list]`、`/skill <name> [任务]` | 浏览 skills;带着某个 skill 开始一轮 |
| `/plugins [trust\|untrust\|reload]`、`/mcp [reload]` | 插件与工作区信任;MCP 服务器状态 |
| `/agents` | 子 agent 角色与本会话的子 agent 记录(可查看转录) |
| `/quit` * | 退出 |
### 协议
请求统一走 OpenAI 兼容 `POST …/chat/completions`(SSE)。工具调用的承载方式由 `--protocol` 决定:
| 协议 | 承载 | 何时执行 |
|---|---|---|
| `native-eos`(默认) | 原生 `tools[]` / SSE `tool_calls` | 整个流结束后(基线) |
| `native-inc` | 同上 | 某个 index 的参数完整(下一个 index 开始或 finish)即执行 |
| `ctl` | 正文中的 CTL 帧,长度前缀参数 | `end` 行一被确认即执行,流仍在继续 |
| `ctl-heredoc` | 正文中的 CTL 帧,`<<TAG` 定界参数 | 同上 |
| `xml` | MiniMax `<minimax:tool_call>` 文本 | 流结束后 |
文本协议(ctl / ctl-heredoc / xml)不发送 `tools[]`,工具结果以
`result <id> exit=<n> <nbytes>` … `end` 帧放在下一条 user 消息里。
同一会话可以随时切换协议:历史中的调用会按当前协议重新渲染。
## CTL tool language
```text
call <id> <name>
arg <key> <nbytes>
<raw bytes exactly nbytes>
arg <key> <<TAG
<lines, verbatim>
TAG
arg <key> short inline value
end
```
Execution happens only on confirmed `end` (`CTL_EV_CALL_READY`); no prefix of
a call is ever executable. See [docs/theory_tool_cst.md](docs/theory_tool_cst.md).
## Starvation experiment
## 开发者
```bash
make check
./scripts/replay_starvation.sh
./tests/test_replay_real # 真实 DeepSeek 录制流上的逐字节截断(实验 C)
scripts/prompt_smoke.sh
scripts/e2e_webui.sh
```
CTL vs JSON-buffer 截断数字写入 [docs/eval_tool_cst.md](docs/eval_tool_cst.md) 实验 A / C;与 mini_calc e2e 一起作为 Tool-loop CST 附录素材(**不**替代 SD 主论文 Markdown→HTML 实验)。
`icons/agent-motion/` 为 SVG 资产;`make hermit-font` 生成 `res/hermit-icons.ttf`(sbix 彩色位图,96 帧)与 `res/hermit-frames/`。安装脚本会把字体装进系统字体目录。
+248
View File
@@ -0,0 +1,248 @@
cmake_minimum_required(VERSION 3.16)
project(cst-agent-app LANGUAGES C CXX VERSION 0.1.0)
# The Qt front end (app/) embeds the C engine in-process: it links libcstcore
# and never opens a port. Two targets:
#
# cst-app-selftest pure C smoke test of the embedding path (no Qt), so the
# C side is still guarded on machines without Qt Quick
# cst-agent-app the GUI (Qt 6 Quick + QML), built when the Qt modules
# are there
#
# Standalone build (builds the engine from ../ too):
# cmake -S app -B build-app -DCMAKE_BUILD_TYPE=Debug && cmake --build build-app -j
# Inside the repo build (the parent defines the cstcore target, shared with the CLI):
# cmake -B build -DCST_BUILD_APP=ON && cmake --build build --target cst-agent-app
#
# Desktop install (the window, its launcher entry and the icon; the CLI has
# its own installer) -- default.nix installs exactly this component:
# cmake --install build --component app --prefix ~/.local
#
# Extra QML import paths, e.g. a Kirigami installed away from the Qt prefix:
# -DCST_APP_QML_IMPORT=... (added to QML2_IMPORT_PATH / the app's runtime)
option(CST_APP_GUI "build the Qt GUI (needs Qt6 Quick, Qml, QuickControls2)" ON)
option(CST_APP_SELFTEST "build the C embedding smoke test" ON)
# --- the engine ----------------------------------------------------------
# Used as a subproject (../CMakeLists.txt already defined cstcore, engine
# compiled once for CLI and app) or built here from the sources next door.
if(NOT TARGET cstcore)
set(CST_APP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/..")
include_directories("${CST_APP_ROOT}/include" "${CST_APP_ROOT}/vendor/cjson")
file(GLOB CST_APP_CORE_SRC
"${CST_APP_ROOT}/src/*.c"
"${CST_APP_ROOT}/src/tools/*.c"
"${CST_APP_ROOT}/vendor/cjson/cJSON.c")
list(REMOVE_ITEM CST_APP_CORE_SRC
"${CST_APP_ROOT}/src/main.c"
"${CST_APP_ROOT}/src/tui.c"
"${CST_APP_ROOT}/src/tui_stub.c"
"${CST_APP_ROOT}/src/textsel.c")
# The HTTP front end is not part of an in-process app: no server, no port.
list(REMOVE_ITEM CST_APP_CORE_SRC
"${CST_APP_ROOT}/src/net.c"
"${CST_APP_ROOT}/src/http_srv.c"
"${CST_APP_ROOT}/src/webui.c")
# web_md.c stays in: the window renders markdown with it (AgentCore::
# renderMarkdown) and the md_to_html tool needs it. Only the HTTP server
# is left out.
if(EXISTS "${CST_APP_ROOT}/.gen/models_builtin.inc")
include_directories("${CST_APP_ROOT}/.gen")
endif()
add_library(cstcore STATIC ${CST_APP_CORE_SRC})
target_compile_definitions(cstcore PRIVATE CST_NO_WEBUI=1)
find_package(CURL REQUIRED)
find_package(Threads REQUIRED)
target_link_libraries(cstcore PUBLIC ${CURL_LIBRARIES} Threads::Threads m)
message(STATUS "app: building the engine from ${CST_APP_ROOT}")
else()
message(STATUS "app: linking the cstcore target of the parent build")
endif()
# --- the C smoke test ----------------------------------------------------
if(CST_APP_SELFTEST)
add_executable(cst-app-selftest tools/selftest.c)
target_link_libraries(cst-app-selftest PRIVATE cstcore)
enable_testing()
add_test(NAME cst-app-selftest COMMAND cst-app-selftest)
endif()
# --- the GUI -------------------------------------------------------------
if(CST_APP_GUI)
# Android's platform file talks to the platform through QtAndroidPrivate
# (the POST_NOTIFICATIONS probe), whose include path comes with CorePrivate.
if(ANDROID)
find_package(Qt6 6.4 COMPONENTS Core Gui Qml Quick QuickControls2 Test
CorePrivate QUIET)
else()
find_package(Qt6 6.4 COMPONENTS Core Gui Qml Quick QuickControls2 Test QUIET)
endif()
if(NOT Qt6_FOUND)
message(WARNING
"app: Qt 6 Quick/Qml not found, skipping cst-agent-app "
"(the C selftest still builds; install e.g. qt6.qtdeclarative / "
"qt6.qtquickcontrols2 and reconfigure)")
else()
qt_standard_project_setup()
# Qt 6.5+ policies: keep the module resource at :/qt/qml/<URI>/ (what
# main.cpp loads) and let CMake generate the qmldir of qml/ for us.
qt_policy(SET QTP0001 NEW)
qt_policy(SET QTP0004 NEW)
# The front end's platform tools: one file per platform, the same split
# core/ToolProvider.cpp makes. Android brings its own (JNI, owner
# "app:android"), Windows its own (PowerShell popup, owner "app:windows");
# the rest use the Linux file.
if(ANDROID)
set(CST_APP_PLATFORM_SRC src/platform/android/AndroidTools.cpp)
elseif(WIN32)
set(CST_APP_PLATFORM_SRC src/platform/windows/NotifyTool.cpp)
else()
set(CST_APP_PLATFORM_SRC src/platform/linux/NotifyTool.cpp)
endif()
qt_add_executable(cst-agent-app
src/main.cpp
src/core/AgentCore.cpp
src/core/ToolProvider.cpp
src/core/PdfTools.cpp
src/ui/UiTest.cpp
src/ui/ThemeIcons.cpp
src/ui/SessionImages.cpp
src/ui/BackKey.cpp
${CST_APP_PLATFORM_SRC})
target_include_directories(cst-agent-app PRIVATE
src "${CMAKE_CURRENT_SOURCE_DIR}/../include")
target_compile_definitions(cst-agent-app PRIVATE CST_APP_VERSION="${PROJECT_VERSION}")
if(CST_APP_QML_IMPORT)
target_compile_definitions(cst-agent-app PRIVATE
CST_APP_QML_IMPORT="${CST_APP_QML_IMPORT}")
endif()
target_link_libraries(cst-agent-app PRIVATE
Qt6::Core Qt6::Gui Qt6::Qml Qt6::Quick Qt6::QuickControls2 Qt6::Test cstcore)
if(ANDROID)
# app/src/platform/android/AndroidTools.cpp talks to the platform
# through QtAndroidPrivate (permissions) -- a private header, hence the
# private module for its include path.
target_link_libraries(cst-agent-app PRIVATE Qt6::CorePrivate)
endif()
if(WIN32)
set_target_properties(cst-agent-app PROPERTIES WIN32_EXECUTABLE TRUE)
endif()
# A desktop install. The icon goes where the theme layout says, so the
# entry's Icon= name finds it, and the entry's file name is the app_id Qt
# sets (QGuiApplication::applicationName) -- rename one and the launcher
# loses the icon. All of it in the "app" component: the CLI keeps coming
# from scripts/bootstrap_linux.sh, and two `cst-agent` in PATH is how a
# version nobody meant to run gets run.
if(NOT ANDROID)
include(GNUInstallDirs)
install(TARGETS cst-agent-app
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT app)
install(FILES linux/cst-agent-app.desktop
DESTINATION ${CMAKE_INSTALL_DATADIR}/applications COMPONENT app)
install(FILES linux/cst-agent-app.svg
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps
COMPONENT app)
endif()
# --- Android (APK) -----------------------------------------------------
# The engine is compiled in (top-level CMakeLists: -DCST_BUILD_TUI=OFF,
# -DCST_BUILD_WEBUI=OFF, so src/webui_stub.c stands in for the server and
# nothing listens on a port). The manifest, icons and strings live in
# app/android/, which androiddeployqt copies next to its own gradle
# project. minSdk 24 is the engine's own API_LEVEL (scripts/
# build_third_party_android.sh builds curl/mbedTLS for android-24).
if(ANDROID)
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/../include/cst_version.h"
_cst_ver_lines REGEX "#define CST_VERSION_(MAJOR|MINOR|PATCH) ")
foreach(_line ${_cst_ver_lines})
if(_line MATCHES "CST_VERSION_MAJOR ([0-9]+)")
set(_cst_vmaj "${CMAKE_MATCH_1}")
elseif(_line MATCHES "CST_VERSION_MINOR ([0-9]+)")
set(_cst_vmin "${CMAKE_MATCH_1}")
elseif(_line MATCHES "CST_VERSION_PATCH ([0-9]+)")
set(_cst_vpat "${CMAKE_MATCH_1}")
endif()
endforeach()
set_target_properties(cst-agent-app PROPERTIES
QT_ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android"
QT_ANDROID_MIN_SDK_VERSION 24
QT_ANDROID_TARGET_SDK_VERSION 35
QT_ANDROID_VERSION_NAME "${_cst_vmaj}.${_cst_vmin}.${_cst_vpat}"
QT_ANDROID_VERSION_CODE 1
QT_ANDROID_ABIS "${ANDROID_ABI}")
message(STATUS "app: Android package "
"${_cst_vmaj}.${_cst_vmin}.${_cst_vpat}, ABI ${ANDROID_ABI}, "
"minSdk 24, targetSdk 35")
# Signing: androiddeployqt signs the APK itself and refuses a signed
# gradle output ("Could not copy unsigned APK"), so the keystore goes
# here, not into gradle. The path, alias and passwords arrive through
# the QT_ANDROID_KEYSTORE_* environment variables;
# scripts/build_apk_android.sh points them at the standard Android debug
# key it creates on first use, and CST_ANDROID_KEYSTORE overrides it.
if(DEFINED ENV{QT_ANDROID_KEYSTORE_PATH} AND NOT "$ENV{QT_ANDROID_KEYSTORE_PATH}" STREQUAL "")
set(QT_ANDROID_SIGN_APK TRUE)
message(STATUS "app: signing the APK with "
"$ENV{QT_ANDROID_KEYSTORE_PATH} ($ENV{QT_ANDROID_KEYSTORE_ALIAS})")
else()
message(STATUS "app: QT_ANDROID_KEYSTORE_PATH unset -- the APK stays "
"unsigned and 'adb install' will refuse it (INSTALL_PARSE_FAILED_NO_CERTIFICATES)")
endif()
endif()
# Theme is read by every component, so it is a QML singleton (one instance,
# no object needed in the tree).
set_source_files_properties(qml/Theme.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)
# Keep the module flat in the resource tree (:qt/qml/CstAgent/Main.qml).
# Sources live in qml/, but a module whose files sit in a subdirectory of
# the URI makes Qt register the types with relative URLs ("qmlRegisterType
# requires absolute URLs" on every start).
foreach(_qml Main ChatView Sidebar SessionRow MessageCard ToolCard ThinkBlock
NoteLine TodoPanel Composer ConsentDialog AskDialog SettingsDialog TaskPanel
ThemeIcon Theme ImageStrip)
set_source_files_properties(qml/${_qml}.qml PROPERTIES QT_RESOURCE_ALIAS ${_qml}.qml)
endforeach()
qt_add_qml_module(cst-agent-app
URI CstAgent
VERSION 1.0
QML_FILES
qml/Main.qml
qml/ChatView.qml
qml/Sidebar.qml
qml/SessionRow.qml
qml/MessageCard.qml
qml/ToolCard.qml
qml/ThinkBlock.qml
qml/NoteLine.qml
qml/TodoPanel.qml
qml/Composer.qml
qml/TaskPanel.qml
qml/ConsentDialog.qml
qml/AskDialog.qml
qml/SettingsDialog.qml
qml/ThemeIcon.qml
qml/ImageStrip.qml
qml/Theme.qml)
# The icons the window asks for, compiled in (app/icons, Breeze's scalable
# names copied at 24@3x). The desktop finds them in the platform's icon
# theme and only falls back to these (ThemeIcons.cpp); a machine without
# any theme -- Android -- has nothing else, and before this the QML glyph
# fallback was all that showed, which the phone's fonts cannot render.
set(CST_APP_ICONS
go-down mail-attachment application-menu settings-configure edit-copy
edit-delete arrow-down arrow-right list-add task-complete box
document-edit text-x-generic folder-open edit-find code-context
internet-services format-list-unordered help-hint)
set(_cst_icon_files "")
foreach(_icon ${CST_APP_ICONS})
list(APPEND _cst_icon_files "${CMAKE_CURRENT_SOURCE_DIR}/icons/${_icon}.svg")
endforeach()
qt_add_resources(cst-agent-app "cst_icons"
PREFIX "/cst-icons"
BASE "${CMAKE_CURRENT_SOURCE_DIR}/icons"
FILES ${_cst_icon_files})
endif()
endif()
+10
View File
@@ -0,0 +1,10 @@
# Deprecated: Qt front end
This directory is the **legacy Qt 6 / QML** Hermit GUI (`cst-agent-app`).
The supported desktop shell is **`apps/desktop`** (Tauri 2 + React), with a
DeepSeek-Harness-inspired layout and an in-process C engine bridge.
Do not add features here. Once Tauri reaches feature parity, this tree will be
moved to `archive/qt-app` or removed. Android APK scripts that target this tree
are transitional.
+467
View File
@@ -0,0 +1,467 @@
# app/ — the Qt front end
CST-agent's GUI: **Qt 6 + QML + the C engine, in one process**. No HTTP
server, no port, no token, no second process — the app creates a `cst_agent_t`
directly and drives it through `cst_agent.h`.
```
app/ the GUI
src/main.cpp entry point, --workspace / --selftest
src/core/AgentCore.* QObject around cst_agent_t: turns, hooks, consent
src/core/ToolProvider.h how the front end hands tools to the engine
src/platform/<os>/ platform tools the app implements itself
qml/Main.qml the window (chat, tool runs, consent dialog)
tools/selftest.c C smoke test of the embedding path (no Qt)
```
## Build
```sh
# engine + GUI + C smoke test
cmake -S app -B build-app -DCMAKE_BUILD_TYPE=Debug
cmake --build build-app -j
QT_QPA_PLATFORM=offscreen ctest --test-dir build-app # cst-app-selftest
# the app alone
./build-app/cst-agent-app --workspace ~/notes
./build-app/cst-agent-app --size 480x900 # the narrow (drawer) layout
./build-app/cst-agent-app --uitest # drive the window, exit code = failures
./build-app/cst-agent-app --selftest # same checks as the C test
```
The standalone build is the supported one: `app/CMakeLists.txt` uses the
`cstcore` target when the parent project defines one, and otherwise builds
the engine itself from `../src` (TUI, `main.c` and the HTTP front end
excluded). Wiring it into the repository's `CMakeLists.txt` as
`-DCST_APP=ON` is on the list below.
Needs Qt 6.4+ with **Quick / Qml / QuickControls2** (`qt6.qtdeclarative`,
`qt6.qtquickcontrols2` on Nix; the online installer's "Qt 6.x Desktop" on
Windows/macOS). Without them the configure step warns and builds only the C
smoke test — that is deliberate: the embedding path stays verifiable
everywhere. Kirigami is not required yet; `qml/Main.qml` uses Qt Quick
Controls and keeps the layout in Kirigami's shape (single column, cards,
navigation drawer) so swapping in `org.kde.kirigami` later is a QML-only
change. Point the app at a Kirigami outside the Qt prefix with
`-DCST_APP_QML_IMPORT=/path/to/qml`.
## Install (Linux desktop)
The window installs itself: the binary, a launcher entry and the icon the
launcher draws for it. All three are one CMake component (`app`), so the CLI
keeps coming from `scripts/bootstrap_linux.sh` and the profile never holds two
`cst-agent` of different vintages; the files live in `app/linux/`.
```sh
# NixOS / nix users: PATH + menu entry + icon. The Qt apps hook bakes the
# plugin and QML module paths into the wrapper, so the app runs outside a
# nix-shell and nix-collect-garbage cannot pull Qt out from under it.
nix-build # ./result/bin/cst-agent-app, run it in place
nix profile add --file . # or: ./result/bin/cst-agent-app
nix profile remove cst-agent # uninstall
# anywhere with Qt 6 (Quick/Qml/QuickControls2) and libcurl:
cmake -B build-app -DCST_BUILD_APP=ON -DCMAKE_BUILD_TYPE=Release
cmake --build build-app -j
cmake --install build-app --component app --prefix ~/.local
```
Launched from a menu, the workspace is the directory the app starts in
(`$HOME` there), so sessions land in `~/.agent/sessions`; pass
`--workspace <dir>` to pin another one.
## Why in one process
The engine is a library, not a daemon: `libcstcore.a` (Makefile) / the
`cstcore` target (CMake). The app owns one `cst_agent_t` per window, so
there is no protocol to version, no socket to authenticate and no second
process to babysit — and the CLI, TUI and WebUI keep working off the same
source.
- `AgentCore::send()` runs `cst_agent_run_turn_ex()` on a worker thread;
the `cst_agent_hooks_t` callbacks turn into Qt signals (assistant deltas,
tool events, tool results, todo, turn end).
- Consent is a blocking hook: the worker waits on a `QWaitCondition`, the
GUI answers, the turn goes on. `CST_PERM_DENY / ONCE / ALWAYS_TOOL /
ALWAYS_PREFIX` map 1:1 onto the buttons, and `ALWAYS_*` still lands in
`.agent/permissions.json`, so a desktop decision is visible to the TUI.
- `cancel()` is `cst_agent_request_cancel()`; the turn unwinds as a normal
result, not an exception.
## Layout and input
One shell, three sizes (everything is styled from `qml/Theme.qml`):
- **Desktop**: the sidebar is docked and its divider can be dragged (double
click restores the auto width). Hover states, tooltips, selectable text and
a wheel-scrolled transcript.
- **Narrow window** (below `Theme.compactBreakpoint`, 880 px): the sidebar
folds away, the header grows a `☰` button, and the settings slide in over
the transcript with a scrim; the sidebar itself scrolls, because a phone
window cannot show it all.
- **Touch**: controls keep a `Theme.touchTarget` (34 px) hit area, buttons do
not depend on hover, the composer asks the platform keyboard not to
autocorrect (`ImhNoPredictiveText`), and Enter/Shift+Enter still behave.
`--uitest` checks this without a human: it loads the window, clicks with
synthesized **mouse** events, taps with a synthesized **touch** device, types
into the composer, drives the session list, then narrows the window to 460 px
to assert the dock → drawer switch and opens/closes the drawer. One line per
check, non-zero exit on failure:
```sh
QT_QPA_PLATFORM=offscreen ./build-app/cst-agent-app --uitest
# ok wide window: sidebar docked
# ok mouse click on "general" reaches the engine
# ok touch tap on "coding" reaches the engine
# ...
```
## Sessions
A GUI session is a directory in the workspace's store
(`.agent/sessions/<id>/session.jsonl`, with its `title`, its `attachments/` and
its sub-agent transcripts beside it), the same one the CLI, the TUI and the
WebUI use — `AgentCore::open()` resolves the workspace's current session before
the engine starts, so nothing is written next to the process's working
directory. A store an older version wrote (flat `<id>.jsonl` files) still
reads; `cst-agent --migrate-store` moves it in.
- The sidebar lists the store (newest first): title or first prompt, message
count, "3h ago"; the open one is highlighted. `+ new` starts a session, `×`
deletes one (the engine first moves off a session it has open, so it never
sits on a file that is gone), and a click switches.
- Switching **replays** the transcript: `AgentCore::history()` walks the stored
messages and returns the same rows the live signals build — messages,
thoughts, notes, and one card per tool call, with its result paired by name
(a call with no result keeps state `unfinished`, so no spinner runs
forever). A reopened session therefore renders like the turn that wrote it.
- Session controls are disabled while a turn runs: switching would move the
engine out from under it.
`--uitest` covers the flow end to end: `writeFixtureSession()` writes a small
session through the store API (a tool call with its result), the checks click
its row, assert the five replayed rows and the paired result, start two new
sessions (the view empties), delete one by its `×` (the open one stays), and
switch back.
`--uitest` uses a scratch workspace unless `--workspace` is given, since it
creates and deletes sessions. On a machine without a screen,
`CST_APP_SHOT=shot.png` makes the run save the window as a PNG when it is
done; `CST_APP_DUMP=1` prints how many session rows the visual tree holds.
Every line the run prints also goes to `uitest.log` in the workspace, and the
verdict is the last line of it. That is how a run *on a phone* is read back:
stdout reaches nobody there, an app started from adb cannot be handed
environment variables, and logcat does not carry this build's Qt messages --
so `--uitest --workspace /sdcard/cst-uitest` plus
`adb pull /sdcard/cst-uitest/uitest.log` is the whole round trip.
## Provider, model, key
The sidebar shows where the engine points (`provider · model`); the gear in the
header opens the dialog that changes it.
- The provider list is the engine's own preset table (`cst_provider_count()`),
with each entry's base URL and where its key would come from: "key saved"
(`.agent`-independent, `<config>/cst-agent/credentials`), "key from
OPENAI_API_KEY", or "no key". A key itself is never sent to the QML side —
the dialog only ever describes it. The window starts the engine without a
key (`AgentCore::open()` is passed an empty one), so `open()` resolves it
for the provider it starts on: saved key, then the provider's env variable,
then `CST_API_KEY` — the same order the CLI uses in `main.c`. Without that
the key sat in the file but never in the turn, and every start asked for it
again.
- "Use this" calls `AgentCore::useProvider()`, which runs
`cst_ps_switch_provider()` / `cst_ps_set_key()` on the engine's live config:
a pasted key is verified against the provider's `/models` before it is saved
(offline it is kept unverified and the header says so), the model is
remembered in `settings.json`, and the **session is not touched**. Model
candidates come from the provider entry, the fetched cache
(`cst_ps_cached`, no network) and the remembered pick; the label next to the
field is `cst_model_info` ("200K · text only").
- The dialog also reports the session's token use (`cst_agent_usage`).
`--uitest` checks it end to end: the presets are readable, an unknown provider
is refused, the gear opens the panel, the provider rows exist, a model typed
into the field reaches the engine when "Use this" is clicked, the note says so,
and Close puts the dialog away. The run points `XDG_CONFIG_HOME` at its scratch
directory, so settings and keys of the real user are never rewritten.
## Custom providers, model parameters
The dialog's **Advanced options** covers the two things the presets cannot:
a provider of your own, and what the model should do.
- A custom provider is an entry the engine keeps in
`<config>/cst-agent/models.json` (layer 1 of the model registry, see
`include/cst_models.h`) — the same file a hand-written override would go
into, so the GUI and a text editor are interchangeable:
```json
{ "providers": { "myllm": { "api_base": "https://api.example.com/v1",
"key_env": "MYLLM_API_KEY",
"default_model": "m1",
"models": ["m1", "m2"] } } }
```
`AgentCore::addProvider()` / `removeProvider()` write it
(`cst_models_user_set_provider()` / `cst_models_user_drop_provider()`) and
reload the registry, so the provider is in the list, in `models[]` on the
wire and in `/provider` of the CLI at once. A name a preset uses overrides
that preset (a self-hosted endpoint, a proxy); the other content of the file
(model rules) is kept, and a file that is not a JSON object is never
overwritten. The key is still a key: it is verified against `GET /models` of
the new base URL before it is saved, and stored per provider name as before.
- The generation parameters — **temperature**, **top-p**, **max tokens** — are
remembered per provider in `settings.json` (`"params": {...}`,
`cst_settings_remember_params()`), and applied to the engine's config by
`AgentCore::setGenParams()`, `AgentCore::useProvider()` and
`cst_agent_create()` (so a CLI or TUI run sends what the window was set to).
An **empty field is not sent at all** — that is not the same as sending 0,
which is a real temperature; `cst_llm_build_body()` only adds a field that
was set (`tests/test_llm_body.c:test_gen_params`).
- A long model list (a router lists hundreds) is filtered and capped at 40
chips with "… +N more", and the whole dialog body scrolls: the buttons stay
put and nothing can spill out of the frame.
## Attachments
The next prompt can carry files, and they arrive three ways:
- **📎 in the composer** opens a file picker (`QtQuick.Dialogs`).
- **Dropping files on the window** — a `DropArea` covers it; while something is
dragged over, the border turns accent and says "drop to attach".
- **Ctrl+V** with an image on the clipboard. Text is left to the editor's own
paste: the composer asks `AgentCore::clipboardHasImage()` first and only
intercepts the keystroke when there is an image.
`AgentCore::attachFile()` / `attachClipboard()` call `cst_agent_attach_file()` /
`cst_agent_attach_bytes()`: the engine validates the file, copies it into the
session's own directory (`.agent/sessions/<id>/attachments/`), and the next
`run_turn` carries it — the
window only shows what the engine's `pending` list says, one chip per file in
the engine's own words ("note.txt (text/plain, 21 B)"), with "clear all"
(`cst_agent_pending_clear`). A prompt consumes the list, so the chips go away
with the turn. When the model cannot be shown images
(`cst_agent_sees_images() == 0`), the composer says so and the engine sends
them as text notes instead.
`--uitest` writes a file into its scratch workspace and checks the whole path:
`attachFile` succeeds, the engine reports one pending attachment, a missing file
is refused with a reason, the composer shows one chip, "clear all" empties the
list, and — with an 8×8 image put on the clipboard — `clipboardHasImage()` and
`attachClipboard()` behave.
## Images
What a session keeps as a picture is shown, not only stored: a file
`view_image` returned, an image an MCP server sent, a screenshot the user
attached or pasted. Each one appears as a thumbnail in the transcript -- a
prompt's pictures under the message, a tool's under its card -- with the name,
size and origin in the tooltip. The height is capped so a 4K screenshot cannot
push the conversation off the screen, and a file the store no longer has says
which image it was instead of leaving a hole.
The view never touches the filesystem on its own authority: the thumbnails
come from `image://cstattach/<stored name>` (`app/src/ui/SessionImages.cpp`),
where the name is the one the engine wrote next to the session and is checked
with the engine's own `cst_attach_rel_ok()`, so only the session's attachment
directory can be read. The picture is decoded at the size of its thumbnail
rather than at its full resolution, and the provider's directory follows the
session: `AgentCore::attachmentDir()` is re-read on every switch.
A document (PDF, UTF-8 text) still arrives as its name in the message text --
those are sent to the model as text, not as a picture.
## Files the agent delivers
The opposite direction: the engine's `deliver_file` tool (registered in
`src/tools/registry.c`, run in `src/tools/fs_tools.c`) copies a finished file
out of the workspace into the session's own store, and the transcript shows it
as a **file card** -- an extension badge, the file's name, its type and size,
and two buttons.
- The copy is marked `for_user` (`cst_attachment_t.for_user`,
`cst_attach_import_artifact()`): any bytes up to `CST_ARTIFACT_MAX_BYTES`
(64 MB), the name's extension decides the mime, and **no request ever
contains it** -- `src/llm_openai.c` skips those entries when it builds the
body, which is what keeps a delivered report from being pasted back into the
context. `tests/test_artifacts.c` holds that down at the wire level.
- A card never invents a path. The row carries the stored file's name, and
`AgentCore::openArtifact()` / `shareArtifact()` accept it only when one of
the session's own messages carries that name (`artifactPathOf()`, plus the
engine's `cst_attach_rel_ok()`), so a forged name is refused with a reason.
- **Open** hands the file to the system: Android builds a `content://` URI
through the app's FileProvider, checks `resolveActivity()`, starts
`ACTION_VIEW` and grants the reader permission; a desktop calls
`QDesktopServices::openUrl`. **Share** uses the phone's share sheet; a
desktop has none, so the path goes to the clipboard.
- `CST_APP_NO_OPEN=1` makes both do nothing but report the line they would
write. `--uitest` sets it, so a test run never opens anything for real: it
replays a session with a delivered `report.md`, checks the card and its two
buttons, clicks Open (the header must say `opened report.md`), clicks Share
and checks a name the session does not own is refused.
### Making one: `md_to_pdf`
The front end registers a tool of its own for this (`app/src/core/PdfTools.cpp`,
owner `app:qt`, `platforms = NULL` so every platform the window runs on gets
it): markdown, or a workspace `.md`/`.html` file, becomes an A4 PDF with 15 mm
margins in the workspace, and goes through the same
`cst_attach_import_artifact()` path as `deliver_file` -- so it arrives as a
file card the person can open, print or share, and its bytes never enter a
request. The markdown is rendered by the engine (`cst_web_md_document()`, the
same renderer the WebUI and `md_to_html` use) and Qt lays the HTML out
(`QTextDocument` + `QPdfWriter`, both QtGui); pagination is written here,
page rect by page rect, because `QPrinter`/PrintSupport is desktop-only and a
phone has no print subsystem. The tool runs on the turn's worker thread, and
`--uitest` runs it through the registry and checks the file starts with
`%PDF-`.
The card row on the phone is the same one a picture uses: the store keeps the
PDF next to the session, the image provider refuses it (it is not an image),
and the file card carries it.
## Transcript, tool calls, streaming text
- A tool call is a card of its own, and the call **id** is what pairs it with
its result: the same tool may run twice in a turn, and pairing by name (what
the window did before) hung the first card on "running" forever while the
second one took its result. `AgentCore::toolEvent()` and `toolResult()` carry
the id (`ctl_tool_call_t.id`), `AgentCore::history()` fills it from the
session (`tool_call_id`, `tool_calls_json`), and only an id-less call from an
old text-protocol session still falls back to the name.
- Nothing may keep spinning after a turn: `closeAllRows()` settles every open
row when the turn ends, and a call with no result becomes "no result"
(`unfinished`) instead of a spinner that runs forever.
- The answer is rendered **while it streams**: a 120 ms timer re-renders the
open answer with the engine's own markdown renderer (`cst_web_md_html`, via
`AgentCore::renderMarkdown()`), so a list or a code fence fills in formatted
instead of turning into markdown when the turn is over. A replayed session
renders once, when its rows are built.
- Every signal handler is a plain function on the window
(`engineToolEvent`, `engineToolResult`, `engineTurnFinished`,
`engineAssistant`, ...) so `--uitest` can drive the same path: it opens two
calls of one tool, delivers one result, and asserts that the result landed on
its own card and that the turn end settled the other one. `rowJson(i)` exists
for that (a row as JSON — an object would not survive
`QMetaObject::invokeMethod`).
## Icons, colors
- Icons come from the desktop's **icon theme** (Breeze on KDE), through
`image://csttheme/<name>?color=%23rrggbb` (`app/src/ui/ThemeIcons.{h,cpp}`).
Qt Quick has no icon provider of its own without Kirigami, so the window used
unicode glyphs before (a clip emoji, a gear, a hamburger): those render in
whichever font covers them — colour emoji in a grey toolbar — and are a box
on a machine without that glyph. `app/qml/ThemeIcon.qml` is the one place
that asks for an icon, and every use still names the old character as
`glyph:`: a host with no icon theme degrades to what it looked like before
rather than going blank.
- The provider fills Qt's theme search paths itself (XDG data dirs, `~/.icons`
and, on NixOS, `/run/current-system/sw/share/icons`): Qt only builds them
from XDG once a theme name is set. It then tries the theme the desktop chose,
else `breeze-dark` (this window is dark), `breeze`, `hicolor`. Rasterising
Breeze needs the Qt SVG image format plugin (`qt6.qtsvg` on Nix, part of a
desktop Qt install) — without it the icons fall back to the glyphs instead of
disappearing.
- `Theme.toolIcon(name)` maps a tool onto its icon: patch/write → pencil,
read → text page, list/glob → folder, grep → magnifier, shell → braces,
web → globe, plan → list, ask → question mark. Toolbar icons are 22 px
(Breeze's toolbar size), card and row icons 14–16 px.
- `textFaint` is readable grey, not decoration (~5:1 on the card fill): it
carries hints, secondary lines and provider URLs. Anything written *on* the
accent fill (a selected provider row, the open session) uses `accentText`,
`accentTextDim` and `okOnAccent` — green or faint grey on `accentDim` is
unreadable. The names are not `onAccent…`: QML reads every `onFoo` property
as a signal handler and refuses the assignment.
- The composer's frame is one `Theme.pad` around its column on **all** sides;
with the top margin alone the clip and Send hung over the lower border.
## Tools the app provides
A tool implemented in the front end is registered with `cst_tool_register()`
and the owner `app:<name>`, exactly like a plugin or MCP server would:
```c
cst_tool_def_t def = {0};
def.name = "notification_send";
def.desc = "Send a system notification.";
def.perm = CST_TP_ASK; /* class: drives the consent dialog */
def.perm_name = "notify"; /* policy: what the user is really granting */
def.platforms = ANDROID_ONLY; /* NULL = everywhere */
def.available = probe; /* 0 / -1 with a reason; cached */
def.run_ex = my_run;
def.ud = my_state;
def.owner = "app:android";
cst_tool_register(&def);
```
- `platforms` + `available` decide *whether* the tool exists here: an
Android-only tool never reaches the prompt or `tools[]` on Linux, and
`cst_tool_run()` refuses it with the reason if a model asks anyway.
- A front-end tool may take over the **name** of a built-in that cannot run
on this host (the Android clipboard replacing the desktop `xclip` one);
it may not shadow one that works.
- `cst_tool_unregister_owner("app:android")` drops them again — do it when a
platform service goes away, then `cst_tool_meta_reload()`.
- `setenv("CST_PLATFORM", ...)` overrides the detected host name (tests, a
launcher that knows better).
Note `run_ex` runs on the worker thread while the turn is going: touch the
GUI only through queued signals.
## Platform notes
| Platform | How the engine gets built | Platform tools |
|---|---|---|
| Linux | `cmake -S app -B build-app` (libcurl via pkg-config) | clipboard (shell helpers), notification (`notify-send` / D-Bus) |
| Windows | Qt's MinGW kit, `cmake -G Ninja -DCMAKE_PREFIX_PATH=<Qt>/lib/cmake`; the engine needs libcurl for Windows (see `docs/README-windows.md`) | notification via the WinRT/tray API, clipboard through the core's Win32 path |
| Android | engine compiled with the NDK inside the APK (`scripts/build_apk_android.sh`, `-DCST_TUI=0`, `CST_NO_WEBUI=1`); no port, QML talks to `AgentCore` in-process | notification (`Notifier.java`: channel + permission probe), clipboard (`QClipboard` under the engine's own tool names), share sheet (`ACTION_SEND` + chooser), and the file card's open/share through the app's FileProvider (`AndroidTools.cpp`) |
| macOS | Qt from the installer, libcurl from the system | notification (`osascript`), clipboard (`pbpaste`/`pbcopy`) |
Android's long-term shape: the core lives in the APK (no Termux needed), the
platform tools are Kotlin/JNI behind the same `cst_tool_register()` contract.
The build flag that keeps Unix helpers out of the picture is
`CST_PLATFORM=android` (or the `__ANDROID__` detection inside the engine).
A Java class is added by dropping it in `app/android/src/<package>/`:
androiddeployqt copies `app/android/` with the rest of the package source and
Qt's Gradle template puts its `src/` on `java.srcDirs`, so no build-script
change is needed (`Notifier.java` is the first one; a Java helper is the only
way to catch a throwable where the platform throws instead of returning).
`CstService.java` (the foreground service that holds a phone awake while a
turn runs) went in the same way; it is started by `app::holdForeground()`
when a turn begins and stopped by `app::releaseForeground()` when it ends,
so nothing about it is visible when the app is idle.
## Status
- [x] engine as a library (`libcstcore.a` / `cstcore`), in-process embed API
- [x] tool metadata: `perm_name`, `platforms`, `available`, shadowing rule
- [x] `AgentCore` (turns, cancel, consent, todo) and the C smoke test
- [x] QML shell: transcript cards, tool cards with diff coloring, thinking
blocks, consent/ask dialogs, sidebar, responsive dock/drawer layout,
`--uitest` for mouse, touch and small-screen checks
- [x] session list in the sidebar: new / switch / delete, transcript replay
- [x] settings dialog: provider, model, key (`cst_ps_*`), token counters
- [x] attachments: picker, drop on the window, Ctrl+V image paste
- [x] icons from the desktop's icon theme (Breeze), with a glyph fallback
- [x] contrast pass: faint text and selected rows are readable
- [x] images in the transcript: tool results and attachments are drawn as
thumbnails (`image://cstattach/<stored name>`, see the Images section)
- [x] Android APK: the engine is linked in (no port), builds, installs under
`xyz.whcself.cstagent` and runs on the device (see `docs/android.md`)
- [x] the saved provider key reaches the engine on every start (`AgentCore::open()`
resolves it: saved key, provider environment, `CST_API_KEY`)
- [x] delivered files: `deliver_file` stores the copy next to the session and the
transcript draws a file card with Open and Share (see the Files section)
- [x] Android platform tools (JNI: notification, clipboard, share sheet) and the
file card's open/share through the app's FileProvider
- [x] a turn keeps running with the app off screen (Android foreground service
+ wake lock; nothing to do on a desktop)
- [x] desktop install: launcher entry + icon, `nix profile add --file .`
- [ ] a real turn driven through the window (needs a provider key)
- [ ] SAF file picker, the back gesture, the icon glyphs on the phone
- [ ] Kirigami (the rest of the Breeze look: colors, controls), tray,
global shortcuts
+113
View File
@@ -0,0 +1,113 @@
<?xml version="1.0"?>
<!-- The APK's manifest (QT_ANDROID_PACKAGE_SOURCE_DIR in app/CMakeLists.txt):
androiddeployqt copies this file and res/ into its gradle project and
fills in the INSERT_* placeholders below (version code and name, library
name, app arguments). An XML comment may not contain a double hyphen, so
the placeholder syntax is only spelled out in the attributes themselves.
The SDK levels are not here on purpose: they come from
QT_ANDROID_MIN_SDK_VERSION and QT_ANDROID_TARGET_SDK_VERSION in
app/CMakeLists.txt, and androiddeployqt writes them into the generated
gradle.properties. The app name and icon come from res/ next to this
file (values/strings.xml, drawable/ic_launcher.xml).
WHAT THIS APP IS: the engine runs in this process (no server, no port) and
writes everything (workspace, session store, settings, credentials) under
the app's own data directory, which main.cpp points the engine at (see
androidRoot() there).
Permissions: INTERNET for the providers the user configures,
POST_NOTIFICATIONS for the app's notification_send tool (Android 13+
asks at runtime; the tool stays hidden until it is granted), the
foreground-service permissions with WAKE_LOCK for the service that keeps
a turn going while the phone is in a pocket (CstService.java), and
MANAGE_EXTERNAL_STORAGE ("all files access", Android 11+) so the engine
can read a path in shared storage that a task names rather than picks:
Android only offers the Settings screen for it, so main.cpp opens that
once and everything still works without it: what the system picker (SAF)
hands over is copied into the app's own directory (AttachFile.java). No
cleartext traffic: every provider URL is https. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz.whcself.cstagent"
android:installLocation="auto"
android:versionCode="-- %%INSERT_VERSION_CODE%% --"
android:versionName="-- %%INSERT_VERSION_NAME%% --">
<!-- %%INSERT_PERMISSIONS -->
<!-- %%INSERT_FEATURES -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- "All files access": without it the engine can only read the app's own
directory, so a task that names a file in shared storage cannot be
answered. Android 11+ has no runtime dialog for it, only the Settings
screen (AttachFile.java opens it once). Files the user picks work
either way: their content:// grant is copied into the app first. -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true" />
<application
android:name="org.qtproject.qt.android.bindings.QtApplication"
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:enableOnBackInvokedCallback="false">
<activity
android:name="org.qtproject.qt.android.bindings.QtActivity"
android:label="@string/app_name"
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|keyboard|keyboardHidden|navigation|density|mcc|mnc"
android:launchMode="singleTop"
android:screenOrientation="unspecified"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="-- %%INSERT_APP_LIB_NAME%% --" />
<meta-data
android:name="android.app.arguments"
android:value="-- %%INSERT_APP_ARGUMENTS%% --" />
</activity>
<!-- The share tool hands a file out of the workspace, and a file
crossing an app boundary has to travel as a content:// uri. This
is Qt's own provider (androidx.core.content.FileProvider, paths
from res/xml/qtprovider_paths.xml): its files-path is the app's
files directory, which is where the workspace lives. -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.qtprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/qtprovider_paths" />
</provider>
<!-- A turn can outlive the screen: while one is running the front end
starts this service (AgentCore::send -> app::holdForeground), which
makes the process a foreground one, so Android neither freezes nor
kills it in the background, and takes a partial wake lock so the
CPU keeps going with the phone in a pocket. dataSync is the type
that fits "the app is finishing some work". -->
<service
android:name="xyz.whcself.cstagent.CstService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Launcher icon: the terminal prompt the app is about ("&gt;_"), the window's
own colors (bg #12161a, accent #5cc0f0, faint #8d959c). A vector drawable
works from API 24 up; a proper adaptive icon (mipmap-anydpi-v26 + a PNG
fallback) is polish for later. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#12161a"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:strokeColor="#5cc0f0"
android:strokeWidth="7"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:pathData="M32,38 L52,54 L32,70" />
<path
android:fillColor="#00000000"
android:strokeColor="#8d959c"
android:strokeWidth="7"
android:strokeLineCap="round"
android:pathData="M58,74 L78,74" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The name under the launcher icon. -->
<resources>
<string name="app_name">CST-agent</string>
</resources>
@@ -0,0 +1,189 @@
package xyz.whcself.cstagent;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.provider.Settings;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/* What the user picks in the system file chooser comes back as a content://
* URI, and the engine opens files by path -- so the bytes are copied into the
* app's own directory first. That copy needs no permission at all (the grant
* travels with the URI), which is what makes picking work on a phone that
* grants nothing else.
*
* The "all files access" below is a different thing: it is what lets the
* engine read /sdcard by path afterwards (a model that opens a file the user
* names rather than picks). Android 11+ has no runtime dialog for it -- only
* the Settings screen -- so it is a request, not a demand: everything works
* without it, one file at a time.
*
* Qt swallows a Java exception (it comes back as a null object), so every
* method catches its own and answers with a reason instead.
*/
public final class AttachFile {
private AttachFile() {}
private static final long MAX_BYTES = 256L * 1024 * 1024;
public static boolean isContent(String s) {
return s != null && s.startsWith("content:");
}
/* content://<uri> -> the path of a copy inside destDir; "" when the string
* is already a path; "error: ..." when the copy failed. */
public static String materialize(Context ctx, String pathOrUri, String destDir) {
if (pathOrUri == null || pathOrUri.isEmpty())
return "error: no file was picked";
if (!isContent(pathOrUri))
return "";
try {
if (ctx == null)
return "error: no Android context";
final Uri uri = Uri.parse(pathOrUri);
String name = displayName(ctx, uri);
if (name == null || name.trim().isEmpty())
name = uri.getLastPathSegment();
name = sanitize(name);
File dir = new File(destDir);
if (!dir.isDirectory() && !dir.mkdirs())
return "error: cannot use " + destDir;
File out = unique(dir, name);
final ContentResolver cr = ctx.getContentResolver();
final InputStream in = cr.openInputStream(uri);
if (in == null)
return "error: the picker gave no data for that file";
long total = 0;
try {
final OutputStream os = new FileOutputStream(out);
try {
final byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) > 0) {
total += n;
if (total > MAX_BYTES) {
os.close();
in.close();
out.delete();
return "error: that file is larger than 256 MB";
}
os.write(buf, 0, n);
}
} finally {
os.close();
}
} finally {
in.close();
}
if (total == 0) {
out.delete();
return "error: that file is empty";
}
return out.getAbsolutePath();
} catch (Throwable t) {
return "error: cannot read the picked file: " + t;
}
}
/* Android 11+ keeps "all files access" in a special app-op; older systems
* have no such gate. */
public static boolean hasAllFilesAccess(Context ctx) {
try {
if (Build.VERSION.SDK_INT < 30)
return true;
return Environment.isExternalStorageManager();
} catch (Throwable t) {
return false;
}
}
/* The Settings screen Android requires for it. "" when it was opened. */
public static String requestAllFilesAccess(Context ctx) {
try {
if (Build.VERSION.SDK_INT < 30 || ctx == null)
return "";
if (Environment.isExternalStorageManager())
return "";
final Intent intent = new Intent(
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
Uri.parse("package:" + ctx.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException notFound) {
final Intent all = new Intent(
Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
all.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(all);
}
return "";
} catch (Throwable t) {
return "cannot open the storage settings: " + t;
}
}
private static String displayName(Context ctx, Uri uri) {
Cursor c = null;
try {
c = ctx.getContentResolver().query(uri,
new String[] { OpenableColumns.DISPLAY_NAME }, null, null,
null);
if (c != null && c.moveToFirst()) {
final int i = c.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (i >= 0)
return c.getString(i);
}
} catch (Throwable ignored) {
/* fall back to the last path segment */
} finally {
if (c != null)
c.close();
}
return null;
}
/* A plain file name: no separators, no traversal, no control bytes. */
private static String sanitize(String name) {
if (name == null || name.isEmpty())
return "picked.bin";
final StringBuilder b = new StringBuilder();
for (int i = 0; i < name.length() && b.length() < 120; i++) {
final char ch = name.charAt(i);
if (ch == '/' || ch == '\\' || ch < 0x20)
b.append('_');
else
b.append(ch);
}
String s = b.toString();
while (s.startsWith("."))
s = s.substring(1);
if (s.isEmpty())
return "picked.bin";
return s;
}
private static File unique(File dir, String name) {
File f = new File(dir, name);
if (!f.exists())
return f;
final int dot = name.lastIndexOf('.');
final String stem = dot > 0 ? name.substring(0, dot) : name;
final String ext = dot > 0 ? name.substring(dot) : "";
for (int i = 2; i < 1000; i++) {
f = new File(dir, stem + "-" + i + ext);
if (!f.exists())
return f;
}
return f;
}
}
@@ -0,0 +1,143 @@
package xyz.whcself.cstagent;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
/**
* The service that keeps a turn running while the app is not on screen.
*
* A phone freezes an app it cannot see (and may kill it), so a turn that takes
* minutes -- a build, a long web fetch, a provider that thinks -- dies in the
* pocket. While one is going, AgentCore::send() starts this service through
* app::holdForeground(); being a foreground service makes the process one
* Android does not touch, and the partial wake lock keeps the CPU awake with
* the screen off. turnFinished() stops it again (app::releaseForeground()), so
* the permanent notification exists exactly as long as the work does.
*
* Started with an explicit component (AndroidTools.cpp builds the Intent), no
* intent filter: nothing outside the app can start it.
*/
public class CstService extends Service {
/** Same channel the notification_send tool uses: one place in settings. */
private static final String CHANNEL_ID = "cst-agent";
private static final int NOTE_ID = 2;
private static final String ACTION_STOP = "xyz.whcself.cstagent.STOP";
/** A turn that runs longer than this is stuck; the lock must not outlive it. */
private static final long WAKE_LOCK_TIMEOUT_MS = 30 * 60 * 1000L;
private PowerManager.WakeLock wake;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_STOP.equals(intent.getAction())) {
stopEverything();
return START_NOT_STICKY;
}
String text = intent == null ? null : intent.getStringExtra("text");
try {
startForeground(NOTE_ID, buildNote(text));
} catch (Throwable t) {
/* Android 12+ refuses a foreground start from the background: the
* turn then simply runs without the protection rather than not at
* all. Nothing to show the user here -- the turn's own result is
* what matters. */
stopSelf();
return START_NOT_STICKY;
}
acquireWake();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
releaseWake();
super.onDestroy();
}
private void stopEverything() {
releaseWake();
if (Build.VERSION.SDK_INT >= 24)
stopForeground(STOP_FOREGROUND_REMOVE);
else
stopForeground(true);
stopSelf();
}
private void acquireWake() {
try {
if (wake == null) {
PowerManager pm =
(PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm == null)
return;
wake = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"cst-agent:turn");
wake.setReferenceCounted(false);
}
wake.acquire(WAKE_LOCK_TIMEOUT_MS);
} catch (Throwable ignored) {
/* no wake lock: the turn still runs while the screen is on */
}
}
private void releaseWake() {
try {
if (wake != null && wake.isHeld())
wake.release();
} catch (Throwable ignored) {
}
}
/** "the agent is working: <first line of the prompt>", tapping opens it. */
private Notification buildNote(String text) {
Context ctx = getApplicationContext();
NotificationManager manager =
(NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null && Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "CST-agent", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("A turn is running");
manager.createNotificationChannel(channel);
}
Notification.Builder builder = Build.VERSION.SDK_INT >= 26
? new Notification.Builder(ctx, CHANNEL_ID)
: new Notification.Builder(ctx);
builder.setContentTitle("CST-agent is working")
.setSmallIcon(smallIcon())
.setOngoing(true)
.setShowWhen(false);
if (text != null && !text.isEmpty())
builder.setContentText(text);
Intent open = ctx.getPackageManager().getLaunchIntentForPackage(ctx.getPackageName());
if (open != null) {
open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
builder.setContentIntent(PendingIntent.getActivity(ctx, 0, open,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
}
return builder.build();
}
/** A framework drawable first (the same order the tool uses), then the app's. */
private int smallIcon() {
int icon = getResources().getIdentifier("ic_dialog_info", "drawable", "android");
if (icon == 0)
icon = getResources().getIdentifier("stat_notify_chat", "drawable", "android");
if (icon == 0)
icon = getApplicationInfo().icon;
return icon;
}
}
@@ -0,0 +1,60 @@
package xyz.whcself.cstagent;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
/**
* The notification behind the engine's notification_send tool.
*
* It lives in Java because a Java exception is invisible to C++ by the time
* Qt's JNI wrapper is done with the call: Notification.Builder.build() can
* throw (a small icon Android refuses, a channel it does not know) and the
* JNI call then simply returns null -- the tool could only say "failed, no
* exception detail" on a device where the phone's own shade never saw
* anything. Catching it here turns the failure into the line the tool shows.
*
* Called from app/src/platform/android/AndroidTools.cpp through QJniObject.
* androiddeployqt copies this file with the rest of the package source
* (QT_ANDROID_PACKAGE_SOURCE_DIR, app/android/) and Qt's Gradle template adds
* "src" to java.srcDirs, so no build script change is needed for a file
* added here.
*/
public final class Notifier {
private Notifier() {}
/**
* Post one notification. An empty channelId means an API below 26, which
* has no channels. Returns "" when it went out, the Java failure
* otherwise (class name and message), so the tool result can name it.
*/
public static String post(Context ctx, String channelId, String title,
String text, int iconId, Intent tap, int id) {
try {
Notification.Builder builder = channelId == null || channelId.isEmpty()
? new Notification.Builder(ctx)
: new Notification.Builder(ctx, channelId);
builder.setContentTitle(title).setContentText(text).setSmallIcon(iconId);
if (tap != null) {
tap.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pending = PendingIntent.getActivity(
ctx, 0, tap,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pending);
}
NotificationManager manager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager == null)
return "no NotificationManager";
manager.notify(id, builder.build());
return "";
} catch (Throwable t) {
String message = t.getMessage();
return t.getClass().getSimpleName()
+ (message == null || message.isEmpty() ? "" : ": " + message);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="m3 5v2h16v-2h-16m0 5v2h16v-2h-16m0 5v2h16v-2h-16" class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 446 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="m3.707031 7l-.707031.707031 6.125 6.125 1.875 1.875 1.875-1.875 6.125-6.125-.707031-.707031-6.125 6.125-1.167969 1.167969-1.167969-1.167969-6.125-6.125" class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 549 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="m7.707031 3l-.707031.707031 6.125 6.125 1.167969 1.167969-1.167969 1.167969-6.125 6.125.707031.707031 6.125-6.125 1.875-1.875-1.875-1.875-6.125-6.125" class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 547 B

+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 24 24" width="24" height="24">
<defs>
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path class="ColorScheme-Text" transform="translate(-.99999-.99999)" d="m4 4v16h16v-16h-16m1 1h14v14h-14v-14" fill="currentColor"/>
<path d="m3.5056345 10.977883v-7.5052069h14.878582v15.010415h-14.878582z" class="ColorScheme-Text" fill="currentColor" fill-opacity=".50196078"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 589 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="m10.04492 3c-1.77683 0-2.521484.706446-2.521484 2.509766v2.441406c0 1.11382-.034195 2.404297-1.015625 2.404297h-.507813v1.289062h.507813c.98148 0 1.015625 1.290477 1.015625 2.404297v2.441406c0 1.80332.744654 2.509766 2.521484 2.509766v-1.183594c-1.18455 0-1.201172-.478327-1.201172-2.210937v-2.01563c0-.83093-.204705-2.067378-1.203125-2.580078.99842-.51271 1.203125-1.751092 1.203125-2.582032v-2.033203c0-1.7326.016592-2.210937 1.201172-2.210937v-1.183594m1.894531 0v1.183594c1.18456 0 1.216797.478337 1.216797 2.210937v2.033203c0 .83094.204705 2.069322 1.203125 2.582032-.99842.5127-1.203125 1.749148-1.203125 2.580078v2.01563c0 1.73261-.032187 2.210937-1.216797 2.210937v1.183594c1.77684 0 2.537109-.706446 2.537109-2.509766v-2.441406c0-1.11382.068644-2.404297 1.033204-2.404297h.490234v-1.289062h-.490234c-.96457 0-1.033204-1.290477-1.033204-2.404297v-2.441406c0-1.80332-.760269-2.509766-2.537109-2.509766" class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="m14.996094 3l-11.992188 11.992188h-.003906v4.00781h1 2 1.00781v-.003906l11.992188-11.992188-.001953-.001953.001953-.001953-4-4-.001953.001953-.001953-.001953m-1.998047 3.412109l2.589844 2.589844-7.587891 7.587891v-1.589844h-1-1v-1-.589844l6.998047-6.998047m-7.998047 7.998047v1.589844h1 1v1 .589844l-.410156.410156h-1.589844l-1-1v-1.589844l1-1" class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 741 B

+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" version="1.1" width="24" height="24">
<defs>
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path class="ColorScheme-Text" style="fill:currentColor; fill-opacity:1; stroke:none" d="M 3 3 L 3 17 L 7 17 L 7 19 L 17 19 L 17 10 L 13 6 L 12 6 L 9 3 L 3 3 Z M 4 4 L 8 4 L 8 6 L 7 6 L 7 16 L 4 16 L 4 4 Z M 8 7 L 12 7 L 12 11 L 16 11 L 16 18 L 8 18 L 8 7 Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 583 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-NegativeText { color: #da4453; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" class="ColorScheme-NegativeText" d="M8 3v2h1V4h4v1h1V3H8M4 6v1h14V6H4m2 2v11h10V8h-1v10H7V8H6"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 471 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M 9 3 C 5.6759952 3 3 5.6759952 3 9 C 3 12.324005 5.6759952 15 9 15 C 10.481205 15 11.830584 14.465318 12.875 13.582031 L 18.292969 19 L 19 18.292969 L 13.582031 12.875 C 14.465318 11.830584 15 10.481205 15 9 C 15 5.6759952 12.324005 3 9 3 z M 9 4 C 11.770005 4 14 6.2299952 14 9 C 14 11.770005 11.770005 14 9 14 C 6.2299952 14 4 11.770005 4 9 C 4 6.2299952 6.2299952 4 9 4 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 774 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor" d="M 3 3 L 3 4 L 3 19 L 4 19 L 19 19 L 19 18 L 19 5 L 12. 5 L 10. 3 L 10 3 L 10 3 L 4 3 L 3 3 z M 9 8 L 18 8 L 18 18 L 4 18 L 4 10 L 7 10 L 7 10 L 7 10 L 9 8 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 528 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M 4 3 C 3.4477153 3 3 3.4477153 3 4 C 3 4.5522847 3.4477153 5 4 5 C 4.5522847 5 5 4.5522847 5 4 C 5 3.4477153 4.5522847 3 4 3 z M 10 3 L 10 4 L 19 4 L 19 3 L 10 3 z M 10 5 L 10 6 L 16 6 L 16 5 L 10 5 z M 4 9 C 3.4477153 9 3 9.4477153 3 10 C 3 10.552285 3.4477153 11 4 11 C 4.5522847 11 5 10.552285 5 10 C 5 9.4477153 4.5522847 9 4 9 z M 10 9 L 10 10 L 19 10 L 19 9 L 10 9 z M 10 11 L 10 12 L 12 12 L 12 11 L 10 11 z M 4 15 C 3.4477153 15 3 15.447715 3 16 C 3 16.552285 3.4477153 17 4 17 C 4.5522847 17 5 16.552285 5 16 C 5 15.447715 4.5522847 15 4 15 z M 10 15 L 10 16 L 19 16 L 19 15 L 10 15 z M 10 17 L 10 18 L 16 18 L 16 17 L 10 17 z M 17 18 L 17 19 L 19 19 L 19 18 L 17 18 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="m3.707031 7l-.707031.707031 6.125 6.125 1.875 1.875 1.875-1.875 6.125-6.125-.707031-.707031-6.125 6.125-1.167969 1.167969-1.167969-1.167969-6.125-6.125" class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 549 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M 11 3 C 6.568 3 3 6.568 3 11 C 3 15.432 6.568 19 11 19 C 15.432 19 19 15.432 19 11 C 19 6.568 15.432 3 11 3 z M 11 4 C 14.878 4 18 7.122 18 11 C 18 14.878 14.878 18 11 18 C 7.122 18 4 14.878 4 11 C 4 7.122 7.122 4 11 4 z M 10 6 L 10 8 L 12 8 L 12 6 L 10 6 z M 10 9 L 10 16 L 12 16 L 12 9 L 10 9 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 696 B

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 24 KiB

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M 10 4 L 10 11 L 3 11 L 3 12 L 10 12 L 10 19 L 11 19 L 11 12 L 18 12 L 18 11 L 11 11 L 11 4 L 10 4 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 499 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M 12.902344 3 L 3.734375 12.167969 C 2.167415 13.734929 2.167415 16.257279 3.734375 17.824219 C 5.301315 19.391169 7.823675 19.391169 9.390625 17.824219 L 17.851562 9.3632812 L 18.558594 8.65625 C 19.733804 7.48104 19.733794 5.5892625 18.558594 4.4140625 C 17.383384 3.2388525 15.491616 3.2388525 14.316406 4.4140625 L 13.609375 5.1210938 L 5.1484375 13.582031 C 4.3649575 14.365511 4.3649675 15.626686 5.1484375 16.410156 C 5.9319175 17.193636 7.1930825 17.193646 7.9765625 16.410156 L 16.4375 7.9492188 L 15.730469 7.2421875 L 7.9765625 14.996094 L 7.2695312 15.703125 C 6.8777912 16.094865 6.2471888 16.094865 5.8554688 15.703125 C 5.4637287 15.311405 5.4637187 14.680813 5.8554688 14.289062 L 14.316406 5.828125 L 15.023438 5.1210938 C 15.806917 4.3376037 17.068092 4.3376037 17.851562 5.1210938 C 18.635042 5.9045538 18.635042 7.1657387 17.851562 7.9492188 L 8.6835938 17.117188 C 7.5083838 18.292397 5.6166162 18.292397 4.4414062 17.117188 C 3.2661862 15.941977 3.2661862 14.05021 4.4414062 12.875 L 13.609375 3.7070312 L 12.902344 3 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M 11.5 3 C 10.286139 3 9.2809778 3.8559279 9.0507812 5 L 3 5 L 3 6 L 9.0507812 6 C 9.2809778 7.1440721 10.286139 8 11.5 8 C 12.713861 8 13.719022 7.1440721 13.949219 6 L 19 6 L 19 5 L 13.949219 5 C 13.719022 3.8559279 12.713861 3 11.5 3 z M 5.5 14 C 4.1149999 14 3 15.115 3 16.5 C 3 17.885 4.1149999 19 5.5 19 C 6.7138604 19 7.7190223 18.144072 7.9492188 17 L 19 17 L 19 16 L 7.9492188 16 C 7.7190223 14.855928 6.7138604 14 5.5 14 z M 5.5 15 C 6.3310001 15 7 15.669 7 16.5 C 7 17.331 6.3310001 18 5.5 18 C 4.6689999 18 4 17.331 4 16.5 C 4 15.669 4.6689999 15 5.5 15 z " class="ColorScheme-Text"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 966 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<defs id="defs3051">
<style id="current-color-scheme" type="text/css">.ColorScheme-Text { color: #fcfcfc; } </style>
</defs>
<g transform="translate(1,1)">
<path class="ColorScheme-Text" d="M 19,9 12,16 8,12 9.4896719,10.543135 12,13 17.482382,7.5492102 Z M 4,3 V 5 H 3 V 6 H 4 V 7 H 3 v 1 h 1 v 6 H 3 v 1 h 1 v 1 H 3 v 1 h 1 v 2 h 3 12 v -1 -7 h -1 v 1 1 2 1 2 H 10 9 7 V 16 15 13 12 10 9 7 6 4 h 2 1 8 v 2 h 1 V 3 H 7 Z m 4,3 v 2 h 2 V 6 Z m 3,0 v 1 h 6 V 6 Z" style="fill:currentColor;fill-opacity:1;stroke:none"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 669 B

+14
View File
@@ -0,0 +1,14 @@
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="24" version="1.1" height="24" viewBox="0 0 24 24">
<defs id="defs3871"/>
<metadata id="metadata3874"/>
<g transform="translate(1,1)">
<g inkscape:label="Capa 1" inkscape:groupmode="layer" id="layer1" transform="matrix(1 0 0 1 -326 -534.3622)">
<rect width="8" x="329" y="537.36218" height="1.00002" style="fill:#6c7a89" id="rect4279"/>
<rect width="16" x="329" y="541.36218" height="1" style="fill:#6c7a89" id="rect4281"/>
<rect width="16" x="329" y="548.36218" height="1" style="fill:#6c7a89" id="rect4283"/>
<rect width="8" x="329" y="545.36218" height="1" style="fill:#6c7a89" id="rect4285"/>
<rect width="12" x="329" y="552.36218" height="0.999983" style="fill:#6c7a89" id="rect4287"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 919 B

+15
View File
@@ -0,0 +1,15 @@
[Desktop Entry]
Type=Application
Name=CST-agent
GenericName=Local coding agent
Comment=The engine in a window: workspace is the directory it is started in
Exec=cst-agent-app
TryExec=cst-agent-app
Icon=cst-agent-app
Terminal=false
StartupNotify=true
# Qt puts the application name in the Wayland app_id / WM_CLASS, so this has to
# stay the file's own name or the launcher draws a generic icon.
StartupWMClass=cst-agent-app
Categories=Development;Utility;
Keywords=agent;ai;assistant;code;
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- The launcher icon: the prompt the CLI shows, on a tile in the window's own
palette (app/qml/Theme.qml). Installed under hicolor/scalable, so the
desktops that want raster sizes render it themselves. -->
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
<rect x="6" y="6" width="116" height="116" rx="26" ry="26"
fill="#15181a" stroke="#343b41" stroke-width="5"/>
<path d="M36 42 L56 64 L36 86" fill="none" stroke="#3daee9" stroke-width="12"
stroke-linecap="round" stroke-linejoin="round"/>
<path d="M69 88 H94" fill="none" stroke="#eff0f1" stroke-width="12"
stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 712 B

+108
View File
@@ -0,0 +1,108 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// on_ask_user: the agent stopped and wants an answer from the human. Options
// (when the engine sends any) become buttons; the field is always there.
Dialog {
id: dialog
property string question: ""
property string optionText: ""
signal answered(string text)
readonly property var options: {
const raw = optionText.split(/[|\n]/).map(s => s.trim()).filter(s => s.length > 0 && s.length < 60)
return raw.length > 1 && raw.length <= 8 ? raw : []
}
modal: true
anchors.centerIn: parent
width: Math.min(620, parent ? parent.width - 60 : 620)
padding: Theme.pad
background: Rectangle {
color: Theme.surface
border.width: 1
border.color: Theme.border
radius: Theme.radius
}
function send(text) {
const t = text.trim()
if (!t.length)
return
answered(t)
close()
}
contentItem: ColumnLayout {
spacing: Theme.gap
RowLayout {
spacing: Theme.gap
Rectangle { width: 8; height: 8; radius: 4; color: Theme.accent }
Text {
text: "The agent asks"
color: Theme.text
font.pixelSize: Theme.bodySize + 1
font.bold: true
}
}
Text {
Layout.fillWidth: true
text: dialog.question
color: Theme.text
font.pixelSize: Theme.bodySize
wrapMode: Text.Wrap
}
Text {
Layout.fillWidth: true
visible: dialog.optionText.length > 0 && dialog.options.length === 0
text: dialog.optionText
color: Theme.textDim
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
Flow {
Layout.fillWidth: true
visible: dialog.options.length > 0
spacing: Theme.gap
Repeater {
model: dialog.options
Button {
text: modelData
onClicked: dialog.send(modelData)
}
}
}
TextField {
id: answer
Layout.fillWidth: true
placeholderText: "your answer"
placeholderTextColor: Theme.textFaint
color: Theme.text
font.pixelSize: Theme.bodySize
selectByMouse: true
onAccepted: dialog.send(text)
background: Rectangle {
radius: Theme.radiusSm
color: Theme.bg
border.width: 1
border.color: answer.activeFocus ? Theme.accentDim : Theme.border
}
}
}
footer: DialogButtonBox {
padding: Theme.pad
Button {
text: "Send"
highlighted: true
enabled: answer.text.trim().length > 0
DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole
onClicked: dialog.send(answer.text)
}
}
onOpened: answer.forceActiveFocus()
}
+152
View File
@@ -0,0 +1,152 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// The transcript: cards for the messages, a card per tool call, folded
// thinking blocks and one-line notes. Follows the tail of the conversation
// until the user scrolls away from it.
Item {
id: view
property var model: null
property bool running: false
ListView {
id: list
objectName: "transcript"
anchors.fill: parent
anchors.leftMargin: Theme.gapL
anchors.rightMargin: Theme.gapL
model: view.model
clip: true
spacing: Theme.gap
topMargin: Theme.gapL
bottomMargin: Theme.gapL
cacheBuffer: 2000
boundsBehavior: Flickable.StopAtBounds
// The delegate picks the card by row kind; the components below read
// the ListModel roles directly, which is why they are declared in the
// delegate's scope.
delegate: Loader {
id: rowLoader
width: list.width
sourceComponent: model.kind === "tool" ? toolComp
: model.kind === "think" ? thinkComp
: model.kind === "note" ? noteComp : msgComp
Component {
id: msgComp
MessageCard {
role: model.role
text: model.text
complete: model.complete
images: model.images !== undefined ? model.images : ""
/* html comes from the streaming renderer (Main.qml) or,
* for a replayed session, from here once. */
html: model.html.length > 0 ? model.html
: (model.role === "agent" || model.role === "error") &&
model.complete && model.text.length > 0
? agent.renderMarkdown(model.text) : ""
}
}
Component {
id: thinkComp
ThinkBlock {
text: model.text
complete: model.complete
}
}
Component {
id: toolComp
ToolCard {
objectName: "toolCard"
name: model.name
state: model.state
detail: model.detail
output: model.output
exitCode: model.exitCode
hasResult: model.complete
images: model.images !== undefined ? model.images : ""
}
}
Component {
id: noteComp
NoteLine {
text: model.text
level: model.state === "warn" || model.state === "error" ? model.state : "info"
}
}
}
onMovementEnded: view.stickBottom = atYEnd
onCountChanged: if (view.stickBottom) Qt.callLater(list.positionViewAtEnd)
onContentHeightChanged: if (view.stickBottom) Qt.callLater(list.positionViewAtEnd)
}
// Follow the tail unless the user asked otherwise.
property bool stickBottom: true
// Empty state: what this window is and what to do with it.
ColumnLayout {
anchors.centerIn: parent
width: Math.min(parent.width - 80, 520)
spacing: Theme.gap
visible: view.model ? view.model.count === 0 : true
Text {
Layout.alignment: Qt.AlignHCenter
text: "CST-agent"
color: Theme.text
font.pixelSize: 22
font.bold: true
}
Text {
Layout.alignment: Qt.AlignHCenter
text: "The engine runs in this window — no server, no second process."
color: Theme.textDim
font.pixelSize: Theme.bodySize
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
Layout.fillWidth: true
}
Text {
Layout.alignment: Qt.AlignHCenter
Layout.topMargin: Theme.gap
text: "Ask for a change, a command to run, a file to explain.\n" +
"Every write, delete and command asks first: Deny / Once / Always.\n" +
"Enter sends, Shift+Enter adds a line, Esc stops a running turn."
color: Theme.textFaint
font.pixelSize: Theme.smallSize
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
Layout.fillWidth: true
}
}
// Jump back to the live end of the conversation.
RoundButton {
id: jump
anchors.right: parent.right
anchors.bottom: parent.bottom
anchors.margins: Theme.padL
width: Theme.jumpButton
height: Theme.jumpButton
visible: !view.stickBottom && list.contentHeight > list.height
contentItem: ThemeIcon {
name: "go-down"
glyph: "↓"
size: 20
color: Theme.text
}
background: Rectangle {
radius: width / 2
color: jump.hovered ? Theme.surfaceHi : Theme.surfaceAlt
border.width: 1
border.color: Theme.border
}
onClicked: {
view.stickBottom = true
list.positionViewAtEnd()
}
}
}
+252
View File
@@ -0,0 +1,252 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs
import QtQuick.Layouts
// The input line: multiline, Enter sends, the button changes with the turn
// state. Sized for a thumb as much as for a mouse, and it asks the platform
// keyboard not to autocorrect what is usually code or a path.
//
// Files arrive three ways -- the clip picker, a drop on the window (Main.qml)
// and an image on the clipboard (Ctrl+V) -- and all of them end up in the
// engine's pending list, which the next prompt carries.
Rectangle {
id: root
objectName: "composer"
property bool running: false
property bool compact: false
property string note: "" // a failure, or what was just attached
property var attachments: [] // AgentCore::pending, "name (mime, 12 KB)"
property alias text: input.text
signal submitted(string text)
function submit() {
const t = input.text.trim()
if (!t.length)
return
input.text = ""
submitted(t)
}
/* A file: from the picker, or a URL dropped on the window. */
function localPath(url) {
let s = String(url)
// A phone's picker (SAF) hands over content:// URIs: they are not
// paths and must not be decoded -- the app copies what they point at
// into its own directory before the engine sees it (see
// app::materializeAttachment).
if (s.startsWith("content://"))
return s
if (s.startsWith("file://"))
s = s.substring(7)
/* Windows keeps its drive letter after the slash. */
if (/^\/[A-Za-z]:/.test(s))
s = s.substring(1)
return decodeURIComponent(s)
}
function attachPath(path) {
const r = agent.attachFile(path)
note = r.length ? r : ""
}
radius: Theme.radius
color: Theme.surface
border.width: 1
border.color: input.activeFocus ? Theme.accentDim : Theme.border
/* One pad of frame on every side of the column: with the top margin
* alone the last row (the clip and Send) hung over the lower border,
* which is what put the clip on the frame instead of inside it. */
implicitHeight: layout.implicitHeight + Theme.pad * 2
ColumnLayout {
id: layout
anchors {
fill: parent
margins: Theme.pad
}
spacing: 6
// What the next prompt will carry, in the engine's own words.
Flow {
Layout.fillWidth: true
visible: root.attachments.length > 0
spacing: 6
Repeater {
model: root.attachments
delegate: Rectangle {
id: chip
required property var modelData
required property int index
objectName: "attachChip" + chip.index
implicitWidth: chipText.implicitWidth + 14
implicitHeight: 24
radius: Theme.radiusSm
color: Theme.surfaceAlt
border.width: 1
border.color: Theme.border
Text {
id: chipText
anchors.centerIn: parent
text: String(chip.modelData)
color: Theme.textDim
font.pixelSize: Theme.smallSize
}
}
}
Button {
id: clearAtt
objectName: "clearAttachments"
text: "clear all"
implicitHeight: 24
onClicked: {
agent.clearPending()
root.note = ""
}
background: Rectangle {
radius: Theme.radiusSm
color: clearAtt.hovered ? Theme.surfaceHi : "transparent"
border.width: 1
border.color: Theme.border
}
contentItem: Text {
text: clearAtt.text
color: clearAtt.hovered ? Theme.text : Theme.textFaint
font.pixelSize: Theme.smallSize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
}
Text {
Layout.fillWidth: true
visible: root.note.length > 0
text: root.note
color: Theme.warn
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
TextArea {
id: input
objectName: "composerInput"
Layout.fillWidth: true
Layout.preferredHeight: Math.min(root.compact ? 120 : 170,
Math.max(56, contentHeight + 12))
placeholderText: root.running
? "Send a correction now — Esc pauses execution"
: (root.compact
? "Ask for something…"
: "Ask for something (Enter sends, Shift+Enter for a new line)")
placeholderTextColor: Theme.textFaint
color: Theme.text
font.pixelSize: Theme.bodySize
wrapMode: TextArea.Wrap
selectByMouse: true
selectionColor: Theme.accentDim
inputMethodHints: Qt.ImhMultiLine | Qt.ImhNoPredictiveText |
Qt.ImhNoAutoUppercase
background: Rectangle { color: "transparent" }
enabled: true
Keys.onPressed: function (ev) {
if (ev.key === Qt.Key_Return || ev.key === Qt.Key_Enter) {
if (!(ev.modifiers & Qt.ShiftModifier)) {
root.submit()
ev.accepted = true
}
return
}
/* An image has nothing the editor could paste, so Ctrl+V
* becomes an attachment there; text stays with the
* editor's own paste. */
if ((ev.modifiers & Qt.ControlModifier) && ev.key === Qt.Key_V &&
agent.clipboardHasImage()) {
root.note = agent.attachClipboard()
ev.accepted = true
}
}
}
ToolButton {
id: attach
objectName: "attachButton"
Layout.alignment: Qt.AlignBottom
implicitWidth: root.compact ? Theme.touchTarget : 40
implicitHeight: Theme.touchTarget + 4
enabled: !root.running
ToolTip.visible: hovered
ToolTip.text: "Attach a file — or drop one on the window, or paste an image"
contentItem: ThemeIcon {
name: "mail-attachment"
glyph: "📎"
size: 20
color: attach.enabled ? (attach.hovered ? Theme.text : Theme.textDim)
: Theme.textFaint
}
background: Rectangle {
radius: Theme.radiusSm
color: attach.hovered && attach.enabled ? Theme.surfaceHi
: "transparent"
}
onClicked: picker.open()
}
Button {
id: action
objectName: "sendButton"
Layout.alignment: Qt.AlignBottom
implicitWidth: root.compact ? 68 : 88
implicitHeight: Theme.touchTarget + 4
text: root.running ? (input.text.trim().length ? "Redirect" : "Stop") : "Send"
enabled: root.running || input.text.trim().length > 0
onClicked: root.running && !input.text.trim().length ? agent.cancel() : root.submit()
background: Rectangle {
radius: Theme.radiusSm
color: !action.enabled ? Theme.surfaceAlt
: root.running ? (action.hovered ? "#e05666" : Theme.err)
: (action.hovered ? "#5cc0f0" : Theme.accent)
}
contentItem: Text {
text: action.text
color: action.enabled ? Theme.accentInk : Theme.textFaint
font.pixelSize: Theme.bodySize
font.bold: true
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
}
// On a narrow window the hint would wrap into the editor's space.
Text {
Layout.fillWidth: true
visible: !root.compact
text: {
if (root.running)
return "working — Esc cancels the turn"
let s = "Enter sends · Shift+Enter newline · Esc stops · the clip attaches a file, Ctrl+V an image"
if (root.attachments.length > 0 && agent.seesImages() === 0)
s += " · this model is text-only, images arrive as notes"
return s
}
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
FileDialog {
id: picker
title: "Attach a file"
fileMode: FileDialog.OpenFile
onAccepted: root.attachPath(root.localPath(selectedFile))
}
}
+122
View File
@@ -0,0 +1,122 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// The engine's on_permission hook is blocked on this dialog: nothing runs
// until one of the three answers goes back.
Dialog {
id: dialog
property string tool: ""
property string detail: ""
property string preview: ""
signal answered(int choice)
modal: true
anchors.centerIn: parent
width: Math.min(760, parent ? parent.width - 60 : 760)
padding: Theme.pad
title: ""
background: Rectangle {
color: Theme.surface
border.width: 1
border.color: Theme.border
radius: Theme.radius
}
contentItem: ColumnLayout {
spacing: Theme.gap
RowLayout {
spacing: Theme.gap
Rectangle {
width: 8
height: 8
radius: 4
color: Theme.warn
}
Text {
text: "Permission requested"
color: Theme.text
font.pixelSize: Theme.bodySize + 1
font.bold: true
}
Text {
Layout.fillWidth: true
elide: Text.ElideRight
text: dialog.tool
color: Theme.warn
font.family: Theme.mono
font.pixelSize: Theme.monoSize
}
}
Text {
Layout.fillWidth: true
visible: dialog.detail.length > 0
text: dialog.detail
color: Theme.textDim
font.pixelSize: Theme.bodySize
wrapMode: Text.Wrap
}
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: Math.min(320, previewText.implicitHeight + Theme.pad * 2)
visible: dialog.preview.length > 0
color: Theme.bg
radius: Theme.radiusSm
border.width: 1
border.color: Theme.border
Flickable {
id: flick
anchors.fill: parent
anchors.margins: 8
contentWidth: previewText.width
contentHeight: previewText.height
clip: true
ScrollBar.vertical: ScrollBar {}
Text {
id: previewText
width: Math.max(flick.width, implicitWidth)
text: dialog.preview
color: Theme.text
font.family: Theme.mono
font.pixelSize: Theme.monoSize
textFormat: Text.PlainText
}
}
}
Text {
Layout.fillWidth: true
text: "“Always” is remembered for this tool in .agent/permissions.json — the TUI and the CLI see the same decision."
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
}
footer: DialogButtonBox {
spacing: Theme.gap
padding: Theme.pad
Button {
text: "Deny"
DialogButtonBox.buttonRole: DialogButtonBox.RejectRole
onClicked: { dialog.answered(0); dialog.close() }
}
Button {
text: "Once"
highlighted: true
DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole
onClicked: { dialog.answered(1); dialog.close() }
}
Button {
text: "Always"
DialogButtonBox.buttonRole: DialogButtonBox.ActionRole
onClicked: { dialog.answered(2); dialog.close() }
}
}
}
+269
View File
@@ -0,0 +1,269 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// The files a message or a tool call carries.
//
// A picture is a thumbnail from the session's own store (image://cstattach/,
// app/src/ui/SessionImages.cpp) and opens with whatever the system uses for
// images when it is tapped. A file the agent delivered (deliver_file) is a card
// with the name, the type, the size and two buttons: open and share. The names
// are the ones the engine wrote next to the session -- a card never invents a
// path.
//
// One line per file, written by AgentCore.cpp (filesText):
// <kind>|<stored name>|<name>|<origin>|<mime>|<bytes>|<w>x<h>
// A session saved by an older version wrote "<stored name>|<name>|<origin>|
// <w>x<h>" for pictures; both shapes are read here.
Flow {
id: strip
objectName: "imageStrip"
/* A row carries this as text: a ListModel role cannot hold a list. */
property string text: ""
property var files: decode(text)
/* The last refusal, so a tap that cannot work says why (the header's own
* status line is the engine's). */
property string errorText: ""
spacing: 6
function decode(t) {
const out = []
const lines = String(t).split("\n")
for (let i = 0; i < lines.length; i++) {
if (!lines[i].length)
continue
const f = lines[i].split("|")
if (!f[0].length)
continue
const old = f.length < 7 // a picture line from an old session
const dim = String(old ? f[3] : f[6]).split("x")
let w = 0, h = 0
if (dim.length === 2) {
w = parseInt(dim[0], 10) || 0
h = parseInt(dim[1], 10) || 0
}
const rel = old ? f[0] : f[1]
out.push({ kind: old ? "img" : f[0],
rel: rel,
name: (old ? f[1] : f[2]) || rel,
origin: (old ? f[2] : f[3]) || "",
mime: old ? "image/*" : (f[4] || ""),
bytes: old ? 0 : (parseInt(f[5], 10) || 0),
w: w, h: h,
url: "image://cstattach/" + rel })
}
return out
}
function humanSize(n) {
if (!n || n <= 0)
return ""
if (n >= 1024 * 1024)
return (n / (1024 * 1024)).toFixed(1) + " MB"
if (n >= 1024)
return Math.round(n / 1024) + " KB"
return n + " B"
}
/* The two things a file card does. The engine answers with "" when it
* worked (it puts the line in the header itself) or a reason. */
function openFile(rel) {
errorText = agent.openArtifact(rel)
}
function shareFile(rel) {
errorText = agent.shareArtifact(rel)
}
Repeater {
model: strip.files
delegate: Rectangle {
id: cell
required property var modelData
required property int index
readonly property bool isFile: String(modelData.kind) !== "img"
readonly property bool hovered: mouse.containsMouse
/* Images keep their own shape, capped; a file card is a fixed
* width so a long name cannot stretch the transcript. */
readonly property real ratio: {
const w = Number(modelData.w), h = Number(modelData.h)
return (w > 0 && h > 0) ? w / h : 1.5
}
readonly property int cap: 150
objectName: isFile ? ("fileCard" + index) : ("imageThumb" + index)
width: isFile ? 300
: Math.max(56, Math.min(Math.round(cap * ratio), 320))
height: isFile ? 52
: Math.max(40, Math.min(cap, Math.round(width / ratio)))
radius: Theme.radiusSm
color: Theme.bg
border.width: 1
border.color: hovered ? Theme.accentDim : Theme.border
clip: true
MouseArea {
id: mouse
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.NoButton
}
// --- a picture: tap it to look at it ---------------------------
Image {
id: pic
anchors.fill: parent
anchors.margins: 2
visible: !cell.isFile && status === Image.Ready
source: String(cell.modelData.url)
sourceSize.width: 512
sourceSize.height: 512
fillMode: Image.PreserveAspectFit
asynchronous: false
}
Text {
anchors.centerIn: parent
width: parent.width - 8
visible: !cell.isFile && pic.status === Image.Error
text: String(cell.modelData.name)
elide: Text.ElideMiddle
horizontalAlignment: Text.AlignHCenter
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
MouseArea {
anchors.fill: parent
enabled: !cell.isFile
cursorShape: Qt.PointingHandCursor
onClicked: strip.openFile(String(cell.modelData.rel))
}
// --- a delivered file: name, type, open, share -----------------
RowLayout {
id: row
visible: cell.isFile
anchors.fill: parent
anchors.leftMargin: 8
anchors.rightMargin: 6
spacing: 6
/* The extension stands in for an icon: no theme lookup, and a
* ZIP that says ZIP is more use than a generic sheet. */
Rectangle {
implicitWidth: 40
implicitHeight: 30
radius: Theme.radiusSm
color: Theme.surfaceHi
Text {
anchors.centerIn: parent
text: {
const n = String(cell.modelData.name)
const dot = n.lastIndexOf(".")
if (dot < 0 || dot === n.length - 1)
return "FILE"
return n.slice(dot + 1, dot + 5).toUpperCase()
}
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
}
ColumnLayout {
Layout.fillWidth: true
spacing: 0
Text {
Layout.fillWidth: true
text: String(cell.modelData.name)
color: Theme.text
font.pixelSize: Theme.bodySize
elide: Text.ElideMiddle
}
Text {
Layout.fillWidth: true
text: {
const m = cell.modelData
let s = m.mime ? String(m.mime) : ""
const size = strip.humanSize(m.bytes)
if (size)
s += (s ? " · " : "") + size
if (m.origin && m.origin !== "user" && m.origin !== "tool")
s += (s ? " · " : "") + m.origin
return s
}
color: Theme.textFaint
font.pixelSize: Theme.smallSize
elide: Text.ElideRight
}
}
ToolButton {
objectName: "fileOpen" + cell.index
implicitWidth: Theme.touchTarget
implicitHeight: Theme.touchTarget
onClicked: strip.openFile(String(cell.modelData.rel))
contentItem: Text {
text: "Open"
color: parent.hovered ? Theme.text : Theme.textDim
font.pixelSize: Theme.smallSize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
border.width: 1
border.color: Theme.border
}
}
ToolButton {
objectName: "fileShare" + cell.index
implicitWidth: Theme.touchTarget
implicitHeight: Theme.touchTarget
onClicked: strip.shareFile(String(cell.modelData.rel))
contentItem: Text {
text: "Share"
color: parent.hovered ? Theme.text : Theme.textDim
font.pixelSize: Theme.smallSize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
border.width: 1
border.color: Theme.border
}
}
}
ToolTip.visible: hovered
ToolTip.delay: 400
ToolTip.text: {
const m = cell.modelData
let s = String(m.name)
if (m.w > 0 && m.h > 0)
s += " · " + m.w + "×" + m.h
if (m.mime && m.kind !== "img")
s += " · " + m.mime
return s
}
}
}
/* A tap that could not work says why, right where the card is: a phone
* with nothing installed for the type is the common case ("no app on the
* phone opens report.md"), and a silence there looks like a dead button. */
Text {
objectName: "fileError"
visible: strip.errorText.length > 0
width: strip.width
wrapMode: Text.WordWrap
text: strip.errorText
color: Theme.err
font.pixelSize: Theme.smallSize
}
}
+717
View File
@@ -0,0 +1,717 @@
// The window: a sidebar with the engine's settings, the transcript, the
// composer, and the two dialogs the engine can block on.
//
// One shell, three sizes: the sidebar is docked on a desktop (and can be
// dragged), slides over the transcript when the window is narrow, and every
// control keeps a finger-sized hit area for touch screens. Qt Quick Controls
// only, laid out the way Kirigami expects (sidebar + page, cards, header), so
// swapping in org.kde.kirigami later stays a QML change.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
id: win
width: initialWidth > 0 ? initialWidth : 1180
height: initialHeight > 0 ? initialHeight : 800
minimumWidth: 360
minimumHeight: 420
visible: true
color: Theme.bg
title: "CST-agent — " + (agent.workspace.length ? agent.workspace : "no workspace")
property string statusText: ""
property var sessionsView: [] // the store, for the sidebar
property bool navOpen: false // the sliding sidebar, compact only
TaskPanel { id: taskPanel; anchors.centerIn: parent }
property int sidebarWidth: 0 // 0 = follow the window width
readonly property bool compact: width < Theme.compactBreakpoint
readonly property int sidebarWide: sidebarWidth > 0
? sidebarWidth
: Math.max(228, Math.min(360, Math.round(width * 0.26)))
// The settings panel, used docked and in the sliding panel: one definition,
// two places.
component ShellSidebar: Sidebar {
workspace: agent.workspace
provider: agent.provider
model: agent.model
mode: agent.mode
approval: agent.approval
planMode: agent.planMode
running: agent.running
status: win.statusText
todo: agent.todo
sessions: win.sessionsView
sessionId: agent.sessionId
onModeRequested: function (m) { agent.setMode(m) }
onSessionRequested: function (id) { win.switchSession(id) }
onSessionNewRequested: win.newSession()
onSessionDeleteRequested: function (id) { win.deleteSession(id) }
onApprovalRequested: function (a) { agent.setApproval(a) }
onPlanModeRequested: function (on) { agent.setPlanMode(on) }
}
// ---- the transcript --------------------------------------------------
ListModel { id: transcript }
function lastIndex() { return transcript.count - 1 }
function lastRow() { return transcript.count ? transcript.get(lastIndex()) : null }
function addRow(kind, role, state) {
transcript.append({ kind: kind, role: role, text: "", html: "", complete: false,
name: "", callId: "", state: state, detail: "", output: "",
exitCode: 0, images: "" })
}
// The engine streams one kind at a time: close whatever was open before.
function closeOpenRows(exceptKind) {
const last = lastRow()
if (last && !last.complete && last.kind !== exceptKind)
transcript.setProperty(lastIndex(), "complete", true)
}
function appendDelta(kind, role, text) {
closeOpenRows(kind)
if (!lastRow() || lastRow().kind !== kind || lastRow().complete)
addRow(kind, role, "running")
transcript.setProperty(lastIndex(), "text", lastRow().text + text)
}
// The open card of this call, -1 when none. The id is what tells two calls
// of the same tool apart (pairing by name left the first card running
// forever); a call without one -- an old text-protocol session -- falls
// back to the name.
function findTool(callId, name) {
for (let i = transcript.count - 1; i >= 0; i--) {
const r = transcript.get(i)
if (r.kind !== "tool" || r.complete)
continue
if (callId.length) {
if (r.callId === callId)
return i
continue /* another call: its card is further back */
}
if (r.callId.length)
continue
if (r.name === name)
return i
return -1
}
return -1
}
function openTool(callId, name, state) {
closeOpenRows("tool")
addRow("tool", "tool", state)
transcript.setProperty(lastIndex(), "name", name)
transcript.setProperty(lastIndex(), "callId", callId)
return lastIndex()
}
function submit(text) {
transcript.append({ kind: "message", role: "user", text: text, html: "", complete: true,
name: "", callId: "", state: "", detail: "", output: "",
exitCode: 0, images: "" })
agent.send(text)
}
// A turn is over: nothing else is coming, so nothing may keep spinning.
function closeAllRows() {
for (let i = 0; i < transcript.count; i++) {
const r = transcript.get(i)
if (r.complete)
continue
if (r.kind === "tool" && (r.state === "pending" || r.state === "ready" ||
r.state === "running"))
transcript.setProperty(i, "state", "unfinished")
transcript.setProperty(i, "complete", true)
}
}
// Markdown while it streams: the open answer is re-rendered with the
// engine's own renderer (the timer below), so the text fills in formatted
// instead of turning into markdown when the turn ends.
function renderStreaming() {
for (let i = transcript.count - 1; i >= 0; i--) {
const r = transcript.get(i)
if (r.kind !== "message" || r.role !== "agent" || r.complete)
continue
const html = agent.renderMarkdown(r.text)
if (html !== r.html)
transcript.setProperty(i, "html", html)
return
}
}
// ---- sessions --------------------------------------------------------
function reloadSessions() { win.sessionsView = agent.sessions() }
// A stored session comes back as rows: the engine holds the transcript
// (AgentCore::history()), these rows only mirror it.
function replay() {
transcript.clear()
const rows = agent.history()
for (let i = 0; i < rows.length; i++)
transcript.append(rows[i])
chat.stickBottom = true
}
function switchSession(id) {
if (agent.switchSession(id))
win.reloadSessions()
}
function newSession() {
if (agent.newSession()) {
transcript.clear()
win.reloadSessions()
}
}
function deleteSession(id) {
if (agent.deleteSession(id))
win.reloadSessions()
}
// ---- provider, model, key --------------------------------------------
function openSettings() {
settings.load(agent.providers(), agent.provider, agent.model)
settings.open()
}
function applySettings(provider, model, key, temperature, topP, maxTokens) {
/* The parameters are stored first: useProvider() then picks up what
* was remembered for whichever provider it ends on. */
const perr = agent.setGenParams(provider, temperature, topP, maxTokens)
const err = perr.length ? perr : agent.useProvider(provider, model, key)
settings.note = err.length ? err
: "using " + agent.provider + " / " + agent.model
settings.choices = agent.modelChoices(provider)
settings.syncPick()
}
/* The engine opens the workspace's last session (cst_agent_open()), so the
* window is created with a transcript already in it: draw it, or the pane
* starts empty while the sidebar points at the very session it belongs to.
* A switch draws it the same way (the sessionChanged handler below). */
Component.onCompleted: {
win.reloadSessions()
win.replay()
}
// ---- the shell -------------------------------------------------------
/* A plain Rectangle, not a ToolBar. A Controls ToolBar hands its children
* to a style-owned contentItem, and on this phone that item sat 35 px below
* the bar itself -- header y 0 h 42 with its gear at y 56 -- so the gear
* was drawn, and clicked, outside the header, over the sidebar. A
* Rectangle puts its children where it is (checked with --uitest on the
* device and on both styles at home). */
header: Rectangle {
id: appBar
objectName: "appBar"
implicitHeight: Theme.headerHeight
color: Theme.surface
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: Theme.border
}
RowLayout {
anchors.fill: parent
anchors.leftMargin: Theme.pad
anchors.rightMargin: Theme.gap
spacing: Theme.gap
// The docked sidebar has its own title: only the sliding one needs
// a way in.
ToolButton {
objectName: "navButton"
visible: win.compact
implicitWidth: Theme.touchTarget
implicitHeight: Theme.touchTarget
ToolTip.visible: hovered && !win.compact
ToolTip.text: "Settings and plan"
contentItem: ThemeIcon {
name: "application-menu"
glyph: "☰"
size: 22
color: parent.hovered ? Theme.text : Theme.textDim
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
}
onClicked: win.navOpen = !win.navOpen
}
Text {
visible: !win.compact
text: "CST-agent"
color: Theme.text
font.pixelSize: Theme.bodySize
font.bold: true
}
Text {
Layout.fillWidth: true
elide: Text.ElideMiddle
text: agent.workspace.length ? agent.workspace : "(no workspace)"
color: Theme.textDim
font.pixelSize: Theme.smallSize
}
Text {
objectName: "statusText"
visible: win.statusText.length > 0 && !win.compact
text: win.statusText
color: Theme.textFaint
font.pixelSize: Theme.smallSize
elide: Text.ElideRight
Layout.maximumWidth: 260
}
BusyIndicator {
running: agent.running
visible: agent.running
implicitWidth: 22
implicitHeight: 22
}
ToolButton {
objectName: "settingsButton"
implicitWidth: Theme.touchTarget
implicitHeight: Theme.touchTarget
ToolTip.visible: hovered
ToolTip.text: "Provider, model and key"
contentItem: ThemeIcon {
name: "settings-configure"
glyph: "⚙"
size: 22
color: parent.hovered ? Theme.text : Theme.textDim
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
}
onClicked: win.openSettings()
}
ToolButton {
objectName: "clearButton"
enabled: transcript.count > 0 && !agent.running
implicitWidth: win.compact ? Theme.touchTarget : 56
implicitHeight: Theme.touchTarget
ToolTip.visible: hovered
ToolTip.text: "Clear the transcript (Ctrl+L) — the session file keeps its history"
contentItem: Text {
text: "Clear"
color: parent.enabled ? (parent.hovered ? Theme.text : Theme.textDim) : Theme.textFaint
font.pixelSize: Theme.smallSize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered && parent.enabled ? Theme.surfaceHi : "transparent"
}
onClicked: {
transcript.clear()
win.statusText = ""
}
}
ToolButton {
objectName: "taskPanelButton"
text: "Tasks"
implicitHeight: Theme.touchTarget
onClicked: taskPanel.open()
}
}
}
RowLayout {
anchors.fill: parent
spacing: 0
ShellSidebar {
id: dockedSidebar
objectName: "dockedSidebar"
visible: !win.compact
Layout.fillHeight: true
Layout.preferredWidth: win.sidebarWide
}
// Drag the divider: a mouse affordance that costs nothing on touch
// (the handle is only there while the sidebar is docked).
Item {
id: divider
visible: !win.compact
Layout.fillHeight: true
implicitWidth: 5
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
width: 1
height: parent.height
color: dividerMa.pressed ? Theme.accentDim
: dividerMa.containsMouse ? Theme.surfaceHi : Theme.border
}
MouseArea {
id: dividerMa
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.SplitHCursor
property real startX: 0
property int startW: 0
onPressed: function (mouse) {
startX = mouse.x
startW = win.sidebarWide
}
onPositionChanged: function (mouse) {
if (pressed)
win.sidebarWidth = Math.max(200, Math.min(560, startW + Math.round(mouse.x - startX)))
}
onDoubleClicked: win.sidebarWidth = 0
}
}
ColumnLayout {
Layout.fillWidth: true
Layout.fillHeight: true
spacing: 0
ChatView {
id: chat
objectName: "chatView"
Layout.fillWidth: true
Layout.fillHeight: true
model: transcript
running: agent.running
}
Composer {
id: composer
Layout.fillWidth: true
Layout.leftMargin: win.compact ? Theme.gap : Theme.gapL
Layout.rightMargin: win.compact ? Theme.gap : Theme.gapL
Layout.bottomMargin: win.compact ? Theme.gap : Theme.gapL
running: agent.running
compact: win.compact
attachments: agent.pending
onSubmitted: function (text) { win.submit(text) }
}
}
}
// ---- compact: the sidebar slides in over the transcript --------------
/* Files dropped anywhere on the window: the engine copies them next to
* the session and the next prompt carries them. The picker and Ctrl+V in
* the composer land in the same list. */
DropArea {
id: dropZone
objectName: "dropZone"
anchors.fill: parent
onDropped: function (drop) {
if (!drop.hasUrls)
return
let note = ""
let n = 0
for (let i = 0; i < drop.urls.length; i++) {
const r = agent.attachFile(composer.localPath(drop.urls[i]))
if (r.length)
note = r
else
n++
}
composer.note = note.length ? note
: n + (n === 1 ? " file attached" : " files attached")
drop.accept()
}
}
// While something is dragged over the window, say what will happen.
Rectangle {
anchors.fill: parent
visible: dropZone.containsDrag
color: "transparent"
border.width: 2
border.color: Theme.accent
Text {
anchors.centerIn: parent
text: "drop to attach"
color: Theme.accent
font.pixelSize: Theme.bodySize
font.bold: true
}
}
Rectangle {
id: scrim
objectName: "navScrim"
visible: win.navOpen && win.compact
anchors.fill: parent
color: "#000000"
opacity: 0.45
MouseArea {
anchors.fill: parent
onClicked: win.navOpen = false
onWheel: function (wheel) { wheel.accepted = true }
}
}
Rectangle {
id: navPanel
objectName: "navPanel"
visible: win.navOpen && win.compact
anchors {
left: parent.left
top: parent.top
bottom: parent.bottom
}
width: Math.min(320, win.width * 0.88)
color: Theme.surface
border.width: 1
border.color: Theme.border
x: win.navOpen && win.compact ? 0 : -width
Behavior on x { NumberAnimation { duration: 140; easing.type: Easing.OutCubic } }
Flickable {
anchors.fill: parent
contentHeight: panelSidebar.implicitHeight
clip: true
ScrollBar.vertical: ScrollBar {}
ShellSidebar {
id: panelSidebar
width: parent.width
border.width: 0
}
}
}
ConsentDialog {
id: consent
onAnswered: function (choice) { agent.answerPermission(choice) }
}
SettingsDialog {
id: settings
onApplyRequested: function (provider, model, key, temperature, topP, maxTokens) {
win.applySettings(provider, model, key, temperature, topP, maxTokens)
}
}
AskDialog {
id: ask
onAnswered: function (text) { agent.answerQuestion(text) }
}
Shortcut { sequence: "Escape"; enabled: agent.running; onActivated: agent.cancel() }
Shortcut {
sequence: "Ctrl+L"
enabled: !agent.running
onActivated: {
transcript.clear()
win.statusText = ""
}
}
/* The back key a phone has instead of a mouse: it closes what is open, one
* layer at a time -- the dialog on top, then the sliding sidebar. With
* nothing open the key goes on to the platform, and a phone leaves the
* window (Qt finishes the activity), which is right for the last layer.
*
* Which layer that is, and whether there is one, lives in one place: the
* C++ side (app/src/ui/BackKey.cpp) reads `backLayer()` on every Back key
* and calls `stepBack()` -- not a QML Shortcut, which a modal popup never
* lets through. --uitest reads the same two functions. */
function backLayer() {
if (settings.visible)
return "settings"
if (ask.visible)
return "ask"
if (consent.visible)
return "consent"
if (win.navOpen)
return "drawer"
return ""
}
/* One layer back. The dialogs are closed on the next turn of the event
* loop: closing one from inside the key event leaves its modal overlay up
* in this Qt (the dialog says it is closed, the overlay still eats every
* click after it), which --uitest walks straight into. */
function stepBack() {
if (settings.visible)
Qt.callLater(settings.close)
else if (ask.visible)
Qt.callLater(ask.close)
else if (consent.visible)
Qt.callLater(consent.close)
else if (win.navOpen)
win.navOpen = false
}
// ---- engine -> UI ----------------------------------------------------
/* The signal handlers only forward: every one of them has a function
* here, so the same path can be driven from --uitest (which is how the
* two-calls-of-one-tool case stays fixed). */
function engineAssistant(text) { win.appendDelta("message", "agent", text) }
function engineThink(text) { win.appendDelta("think", "agent", text) }
function engineToolEvent(phase, id, name, detail) {
win.closeOpenRows("tool")
let i = win.findTool(id, name)
if (phase === "open" || phase === "arg") {
if (i < 0)
i = win.openTool(id, name, "pending")
if (detail.length)
transcript.setProperty(i, "detail", transcript.get(i).detail + detail)
return
}
if (phase === "ready" || phase === "run") {
if (i < 0)
i = win.openTool(id, name, phase)
transcript.setProperty(i, "state", phase === "run" ? "running" : "queued")
transcript.setProperty(i, "detail", detail)
return
}
// done | denied
if (i < 0)
i = win.openTool(id, name, phase)
transcript.setProperty(i, "state", phase)
if (detail.length && transcript.get(i).output.length === 0)
transcript.setProperty(i, "output", detail)
}
function engineToolResult(id, name, exitCode, output) {
let i = win.findTool(id, name)
if (i < 0) /* a result whose call is not in the view: its own card */
i = win.openTool(id, name, "done")
transcript.setProperty(i, "output", output)
transcript.setProperty(i, "exitCode", exitCode)
transcript.setProperty(i, "state", "done")
transcript.setProperty(i, "complete", true)
}
function engineTurnFinished(rc, err) {
win.renderStreaming(); /* one last render while the row is still open */
win.closeAllRows()
if (err.length)
transcript.append({ kind: "note", role: "error", text: err, html: "",
complete: true, name: "", callId: "", state: "error",
detail: "", output: "", exitCode: 0 })
win.statusText = ""
}
/* The images the prompt just carried (AgentCore::promptImages): the
* composer has appended the user row, so they attach to it. */
function enginePromptImages(images) {
if (!images.length)
return
for (let i = transcript.count - 1; i >= 0; i--) {
const r = transcript.get(i)
if (r.kind === "message" && r.role === "user") {
transcript.setProperty(i, "images", images)
return
}
}
}
/* Files a tool produced, on the card of the call that made them. The
* engine reports the result first and the files after it, so the card is
* normally already complete by the time they arrive -- findTool() only
* looks at cards still running, which is why this looks for the call id
* itself (and falls back to findTool for a call that has no id). */
function engineToolImages(callId, images) {
if (!images.length)
return
let i = -1
if (callId.length) {
for (let k = transcript.count - 1; k >= 0; k--) {
const r = transcript.get(k)
if (r.kind === "tool" && r.callId === callId) {
i = k
break
}
}
} else {
i = win.findTool("", "")
}
if (i >= 0)
transcript.setProperty(i, "images", images)
}
/* For --uitest: one transcript row, or null. */
function rowAt(i) {
return (i >= 0 && i < transcript.count) ? transcript.get(i) : null
}
/* For --uitest: the same row as JSON (a QObject's return value does not
* survive QMetaObject::invokeMethod, a string does). */
function rowJson(i) {
return JSON.stringify(rowAt(i))
}
/* While a turn runs the open answer is re-rendered a few times a second:
* markdown text fills in formatted rather than at the end of the turn. */
Timer {
interval: 120
repeat: true
running: agent.running
onTriggered: win.renderStreaming()
}
Connections {
target: agent
function onSessionChanged() { win.reloadSessions(); win.replay() }
function onSessionListChanged() { win.reloadSessions() }
function onAssistantDelta(text) { win.engineAssistant(text) }
function onThinkDelta(text) { win.engineThink(text) }
function onStatusChanged(text) { win.statusText = text }
function onToolEvent(phase, id, name, detail) {
win.engineToolEvent(phase, id, name, detail)
}
function onToolResult(id, name, exitCode, output) {
win.engineToolResult(id, name, exitCode, output)
}
function onToolImages(callId, images) {
win.engineToolImages(callId, images)
}
function onPromptImages(images) {
win.enginePromptImages(images)
}
function onPermissionRequested(tool, detail, preview) {
consent.tool = tool
consent.detail = detail
consent.preview = preview
consent.open()
}
function onQuestionAsked(question, options) {
ask.question = question
ask.optionText = options
ask.open()
}
/* Nobody answered (the app was in the background, or the dialog sat
* there too long): the turn went on without it, so put the dialog
* away instead of leaving a question that is no longer being asked. */
function onPermissionExpired(tool) { consent.close() }
function onQuestionExpired() { ask.close() }
function onTurnFinished(rc, err) { win.engineTurnFinished(rc, err) }
function onRunningChanged() {
if (!agent.running)
win.closeAllRows()
}
}
}
+117
View File
@@ -0,0 +1,117 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// One message in the transcript: the prompt, the answer, or an error. The
// answer arrives as plain text while it streams and is rendered from markdown
// (by the engine, through AgentCore::renderMarkdown) once it is complete.
Rectangle {
id: card
property string role: "agent" // user | agent | error
property string text: ""
property string html: ""
property bool complete: true
property string images: ""
radius: Theme.radius
color: role === "user" ? Theme.surfaceAlt : Theme.surface
border.width: 1
border.color: role === "error" ? Theme.err
: role === "user" ? Theme.border : Theme.border
implicitHeight: layout.implicitHeight + Theme.pad * 2
ColumnLayout {
id: layout
anchors {
left: parent.left
right: parent.right
top: parent.top
margins: Theme.pad
}
spacing: Theme.gap
RowLayout {
spacing: Theme.gap
Rectangle {
width: 6
height: 6
radius: 3
color: card.role === "user" ? Theme.accent
: card.role === "error" ? Theme.err : Theme.ok
}
Text {
text: card.role === "user" ? "You"
: card.role === "error" ? "Error" : "CST-agent"
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
Text {
visible: !card.complete
text: "streaming…"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
Item { Layout.fillWidth: true }
ToolButton {
implicitWidth: 26
implicitHeight: 22
visible: card.text.length > 0
ToolTip.visible: hovered
ToolTip.text: "Copy"
contentItem: ThemeIcon {
name: "edit-copy"
glyph: "⧉"
size: 14
color: parent.hovered ? Theme.text : Theme.textFaint
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
}
onClicked: {
plain.text = card.text
plain.selectAll()
plain.copy()
}
}
}
// Hidden holder so "copy" always has the plain text, rtf or not.
TextEdit {
id: plain
visible: false
}
TextEdit {
id: streamText
visible: card.html.length === 0
Layout.fillWidth: true
text: card.text
readOnly: true
selectByMouse: true
wrapMode: TextEdit.Wrap
color: card.role === "error" ? Theme.err : Theme.text
font.pixelSize: Theme.bodySize
selectionColor: Theme.accentDim
}
Text {
visible: card.html.length > 0
Layout.fillWidth: true
text: card.html
textFormat: Text.RichText
color: Theme.text
font.pixelSize: Theme.bodySize
wrapMode: Text.Wrap
onLinkActivated: function (link) { Qt.openUrlExternally(link) }
}
// What the prompt carried: pictures from the store, not their names.
ImageStrip {
Layout.fillWidth: true
visible: card.images.length > 0
text: card.images
}
}
}
+29
View File
@@ -0,0 +1,29 @@
import QtQuick
import QtQuick.Layouts
// A one-line note from the engine (status text, a refusal, a hint).
RowLayout {
id: note
property string text: ""
property string level: "info" // info | warn | error
spacing: Theme.gap
Rectangle {
Layout.alignment: Qt.AlignTop
Layout.topMargin: 6
width: 5
height: 5
radius: 3
color: note.level === "error" ? Theme.err
: note.level === "warn" ? Theme.warn : Theme.textFaint
}
Text {
Layout.fillWidth: true
text: note.text
color: note.level === "error" ? Theme.err
: note.level === "warn" ? Theme.warn : Theme.textDim
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
textFormat: Text.PlainText
}
}
+106
View File
@@ -0,0 +1,106 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// One stored session in the sidebar: its name (a rename, else its first
// prompt), how much is in it and when it was last written, and a way to drop
// it. The open one is marked. A file of its own because the sidebar lists them
// through a Repeater -- an inline component would not see modelData there.
Rectangle {
id: srow
property var entry: null
readonly property bool open: entry !== null && entry.current === true
objectName: "sessionRow:" + (entry !== null ? entry.id : "")
implicitHeight: rowCol.implicitHeight + 8
radius: Theme.radiusSm
color: srow.open ? Theme.accentDim
: rowHover.hovered ? Theme.surfaceAlt : "transparent"
border.width: 1
border.color: srow.open ? Theme.accent : "transparent"
signal activated(string id)
signal removeRequested(string id)
// "3h ago"; the entries carry ms since the epoch.
function ago(ms) {
if (!ms)
return "never"
const s = Math.max(0, (Date.now() - ms) / 1000)
if (s < 60)
return "just now"
if (s < 3600)
return Math.floor(s / 60) + "m ago"
if (s < 86400)
return Math.floor(s / 3600) + "h ago"
return Math.floor(s / 86400) + "d ago"
}
HoverHandler { id: rowHover }
MouseArea {
anchors.fill: parent
onClicked: srow.activated(srow.entry.id)
}
RowLayout {
anchors {
left: parent.left
right: parent.right
top: parent.top
margins: 4
}
spacing: 2
ColumnLayout {
id: rowCol
Layout.fillWidth: true
Layout.leftMargin: 4
spacing: 0
Text {
Layout.fillWidth: true
elide: Text.ElideRight
text: srow.entry !== null && srow.entry.title.length ? srow.entry.title
: srow.entry !== null && srow.entry.firstUser.length ? srow.entry.firstUser
: "(no prompt yet)"
color: srow.open ? Theme.accentText : Theme.textDim
font.pixelSize: Theme.smallSize
}
Text {
Layout.fillWidth: true
elide: Text.ElideRight
text: {
if (srow.entry === null)
return ""
const n = srow.entry.messages
const when = srow.ago(srow.entry.mtime)
return n > 0 ? n + (n === 1 ? " message · " : " messages · ") + when
: when
}
color: srow.open ? Theme.accentTextDim : Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
ToolButton {
objectName: "sessionDelete:" + (srow.entry !== null ? srow.entry.id : "")
implicitWidth: 26
implicitHeight: 26
ToolTip.visible: hovered
ToolTip.text: "Delete this session and its transcript"
contentItem: ThemeIcon {
name: "edit-delete"
glyph: "×"
size: 14
color: parent.hovered ? Theme.err
: srow.open ? Theme.accentTextDim : Theme.textFaint
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
}
onClicked: srow.removeRequested(srow.entry.id)
}
}
}
+739
View File
@@ -0,0 +1,739 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// Provider, model and key: what the engine needs before it can talk to a model
// at all. Everything here goes through AgentCore, which moves the engine's own
// config (its session stays where it is) and remembers the choice. A key is
// verified against the provider before it is saved and is never read back into
// this window -- the dialog only ever says where the key it will use comes
// from.
//
// Three things live under "Advanced options", because they are for the odd
// provider or the odd model: the provider's own entry (name, base URL, key
// variable, models -- the engine keeps those in <config>/models.json, which is
// how a provider the presets do not know is added or an existing one is
// pointed somewhere else) and the generation parameters (temperature, top-p,
// max tokens), which are remembered per provider.
Dialog {
id: dlg
objectName: "settingsDialog"
parent: Overlay.overlay
anchors.centerIn: parent
modal: true
closePolicy: Popup.CloseOnEscape
padding: Theme.pad
property var providers: [] // AgentCore::providers()
property var choices: [] // AgentCore::modelChoices(picked)
property string picked: ""
property string model: ""
property string note: "" // what the last action answered
property string keyEnv: ""
property string keyFrom: ""
property bool hasKey: false
property bool advanced: false
property string modelFilter: "" // narrows a long model list
/* The advanced form: the picked provider's entry, editable. */
property string advName: ""
property string advBase: ""
property string advKeyEnv: ""
property string advModel: ""
property string advModels: ""
property string tempText: ""
property string topPText: ""
property string maxTokText: ""
signal applyRequested(string provider, string model, string key,
real temperature, real topP, int maxTokens)
width: Math.min(660, parent ? parent.width - 32 : 660)
height: Math.min(640, parent ? parent.height - 40 : 640)
/* The Basic style paints a light panel; this window is dark, so the
* dialog brings its own surface like every other one here. */
background: Rectangle {
color: Theme.surface
radius: Theme.radius
border.width: 1
border.color: Theme.border
}
// A long provider list (a router lists hundreds) is a wall of chips: the
// filter narrows it and the rest is one line ("+N more").
readonly property int chipCap: 40
readonly property var chips: {
const f = modelFilter.trim().toLowerCase()
const out = []
for (let i = 0; i < choices.length; i++) {
const c = String(choices[i])
if (!f.length || c.toLowerCase().indexOf(f) >= 0)
out.push(c)
}
return out
}
readonly property int chipsHidden: Math.max(0, chips.length - chipCap)
/* "0.2" -> 0.2; anything empty or unreadable -> 0 (the field is not sent,
* which is not the same as sending 0). */
function num(text) {
const v = parseFloat(String(text).replace(",", "."))
return isFinite(v) && v > 0 ? v : 0
}
function pickedEntry() {
for (let i = 0; i < providers.length; i++)
if (providers[i].name === dlg.picked)
return providers[i]
return null
}
/* Fill it in: the presets, the provider the engine is on now, and the
* model that provider last used. */
function load(list, provider, currentModel) {
providers = list
picked = provider
model = currentModel
note = ""
for (let i = 0; i < list.length; i++)
if (list[i].current === true)
picked = list[i].name
choices = picked.length ? agent.modelChoices(picked) : []
modelFilter = ""
syncPick()
}
/* Where the picked provider's key would come from and what it is set to.
* From the entries -- a key itself never reaches the QML side. */
function syncPick() {
hasKey = false
keyFrom = ""
keyEnv = ""
const p = pickedEntry()
if (p) {
hasKey = p.hasKey === true
keyFrom = p.keyFrom
keyEnv = p.keyEnv
/* The advanced form describes the picked provider: edit it, or
* type another name to add one. */
advName = p.name
advBase = p.base
advKeyEnv = p.keyEnv
advModel = p.model
advModels = p.custom === true ? agent.modelChoices(p.name).join(", ") : ""
}
const g = picked.length ? agent.genParams(picked) : null
tempText = g && g.temperature > 0 ? String(g.temperature) : ""
topPText = g && g.top_p > 0 ? String(g.top_p) : ""
maxTokText = g && g.max_tokens > 0 ? String(g.max_tokens) : ""
}
function keyState() {
if (hasKey)
return keyFrom === "saved" ? "a key is saved · paste another to replace it"
: "key from the environment: " + keyFrom
return keyEnv.length ? "no key yet — set " + keyEnv + ", or paste one here"
: "no key yet — paste one here"
}
function usageLine() {
const u = agent.usage()
if (!u.requests)
return "no tokens spent in this session yet"
let s = u.requests + (u.requests === 1 ? " request" : " requests") +
" · " + u.prompt + " in · " + u.out + " out"
if (u.priced)
s += " · " + u.cost.toFixed(4) + " " + u.currency
return s
}
/* Write the form's entry into the engine's user file and list it again. */
function saveProvider() {
/* The fields are the truth here, not the properties: a hand-typed
* edit is what the user wants saved. */
const name = advNameField.text.trim()
const err = agent.addProvider(name, advBaseField.text.trim(),
advKeyEnvField.text.trim(),
advModelField.text.trim(),
advModelsField.text)
if (err.length) {
note = err
return
}
providers = agent.providers()
picked = name
choices = agent.modelChoices(name)
syncPick()
note = "saved " + name + " to models.json — it is in the list above now"
}
function removeProvider() {
const typed = advNameField.text.trim()
const name = typed.length ? typed : picked
const rc = agent.removeProvider(name)
if (rc < 0) {
note = "could not remove " + name
return
}
providers = agent.providers()
note = rc === 0
? name + " is not in models.json (a preset of that name stays)"
: "removed " + name + " from models.json"
if (rc === 1 && providers.length > 0)
picked = providers[0].name
choices = picked.length ? agent.modelChoices(picked) : []
syncPick()
}
/* The form's fields follow the picked provider (and a user edit breaks
* the binding, so the push is imperative). */
onAdvNameChanged: if (advNameField && advNameField.text !== advName) advNameField.text = advName
onAdvBaseChanged: if (advBaseField && advBaseField.text !== advBase) advBaseField.text = advBase
onAdvKeyEnvChanged: if (advKeyEnvField && advKeyEnvField.text !== advKeyEnv) advKeyEnvField.text = advKeyEnv
onAdvModelChanged: if (advModelField && advModelField.text !== advModel) advModelField.text = advModel
onAdvModelsChanged: if (advModelsField && advModelsField.text !== advModels) advModelsField.text = advModels
onTempTextChanged: if (tempField && tempField.text !== tempText) tempField.text = tempText
onTopPTextChanged: if (topPField && topPField.text !== topPText) topPField.text = topPText
onMaxTokTextChanged: if (maxTokField && maxTokField.text !== maxTokText) maxTokField.text = maxTokText
// One labelled field of the advanced form.
component AdvField: ColumnLayout {
property string label: ""
property alias text: field.text
property alias placeholder: field.placeholderText
property int hintWidth: 0
Layout.fillWidth: true
spacing: 2
Text {
text: parent.label
color: Theme.textDim
font.pixelSize: Theme.smallSize
}
TextField {
id: field
Layout.fillWidth: true
implicitHeight: Theme.touchTarget
selectByMouse: true
color: Theme.text
placeholderTextColor: Theme.textFaint
selectionColor: Theme.accentDim
inputMethodHints: Qt.ImhNoPredictiveText
background: Rectangle {
radius: Theme.radiusSm
color: Theme.bg
border.width: 1
border.color: field.activeFocus ? Theme.accentDim : Theme.border
}
}
}
contentItem: ColumnLayout {
objectName: "settingsPanel"
spacing: Theme.gap
Text {
Layout.fillWidth: true
text: "Provider, model, key"
color: Theme.text
font.pixelSize: Theme.bodySize
font.bold: true
}
Text {
Layout.fillWidth: true
text: "Keys are stored under <config>/cst-agent/credentials (mode 0600) and are never shown again."
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
/* Everything scrolls, so the buttons stay where they are and a long
* model list cannot push them out of the dialog. */
Flickable {
id: body
objectName: "settingsBody"
Layout.fillWidth: true
Layout.fillHeight: true
Layout.minimumHeight: 120
clip: true
contentWidth: width
contentHeight: bodyCol.implicitHeight
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar {}
ColumnLayout {
id: bodyCol
width: parent.width
spacing: Theme.gap
ColumnLayout {
Layout.fillWidth: true
spacing: 2
Repeater {
model: dlg.providers
delegate: Rectangle {
id: prow
required property var modelData
readonly property bool selected: dlg.picked === modelData.name
objectName: "providerRow:" + modelData.name
Layout.fillWidth: true
implicitHeight: prowCol.implicitHeight + 8
radius: Theme.radiusSm
color: prow.selected ? Theme.accentDim
: prowHover.hovered ? Theme.surfaceAlt
: "transparent"
border.width: 1
border.color: prow.selected ? Theme.accent : "transparent"
HoverHandler { id: prowHover }
MouseArea {
anchors.fill: parent
onClicked: {
dlg.picked = prow.modelData.name
modelField.text = prow.modelData.model
dlg.choices = agent.modelChoices(prow.modelData.name)
dlg.modelFilter = ""
dlg.syncPick()
}
}
ColumnLayout {
id: prowCol
anchors {
left: parent.left
right: parent.right
top: parent.top
margins: 4
}
spacing: 0
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
Text {
text: prow.modelData.name
color: prow.selected ? Theme.accentText : Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: prow.selected
}
Text {
visible: prow.modelData.current === true
text: "in use"
color: prow.selected ? Theme.okOnAccent : Theme.ok
font.pixelSize: Theme.smallSize
}
Item { Layout.fillWidth: true }
Text {
text: prow.modelData.custom === true
? "custom" : prow.modelData.source
color: prow.selected ? Theme.accentTextDim : Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
Text {
Layout.fillWidth: true
elide: Text.ElideMiddle
text: prow.modelData.base + " · " +
(prow.modelData.hasKey === true
? (prow.modelData.keyFrom === "saved"
? "key saved"
: "key from " + prow.modelData.keyFrom)
: (prow.modelData.keyEnv.length
? "no key (" + prow.modelData.keyEnv + ")"
: "no key"))
color: prow.selected ? Theme.accentTextDim : Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
}
}
}
Text {
Layout.fillWidth: true
text: "Model"
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
TextField {
id: modelField
objectName: "settingsModel"
Layout.fillWidth: true
text: dlg.model
implicitHeight: Theme.touchTarget
selectByMouse: true
color: Theme.text
placeholderText: "model name"
placeholderTextColor: Theme.textFaint
selectionColor: Theme.accentDim
inputMethodHints: Qt.ImhNoPredictiveText
background: Rectangle {
radius: Theme.radiusSm
color: Theme.bg
border.width: 1
border.color: modelField.activeFocus ? Theme.accentDim
: Theme.border
}
}
Text {
Layout.preferredWidth: 90
elide: Text.ElideRight
text: modelField.text.length ? agent.modelInfo(modelField.text) : ""
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
/* A router can list hundreds of models: filter, cap, say how
* many are left instead of filling the dialog. */
RowLayout {
Layout.fillWidth: true
visible: dlg.choices.length > 12
spacing: Theme.gap
TextField {
id: filterField
objectName: "settingsFilter"
Layout.fillWidth: true
text: dlg.modelFilter
implicitHeight: Theme.segmentHeight
selectByMouse: true
color: Theme.text
placeholderText: "filter " + dlg.choices.length + " models"
placeholderTextColor: Theme.textFaint
selectionColor: Theme.accentDim
inputMethodHints: Qt.ImhNoPredictiveText
onTextChanged: dlg.modelFilter = text
background: Rectangle {
radius: Theme.radiusSm
color: Theme.bg
border.width: 1
border.color: filterField.activeFocus ? Theme.accentDim
: Theme.border
}
}
Text {
Layout.preferredWidth: 110
elide: Text.ElideRight
text: dlg.chips.length + " shown"
+ (dlg.chipsHidden ? " · +" + dlg.chipsHidden + " more" : "")
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
Flow {
Layout.fillWidth: true
spacing: 6
visible: dlg.choices.length > 0
Repeater {
model: dlg.chips.slice(0, dlg.chipCap)
delegate: Rectangle {
id: chip
required property var modelData
readonly property string name: String(chip.modelData)
objectName: "modelChoice:" + chip.name
implicitWidth: chipText.implicitWidth + 14
implicitHeight: 26
radius: Theme.radiusSm
color: chipHover.hovered ? Theme.surfaceHi : "transparent"
border.width: 1
border.color: modelField.text === chip.name ? Theme.accent
: Theme.border
HoverHandler { id: chipHover }
Text {
id: chipText
anchors.centerIn: parent
text: chip.name
color: modelField.text === chip.name ? Theme.text
: Theme.textDim
font.pixelSize: Theme.smallSize
}
TapHandler { onTapped: modelField.text = chip.name }
}
}
}
TextField {
id: keyField
objectName: "settingsKey"
Layout.fillWidth: true
implicitHeight: Theme.touchTarget
echoMode: TextInput.Password
selectByMouse: true
color: Theme.text
placeholderText: "API key (leave empty to keep what is there)"
placeholderTextColor: Theme.textFaint
selectionColor: Theme.accentDim
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhSensitiveData
onAccepted: dlg.apply()
background: Rectangle {
radius: Theme.radiusSm
color: Theme.bg
border.width: 1
border.color: keyField.activeFocus ? Theme.accentDim : Theme.border
}
}
Text {
Layout.fillWidth: true
text: dlg.keyState()
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
/* --- advanced ------------------------------------------- */
ToolButton {
id: advToggle
objectName: "settingsAdvanced"
Layout.fillWidth: true
implicitHeight: Theme.segmentHeight
onClicked: dlg.advanced = !dlg.advanced
contentItem: RowLayout {
spacing: 6
ThemeIcon {
name: dlg.advanced ? "arrow-down" : "arrow-right"
glyph: dlg.advanced ? "▾" : "▸"
size: 14
color: Theme.textDim
}
Text {
text: "Advanced options"
color: advToggle.hovered ? Theme.text : Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
Item { Layout.fillWidth: true }
Text {
text: "custom provider · model parameters"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
background: Rectangle {
radius: Theme.radiusSm
color: advToggle.hovered ? Theme.surfaceAlt : "transparent"
}
}
ColumnLayout {
Layout.fillWidth: true
visible: dlg.advanced
spacing: 6
Text {
Layout.fillWidth: true
text: "Provider entry — saved in <config>/cst-agent/models.json. " +
"A name the presets know is overridden, a new one is added."
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
GridLayout {
Layout.fillWidth: true
columns: 2
columnSpacing: Theme.gap
rowSpacing: 4
AdvField {
id: advNameField
objectName: "advName"
label: "Name"
placeholder: "myllm"
Layout.preferredWidth: 180
}
AdvField {
id: advBaseField
objectName: "advBase"
label: "Base URL"
placeholder: "https://api.example.com/v1"
}
AdvField {
id: advKeyEnvField
objectName: "advKeyEnv"
label: "Key variable"
placeholder: "MYLLM_API_KEY"
}
AdvField {
id: advModelField
objectName: "advModel"
label: "Default model"
placeholder: "the model to start with"
}
AdvField {
id: advModelsField
objectName: "advModels"
label: "Models it offers (comma separated, optional)"
placeholder: "m1, m2"
Layout.columnSpan: 2
}
}
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
Button {
id: saveProviderBtn
objectName: "settingsSaveProvider"
text: "Save provider"
implicitHeight: Theme.touchTarget
enabled: advNameField.text.trim().length > 0 &&
advBaseField.text.trim().length > 0
onClicked: dlg.saveProvider()
background: Rectangle {
radius: Theme.radiusSm
color: saveProviderBtn.hovered ? Theme.surfaceHi : Theme.surfaceAlt
border.width: 1
border.color: Theme.border
}
contentItem: Text {
text: saveProviderBtn.text
color: saveProviderBtn.enabled ? Theme.textDim : Theme.textFaint
font.pixelSize: Theme.bodySize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
Button {
id: removeProviderBtn
objectName: "settingsRemoveProvider"
text: "Remove from models.json"
implicitHeight: Theme.touchTarget
readonly property var entry: dlg.pickedEntry()
enabled: entry !== null && entry.custom === true
ToolTip.visible: hovered
ToolTip.text: "Only the user's own entry goes: a built-in preset of the same name stays"
onClicked: dlg.removeProvider()
background: Rectangle {
radius: Theme.radiusSm
color: removeProviderBtn.hovered && removeProviderBtn.enabled
? Theme.surfaceHi : Theme.surfaceAlt
border.width: 1
border.color: Theme.border
}
contentItem: Text {
text: removeProviderBtn.text
color: removeProviderBtn.enabled ? Theme.textDim
: Theme.textFaint
font.pixelSize: Theme.bodySize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
Item { Layout.fillWidth: true }
}
Text {
Layout.fillWidth: true
Layout.topMargin: 4
text: "Model parameters — remembered for " +
(dlg.picked.length ? dlg.picked : "this provider") +
", sent with every request. Empty = the provider's own default."
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
AdvField {
id: tempField
objectName: "advTemperature"
label: "Temperature"
placeholder: "not sent"
Layout.preferredWidth: 130
}
AdvField {
id: topPField
objectName: "advTopP"
label: "Top-p"
placeholder: "not sent"
Layout.preferredWidth: 130
}
AdvField {
id: maxTokField
objectName: "advMaxTokens"
label: "Max tokens"
placeholder: "not sent"
Layout.preferredWidth: 150
}
Item { Layout.fillWidth: true }
}
}
}
}
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
Text {
objectName: "settingsNote"
Layout.fillWidth: true
text: dlg.note.length ? dlg.note : dlg.usageLine()
color: dlg.note.length ? Theme.warn : Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
maximumLineCount: 2
elide: Text.ElideRight
}
Button {
id: closeBtn
objectName: "settingsClose"
text: "Close"
implicitHeight: Theme.touchTarget
onClicked: dlg.close()
background: Rectangle {
radius: Theme.radiusSm
color: closeBtn.hovered ? Theme.surfaceHi : Theme.surfaceAlt
border.width: 1
border.color: Theme.border
}
contentItem: Text {
text: closeBtn.text
color: Theme.textDim
font.pixelSize: Theme.bodySize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
Button {
id: applyBtn
objectName: "settingsApply"
text: "Use this"
implicitHeight: Theme.touchTarget
onClicked: dlg.apply()
background: Rectangle {
radius: Theme.radiusSm
color: applyBtn.hovered ? "#5cc0f0" : Theme.accent
}
contentItem: Text {
text: applyBtn.text
color: Theme.accentInk
font.pixelSize: Theme.bodySize
font.bold: true
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
}
}
/* The model parameters belong to the provider that is picked, so they are
* applied first: useProvider() then takes over what was remembered for
* whichever provider it ends on. */
function apply() {
dlg.applyRequested(dlg.picked, modelField.text, keyField.text,
dlg.num(tempField.text), dlg.num(topPField.text),
Math.round(dlg.num(maxTokField.text)))
}
onOpened: {
keyField.text = ""
modelField.forceActiveFocus()
}
}
+345
View File
@@ -0,0 +1,345 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// What the engine is set to: where it runs, how it frames itself, when it
// asks, whether it is planning. Everything here writes straight into the
// engine's config (AgentCore), never into a copy the engine cannot see.
//
// The panel scrolls (a phone-sized window cannot show it all) and every
// control keeps a finger-sized hit area.
Rectangle {
id: side
property string workspace: ""
property string provider: ""
property string model: ""
property string mode: "coding"
property int approval: 1 // cst_approval_t
property bool planMode: false
property bool running: false
property string status: ""
property string todo: ""
property var sessions: [] // what the store holds (AgentCore::sessions)
property string sessionId: ""
signal modeRequested(string mode)
signal approvalRequested(int approval)
signal planModeRequested(bool on)
signal sessionRequested(string id)
signal sessionNewRequested()
signal sessionDeleteRequested(string id)
readonly property alias contentColumn: col
color: Theme.surface
border.width: 1
border.color: Theme.border
implicitHeight: col.implicitHeight + Theme.pad * 2
// One selectable row of a segmented control.
component Seg: Button {
id: seg
property bool current: false
flat: true
implicitHeight: Theme.segmentHeight
padding: 0
background: Rectangle {
radius: Theme.radiusSm
color: seg.current ? Theme.accentDim : (seg.hovered ? Theme.surfaceAlt : "transparent")
border.width: 1
border.color: seg.current ? Theme.accent : Theme.border
}
contentItem: Text {
text: seg.text
color: seg.current ? Theme.text : Theme.textDim
font.pixelSize: Theme.smallSize
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
Flickable {
anchors.fill: parent
contentWidth: width
contentHeight: col.implicitHeight + Theme.pad * 2
clip: true
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar {}
ColumnLayout {
id: col
x: Theme.pad
y: Theme.pad
width: parent.width - Theme.pad * 2
spacing: Theme.gapL
// --- where ---
ColumnLayout {
Layout.fillWidth: true
spacing: 4
RowLayout {
spacing: Theme.gap
Rectangle { width: 8; height: 8; radius: 4; color: Theme.accent }
Text {
text: "CST-agent"
color: Theme.text
font.pixelSize: Theme.bodySize
font.bold: true
}
Item { Layout.fillWidth: true }
Text {
visible: side.running
text: "turn running"
color: Theme.warn
font.pixelSize: Theme.smallSize
}
}
Text {
Layout.fillWidth: true
text: side.workspace.length ? side.workspace : "(no workspace)"
color: Theme.textDim
font.pixelSize: Theme.smallSize
elide: Text.ElideMiddle
ToolTip.visible: wsHover.hovered
ToolTip.text: side.workspace
HoverHandler { id: wsHover }
}
Text {
Layout.fillWidth: true
visible: side.provider.length > 0 || side.model.length > 0
text: (side.provider.length ? side.provider : "?") +
(side.model.length ? " · " + side.model : "")
color: Theme.textFaint
font.pixelSize: Theme.smallSize
elide: Text.ElideRight
}
Text {
Layout.fillWidth: true
visible: side.sessionId.length > 0
text: "session " + side.sessionId
color: Theme.textFaint
font.pixelSize: Theme.smallSize
elide: Text.ElideMiddle
}
Text {
Layout.fillWidth: true
visible: side.status.length > 0
text: side.status
color: Theme.textFaint
font.pixelSize: Theme.smallSize
elide: Text.ElideRight
}
}
// --- which conversation ---
ColumnLayout {
Layout.fillWidth: true
spacing: 4
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
Text {
text: "Sessions"
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
Item { Layout.fillWidth: true }
// Starting a session while a turn runs would move the
// engine out from under it: the whole block is off then.
ToolButton {
id: newSession
objectName: "newSessionButton"
implicitWidth: 68
implicitHeight: Theme.segmentHeight
enabled: !side.running
ToolTip.visible: hovered
ToolTip.text: "Start a new session"
contentItem: RowLayout {
spacing: 4
ThemeIcon {
name: "list-add"
glyph: "+"
size: 14
color: newSession.enabled
? (newSession.hovered ? Theme.text : Theme.textDim)
: Theme.textFaint
}
Text {
text: "new"
color: newSession.enabled
? (newSession.hovered ? Theme.text : Theme.textDim)
: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered && parent.enabled ? Theme.surfaceHi
: "transparent"
border.width: 1
border.color: Theme.border
}
onClicked: side.sessionNewRequested()
}
}
Repeater {
model: side.sessions
delegate: SessionRow {
Layout.fillWidth: true
entry: modelData
onActivated: function (id) { side.sessionRequested(id) }
onRemoveRequested: function (id) { side.sessionDeleteRequested(id) }
}
}
Text {
Layout.fillWidth: true
visible: side.sessions.length === 0
text: "nothing stored here yet"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
}
// --- how it frames itself ---
ColumnLayout {
Layout.fillWidth: true
spacing: 4
Text { text: "Mode"; color: Theme.textDim; font.pixelSize: Theme.smallSize; font.bold: true }
RowLayout {
Layout.fillWidth: true
spacing: 4
Seg {
objectName: "modeCoding"
Layout.fillWidth: true
text: "coding"
current: side.mode !== "general"
onClicked: side.modeRequested("coding")
}
Seg {
objectName: "modeGeneral"
Layout.fillWidth: true
text: "general"
current: side.mode === "general"
onClicked: side.modeRequested("general")
}
}
Text {
Layout.fillWidth: true
text: side.mode === "general" ? "documents, data, everyday files"
: "code framed: repos, builds, tests"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
}
// --- when it asks ---
ColumnLayout {
Layout.fillWidth: true
spacing: 4
Text { text: "Approval"; color: Theme.textDim; font.pixelSize: Theme.smallSize; font.bold: true }
RowLayout {
Layout.fillWidth: true
spacing: 4
Seg {
Layout.fillWidth: true
text: "ask"
current: side.approval === 0
onClicked: side.approvalRequested(0)
}
Seg {
Layout.fillWidth: true
text: "auto"
current: side.approval === 1
onClicked: side.approvalRequested(1)
}
Seg {
Layout.fillWidth: true
text: "yolo"
current: side.approval === 2
onClicked: side.approvalRequested(2)
}
}
Text {
Layout.fillWidth: true
text: side.approval === 0 ? "every tool asks first"
: side.approval === 2 ? "never asks — writes go through"
: "sandbox and rules decide, asks on doubt"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
RowLayout {
Layout.fillWidth: true
Layout.topMargin: 2
spacing: Theme.gap
Switch {
id: planSwitch
objectName: "planSwitch"
checked: side.planMode
implicitHeight: Theme.touchTarget
onClicked: side.planModeRequested(checked)
/* The Basic style's indicator is a dark pill with a dark
* knob here, so it is drawn: thumb-sized, accent when
* on, clearly off when not. */
indicator: Rectangle {
implicitWidth: 44
implicitHeight: 22
x: planSwitch.leftPadding
y: parent.height / 2 - height / 2
radius: 11
color: planSwitch.checked ? Theme.accentDim : Theme.surfaceAlt
border.width: 1
border.color: planSwitch.checked ? Theme.accent : Theme.border
Rectangle {
width: 16
height: 16
y: 2
x: planSwitch.checked ? parent.width - width - 3 : 3
radius: 8
color: planSwitch.checked ? Theme.text : Theme.textDim
Behavior on x {
NumberAnimation { duration: 120; easing.type: Easing.OutCubic }
}
}
}
}
Text {
text: "Plan mode"
color: Theme.textDim
font.pixelSize: Theme.smallSize
}
Item { Layout.fillWidth: true }
}
Text {
Layout.fillWidth: true
visible: side.planMode
text: "read-only tools and a planning note"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
wrapMode: Text.Wrap
}
}
// --- the plan the engine keeps ---
TodoPanel {
Layout.fillWidth: true
text: side.todo
}
Text {
Layout.fillWidth: true
Layout.topMargin: Theme.gap
text: "engine in-process · v" + Qt.application.version
color: Theme.textFaint
font.pixelSize: Theme.smallSize
elide: Text.ElideRight
}
}
}
}
+94
View File
@@ -0,0 +1,94 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Dialog {
id: root
objectName: "taskControlDialog"
title: "Task control and jobs"
modal: true
standardButtons: Dialog.Close
width: Math.min(760, parent ? parent.width - 24 : 760)
height: Math.min(640, parent ? parent.height - 24 : 640)
property var state: ({})
function refresh() {
try { state = JSON.parse(agent.taskState()) } catch (e) { state = ({}) }
}
onOpened: { refresh(); config.text = agent.workerConfig() }
Timer { interval: 500; repeat: true; running: root.visible; onTriggered: root.refresh() }
ColumnLayout {
anchors.fill: parent
TabBar {
id: tabs
Layout.fillWidth: true
TabButton { text: "Task / Jobs" }
TabButton { text: "Models" }
TabButton { text: "Integration" }
}
StackLayout {
Layout.fillWidth: true
Layout.fillHeight: true
currentIndex: tabs.currentIndex
ColumnLayout {
Label { Layout.fillWidth: true; wrapMode: Text.Wrap; text: (root.state.goal || "No active goal") }
Label { text: "Revision " + (root.state.revision || 0) + " · " + (root.state.status || "idle") + " · " + (root.state.cancel_source || "") }
RowLayout {
CheckBox {
id: readonly
objectName: "taskReadOnly"
text: "Read only"
checked: !!root.state.read_only
onClicked: agent.taskControl(checked, !direct.checked, !!root.state.paused)
}
CheckBox {
id: direct
objectName: "taskMainOnly"
text: "Main agent only"
checked: root.state.delegation === false
onClicked: agent.taskControl(readonly.checked, !checked, !!root.state.paused)
}
Button { text: root.state.paused ? "Resume" : "Pause"; onClicked: agent.taskControl(readonly.checked, !direct.checked, !root.state.paused) }
}
ScrollView {
Layout.fillWidth: true
Layout.fillHeight: true
ColumnLayout {
width: parent.width
Repeater {
model: root.state.jobs || []
Frame {
required property var modelData
Layout.fillWidth: true
ColumnLayout {
anchors.fill: parent
Label { text: modelData.job_id + " · " + modelData.kind + " · " + modelData.status }
Label { Layout.fillWidth: true; text: modelData.resource || ""; elide: Text.ElideMiddle }
Label { Layout.fillWidth: true; wrapMode: Text.Wrap; text: (modelData.output || "").slice(-1000) }
RowLayout {
Button { text: "Cancel"; enabled: modelData.status === "running" || modelData.status === "queued"; onClicked: agent.cancelJob(modelData.job_id, false) }
Button { text: "Force stop"; visible: modelData.status === "running_protected"; onClicked: agent.cancelJob(modelData.job_id, true) }
Button { text: "Review delta"; visible: (modelData.resource || "").indexOf("/.agent/v2/wt-") >= 0; onClicked: { worktree.text = modelData.resource; tabs.currentIndex = 2 } }
}
}
}
}
}
}
}
ColumnLayout {
Label { text: "Role model profiles and budgets (provider credentials stay separate)"; wrapMode: Text.Wrap; Layout.fillWidth: true }
ScrollView { Layout.fillWidth: true; Layout.fillHeight: true; TextArea { id: config; wrapMode: TextEdit.Wrap; selectByMouse: true } }
Label { id: configStatus; Layout.fillWidth: true; wrapMode: Text.Wrap }
Button { text: "Save model configuration"; enabled: !agent.running; onClicked: { const e = agent.saveWorkerConfig(config.text); configStatus.text = e.length ? e : "Saved" } }
}
ColumnLayout {
TextField { id: worktree; Layout.fillWidth: true; placeholderText: "Worker worktree path" }
RowLayout {
Button { text: "Preview"; enabled: !agent.running; onClicked: delta.text = agent.worktreeDiff(worktree.text, false) }
Button { text: "Integrate reviewed delta"; enabled: !agent.running; onClicked: delta.text = agent.worktreeDiff(worktree.text, true) }
}
ScrollView { Layout.fillWidth: true; Layout.fillHeight: true; TextArea { id: delta; readOnly: true; wrapMode: TextEdit.Wrap; selectByMouse: true } }
}
}
}
}
+98
View File
@@ -0,0 +1,98 @@
// One place for the look: colors, spacing, fonts. The window, the cards and
// the dialogs all read from here, so re-theming (or swapping in Kirigami's
// Kirigami.Theme) is a single file.
pragma Singleton
import QtQuick
QtObject {
// Breeze-dark-ish (the desktop the app is built for), no hard contrast.
readonly property color bg: "#15181a"
readonly property color surface: "#1e2225"
readonly property color surfaceAlt: "#262b2f"
readonly property color surfaceHi: "#313840"
readonly property color border: "#343b41"
readonly property color text: "#eff0f1"
readonly property color textDim: "#9aa2a8"
/* Faint is still text: small print (hints, secondary lines, a selected
* row's detail) has to stay readable on both the background and the
* accent fill, so it is a step lighter than it looks in a mockup. */
readonly property color textFaint: "#8d959c"
readonly property color accent: "#3daee9"
readonly property color accentDim: "#1d6f95"
/* What is written *on* the accent fill (a selection, the open session).
* Named "accentText...", not "onAccent...": QML reads any `onFoo` as a
* signal handler and refuses the assignment. */
readonly property color accentText: "#ffffff"
readonly property color accentTextDim: "#dceefb"
/* The dark ink a filled button carries (accent, ok, err are all light). */
readonly property color accentInk: "#12161a"
readonly property color ok: "#27ae60"
readonly property color warn: "#f67400"
readonly property color err: "#da4453"
/* Green on the accent fill is mud: the "in use" mark needs its own ink. */
readonly property color okOnAccent: "#d8f5e3"
readonly property int radius: 6
readonly property int radiusSm: 3
readonly property int gap: 8
readonly property int gapL: 14
readonly property int pad: 12
readonly property int padL: 16
readonly property int bodySize: 14
readonly property int smallSize: 12
readonly property int monoSize: 13
readonly property string mono: "monospace"
readonly property int sidebarWidth: 268
readonly property int contentMax: 1100
// Layout: below the breakpoint the sidebar slides over the transcript
// instead of taking a column, and controls stay thumb-sized above it
// (a finger needs ~34-40 px, a mouse is happy with 26).
readonly property int compactBreakpoint: 880
readonly property int touchTarget: 34
readonly property int segmentHeight: 30
readonly property int headerHeight: 42
readonly property int jumpButton: 40
// Which Breeze icon stands for a tool: the card shows at a glance what
// kind of thing ran. Unknown names still get one (no glyph fallbacks for
// tools -- a missing icon just leaves the name alone).
function toolIcon(name) {
const n = String(name).toLowerCase()
if (n.indexOf("patch") >= 0 || n.indexOf("write") >= 0 || n.indexOf("edit") >= 0)
return "document-edit"
if (n.indexOf("read") >= 0 || n.indexOf("cat") >= 0)
return "text-x-generic"
if (n.indexOf("list_dir") >= 0 || n.indexOf("glob") >= 0 ||
n.indexOf("find") >= 0 || n.indexOf("dir") >= 0 || n.indexOf("file") >= 0)
return "folder-open"
if (n.indexOf("grep") >= 0 || n.indexOf("search") >= 0)
return "edit-find"
if (n.indexOf("bash") >= 0 || n.indexOf("shell") >= 0 ||
n.indexOf("command") >= 0 || n.indexOf("run") >= 0)
return "code-context"
if (n.indexOf("web") >= 0 || n.indexOf("http") >= 0 || n.indexOf("fetch") >= 0)
return "internet-services"
if (n.indexOf("todo") >= 0 || n.indexOf("plan") >= 0)
return "format-list-unordered"
if (n.indexOf("ask") >= 0 || n.indexOf("question") >= 0 || n.indexOf("notif") >= 0)
return "help-hint"
return "code-context"
}
// The tool output / diff line colors, used by ToolCard.
function lineColor(line) {
if (line.startsWith("@@"))
return accent
if (line.startsWith("+++") || line.startsWith("---"))
return textDim
if (line.startsWith("+"))
return ok
if (line.startsWith("-"))
return err
return text
}
}
+50
View File
@@ -0,0 +1,50 @@
import QtQuick
// One icon, from the desktop's icon theme (image://csttheme/, see
// app/src/ui/ThemeIcons.cpp), tinted with a color of the window's own.
//
// `glyph` is the last resort: a machine with no icon theme at all gets the
// unicode character the app used before, rather than an empty hole. Every
// place that shows an icon names its glyph, so nothing can go blank.
Item {
id: root
property string name: ""
property string glyph: ""
property color color: Theme.textDim
property int size: 16
implicitWidth: size
implicitHeight: size
/* "#rrggbb": a color typed to a string in QML carries alpha and a
* leading '#', which the provider's query would choke on. */
function hex(c) {
function two(v) {
const s = Math.round(Math.max(0, Math.min(1, v)) * 255).toString(16)
return s.length < 2 ? "0" + s : s
}
return "#" + two(c.r) + two(c.g) + two(c.b)
}
Image {
id: img
anchors.fill: parent
source: root.name.length
? "image://csttheme/" + root.name + "?color=" + encodeURIComponent(root.hex(root.color))
: ""
sourceSize.width: root.size
sourceSize.height: root.size
fillMode: Image.PreserveAspectFit
smooth: true
visible: status === Image.Ready
}
Text {
anchors.fill: parent
visible: img.status === Image.Error && root.glyph.length > 0
text: root.glyph
color: root.color
font.pixelSize: Math.round(root.size * 0.85)
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
+73
View File
@@ -0,0 +1,73 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// The model's reasoning stream, collapsed by default: it is context, not the
// answer.
Rectangle {
id: block
property string text: ""
property bool complete: false
property bool expanded: false
radius: Theme.radius
color: Theme.surfaceAlt
border.width: 1
border.color: Theme.border
implicitHeight: layout.implicitHeight + Theme.pad
opacity: 0.9
ColumnLayout {
id: layout
anchors {
left: parent.left
right: parent.right
top: parent.top
leftMargin: Theme.pad
rightMargin: Theme.pad
topMargin: Theme.pad / 2
}
spacing: 2
RowLayout {
spacing: Theme.gap
/* A handler, not a MouseArea: a layout decides the geometry of its
* children, and anchoring one of them is undefined behavior. */
TapHandler {
cursorShape: Qt.PointingHandCursor
onTapped: block.expanded = !block.expanded
}
ThemeIcon {
name: block.expanded ? "arrow-down" : "arrow-right"
glyph: block.expanded ? "▾" : "▸"
size: Theme.smallSize + 2
color: Theme.textDim
}
Text {
text: block.complete ? "thinking" : "thinking…"
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
Text {
Layout.fillWidth: true
elide: Text.ElideRight
visible: !block.expanded
text: block.text.replace(/\s+/g, " ").trim()
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
Text {
Layout.fillWidth: true
Layout.topMargin: 4
visible: block.expanded
text: block.text
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.italic: true
wrapMode: Text.Wrap
textFormat: Text.PlainText
}
}
}
+61
View File
@@ -0,0 +1,61 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// The engine's todo list (on_todo), rendered as a small checklist. The text
// is markdown-ish: "- [x] thing" lines.
ColumnLayout {
id: panel
property string text: ""
function entries() {
return text.split("\n")
.map(function (l) { return l.trim() })
.filter(function (l) { return l.length > 0 })
.map(function (l) {
const done = /^[-*]\s*\[[xX]\]/.test(l) || /^\[[xX]\]/.test(l)
const open = /^[-*]\s*\[\s*\]/.test(l) || /^\[\s*\]/.test(l)
return { done: done, todo: open, label: l.replace(/^[-*]?\s*\[[xX ]?\]\s*/, "").replace(/^[-*]\s*/, "") }
})
}
spacing: 6
Text {
text: "Plan"
color: Theme.textDim
font.pixelSize: Theme.smallSize
font.bold: true
}
Repeater {
model: panel.entries()
RowLayout {
Layout.fillWidth: true
spacing: Theme.gap
ThemeIcon {
Layout.alignment: Qt.AlignTop
name: modelData.done ? "task-complete" : "box"
glyph: modelData.done ? "✓" : "○"
size: Theme.smallSize + 2
color: modelData.done ? Theme.ok : Theme.textFaint
}
Text {
Layout.fillWidth: true
text: modelData.label
color: modelData.done ? Theme.textFaint : Theme.textDim
font.pixelSize: Theme.smallSize
font.strikeout: modelData.done
wrapMode: Text.Wrap
}
}
}
Text {
Layout.fillWidth: true
visible: panel.entries().length === 0
text: "no plan yet"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
+225
View File
@@ -0,0 +1,225 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// A tool call: what ran, whether it is still running, and what came back.
// Long output stays folded until asked for, diff lines are colored.
Rectangle {
id: card
property string name: ""
property string state: "pending" // pending | ready | running | done | denied
// | unfinished (replayed, no result)
property string detail: ""
property string output: ""
property int exitCode: 0
property bool hasResult: false
property bool expanded: false
property string images: ""
readonly property bool running: state === "pending" || state === "ready" || state === "running"
readonly property color stateColor: state === "denied" ? Theme.err
: state === "unfinished" ? Theme.textFaint
: running ? Theme.warn
: hasResult && exitCode !== 0 ? Theme.err
: Theme.ok
readonly property string stateText: state === "pending" ? "reading"
: state === "ready" ? "queued"
: state === "running" ? "running"
: state === "denied" ? "denied"
: state === "unfinished" ? "no result"
: hasResult && exitCode !== 0 ? "failed" : "done"
/* How long this call has been going. A tool that takes minutes -- a
* build, a wide search, a command nobody can predict -- must not read as
* a window that has hung: while the card runs, its chip counts. */
property double startedAt: 0
property int runningFor: 0
function elapsedText() {
const s = runningFor
if (s < 60)
return s + "s"
const m = Math.floor(s / 60)
if (m < 60)
return m + ":" + (s % 60 < 10 ? "0" : "") + (s % 60)
return Math.floor(m / 60) + "h" + (m % 60 < 10 ? "0" : "") + (m % 60)
}
/* The clock starts when the card starts running -- and a card that is
* already running when it appears (a replayed transcript) starts one too,
* hence Component.onCompleted. */
function noteRunning() {
if (running && startedAt === 0)
startedAt = Date.now()
else if (!running)
startedAt = 0
}
onRunningChanged: noteRunning()
Component.onCompleted: noteRunning()
Timer {
interval: 1000
repeat: true
running: card.running && card.startedAt > 0
onTriggered: card.runningFor = Math.floor((Date.now() - card.startedAt) / 1000)
}
/* What the chip says: the state, how long it has been running (from five
* seconds on -- before that it is noise), or the exit code once there is
* a result. "no result" is not an outcome, so no exit code belongs on
* it. */
function chipText() {
if (running)
return runningFor >= 5
? stateText + " · " + elapsedText()
: stateText
return stateText + (hasResult && state !== "unfinished"
? " · exit " + exitCode : "")
}
function lines() {
const all = output.split("\n")
return all.length > 500 ? all.slice(0, 500).concat(["… " + (all.length - 500) + " more lines"]) : all
}
radius: Theme.radius
color: Theme.surfaceAlt
border.width: 1
border.color: expanded ? Theme.stateColor : Theme.border
implicitHeight: layout.implicitHeight + Theme.pad
ColumnLayout {
id: layout
anchors {
left: parent.left
right: parent.right
top: parent.top
margins: Theme.pad
}
spacing: 6
RowLayout {
spacing: Theme.gap
BusyIndicator {
visible: card.running
running: card.running
implicitWidth: 16
implicitHeight: 16
Layout.alignment: Qt.AlignVCenter
}
Rectangle {
visible: !card.running
Layout.alignment: Qt.AlignVCenter
width: 6
height: 6
radius: 3
color: card.stateColor
}
/* What kind of tool this was, from the icon theme (Theme.toolIcon
* maps the engine's names onto Breeze ones). */
ThemeIcon {
Layout.alignment: Qt.AlignVCenter
name: Theme.toolIcon(card.name)
size: 16
color: Theme.textDim
}
Text {
text: card.name
color: Theme.text
font.family: Theme.mono
font.pixelSize: Theme.monoSize
font.bold: true
}
Rectangle {
Layout.alignment: Qt.AlignVCenter
radius: Theme.radiusSm
color: "transparent"
border.width: 1
border.color: card.stateColor
implicitWidth: chip.implicitWidth + 10
implicitHeight: chip.implicitHeight + 2
Text {
id: chip
objectName: "toolChip"
anchors.centerIn: parent
text: card.chipText()
color: card.stateColor
font.pixelSize: Theme.smallSize
}
}
Text {
Layout.fillWidth: true
elide: Text.ElideRight
text: card.detail.replace(/\s+/g, " ").trim()
color: Theme.textFaint
font.family: Theme.mono
font.pixelSize: Theme.smallSize
}
ToolButton {
implicitWidth: 26
implicitHeight: 22
visible: card.output.length > 0
contentItem: ThemeIcon {
name: card.expanded ? "arrow-down" : "arrow-right"
glyph: card.expanded ? "▾" : "▸"
size: 14
color: parent.hovered ? Theme.text : Theme.textDim
}
background: Rectangle {
radius: Theme.radiusSm
color: parent.hovered ? Theme.surfaceHi : "transparent"
}
onClicked: card.expanded = !card.expanded
}
}
// What the tool made (view_image, an MCP image): shown as it is, with
// the output left folded -- the picture is the result.
ImageStrip {
Layout.fillWidth: true
visible: card.images.length > 0
text: card.images
}
// Folded view: the first line of the result, so a done card still says
// something without being opened.
Text {
Layout.fillWidth: true
visible: !card.expanded && card.output.length > 0
text: {
const l = card.output.split("\n")
return l[0] + (l.length > 1 ? " …" : "")
}
elide: Text.ElideRight
color: Theme.textFaint
font.family: Theme.mono
font.pixelSize: Theme.smallSize
}
ColumnLayout {
Layout.fillWidth: true
visible: card.expanded && card.output.length > 0
spacing: 0
Repeater {
model: card.expanded ? card.lines() : []
Text {
Layout.fillWidth: true
text: modelData.length ? modelData : " "
color: Theme.lineColor(modelData)
font.family: Theme.mono
font.pixelSize: Theme.monoSize
wrapMode: Text.NoWrap
textFormat: Text.PlainText
}
}
Text {
Layout.topMargin: 4
visible: card.output.split("\n").length > 500
text: "output truncated for the view"
color: Theme.textFaint
font.pixelSize: Theme.smallSize
}
}
}
}
File diff suppressed because it is too large Load Diff
+291
View File
@@ -0,0 +1,291 @@
/* AgentCore: the Qt wrapper around one cst_agent_t.
*
* The engine runs turns on a worker thread; every cst_agent_hooks_t callback
* is turned into a Qt signal, and the two hooks that need an answer
* (on_permission, on_ask_user) block the worker until the GUI replies. No
* HTTP, no socket: the GUI owns the engine in its own process. */
#ifndef CST_APP_AGENTCORE_H
#define CST_APP_AGENTCORE_H
#include <QByteArray>
#include <QHash>
#include <QMutex>
#include <QObject>
#include <QString>
#include <QVariantList>
#include <QVariantMap>
#include <QWaitCondition>
#include "cst_agent.h"
#include "cst_tools.h"
class QThread;
class AgentCore : public QObject {
Q_OBJECT
Q_PROPERTY(bool running READ running NOTIFY runningChanged)
Q_PROPERTY(QString workspace READ workspace NOTIFY workspaceChanged)
Q_PROPERTY(QString mode READ mode NOTIFY modeChanged)
Q_PROPERTY(QString provider READ provider NOTIFY configChanged)
Q_PROPERTY(QString model READ model NOTIFY configChanged)
Q_PROPERTY(int approval READ approval WRITE setApproval NOTIFY approvalChanged)
Q_PROPERTY(bool planMode READ planMode WRITE setPlanMode NOTIFY planModeChanged)
Q_PROPERTY(QString todo READ todo NOTIFY todoChanged)
Q_PROPERTY(QString sessionId READ sessionId NOTIFY sessionChanged)
public:
explicit AgentCore(QObject *parent = nullptr);
~AgentCore() override;
/* Start the engine on a workspace. provider/model/apiKey may be empty to
* fall back to the saved credentials and the provider's default model. */
bool open(const QString &workspace, const QString &provider,
const QString &model, const QString &apiKey, QString *err);
void close();
bool running() const { return m_running; }
QString workspace() const { return m_workspace; }
QString mode() const { return QString::fromUtf8(m_cfg.mode); }
QString provider() const { return QString::fromUtf8(m_cfg.provider); }
QString model() const { return QString::fromUtf8(m_cfg.model); }
int approval() const { return m_cfg.approval; }
bool planMode() const { return m_cfg.plan_mode != 0; }
QString todo() const { return m_todo; }
QString sessionId() const;
/* Markdown -> HTML with the engine's own renderer (cst_web_md_html), so a
* message looks the same here as it does in the WebUI. */
Q_INVOKABLE QString renderMarkdown(const QString &text) const;
/* --- sessions (the workspace's .agent/sessions store) ------------------- */
/* Stored sessions, newest first; one map each: id, title (a rename, else
* empty), firstUser, messages, mtime (ms since the epoch), current. */
Q_INVOKABLE QVariantList sessions() const;
/* The open session as transcript rows, in exactly the shape the live
* signals build (kind, role, text, name, state, detail, output, exitCode,
* complete, images), so a reopened session renders like the turn that wrote
* it. */
Q_INVOKABLE QVariantList history() const;
/* None of these run during a turn; all return false when one does. */
Q_INVOKABLE bool newSession();
Q_INVOKABLE bool switchSession(const QString &id);
Q_INVOKABLE bool deleteSession(const QString &id);
Q_INVOKABLE bool renameSession(const QString &id, const QString &title);
/* --- provider, model, key (see cst_provider_switch.h) ------------------- */
/* The presets: name, base, model (remembered, else the preset's), hasKey
* and keyFrom ("saved", else the environment variable), keyEnv, source and
* current, custom (the user's own provider, kept in the engine's user
* model file). Never a key: the engine keeps those out of the UI's reach. */
Q_INVOKABLE QVariantList providers() const;
/* A provider the engine's presets do not know: it goes into the user model
* file (<config>/cst-agent/models.json), which is where the registry keeps
* them, and the registry is reloaded, so the next providers() call lists
* it. `modelsCsv` is a comma-separated model list (may be empty).
* "" when it worked, else the reason. */
Q_INVOKABLE QString addProvider(const QString &name, const QString &base,
const QString &keyEnv,
const QString &defaultModel,
const QString &modelsCsv);
/* Drop a provider that came from that file (1 = it was there, 0 = it was
* not, -1 = with a reason). A preset of the same name stays. */
Q_INVOKABLE int removeProvider(const QString &name);
/* The generation parameters remembered for a provider (0 = not set, the
* field is not sent at all). */
Q_INVOKABLE QVariantMap genParams(const QString &provider) const;
/* Remember temperature / top-p / max tokens (0 = unset) for a provider and
* apply them to the engine when that provider is the live one.
* "" when it worked, else the reason. */
Q_INVOKABLE QString setGenParams(const QString &provider, double temperature,
double topP, int maxTokens);
/* Model candidates for a provider: its own list, what was fetched into the
* cache, and the remembered pick. No network. */
Q_INVOKABLE QStringList modelChoices(const QString &provider) const;
/* "1M · vision" for the model picker, "" when nothing is known. */
Q_INVOKABLE QString modelInfo(const QString &model) const;
/* Switch provider, model and key in one call. The engine's own config moves
* (its session does not), the choice is remembered, and an empty return
* means it worked; anything else is a reason to show. A key is verified
* against the provider's /models when one is given. */
Q_INVOKABLE QString useProvider(const QString &provider, const QString &model,
const QString &key);
/* Tokens of this session and of the last turn, plus the cost when priced. */
Q_INVOKABLE QVariantMap usage() const;
/* --- attachments (see cst_attach.h) ------------------------------------- */
Q_PROPERTY(QStringList pending READ pendingAttachments NOTIFY pendingChanged)
/* What the next prompt will carry: "<name> (<mime>, 12 KB)" per line. */
QStringList pendingAttachments() const;
/* Copy a file next to the session and give it to the next prompt. "" when
* it worked, else why not. */
Q_INVOKABLE QString attachFile(const QString &path);
/* The same for an image on the clipboard (Ctrl+V). "" when it worked; a
* reason -- "no image on the clipboard" -- when the editor should have the
* keystroke instead. */
Q_INVOKABLE QString attachClipboard();
/* Whether Ctrl+V should become an attachment at all (an image is on the
* clipboard) or stay with the editor (text). */
Q_INVOKABLE bool clipboardHasImage() const;
Q_INVOKABLE void clearPending();
/* The images among the pending attachments, in the engine's order, in the
* same text history() and toolImages() carry (see imagesText()): one line
* per picture, "<stored name>|<name>|<origin>|<w>x<h>". Empty for a PDF or
* a text file, and for a picture whose stored name the engine did not
* report. */
Q_INVOKABLE QString pendingImages() const;
/* Where the current session keeps its stored images: the directory
* image://cstattach/ serves (SessionImages.cpp). "" until the engine is
* open. It follows the session. */
Q_INVOKABLE QString attachmentDir() const;
/* A file card's two buttons: the stored file goes to the system -- a phone
* opens it with ACTION_VIEW or hands it to the share sheet, a desktop gives
* it to its own application or to the clipboard. "" when it went through
* (the header gets the line from statusChanged), else what to say. The name
* is the stored one the card carries; anything else is refused. */
Q_INVOKABLE QString openArtifact(const QString &rel);
Q_INVOKABLE QString shareArtifact(const QString &rel);
/* 1 the model is shown images, 0 it is not (they go as notes), -1 unknown. */
Q_INVOKABLE int seesImages() const;
/* The engine, for the parts that need it (tool registration). */
cst_agent_t *agent() const { return m_agent; }
const cst_agent_config_t *config() const { return &m_cfg; }
/* Ask a question; emits the streaming signals, then turnFinished(). */
Q_INVOKABLE void send(const QString &prompt);
Q_INVOKABLE void cancel();
Q_INVOKABLE QString taskState() const;
Q_INVOKABLE void taskControl(bool readOnly, bool delegation, bool paused);
Q_INVOKABLE void cancelJob(const QString &id, bool force);
Q_INVOKABLE QString workerConfig() const;
Q_INVOKABLE QString saveWorkerConfig(const QString &json);
Q_INVOKABLE QString worktreeDiff(const QString &path, bool integrate);
/* Consent: answers map to CST_PERM_*. */
Q_INVOKABLE void answerPermission(int choice);
Q_INVOKABLE void answerQuestion(const QString &answer);
Q_INVOKABLE void setMode(const QString &mode); /* coding | general */
Q_INVOKABLE void setApproval(int approval); /* cst_approval_t */
Q_INVOKABLE void setPlanMode(bool on);
/* Tools the front end implements itself. The engine copies the definition
* (strings included), so a stack value is fine; ud must outlive it.
* owner is what unregisterOwner() later matches. */
bool registerTool(const cst_tool_def_t *def);
void unregisterOwner(const QString &owner);
/* Re-probe platform tools after a service appeared or went away. */
void reloadToolMeta() { cst_tool_meta_reload(); }
/* Answer every consent question with "once" (the C smoke test, headless
* runs, a --yes flag). */
void setAutoApprove(bool on) { m_autoApprove = on; }
signals:
void configChanged();
void approvalChanged();
void planModeChanged();
void sessionChanged(); /* another session is open now */
void sessionListChanged(); /* the store gained, lost or renamed one */
void pendingChanged(); /* attachments for the next prompt changed */
void statusChanged(const QString &text);
void assistantDelta(const QString &text);
void thinkDelta(const QString &text);
/* A call is identified by its id: the same tool can run twice in one turn,
* and only the id tells the two cards apart. Text protocols carry ids too
* (cst_tool_call_from_native, the ctl parser), so this is never empty. */
void toolEvent(const QString &phase, const QString &id, const QString &name,
const QString &detail);
void toolResult(const QString &id, const QString &name, int exitCode,
const QString &output);
/* Images a tool produced (view_image, an MCP image), right after its
* result, as the text ImageStrip.qml decodes. */
void toolImages(const QString &callId, const QString &images);
/* The images the prompt that was just sent carries, in the same shape,
* fired before the turn's first delta. */
void promptImages(const QString &images);
void todoChanged(const QString &text);
void permissionRequested(const QString &tool, const QString &detail,
const QString &preview);
void questionAsked(const QString &question, const QString &options);
/* The worker asked and nobody answered in time (or the app was in the
* background, where the dialog cannot be seen): the turn went on with a
* refusal, and the window puts its dialog away again. */
void permissionExpired(const QString &tool);
void questionExpired();
void turnFinished(int rc, const QString &err);
void runningChanged();
void workspaceChanged();
void modeChanged();
private:
friend class Turn;
void finishTurn(int rc, const QString &err);
void setRunning(bool on);
/* Take the engine's config over m_cfg again (a switch changed it) and say
* so. */
void syncConfig();
/* Re-read what a session switch changed (id, todo) and say so. */
void afterSessionChange();
/* True when the app is not on screen: a phone in the background (Qt
* suspends it), or a window that is not there at all. A dialog opened now
* would be invisible, so consent is refused instead of waited for. */
bool backgrounded() const;
/* Hook trampolines (C, run on the worker thread). */
static void hookStatus(const char *msg, void *ud);
static void hookAssistant(const char *text, size_t len, void *ud);
static void hookThink(const char *text, size_t len, void *ud);
static void hookToolEvent(const char *phase, const ctl_tool_call_t *call,
const char *detail, void *ud);
static void hookToolResult(const ctl_tool_call_t *call, const char *out,
size_t len, int exit_code, void *ud);
static void hookToolImages(const ctl_tool_call_t *call,
const cst_attachment_t *list, int n, void *ud);
static void hookTodo(const char *text, void *ud);
static int hookPermission(const char *tool, const char *detail,
const char *preview, void *ud);
static int hookAskUser(const char *question, const char *options, char *ans,
size_t ans_sz, void *ud);
/* Post a lambda onto the GUI thread. */
template <typename F>
void post(F f) {
QMetaObject::invokeMethod(this, f, Qt::QueuedConnection);
}
cst_agent_t *m_agent = nullptr;
cst_agent_config_t m_cfg;
cst_agent_hooks_t m_hooks;
QString m_workspace;
QThread *m_turn = nullptr;
bool m_running = false;
bool m_closing = false;
/* consent handshake between the worker and the GUI thread */
QMutex m_askMu;
QWaitCondition m_askCv;
int m_permAnswer = CST_PERM_DENY;
bool m_permPending = false;
QString m_question;
QString m_todo;
/* The session list rebuilt only when a transcript moved: filling one row
* walks the whole file, and the sidebar asks for the list on every store
* change. Keyed by id, dropped when the id is gone. */
struct SessionCache {
qint64 mtime = 0;
qint64 size = 0;
QVariantMap row;
};
mutable QHash<QString, SessionCache> m_sessionCache;
/* Names of the files this window attached, in the engine's pending order:
* the engine's own description says what it is, not where it came from. */
QStringList m_attachNames;
QByteArray m_answer;
bool m_questionPending = false;
bool m_autoApprove = false;
};
#endif /* CST_APP_AGENTCORE_H */
+333
View File
@@ -0,0 +1,333 @@
/* The window's own tools, in Qt rather than in the engine: a document the
* person asked for, laid out as a PDF.
*
* Why here and not in the C engine: laying text out on pages is exactly what
* Qt does (QTextDocument + QPdfWriter, both in QtGui, which the app already
* links), while the engine has no layout code at all -- and md_to_html, its
* sibling, lives in the engine because rendering markdown is a shared
* capability. This one is a front-end capability: it is registered under
* owner "app:qt" and is available on every platform the app runs on.
*
* The path of a document is the one md_to_html walks: markdown (or a
* workspace .md/.html file) -> cst_web_md_document() -> a file inside the
* workspace -> cst_attach_import_artifact(), which is what turns it into a
* file card the person can open or share. The bytes never reach the model.
*
* Pagination is ours on purpose: QPrinter/PrintSupport is a desktop-only
* module (a phone has no print subsystem), and a round of
* pageSize + translate + drawContents per page is all a paginated PDF needs.
* The tool runs on the turn's worker thread, so a long document does not
* freeze the window. */
#include <QByteArray>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMarginsF>
#include <QPageLayout>
#include <QPageSize>
#include <QPainter>
#include <QPdfWriter>
#include <QRectF>
#include <QString>
#include <QTextDocument>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include "core/AgentCore.h"
#include "core/ToolProvider.h"
#include "cst_agent.h"
#include "cst_attach.h"
#include "cst_tools.h"
#include "cst_web_md.h"
namespace app {
namespace {
/* md_to_html caps its input the same way: a document nobody could read is
* not worth laying out. */
constexpr int kMaxInputBytes = 8 * 1024 * 1024;
/* 150 dpi: crisp enough for text, and a good deal lighter on a phone than the
* default 300 (a 40-page document is laid out and written in a moment). */
constexpr int kPdfDpi = 150;
const char *argOf(const ctl_tool_call_t *call, const char *key) {
for (int i = 0; i < call->nargs; i++)
if (strcmp(call->args[i].key, key) == 0)
return call->args[i].value;
return nullptr;
}
int setOut(cst_tool_result_t *r, const QString &text, int rc) {
const QByteArray b = text.toUtf8();
r->out = strdup(b.constData());
r->out_len = r->out ? strlen(r->out) : 0;
r->exit_code = rc;
return rc;
}
/* "docs/notes.md" -> "notes". */
QString stemOf(const QString &path) {
QString base = path;
const int slash = qMax(base.lastIndexOf(QLatin1Char('/')),
base.lastIndexOf(QLatin1Char('\\')));
if (slash >= 0)
base = base.mid(slash + 1);
const int dot = base.lastIndexOf(QLatin1Char('.'));
if (dot > 0)
base = base.left(dot);
return base.isEmpty() ? QStringLiteral("document") : base;
}
/* What the file is called: `out` when given (a directory takes the source's
* name inside it), otherwise the source's stem, or the title. */
QString outPathOf(const ctl_tool_call_t *c, const QString &stem) {
const char *out = argOf(c, "out");
QString name = out && out[0] ? QString::fromUtf8(out) : QString();
if (name.isEmpty())
return stem + QStringLiteral(".pdf");
if (name.endsWith(QLatin1Char('/')) || name.endsWith(QLatin1Char('\\')))
return name + stem + QStringLiteral(".pdf");
if (!QFileInfo(name).fileName().contains(QLatin1Char('.')))
name += QStringLiteral(".pdf");
return name;
}
/* The HTML that goes into the page: an .html file is already a document, a
* .md file (or the `markdown` argument) goes through the engine's renderer,
* which is the same one the WebUI and md_to_html use. */
bool sourceHtml(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
QString *html, QString *out_name, QString *err) {
const char *md = argOf(c, "markdown");
const char *file = argOf(c, "file");
const char *given = argOf(c, "title");
QString title = given && given[0] ? QString::fromUtf8(given) : QString();
QByteArray text;
QString stem;
if (file && file[0]) {
char rel[4096] = "";
if (cst_sandbox_resolve(ctx->workspace_root, file, rel, sizeof(rel)) != 0) {
*err = QStringLiteral("error: path outside the workspace or missing "
"parent: %1")
.arg(QString::fromUtf8(file));
return false;
}
QFile in(QString::fromUtf8(rel));
if (!in.open(QIODevice::ReadOnly)) {
*err = QStringLiteral("error: cannot read %1")
.arg(QString::fromUtf8(file));
return false;
}
if (in.size() > kMaxInputBytes) {
*err = QStringLiteral("error: %1 is larger than %2 MB")
.arg(QString::fromUtf8(file))
.arg(kMaxInputBytes >> 20);
return false;
}
text = in.readAll();
stem = stemOf(QString::fromUtf8(file));
const QString lower = QString::fromUtf8(file).toLower();
if (lower.endsWith(QLatin1String(".html")) ||
lower.endsWith(QLatin1String(".htm"))) {
/* already a document: what md_to_html wrote, or anything else */
*html = QString::fromUtf8(text);
if (title.isEmpty())
title = stem;
*out_name = outPathOf(c, stem);
return true;
}
} else if (md && md[0]) {
text = QByteArray(md);
if (stem.isEmpty())
stem = title.isEmpty() ? QStringLiteral("document") : stemOf(title);
} else {
*err = QStringLiteral("error: give markdown, or a workspace .md or .html "
"file to render");
return false;
}
if (title.isEmpty())
title = stem;
char *doc =
cst_web_md_document(text.constData(), static_cast<size_t>(text.size()),
title.toUtf8().constData());
if (!doc) {
*err = QStringLiteral("error: cannot render the markdown");
return false;
}
*html = QString::fromUtf8(doc);
free(doc);
*out_name = outPathOf(c, stem);
return true;
}
/* Write `html` into `path` as an A4 PDF with 15 mm margins: one page rect,
* translated down per page, and the document is asked for exactly that much
* text at a time -- which is what makes Qt lay out pages instead of one long
* strip. */
bool writePdf(const QString &html, const QString &path, const QString &title,
QString *err) {
std::unique_ptr<QTextDocument> doc(paperDocument(html));
if (!title.isEmpty())
doc->setMetaInformation(QTextDocument::DocumentTitle, title);
QPdfWriter writer(path);
writer.setPageSize(QPageSize(QPageSize::A4));
writer.setPageMargins(QMarginsF(15, 15, 15, 15), QPageLayout::Millimeter);
writer.setResolution(kPdfDpi);
if (!title.isEmpty())
writer.setTitle(title);
QPainter painter(&writer);
if (!painter.isActive()) {
*err = QStringLiteral("error: cannot draw into %1").arg(path);
return false;
}
const QRectF page = writer.pageLayout().paintRectPixels(writer.resolution());
doc->setPageSize(page.size());
const int pages = qMax(1, doc->pageCount());
for (int i = 0; i < pages; i++) {
if (i)
writer.newPage();
painter.save();
painter.translate(page.topLeft());
painter.translate(0, -i * page.height());
doc->drawContents(&painter,
QRectF(0, 0, page.width(), page.height())
.translated(0, i * page.height()));
painter.restore();
}
painter.end();
/* The painter says nothing about the file: the only proof the PDF landed is
* that there is one with bytes in it. */
if (QFileInfo(path).size() <= 0) {
*err = QStringLiteral("error: nothing was written to %1").arg(path);
return false;
}
return true;
}
int mdToPdfPreview(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
char **out) {
(void)ctx;
const char *md = argOf(c, "markdown");
const char *file = argOf(c, "file");
if ((!md || !md[0]) && (!file || !file[0])) {
*out = strdup("error: give markdown, or a .md or .html file to render");
return -1;
}
const QString stem =
file && file[0] ? stemOf(QString::fromUtf8(file)) : QStringLiteral("document");
const QString name = outPathOf(c, stem);
QByteArray line;
if (file && file[0])
line = QStringLiteral("lay out %1 → %2 as a PDF\n")
.arg(QString::fromUtf8(file), name)
.toUtf8();
else
line = QStringLiteral("lay out %1 bytes of markdown → %2 as a PDF\n")
.arg(md ? qstrlen(md) : 0)
.arg(name)
.toUtf8();
*out = strdup(line.constData());
return 0;
}
int mdToPdfRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c,
cst_tool_result_t *r, void *ud) {
(void)ud;
QString html, out_name, err;
if (!sourceHtml(ctx, c, &html, &out_name, &err))
return setOut(r, err, 1);
char full[4096] = "";
if (cst_sandbox_resolve(ctx->workspace_root, out_name.toUtf8().constData(),
full, sizeof(full)) != 0)
return setOut(r, QStringLiteral("error: path outside the workspace: %1")
.arg(out_name),
1);
const QString target = QString::fromUtf8(full);
/* A directory in the way of the name is what the engine's write tools call
* "missing parent": make it, the same way md_to_html does. */
QDir().mkpath(QFileInfo(target).absolutePath());
const char *given = argOf(c, "title");
const QString title = given && given[0] ? QString::fromUtf8(given) : QString();
if (!writePdf(html, target, title, &err))
return setOut(r, err, 1);
const qint64 bytes = QFileInfo(target).size();
const char *session = ctx->agent ? cst_agent_session_path(ctx->agent) : nullptr;
cst_attachment_t *a = nullptr;
char aerr[256] = "";
if (session && session[0])
a = cst_attach_import_artifact(session, full, nullptr, aerr, sizeof(aerr));
QString text = QStringLiteral("wrote %1 (%2 KB, A4, 15 mm margins)\n")
.arg(out_name)
.arg(bytes / 1024);
if (a)
text += QStringLiteral("(the user sees it as a file card they can open or "
"share; you will not be shown its bytes again)\n");
else if (aerr[0])
text += QStringLiteral("(the file is in the workspace; handing it over "
"failed: %1)\n")
.arg(QString::fromUtf8(aerr));
const int rc = setOut(r, text, 0);
if (a) {
r->attach = a;
r->nattach = 1;
}
return rc;
}
} // namespace
/* The document writePdf lays out, with a colour filled in for text that names
* none of its own.
*
* Paper is white and has no theme, but a QTextDocument takes its default text
* colour from the application palette: in a window running a dark palette --
* which is what a phone in dark mode hands Qt -- every plain markdown
* paragraph came out #eeeeee on a white page, i.e. a PDF that looks blank
* when printed, and reads as "the font is oddly faint" on screen. Naming the
* colour makes the page depend on the paper rather than on the window. A
* colour the document does name still wins (an .html file somebody handed us
* keeps its own), so this only fills the holes. */
QTextDocument *paperDocument(const QString &html) {
auto *doc = new QTextDocument;
doc->setDefaultStyleSheet(QStringLiteral("body { color: #000000; }"));
doc->setHtml(html);
return doc;
}
int registerQtTools(AgentCore *core) {
if (!core)
return 0;
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"markdown", "string", 0, "markdown text to render"},
{"file", "string", 0,
"workspace .md file to render, or an .html one to lay out as it is"},
{"out", "string", 0,
"output path in the workspace (default: the source's name + .pdf)"},
{"title", "string", 0, "document title (default: the file name)"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
static cst_tool_def_t def;
memset(&def, 0, sizeof(def));
setMeta(&def, "md_to_pdf",
"Write a document as a PDF: markdown (or a workspace .md/.html "
"file) in, a laid-out A4 PDF out, saved in the workspace and "
"handed to the person as a card they can open, print or share. "
"Use it when the answer should be something to keep or send.",
CST_TP_WRITE, "pdf", nullptr, nullptr);
memcpy(def.params, params, sizeof(params));
def.run_ex = mdToPdfRun;
def.preview = mdToPdfPreview;
def.owner = "app:qt";
return core->registerTool(&def) ? 1 : 0;
}
} // namespace app
+43
View File
@@ -0,0 +1,43 @@
#include "ToolProvider.h"
#include "AgentCore.h"
namespace app {
/* Keep these in one place: every platform tool of the front end uses one of
* them, so the engine's availability gate and the policy UI agree. */
const char *const kDesktopOnly[] = {"desktop", NULL};
const char *const kAndroidOnly[] = {"android", NULL};
int registerPlatformTools(AgentCore *core) {
if (!core)
return 0;
int n = 0;
#if defined(__ANDROID__)
n += platformRegisterAndroid(core);
#elif defined(__APPLE__)
n += platformRegisterMac(core);
#elif defined(_WIN32)
n += platformRegisterWindows(core);
#elif defined(__linux__)
n += platformRegisterLinux(core);
#endif
/* Qt is not a platform API: these exist wherever the window does. */
n += registerQtTools(core);
/* A service may have appeared or gone since the last probe (a desktop
* session starting, the notification daemon coming up). */
cst_tool_meta_reload();
return n;
}
void unregisterPlatformTools(AgentCore *core) {
if (!core)
return;
core->unregisterOwner(QStringLiteral("app:linux"));
core->unregisterOwner(QStringLiteral("app:windows"));
core->unregisterOwner(QStringLiteral("app:macos"));
core->unregisterOwner(QStringLiteral("app:android"));
core->unregisterOwner(QStringLiteral("app:qt"));
}
} // namespace app
+126
View File
@@ -0,0 +1,126 @@
/* How the front end hands a tool to the engine.
*
* A tool implemented in C++ is an ordinary cst_tool_def_t: the engine owns a
* copy of the definition, so a static (or stack) value is enough, and
* `ud`/`run_ex` keep pointing at the front end's state. The callback runs on
* the turn's worker thread -- touch Qt objects only through queued signals.
*
* See app/src/platform/linux/NotifyTool.cpp for a worked example, and
* tests/test_embed.c for the same contract without Qt.
*/
#ifndef CST_APP_TOOLPROVIDER_H
#define CST_APP_TOOLPROVIDER_H
#include <QString>
#include "cst_tools.h"
/* The engine wrapper of the front end (core/AgentCore.h). Only a pointer
* travels through this header, so the class stays incomplete here. */
class AgentCore;
/* Same for the document md_to_pdf lays out (PdfTools.cpp): the caller owns
* it, and the test in ui/UiTest.cpp inspects how it draws. */
class QTextDocument;
namespace app {
/* Fill a definition in one place, so every front-end tool carries the same
* metadata (class + policy name + platform list + probe). */
inline void setMeta(cst_tool_def_t *def, const char *name, const char *desc,
cst_tool_perm_t perm, const char *perm_name,
const char *const *platforms,
int (*available)(char *, size_t)) {
def->name = name;
def->desc = desc;
def->perm = perm;
def->perm_name = perm_name;
def->platforms = platforms;
def->available = available;
}
/* Tools that only work on the phone. */
extern const char *const kAndroidOnly[];
/* Tools that only work on a desktop (linux / win / macos). */
extern const char *const kDesktopOnly[];
/* The platform tools this app provides. Called once the engine exists;
* returns how many were registered. */
int registerPlatformTools(AgentCore *core);
/* The tools this front end provides that are the same on every platform
* (they are Qt, not a platform API): today md_to_pdf, owned by "app:qt".
* Called next to registerPlatformTools(). */
int registerQtTools(AgentCore *core);
/* The document md_to_pdf lays out from `html`: the page's own defaults
* applied (text with no colour of its own is black, not the window's palette
* colour). The caller owns the result. */
QTextDocument *paperDocument(const QString &html);
/* Drop them again (they belong to the owners "app:*"). */
void unregisterPlatformTools(AgentCore *core);
/* One entry point per platform, implemented by the file under
* src/platform/<os>/; ToolProvider.cpp picks one at compile time. */
int platformRegisterLinux(AgentCore *core);
int platformRegisterMac(AgentCore *core);
int platformRegisterWindows(AgentCore *core);
int platformRegisterAndroid(AgentCore *core);
/* Hand a file of the session's store to the system: a phone opens it with
* ACTION_VIEW through the app's FileProvider, a desktop gives it to whatever
* the desktop uses. `title` is the name a person knows the file by (the
* stored copy is named by its id, which means nothing outside), used for the
* status line. Both return "" on success and a reason to show the user
* otherwise; *status (optional) gets the line to put in the header.
* CST_APP_NO_OPEN=1 makes both do nothing (--uitest drives the window without
* opening anything for real). */
QString openLocalFile(const QString &path, const QString &title, QString *status);
/* The same file through the share sheet where there is one (Android); a
* desktop has no share sheet, so the path goes to the clipboard. */
QString shareLocalFile(const QString &path, const QString &title,
QString *status);
/* Hold the machine while a turn runs, so it survives the app leaving the
* screen: a phone starts a foreground service with a partial wake lock (the
* process is one Android will not freeze or kill, and the CPU keeps going
* with the screen off) and shows a notification naming the work; a desktop
* does nothing -- the window *is* the app there. Returns "" when the hold is
* in place (or when the platform has nothing to do), a reason otherwise; the
* turn runs either way. `text` is what the phone's notification says. */
QString holdForeground(const QString &text);
/* Drop it again, at the end of the turn (a phone: the notification goes). */
void releaseForeground();
/* Turn what a file chooser handed over into a path the engine can open. A
* desktop picker gives a path and nothing happens; a phone's is a SAF
* content:// URI, which the app copies into its own directory first (the
* grant travels with the URI, so no permission is involved -- and without
* the copy the engine, which opens files by path, would fail with "cannot
* read"). Returns the path to read, or "" with *err filled. */
QString materializeAttachment(const QString &pathOrUri, QString *err);
/* Does this app have "all files access" (Android 11+)? A desktop always
* does. Without it the app still attaches whatever the picker handed it; what
* it cannot do is read shared storage by path. */
bool hasAllFilesAccess();
/* Ask for it, through the one screen Android offers (there is no runtime
* dialog for it). A desktop, a phone that already has it or one too old to
* know about it returns "" and nothing opens. */
QString requestAllFilesAccess();
/* Take the whole screen. A phone's status bar -- and a tablet's taskbar, which
* is a status bar with icons in it -- is drawn *over* the window, and the
* window here draws from its own first pixel, so the bars sit on the app's top
* row and the controls there cannot be touched. Hiding them is what "full
* screen" means on a phone; a desktop has no such bars to ask about and
* returns "". Asking is repeatable and cheap: the bars come back with a swipe
* from the edge or a switch to another app, so the front end asks again every
* time the window comes to the front. Returns "" once they are gone, a reason
* otherwise (which the front end logs). */
QString requestFullscreen();
/* The arguments the Android activity was started with (the
* "applicationArguments" intent extra): the way
* `cst-agent-app --uitest --workspace DIR` is reachable on a device, since
* Qt's own plumbing for that extra does not reach this build. Empty
* everywhere else, and empty on a device that was not started with any. */
QStringList activityArguments();
} // namespace app
#endif /* CST_APP_TOOLPROVIDER_H */
+378
View File
@@ -0,0 +1,378 @@
/* cst-agent-app: the Qt front end.
*
* cst-agent-app --workspace DIR [--provider p] [--model m] [--api-key k]
* cst-agent-app --size WxH window geometry (480x900, 1180x800, ...)
* cst-agent-app --selftest embedding checks, no window, no network
*
* The engine runs in this process (see app/README.md); nothing listens on a
* port and no second process is started. */
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickStyle>
#include <QQuickWindow>
#include <QStandardPaths>
#include <QTemporaryDir>
#include <QTextStream>
#include <QUrl>
#if defined(Q_OS_ANDROID)
#include <QJniObject>
#include <QtCore/private/qandroidextras_p.h>
#endif
#include <cstdio>
#include <cstring>
#include <memory>
#include "core/AgentCore.h"
#include "core/ToolProvider.h"
#include "ui/UiTest.h"
#include "ui/BackKey.h"
#include "ui/SessionImages.h"
#include "ui/ThemeIcons.h"
#include "cst_version.h"
#if defined(Q_OS_ANDROID)
/* Where an Android app is allowed to write: its own data directory. There is
* no usable $HOME, no writable "/" (QDir::currentPath()) and no /tmp, while
* the engine wants a config dir ($XDG_CONFIG_HOME/cst-agent, os_config_dir())
* and a scratch dir (the first writable entry of os_temp_dir()'s list). All
* of them are pointed here -- once, before the engine exists. */
QString androidRoot() {
const QString root =
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
return root.isEmpty() ? QDir::tempPath() + QStringLiteral("/cst-agent")
: root;
}
#endif
namespace {
int runSelftest() {
QTextStream out(stdout);
int bad = 0;
QTemporaryDir tmp, cfg;
if (!tmp.isValid() || !cfg.isValid()) {
out << "selftest: cannot create a scratch dir\n";
return 1;
}
/* The window passes no --api-key, so the key the user saved for the provider
* has to come back from <config>/cst-agent/credentials -- the file the
* settings dialog writes. Planted in a scratch config dir, never in the
* real one. */
const QString cfgdir = cfg.path() + QStringLiteral("/cst-agent");
QDir().mkpath(cfgdir);
QFile creds(cfgdir + QStringLiteral("/credentials"));
if (!creds.open(QIODevice::WriteOnly | QIODevice::Truncate) ||
creds.write("deepseek.api_key=selftest-saved\n") < 0) {
out << "selftest: cannot write a scratch credentials file\n";
return 1;
}
creds.close();
qputenv("XDG_CONFIG_HOME", cfg.path().toUtf8());
AgentCore core;
QString err;
if (!core.open(tmp.path(), QStringLiteral("deepseek"), QString(), QString(),
&err)) {
out << "selftest: engine did not start: " << err << "\n";
return 1;
}
const cst_agent_config_t *live =
core.agent() ? cst_agent_config(core.agent()) : nullptr;
if (!live || strcmp(live->api_key, "selftest-saved") != 0) {
out << "selftest: the saved key did not reach the engine config\n";
bad++;
} else {
out << "selftest: the saved key is in the engine config\n";
}
if (!core.open(tmp.path(), QStringLiteral("deepseek"),
QStringLiteral("deepseek-flash"), QStringLiteral("test-key"),
&err)) {
out << "selftest: engine did not start: " << err << "\n";
return 1;
}
out << "selftest: engine started in-process\n";
if (core.agent() == nullptr) {
out << "selftest: no agent handle\n";
return 1;
}
/* the front end's own tools go through the engine's registry */
const int n = app::registerPlatformTools(&core);
out << "selftest: platform tools registered: " << n << "\n";
const cst_tool_def_t *t = cst_tool_find("notification_send");
if (!t) {
out << "selftest: notification_send is not in the registry\n";
bad++;
} else {
if (t->owner == nullptr || strncmp(t->owner, "app:", 4) != 0) {
out << "selftest: notification_send has no app owner\n";
bad++;
}
char why[160] = "";
const bool ok = cst_tool_available(t, why, sizeof(why)) == 0;
out << "selftest: notification_send available=" << (ok ? "yes" : "no")
<< (ok ? "" : QStringLiteral(" (%1)").arg(QString::fromUtf8(why)))
<< "\n";
}
/* The engine's own deliver_file: the file a tool hands to the person. */
const cst_tool_def_t *dv = cst_tool_find("deliver_file");
if (!dv) {
out << "selftest: deliver_file is not in the registry\n";
bad++;
} else {
char why[160] = "";
const bool ok = cst_tool_available(dv, why, sizeof(why)) == 0;
out << "selftest: deliver_file available=" << (ok ? "yes" : "no")
<< (ok ? "" : QStringLiteral(" (%1)").arg(QString::fromUtf8(why)))
<< "\n";
}
/* the mode comes from the engine, not from the UI */
core.setMode(QStringLiteral("general"));
if (core.mode() != QLatin1String("general")) {
out << "selftest: mode did not stick\n";
bad++;
}
app::unregisterPlatformTools(&core);
if (cst_tool_find("notification_send") != nullptr) {
out << "selftest: platform tools were not dropped\n";
bad++;
}
core.close();
out << (bad ? "selftest: FAILED\n" : "selftest: OK\n");
out.flush();
return bad ? 1 : 0;
}
} // namespace
int main(int argc, char **argv) {
/* --selftest stays headless: no window, no QML, no display needed. */
bool selftest = false;
for (int i = 1; i < argc; i++)
if (strcmp(argv[i], "--selftest") == 0)
selftest = true;
if (selftest) {
QCoreApplication app(argc, argv);
return runSelftest();
}
QGuiApplication app(argc, argv);
/* The window styles its own controls; the platform style only adds noise
* here (the KDE Breeze plugin logs a line per registered type and trips
* over the composer's TextArea). An explicit choice still wins. */
if (qEnvironmentVariableIsEmpty("QT_QUICK_CONTROLS_STYLE"))
QQuickStyle::setStyle(QStringLiteral("Basic"));
QGuiApplication::setApplicationName(QStringLiteral("cst-agent-app"));
QGuiApplication::setApplicationVersion(QStringLiteral(CST_VERSION));
QGuiApplication::setOrganizationName(QStringLiteral("cst-agent"));
QCommandLineParser parser;
parser.setApplicationDescription(
QStringLiteral("CST-agent desktop front end (engine in-process)"));
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption wsOpt({QStringLiteral("w"), QStringLiteral("workspace")},
QStringLiteral("workspace directory"),
QStringLiteral("dir"));
QCommandLineOption providerOpt(QStringLiteral("provider"),
QStringLiteral("provider name"),
QStringLiteral("name"));
QCommandLineOption modelOpt(QStringLiteral("model"),
QStringLiteral("model name"), QStringLiteral("name"));
QCommandLineOption planOpt(QStringLiteral("plan"),
QStringLiteral("start in plan mode"));
QCommandLineOption uitestOpt(
QStringLiteral("uitest"),
QStringLiteral("drive the window with synthesized mouse/touch input and exit"));
QCommandLineOption sizeOpt(QStringLiteral("size"),
QStringLiteral("initial window size, e.g. 480x900"),
QStringLiteral("WxH"));
/* A device run cannot be handed an environment (see activityArguments()), so
* what a desktop run asks for with CST_APP_SHOT=shot.png has to be an
* argument here. */
QCommandLineOption shotsOpt(
QStringLiteral("shots"),
QStringLiteral("--uitest: save a picture of the window at the interesting "
"points, in the workspace"));
parser.addOption(wsOpt);
parser.addOption(providerOpt);
parser.addOption(modelOpt);
parser.addOption(planOpt);
parser.addOption(uitestOpt);
parser.addOption(sizeOpt);
parser.addOption(shotsOpt);
/* What the process was started with, plus -- on a phone -- what the
* activity was started with: Qt's own applicationArguments plumbing does
* not deliver the extra on the NX789J (see activityArguments()), and
* without it there is no way to hand this window a workspace or a --uitest
* run on a device that has no keyboard. */
QStringList args = QCoreApplication::arguments();
#if defined(Q_OS_ANDROID)
args += app::activityArguments();
#endif
parser.process(args);
QString ws = parser.value(wsOpt);
if (ws.isEmpty()) {
#if defined(Q_OS_ANDROID)
ws = androidRoot() + QStringLiteral("/workspace");
#else
ws = QDir::currentPath();
#endif
}
ws = QFileInfo(ws).absoluteFilePath();
/* --uitest drives a scratch workspace when none was given: the session
* checks create and delete sessions, which is not something to do in
* whatever directory the app happened to be started from. */
std::unique_ptr<QTemporaryDir> scratch;
if (parser.isSet(uitestOpt) && parser.value(wsOpt).isEmpty()) {
scratch.reset(new QTemporaryDir);
if (scratch->isValid()) {
ws = scratch->path();
/* settings.json and credentials live in <config>/cst-agent: point them
* at the scratch dir too, so a test run never rewrites the user's own
* provider choice or key. */
qputenv("XDG_CONFIG_HOME", scratch->path().toUtf8());
}
}
/* Before the window exists: maybeShot() reads this at the point a picture is
* wanted (the settings dialog, the end of the run). */
if (parser.isSet(shotsOpt))
qputenv("CST_APP_SHOT",
(ws + QStringLiteral("/uitest-shot.png")).toUtf8());
#if defined(Q_OS_ANDROID)
/* Before the engine is created: its settings, credentials and session store
* all resolve their paths from the environment. */
const QString root = androidRoot();
for (const QString &sub : {QStringLiteral("config"), QStringLiteral("tmp")})
QDir().mkpath(root + QLatin1Char('/') + sub);
qputenv("XDG_CONFIG_HOME", (root + QStringLiteral("/config")).toUtf8());
qputenv("TMPDIR", (root + QStringLiteral("/tmp")).toUtf8());
qputenv("HOME", root.toUtf8());
#endif
AgentCore core;
QString err;
if (!core.open(ws, parser.value(providerOpt), parser.value(modelOpt),
QString(), &err)) {
QTextStream(stderr) << "cannot start the engine: " << err << "\n";
return 1;
}
app::registerPlatformTools(&core); /* the app's own tools */
#if defined(Q_OS_ANDROID)
/* notification_send sits behind POST_NOTIFICATIONS from Android 13 on, and
* the tool is hidden while it is not granted (its probe says so): ask once,
* here, so the tool is there for the first turn rather than a prompt that
* shows up mid-answer. Denying it only costs the tool. */
if (QNativeInterface::QAndroidApplication::context().isValid() &&
QtAndroidPrivate::checkPermission(
QStringLiteral("android.permission.POST_NOTIFICATIONS"))
.result() != QtAndroidPrivate::Authorized) {
QtAndroidPrivate::requestPermission(
QStringLiteral("android.permission.POST_NOTIFICATIONS"));
}
/* "All files access" is the other half of storage: it is what lets the
* engine read a path in shared storage (a file the user names, not one the
* picker hands over -- that one is copied into the app either way, see
* AttachFile.java). Android has no runtime dialog for it, only the Settings
* screen, so it is opened once (a marker file remembers) and never
* insisted on: without it everything still works, one picked file at a
* time. The line below is what logcat shows when a device behaves oddly. */
const bool allFiles = app::hasAllFilesAccess();
qInfo("storage: all files access = %s", allFiles ? "yes" : "no");
if (!allFiles) {
const QString marker = androidRoot() + QStringLiteral("/.all-files-asked");
if (!QFileInfo::exists(marker)) {
const QString why = app::requestAllFilesAccess();
if (!why.isEmpty())
qWarning("all files access: %s", qUtf8Printable(why));
QFile asked(marker);
if (asked.open(QIODevice::WriteOnly))
asked.write("1\n");
}
}
#endif
if (parser.isSet(planOpt))
core.setPlanMode(true);
/* --uitest: same window, driven by synthesized input (app/src/ui/UiTest.cpp). */
if (parser.isSet(uitestOpt))
return app::runUiTest(core, parser.value(sizeOpt));
/* The layout is responsive; --size is how it gets exercised without a
* different screen (see app/README.md). */
int winW = 0, winH = 0;
const QString size = parser.value(sizeOpt);
if (!size.isEmpty()) {
const int x = size.indexOf(QLatin1Char('x'));
bool okW = false, okH = false;
if (x > 0) {
winW = size.left(x).toInt(&okW);
winH = size.mid(x + 1).toInt(&okH);
}
if (!okW || !okH || winW < 320 || winH < 360) {
QTextStream(stderr) << "--size wants WxH (at least 320x360)\n";
return 2;
}
}
QQmlApplicationEngine engine;
/* image://csttheme/ plus the desktop's icon theme behind it. */
app::installThemeIcons(&engine);
/* image://cstattach/: the session's own store, so the pictures a tool made
* (view_image, an MCP image) and the ones the user attached are shown, not
* only named. The directory follows the session. */
app::SessionImages *images = app::installSessionImages(&engine);
images->setDir(core.attachmentDir());
QObject::connect(&core, &AgentCore::sessionChanged, images,
[images, &core] { images->setDir(core.attachmentDir()); });
engine.rootContext()->setContextProperty(QStringLiteral("agent"), &core);
engine.rootContext()->setContextProperty(QStringLiteral("initialWidth"), winW);
engine.rootContext()->setContextProperty(QStringLiteral("initialHeight"), winH);
const QUrl url(QStringLiteral("qrc:/qt/qml/CstAgent/Main.qml"));
QObject::connect(
&engine, &QQmlApplicationEngine::objectCreated, &app,
[url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
},
Qt::QueuedConnection);
engine.load(url);
if (engine.rootObjects().isEmpty())
return 1;
/* The phone's back key, one layer at a time (app/src/ui/BackKey.h). */
app::installBackKey(engine.rootObjects().value(0),
engine.rootObjects().value(0));
/* The system bars are drawn over the window (see requestFullscreen): ask for
* the whole screen, and ask again whenever the app comes back to the front,
* because a swipe from the edge or a switch to another app brings them back.
* A refusal is not fatal -- it is logged and the window keeps working with
* the bars over its top row. */
{
const QString why = app::requestFullscreen();
if (!why.isEmpty())
qWarning("fullscreen: %s", qUtf8Printable(why));
QQuickWindow *qwin =
qobject_cast<QQuickWindow *>(engine.rootObjects().value(0));
if (qwin)
QObject::connect(qwin, &QQuickWindow::sceneGraphInitialized, qwin,
[] { app::requestFullscreen(); });
QObject::connect(&app, &QGuiApplication::applicationStateChanged, &app,
[](Qt::ApplicationState state) {
if (state == Qt::ApplicationActive)
app::requestFullscreen();
});
}
return app.exec();
}
+988
View File
@@ -0,0 +1,988 @@
/* Platform tools on Android, implemented by the app: the same contract as
* app/src/platform/linux/NotifyTool.cpp, with Android APIs behind it.
*
* The engine only ever sees the capability: `platforms = kAndroidOnly` (the
* engine reports "android" when it was compiled with the NDK, see
* src/tools/registry.c: cst_platform_name()) plus an `available` probe decide
* whether a tool reaches the prompt and tools[] at all -- a Termux build on
* the same device reports "termux" and gets the android tools too, an APK
* never gets the desktop ones. `owner = "app:android"` is what
* unregisterPlatformTools() drops again.
*
* WHERE THE CODE RUNS: `run_ex` is called on the turn's worker thread, never
* on the GUI thread. JNI calls are fine from any thread (Qt attaches it),
* Qt GUI objects are not -- a tool that needs the widget tree
* has to hop back with a blocking queued call (onGuiThread() below).
*
* The clipboard tools keep the names of the engine's built-ins: those are
* gated to CST_PLAT_DESKTOP and the registry lets an app tool of the same
* name shadow the built-in (src/tools/registry.c: cst_tool_find()), so the
* model sees one capability either way. */
#include <QByteArray>
#include <QClipboard>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QFuture>
#include <QGuiApplication>
#include <QJniEnvironment>
#include <QJniObject>
#include <QMetaObject>
#include <QSemaphore>
#include <QStandardPaths>
#include <QString>
#include <QStringList>
#include <QThread>
#include <QtCore/private/qandroidextras_p.h>
#include <cstdio>
#include <cstring>
#include <memory>
#include <utility>
#include "core/AgentCore.h"
#include "core/ToolProvider.h"
namespace app {
namespace {
/* --- small helpers ------------------------------------------------------- */
const char *argOf(const ctl_tool_call_t *call, const char *key) {
for (int i = 0; i < call->nargs; i++)
if (strcmp(call->args[i].key, key) == 0)
return call->args[i].value;
return nullptr;
}
void setOut(cst_tool_result_t *r, const QByteArray &text, int rc) {
r->out = strdup(text.constData());
r->out_len = r->out ? strlen(r->out) : 0;
r->exit_code = rc;
}
/* How long the worker is willing to wait for the GUI thread to pick its work
* up. The hop itself is always waited for to the end (the closure writes into
* the caller's stack), so what this bounds is the case that makes a turn look
* stuck: a GUI thread that is not getting to the event loop at all. */
constexpr int kGuiStallMs = 3000;
/* Anything that touches a Qt GUI object (the clipboard) or an Activity has to
* run on the GUI thread; the turn's worker thread waits for it.
*
* The wait is bounded: a blocking queued call to a GUI thread that is busy
* (the session list reading transcripts used to do exactly that) would park
* the worker for as long as it lasts. A cheap ping first tells whether the
* GUI thread is there at all; only then is the real work handed over and
* waited for, which keeps the closure valid for its whole life. */
template <typename Fn>
bool onGuiThread(Fn &&fn) {
if (!qApp || QThread::currentThread() == qApp->thread()) {
fn();
return true;
}
auto pinged = std::make_shared<QSemaphore>(0);
QMetaObject::invokeMethod(qApp, [pinged] { pinged->release(); },
Qt::QueuedConnection);
if (!pinged->tryAcquire(1, kGuiStallMs))
return false; /* a GUI thread that is not answering: do not wait on it */
QMetaObject::invokeMethod(qApp, std::forward<Fn>(fn),
Qt::BlockingQueuedConnection);
return true;
}
jint sdkInt() {
static const jint sdk = QJniObject::getStaticField<jint>(
"android/os/Build$VERSION", "SDK_INT");
return sdk;
}
QJniObject appContext() {
return QNativeInterface::QAndroidApplication::context();
}
/* The strings the activity was started with. Qt is meant to hand the
* "applicationArguments" extra to QCoreApplication::arguments() by itself; on
* the NX789J it does not -- `am start ... --esa applicationArguments
* "--workspace,/sdcard/x"` left the window on its default workspace, and so
* did the same extra as a plain string. So the intent is asked directly, which
* is what makes `cst-agent-app --uitest --workspace DIR` (or any other
* argument) reachable on a device with no keyboard attached.
*
* Everything here degrades to "no arguments": an invalid object, a missing
* method, or a context that is not an activity all come back empty. */
QStringList intentArguments() {
QStringList out;
QJniObject activity = appContext();
if (!activity.isValid())
return out;
QJniObject intent =
activity.callObjectMethod("getIntent", "()Landroid/content/Intent;");
if (!intent.isValid())
return out;
const QJniObject key =
QJniObject::fromString(QStringLiteral("applicationArguments"));
/* Three shapes for the same extra, and which one arrives depends on who
* sent it: `am start --esa applicationArguments "--uitest,--workspace,/x"`
* stores a String[] (an empty launch, arguments and all, is what that cost
* us -- getStringArrayListExtra answers null for an array), a launcher or
* Qt's own loader uses putStringArrayListExtra, and `--es` puts one
* comma-separated string there. Try each, in that order. */
const QJniObject array = intent.callObjectMethod(
"getStringArrayExtra", "(Ljava/lang/String;)[Ljava/lang/String;",
key.object<jstring>());
if (array.isValid()) {
QJniEnvironment env;
const jobjectArray a = reinterpret_cast<jobjectArray>(array.object());
const jsize n = env->GetArrayLength(a);
for (jsize i = 0; i < n; i++) {
const jstring item =
reinterpret_cast<jstring>(env->GetObjectArrayElement(a, i));
if (!item)
continue;
const char *c = env->GetStringUTFChars(item, nullptr);
if (c) {
out << QString::fromUtf8(c);
env->ReleaseStringUTFChars(item, c);
}
env->DeleteLocalRef(item);
}
if (!out.isEmpty())
return out;
}
QJniObject list = intent.callObjectMethod(
"getStringArrayListExtra", "(Ljava/lang/String;)Ljava/util/ArrayList;",
key.object<jstring>());
if (list.isValid()) {
const jint n = list.callMethod<jint>("size", "()I");
for (jint i = 0; i < n; i++) {
QJniObject item =
list.callObjectMethod("get", "(I)Ljava/lang/Object;", i);
if (item.isValid())
out << item.toString();
}
if (!out.isEmpty())
return out;
}
const QJniObject one = intent.callObjectMethod(
"getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;",
key.object<jstring>());
if (one.isValid()) {
const QStringList parts =
one.toString().split(QLatin1Char(','), Qt::SkipEmptyParts);
out << parts;
}
return out;
}
/* --- notification_send --------------------------------------------------- */
/* Android 13 (API 33) put notifications behind a runtime permission; before
* that the permission does not exist and they always work. main.cpp asks for
* it once at startup, so the probe is normally green on a device where the
* user said yes. */
int notifyProbe(char *why, size_t why_sz) {
if (sdkInt() < 33)
return 0;
const QFuture<QtAndroidPrivate::PermissionResult> f =
QtAndroidPrivate::checkPermission(
QStringLiteral("android.permission.POST_NOTIFICATIONS"));
if (f.result() == QtAndroidPrivate::Authorized)
return 0;
snprintf(why, why_sz,
"POST_NOTIFICATIONS is not granted (Android 13+ asks the user the "
"first time the app runs)");
return -1;
}
bool postNotification(const QString &title, const QString &message,
QString *err) {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
*err = QStringLiteral("no Android context");
return false;
}
QJniObject manager = ctx.callObjectMethod(
"getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;",
QJniObject::fromString(QStringLiteral("notification")).object<jstring>());
if (!manager.isValid()) {
*err = QStringLiteral("no NotificationManager");
return false;
}
const QString channelId = QStringLiteral("cst-agent");
if (sdkInt() >= 26) {
QJniObject channel(
"android/app/NotificationChannel",
"(Ljava/lang/String;Ljava/lang/CharSequence;I)V",
QJniObject::fromString(channelId).object<jstring>(),
QJniObject::fromString(QStringLiteral("CST-agent")).object<jstring>(),
static_cast<jint>(3) /* IMPORTANCE_DEFAULT */);
manager.callMethod<void>("createNotificationChannel",
"(Landroid/app/NotificationChannel;)V",
channel.object<jobject>());
}
/* The small icon. The R classes are not reachable from here, so the id is
* looked up by name, and build() throws IllegalArgumentException ("Invalid
* notification (no valid small icon)") when there is none at all: every
* candidate that can be there is tried -- the framework drawables first,
* then the launcher icon the APK itself carries (AGP puts it in mipmap, a
* hand made APK in drawable/icon). */
QJniObject res = ctx.callObjectMethod("getResources",
"()Landroid/content/res/Resources;");
QJniObject pkg = ctx.callObjectMethod("getPackageName",
"()Ljava/lang/String;");
jint icon = 0;
if (res.isValid()) {
auto idOf = [&res, &pkg](const char *name, const char *type,
const char *owner) {
return res.callMethod<jint>(
"getIdentifier", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
QJniObject::fromString(QString::fromLatin1(name)).object<jstring>(),
QJniObject::fromString(QString::fromLatin1(type)).object<jstring>(),
owner ? QJniObject::fromString(QString::fromLatin1(owner)).object<jstring>()
: pkg.object<jstring>());
};
for (const char *n : {"ic_dialog_info", "ic_popup_reminder",
"stat_notify_chat", "sym_def_app_icon"}) {
icon = idOf(n, "drawable", "android");
if (icon != 0)
break;
}
for (const char *n : {"ic_launcher", "icon", "app_icon", "qt_icon"}) {
if (icon == 0)
icon = idOf(n, "mipmap", nullptr);
if (icon == 0)
icon = idOf(n, "drawable", nullptr);
if (icon != 0)
break;
}
}
if (icon == 0) {
*err = QStringLiteral("no small icon: it is in neither the framework "
"resources nor the APK's own");
return false;
}
/* Tapping it opens the app again (the launch intent of the package). */
QJniObject pm = ctx.callObjectMethod(
"getPackageManager", "()Landroid/content/pm/PackageManager;");
/* The builder, the build and the notify happen in Java (Notifier.java):
* a Java exception is invisible to C++ once Qt's JNI wrapper has cleared
* it, so on the phone this only ever said "failed, no exception detail"
* while the shade stayed empty. Java catches it and hands back the line to
* show. */
QJniObject launch;
if (pm.isValid() && pkg.isValid())
launch = pm.callObjectMethod(
"getLaunchIntentForPackage",
"(Ljava/lang/String;)Landroid/content/Intent;", pkg.object<jstring>());
QJniObject posted = QJniObject::callStaticObjectMethod(
"xyz/whcself/cstagent/Notifier", "post",
"(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;"
"Ljava/lang/String;ILandroid/content/Intent;I)Ljava/lang/String;",
ctx.object<jobject>(),
QJniObject::fromString(channelId).object<jstring>(),
QJniObject::fromString(title).object<jstring>(),
QJniObject::fromString(message).object<jstring>(), icon,
launch.isValid() ? launch.object<jobject>() : nullptr,
static_cast<jint>(1));
const QString java =
posted.isValid() ? posted.toString()
: QStringLiteral("the Notifier helper is not in this APK");
if (!java.isEmpty()) {
*err = QStringLiteral("cannot post the notification: %1").arg(java);
return false;
}
return true;
}
/* Runs on the turn's worker thread: no GUI objects here. */
int notifyRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)ud;
const char *message = argOf(call, "message");
const char *title = argOf(call, "title");
if (!message || !message[0]) {
setOut(r, QByteArrayLiteral("error: notification_send needs a message"), 1);
return 0;
}
const QString t = title && title[0] ? QString::fromUtf8(title)
: QStringLiteral("CST-agent");
const QString m = QString::fromUtf8(message);
QString err;
bool ok = false;
onGuiThread([&] { ok = postNotification(t, m, &err); });
if (ok)
setOut(r, QByteArrayLiteral("notification sent"), 0);
else
setOut(r, QByteArrayLiteral("error: ") + err.toUtf8(), 1);
return 0;
}
/* --- clipboard_read / clipboard_write ----------------------------------- */
int clipboardProbe(char *why, size_t why_sz) {
if (QGuiApplication::clipboard())
return 0;
snprintf(why, why_sz, "no QClipboard (no GUI application)");
return -1;
}
int clipboardReadRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)ud;
const char *cap = argOf(call, "max_bytes");
const long max =
cap && cap[0] ? strtol(cap, nullptr, 10) : 65536L;
QString text;
bool have = false;
onGuiThread([&] {
if (QClipboard *cb = QGuiApplication::clipboard()) {
text = cb->text();
have = true;
}
});
if (!have) {
setOut(r, QByteArrayLiteral("error: no clipboard"), 1);
return 0;
}
QByteArray body = text.toUtf8();
const bool cut = max > 0 && body.size() > max;
if (cut)
body.truncate(static_cast<int>(max));
QByteArray out =
QByteArrayLiteral("clipboard text (") + QByteArray::number(body.size()) +
QByteArrayLiteral(" bytes") +
(cut ? QByteArrayLiteral(", truncated") : QByteArray()) +
QByteArrayLiteral("):\n") + body + QByteArrayLiteral("\n");
setOut(r, out, 0);
return 0;
}
int clipboardWriteRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)ud;
const char *text = argOf(call, "text");
if (!text) {
setOut(r, QByteArrayLiteral("error: clipboard_write needs text"), 1);
return 0;
}
const QString t = QString::fromUtf8(text);
bool ok = false;
onGuiThread([&] {
if (QClipboard *cb = QGuiApplication::clipboard()) {
cb->setText(t);
ok = true;
}
});
if (ok)
setOut(r, QByteArrayLiteral("clipboard: replaced with ") +
QByteArray::number(t.toUtf8().size()) +
QByteArrayLiteral(" bytes"),
0);
else
setOut(r, QByteArrayLiteral("error: no clipboard"), 1);
return 0;
}
/* --- share --------------------------------------------------------------- */
/* A path inside the workspace, resolved the way the engine's file tools do:
* relative to the workspace and never outside it. */
QString resolveInWorkspace(const cst_tool_ctx_t *ctx, const char *rel) {
if (!ctx || !ctx->workspace_root || !rel || !rel[0])
return QString();
const QString root = QDir::cleanPath(QString::fromUtf8(ctx->workspace_root));
const QString full = QDir::cleanPath(root + QLatin1Char('/') +
QString::fromUtf8(rel));
if (full != root && !full.startsWith(root + QLatin1Char('/')))
return QString();
return full;
}
QString mimeOf(const QString &path) {
const QString ext = QFileInfo(path).suffix().toLower();
if (ext == QLatin1String("png")) return QStringLiteral("image/png");
if (ext == QLatin1String("jpg") || ext == QLatin1String("jpeg"))
return QStringLiteral("image/jpeg");
if (ext == QLatin1String("webp")) return QStringLiteral("image/webp");
if (ext == QLatin1String("gif")) return QStringLiteral("image/gif");
if (ext == QLatin1String("pdf")) return QStringLiteral("application/pdf");
if (ext == QLatin1String("json")) return QStringLiteral("application/json");
if (ext == QLatin1String("txt") || ext == QLatin1String("md") ||
ext == QLatin1String("log"))
return QStringLiteral("text/plain");
return QStringLiteral("*/*");
}
/* ACTION_SEND through the system share sheet. `text` shares a sentence (the
* usual case: the user takes it to another app), `file` shares one file out of
* the workspace by way of the FileProvider Qt's manifest template declares
* (androidx.core.content.FileProvider, authority <package>.qtprovider). */
bool shareText(const QString &text, const QString &subject, QString *err) {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
*err = QStringLiteral("no Android context");
return false;
}
QJniObject send = QJniObject::fromString(QStringLiteral("android.intent.action.SEND"));
QJniObject intent("android/content/Intent", "(Ljava/lang/String;)V",
send.object<jstring>());
intent.callObjectMethod("setType",
"(Ljava/lang/String;)Landroid/content/Intent;",
QJniObject::fromString(QStringLiteral("text/plain"))
.object<jstring>());
intent.callObjectMethod(
"putExtra",
"(Ljava/lang/String;Ljava/lang/CharSequence;)Landroid/content/Intent;",
QJniObject::fromString(QStringLiteral("android.intent.extra.TEXT"))
.object<jstring>(),
QJniObject::fromString(text).object<jstring>());
if (!subject.isEmpty())
intent.callObjectMethod(
"putExtra",
"(Ljava/lang/String;Ljava/lang/CharSequence;)Landroid/content/Intent;",
QJniObject::fromString(QStringLiteral("android.intent.extra.SUBJECT"))
.object<jstring>(),
QJniObject::fromString(subject).object<jstring>());
QJniObject chooser("android/content/Intent", "(Ljava/lang/String;)V",
QJniObject::fromString(QStringLiteral("android.intent.action.CHOOSER"))
.object<jstring>());
/* Intent.createChooser(Intent, CharSequence) -- the share sheet itself. */
QJniObject sheet = QJniObject::callStaticObjectMethod(
"android/content/Intent", "createChooser",
"(Landroid/content/Intent;Ljava/lang/CharSequence;)Landroid/content/Intent;",
intent.object<jobject>(),
QJniObject::fromString(QStringLiteral("Share with")).object<jstring>());
QJniObject toStart = sheet.isValid() ? sheet : intent;
toStart.callObjectMethod("addFlags", "(I)Landroid/content/Intent;",
static_cast<jint>(0x10000000) /* NEW_TASK */);
ctx.callMethod<void>("startActivity", "(Landroid/content/Intent;)V",
toStart.object<jobject>());
return true;
}
/* The content:// uri of a file inside the app's own data directory. The
* FileProvider and its paths xml come from Qt's manifest template
* (authority <package>.qtprovider, files-path "/"), which covers the whole
* workspace and the session store. */
QJniObject contentUriFor(const QString &path, QString *err) {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
*err = QStringLiteral("no Android context");
return QJniObject();
}
QJniObject pkg = ctx.callObjectMethod("getPackageName", "()Ljava/lang/String;");
const QString authority = pkg.toString() + QStringLiteral(".qtprovider");
QJniObject file("java/io/File", "(Ljava/lang/String;)V",
QJniObject::fromString(path).object<jstring>());
QJniObject uri = QJniObject::callStaticObjectMethod(
"androidx/core/content/FileProvider", "getUriForFile",
"(Landroid/content/Context;Ljava/lang/String;Ljava/io/File;)Landroid/net/Uri;",
ctx.object<jobject>(),
QJniObject::fromString(authority).object<jstring>(),
file.object<jobject>());
if (!uri.isValid())
*err = QStringLiteral("the FileProvider did not hand out a uri for ") + path;
return uri;
}
bool shareFile(const QString &path, const QString &text, QString *err) {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
*err = QStringLiteral("no Android context");
return false;
}
QJniObject uri = contentUriFor(path, err);
if (!uri.isValid())
return false;
QJniObject action = QJniObject::fromString(QStringLiteral("android.intent.action.SEND"));
QJniObject intent("android/content/Intent", "(Ljava/lang/String;)V",
action.object<jstring>());
intent.callObjectMethod("setType",
"(Ljava/lang/String;)Landroid/content/Intent;",
QJniObject::fromString(mimeOf(path)).object<jstring>());
intent.callObjectMethod(
"putExtra",
"(Ljava/lang/String;Landroid/os/Parcelable;)Landroid/content/Intent;",
QJniObject::fromString(QStringLiteral("android.intent.extra.STREAM"))
.object<jstring>(),
uri.object<jobject>());
if (!text.isEmpty())
intent.callObjectMethod(
"putExtra",
"(Ljava/lang/String;Ljava/lang/CharSequence;)Landroid/content/Intent;",
QJniObject::fromString(QStringLiteral("android.intent.extra.TEXT"))
.object<jstring>(),
QJniObject::fromString(text).object<jstring>());
intent.callObjectMethod(
"addFlags", "(I)Landroid/content/Intent;",
static_cast<jint>(0x10000000 /* NEW_TASK */ | 0x00000001 /* GRANT_READ_URI_PERMISSION */));
QJniObject sheet = QJniObject::callStaticObjectMethod(
"android/content/Intent", "createChooser",
"(Landroid/content/Intent;Ljava/lang/CharSequence;)Landroid/content/Intent;",
intent.object<jobject>(),
QJniObject::fromString(QStringLiteral("Share with")).object<jstring>());
QJniObject toStart = sheet.isValid() ? sheet : intent;
toStart.callObjectMethod("addFlags", "(I)Landroid/content/Intent;",
static_cast<jint>(0x10000000));
ctx.callMethod<void>("startActivity", "(Landroid/content/Intent;)V",
toStart.object<jobject>());
return true;
}
int shareRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ud;
const char *text = argOf(call, "text");
const char *file = argOf(call, "file");
const char *subject = argOf(call, "subject");
if ((!text || !text[0]) && (!file || !file[0])) {
setOut(r, QByteArrayLiteral("error: share needs text or file"), 1);
return 0;
}
QString path;
if (file && file[0]) {
path = resolveInWorkspace(ctx, file);
if (path.isEmpty() || !QFileInfo::exists(path)) {
setOut(r, QByteArrayLiteral("error: ") + QByteArray(file) +
QByteArrayLiteral(" is not inside the workspace"),
1);
return 0;
}
}
const QString body = text ? QString::fromUtf8(text) : QString();
const QString subjectLine = subject ? QString::fromUtf8(subject) : QString();
QString err;
bool ok = false;
onGuiThread([&] {
ok = path.isEmpty() ? shareText(body, subjectLine, &err)
: shareFile(path, body, &err);
});
if (!ok) {
setOut(r, QByteArrayLiteral("error: ") + err.toUtf8(), 1);
return 0;
}
setOut(r, path.isEmpty()
? QByteArrayLiteral("the share sheet is open with the text")
: QByteArrayLiteral("the share sheet is open with ") +
path.toUtf8(),
0);
return 0;
}
int shareProbe(char *why, size_t why_sz) {
if (appContext().isValid())
return 0;
snprintf(why, why_sz, "no Android activity to share from");
return -1;
}
/* Registered once; the engine keeps a copy until the owner is unregistered. */
cst_tool_def_t g_notify;
cst_tool_def_t g_clip_read;
cst_tool_def_t g_clip_write;
cst_tool_def_t g_share;
} // namespace
/* What main() asks for (ToolProvider.h): the reading itself is the JNI helper
* above, next to the Android context it needs. It sits outside the anonymous
* namespace so main.cpp can link to it. */
QStringList activityArguments() { return intentArguments(); }
/* A file card's "open": whatever app the phone has for the type, with the read
* permission granted to the app that picks it up. */
QString openLocalFile(const QString &path, const QString &title,
QString *status) {
const QString name = title.isEmpty() ? QFileInfo(path).fileName() : title;
if (qEnvironmentVariableIsSet("CST_APP_NO_OPEN")) {
if (status)
*status = QStringLiteral("opened %1 (test mode)").arg(name);
return QString();
}
if (!QFileInfo::exists(path))
return QStringLiteral("the file is gone: %1").arg(name);
QString err;
bool ok = false;
onGuiThread([&] {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
err = QStringLiteral("no Android context");
return;
}
QJniObject uri = contentUriFor(path, &err);
if (!uri.isValid())
return;
QJniObject action =
QJniObject::fromString(QStringLiteral("android.intent.action.VIEW"));
QJniObject intent("android/content/Intent", "(Ljava/lang/String;)V",
action.object<jstring>());
intent.callObjectMethod(
"setDataAndType",
"(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/Intent;",
uri.object<jobject>(),
QJniObject::fromString(mimeOf(path)).object<jstring>());
intent.callObjectMethod("addFlags", "(I)Landroid/content/Intent;",
static_cast<jint>(0x10000000 /* NEW_TASK */ |
0x00000001 /* GRANT_READ_URI */));
/* Nothing installed for the type: say so rather than fail silently. */
QJniObject pm = ctx.callObjectMethod(
"getPackageManager", "()Landroid/content/pm/PackageManager;");
QJniObject found =
pm.isValid()
? pm.callObjectMethod(
"resolveActivity",
"(Landroid/content/Intent;I)Landroid/content/pm/ResolveInfo;",
intent.object<jobject>(),
static_cast<jint>(0x00010000) /* MATCH_DEFAULT_ONLY */)
: QJniObject();
if (!found.isValid()) {
err = QStringLiteral("no app on the phone opens %1").arg(name);
return;
}
ctx.callMethod<void>("startActivity", "(Landroid/content/Intent;)V",
intent.object<jobject>());
ok = true;
});
if (!ok)
return err.isEmpty() ? QStringLiteral("cannot open %1").arg(name) : err;
if (status)
*status = QStringLiteral("opened %1").arg(name);
return QString();
}
/* The share sheet, the same way the share tool opens it. */
QString shareLocalFile(const QString &path, const QString &title,
QString *status) {
const QString name = title.isEmpty() ? QFileInfo(path).fileName() : title;
if (qEnvironmentVariableIsSet("CST_APP_NO_OPEN")) {
if (status)
*status = QStringLiteral("shared %1 (test mode)").arg(name);
return QString();
}
if (!QFileInfo::exists(path))
return QStringLiteral("the file is gone: %1").arg(name);
QString err;
bool ok = false;
onGuiThread([&] { ok = shareFile(path, QString(), &err); });
if (!ok)
return err.isEmpty() ? QStringLiteral("cannot share %1").arg(name) : err;
if (status)
*status = QStringLiteral("share sheet: %1").arg(name);
return QString();
}
/* An Intent aimed at one of our own classes, by name: the Java side is
* reached through an explicit component, so no other app can call it (and no
* intent filter has to exist). Empty action means "start". */
QJniObject serviceIntent(const QJniObject &ctx, const QString &action) {
QJniObject pkg = ctx.callObjectMethod("getPackageName",
"()Ljava/lang/String;");
if (!pkg.isValid())
return QJniObject();
QJniObject comp(
"android/content/ComponentName", "(Ljava/lang/String;Ljava/lang/String;)V",
pkg.object<jstring>(),
QJniObject::fromString(
QStringLiteral("xyz.whcself.cstagent.CstService"))
.object<jstring>());
if (!comp.isValid())
return QJniObject();
QJniObject intent("android/content/Intent");
intent.callObjectMethod(
"setComponent",
"(Landroid/content/ComponentName;)Landroid/content/Intent;",
comp.object<jobject>());
if (!action.isEmpty())
intent.callObjectMethod("setAction",
"(Ljava/lang/String;)Landroid/content/Intent;",
QJniObject::fromString(action).object<jstring>());
return intent;
}
/* A turn can outlive the screen, and a phone freezes or kills an app it
* cannot see: CstService (app/android/src/xyz/whcself/cstagent/CstService.java)
* is started as a foreground service for as long as one runs, and it takes the
* partial wake lock that keeps the CPU awake with the screen off. The explicit
* component means nothing outside the app can start it. */
QString holdForeground(const QString &text) {
if (qEnvironmentVariableIsSet("CST_APP_NO_SERVICE"))
return QString(); /* a test run leaves the phone alone */
QString err;
onGuiThread([&] {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
err = QStringLiteral("no Android context");
return;
}
QJniObject intent = serviceIntent(ctx, QString());
if (!intent.isValid()) {
err = QStringLiteral("no ComponentName for CstService");
return;
}
intent.callObjectMethod(
"putExtra",
"(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;",
QJniObject::fromString(QStringLiteral("text")).object<jstring>(),
QJniObject::fromString(text).object<jstring>());
QJniObject started =
sdkInt() >= 26
? ctx.callObjectMethod(
"startForegroundService",
"(Landroid/content/Intent;)Landroid/content/ComponentName;",
intent.object<jobject>())
: ctx.callObjectMethod(
"startService",
"(Landroid/content/Intent;)Landroid/content/ComponentName;",
intent.object<jobject>());
if (!started.isValid())
err = QStringLiteral("the phone refused the foreground service");
});
return err;
}
void releaseForeground() {
if (qEnvironmentVariableIsSet("CST_APP_NO_SERVICE"))
return;
onGuiThread([&] {
QJniObject ctx = appContext();
if (!ctx.isValid())
return;
QJniObject intent = serviceIntent(
ctx, QStringLiteral("xyz.whcself.cstagent.STOP"));
if (intent.isValid())
ctx.callMethod<jboolean>("stopService",
"(Landroid/content/Intent;)Z",
intent.object<jobject>());
});
}
/* What the picker gave us -> a path the engine can open. A SAF URI is copied
* into the app's own cache (the URI's grant covers the read; no permission is
* involved), a plain path is left alone. */
QString materializeAttachment(const QString &pathOrUri, QString *err) {
if (err)
err->clear();
if (pathOrUri.isEmpty())
return QString();
if (!pathOrUri.startsWith(QLatin1String("content://"))) {
QString p = pathOrUri;
if (p.startsWith(QLatin1String("file://")))
p = p.mid(7);
return p;
}
const QString dest = QStandardPaths::writableLocation(
QStandardPaths::CacheLocation) +
QStringLiteral("/picked");
QString result, failure;
onGuiThread([&] {
QJniObject ctx = appContext();
if (!ctx.isValid()) {
failure = QStringLiteral("no Android context to copy the file with");
return;
}
QJniObject out = QJniObject::callStaticObjectMethod(
"xyz/whcself/cstagent/AttachFile", "materialize",
"(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)"
"Ljava/lang/String;",
ctx.object<jobject>(), QJniObject::fromString(pathOrUri).object<jstring>(),
QJniObject::fromString(dest).object<jstring>());
if (!out.isValid()) {
failure = QStringLiteral("the phone could not hand that file over");
return;
}
const QString s = out.toString();
if (s.startsWith(QLatin1String("error: ")))
failure = s.mid(7);
else if (!s.isEmpty())
result = s;
/* "" means it was a path all along; the caller keeps what it had */
});
if (!failure.isEmpty()) {
if (err)
*err = failure;
return QString();
}
return result.isEmpty() ? pathOrUri : result;
}
bool hasAllFilesAccess() {
bool granted = true;
onGuiThread([&] {
QJniObject ctx = appContext();
if (!ctx.isValid())
return;
granted = QJniObject::callStaticMethod<jboolean>(
"xyz/whcself/cstagent/AttachFile", "hasAllFilesAccess",
"(Landroid/content/Context;)Z", ctx.object<jobject>());
});
return granted;
}
QString requestAllFilesAccess() {
if (qEnvironmentVariableIsSet("CST_APP_NO_PERM"))
return QString(); /* a test run touches no settings */
QString err;
onGuiThread([&] {
QJniObject ctx = appContext();
if (!ctx.isValid())
return;
QJniObject out = QJniObject::callStaticObjectMethod(
"xyz/whcself/cstagent/AttachFile", "requestAllFilesAccess",
"(Landroid/content/Context;)Ljava/lang/String;",
ctx.object<jobject>());
if (out.isValid()) {
const QString s = out.toString();
if (!s.isEmpty())
err = s;
}
});
return err;
}
/* The status bar -- and on a tablet in desktop mode the taskbar, which is a
* status bar full of icons -- is drawn over the window, and this window draws
* from its own first pixel, so the bars land on the app's top row and the
* controls there cannot be touched. Which call hides them depends on the API
* level: WindowInsetsController from Android 11 (API 30) on, the older
* systemUiVisibility flags before it. Measured on the tablet: the app's own
* title row was under the taskbar, this puts the window on the whole screen
* and the row is touchable again.
*
* Nothing here is fatal: an invalid context, a missing class or a null insets
* controller comes back as a reason (which main.cpp logs) and the window keeps
* working with the bars over it. */
QString requestFullscreen() {
QString err;
onGuiThread([&] {
QJniObject activity = appContext();
if (!activity.isValid()) {
err = QStringLiteral("no activity");
return;
}
QJniObject window =
activity.callObjectMethod("getWindow", "()Landroid/view/Window;");
if (!window.isValid()) {
err = QStringLiteral("no window");
return;
}
if (sdkInt() >= 30) {
/* Edge to edge plus the bars hidden: the window is told to fill the
* screen itself rather than lay out inside the bars. */
window.callMethod<void>("setDecorFitsSystemWindows", "(Z)V", false);
QJniObject control = window.callObjectMethod(
"getInsetsController", "()Landroid/view/WindowInsetsController;");
if (!control.isValid()) {
err = QStringLiteral("no insets controller");
return;
}
const jint bars = QJniObject::callStaticMethod<jint>(
"android/view/WindowInsets$Type", "systemBars", "()I");
control.callMethod<void>("hide", "(I)V", bars);
/* BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE: a swipe from the edge brings
* the bars back for a moment and they leave again by themselves. */
control.callMethod<void>("setSystemBarsBehavior", "(I)V", 2);
return;
}
QJniObject decor =
window.callObjectMethod("getDecorView", "()Landroid/view/View;");
if (!decor.isValid()) {
err = QStringLiteral("no decor view");
return;
}
/* SYSTEM_UI_FLAG_HIDE_NAVIGATION | FULLSCREEN | LAYOUT_STABLE |
* LAYOUT_HIDE_NAVIGATION | LAYOUT_FULLSCREEN | IMMERSIVE_STICKY */
const jint flags = 0x00000002 | 0x00000004 | 0x00000100 | 0x00000200 |
0x00000400 | 0x00001000;
decor.callMethod<void>("setSystemUiVisibility", "(I)V", flags);
});
return err;
}
int platformRegisterAndroid(AgentCore *core) {
if (!core)
return 0;
int n = 0;
{
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"message", "string", 1, "text of the notification"},
{"title", "string", 0, "title line (default: CST-agent)"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
memset(&g_notify, 0, sizeof(g_notify));
setMeta(&g_notify, "notification_send",
"Show a notification in the phone's shade (what the user sees "
"outside the app).",
CST_TP_ASK, "notify", kAndroidOnly, notifyProbe);
memcpy(g_notify.params, params, sizeof(params));
g_notify.run_ex = notifyRun;
g_notify.owner = "app:android";
n += core->registerTool(&g_notify) ? 1 : 0;
}
{
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"max_bytes", "integer", 0, "cap on the returned text (default 65536)"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
memset(&g_clip_read, 0, sizeof(g_clip_read));
setMeta(&g_clip_read, "clipboard_read",
"Read the text on the phone's clipboard — what the user copied "
"outside the workspace. Returns UTF-8 text.",
CST_TP_READ, "read", kAndroidOnly, clipboardProbe);
memcpy(g_clip_read.params, params, sizeof(params));
g_clip_read.run_ex = clipboardReadRun;
g_clip_read.owner = "app:android";
n += core->registerTool(&g_clip_read) ? 1 : 0;
}
{
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"text", "string", 1, "text to put on the clipboard"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
memset(&g_clip_write, 0, sizeof(g_clip_write));
setMeta(&g_clip_write, "clipboard_write",
"Replace the phone's clipboard with text, so the user can paste it "
"into another app. Overwrites what they had copied.",
CST_TP_WRITE, "write", kAndroidOnly, clipboardProbe);
memcpy(g_clip_write.params, params, sizeof(params));
g_clip_write.run_ex = clipboardWriteRun;
g_clip_write.owner = "app:android";
n += core->registerTool(&g_clip_write) ? 1 : 0;
}
{
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"text", "string", 0, "text to share"},
{"file", "string", 0, "workspace-relative file to share"},
{"subject", "string", 0, "subject line of the shared item"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
memset(&g_share, 0, sizeof(g_share));
setMeta(&g_share, "share",
"Hand text or a workspace file to the system share sheet, so the "
"user can send it to another app.",
CST_TP_ASK, "share", kAndroidOnly, shareProbe);
memcpy(g_share.params, params, sizeof(params));
g_share.run_ex = shareRun;
g_share.owner = "app:android";
n += core->registerTool(&g_share) ? 1 : 0;
}
return n;
}
} // namespace app
+184
View File
@@ -0,0 +1,184 @@
/* Platform tools on Linux, implemented by the app (not by the engine): they
* exist exactly where the desktop service does, and the engine only ever sees
* the capability -- platforms + probe decide whether the tool is offered. */
#include <QByteArray>
#include <QClipboard>
#include <QDesktopServices>
#include <QFileInfo>
#include <QGuiApplication>
#include <QProcess>
#include <QString>
#include <QStringList>
#include <QUrl>
#include <cstdio>
#include <cstring>
#include "core/AgentCore.h"
#include "core/ToolProvider.h"
namespace app {
namespace {
/* whereis-style check without a shell: the same rule the engine uses for the
* clipboard helpers. */
bool haveProgram(const char *name) {
QByteArray path = qgetenv("PATH");
const QList<QByteArray> dirs = path.split(':');
for (const QByteArray &d : dirs) {
QByteArray dir = d.isEmpty() ? QByteArray(".") : d;
QByteArray cand = dir + "/" + name;
if (QFileInfo::exists(QString::fromLocal8Bit(cand)) &&
QFileInfo(QString::fromLocal8Bit(cand)).isExecutable())
return true;
}
return false;
}
/* 0 when notifications can be shown; -1 with the reason otherwise. */
int notifyProbe(char *why, size_t why_sz) {
if (haveProgram("notify-send"))
return 0;
if (haveProgram("gdbus") && !qgetenv("DBUS_SESSION_BUS_ADDRESS").isEmpty())
return 0;
snprintf(why, why_sz,
"no notification service (no notify-send, no D-Bus session bus)");
return -1;
}
const char *argOf(const ctl_tool_call_t *call, const char *key) {
for (int i = 0; i < call->nargs; i++)
if (strcmp(call->args[i].key, key) == 0)
return call->args[i].value;
return nullptr;
}
/* Runs on the turn's worker thread: no GUI objects here. */
int notifyRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)ud;
const char *title = argOf(call, "title");
const char *message = argOf(call, "message");
if (!message || !message[0]) {
const char *msg = "error: notification_send needs a message";
r->out = strdup(msg);
r->out_len = r->out ? strlen(msg) : 0;
r->exit_code = 1;
return 0;
}
QStringList args;
if (title && title[0])
args << QString::fromUtf8(title);
else
args << QStringLiteral("CST-agent");
args << QString::fromUtf8(message);
const int rc = QProcess::execute(QStringLiteral("notify-send"), args);
const QByteArray text =
(rc == 0 ? QByteArrayLiteral("notification sent")
: QByteArrayLiteral("notify-send failed (rc=") +
QByteArray::number(rc) + QByteArrayLiteral(")"));
r->out = strdup(text.constData());
r->out_len = r->out ? strlen(r->out) : 0;
r->exit_code = rc == 0 ? 0 : 1;
return 0;
}
/* Registered once; the engine keeps a copy until the owner is unregistered. */
cst_tool_def_t g_notify;
} // namespace
/* A file card's "open": xdg-open through QDesktopServices, so the desktop's
* own application for the type comes up. */
QString openLocalFile(const QString &path, const QString &title,
QString *status) {
const QString name = title.isEmpty() ? QFileInfo(path).fileName() : title;
if (qEnvironmentVariableIsSet("CST_APP_NO_OPEN")) {
if (status)
*status = QStringLiteral("opened %1 (test mode)").arg(name);
return QString();
}
if (!QFileInfo::exists(path))
return QStringLiteral("the file is gone: %1").arg(name);
if (!QDesktopServices::openUrl(QUrl::fromLocalFile(path)))
return QStringLiteral("no application on this desktop opens %1").arg(name);
if (status)
*status = QStringLiteral("opened %1").arg(name);
return QString();
}
/* No share sheet here: the path is what another program (or another window)
* needs, so it goes to the clipboard. */
QString shareLocalFile(const QString &path, const QString &title,
QString *status) {
const QString name = title.isEmpty() ? QFileInfo(path).fileName() : title;
if (qEnvironmentVariableIsSet("CST_APP_NO_OPEN")) {
if (status)
*status = QStringLiteral("shared %1 (test mode)").arg(name);
return QString();
}
if (!QFileInfo::exists(path))
return QStringLiteral("the file is gone: %1").arg(name);
QGuiApplication::clipboard()->setText(path);
if (status)
*status = QStringLiteral("%1: the path is on the clipboard").arg(name);
return QString();
}
/* A desktop has nothing to hold: the window is the app, and a turn runs as
* long as it is open -- the machine does not freeze a process it can see.
* Kept here so the front end calls one API on every platform. */
QString holdForeground(const QString &text) {
(void)text;
return QString();
}
void releaseForeground() {}
/* A desktop picker hands over a path, so there is nothing to turn into one:
* a file:// URL loses its scheme and a content:// URI (a portal that never
* gave us a path) is refused with what the user should do instead. */
QString materializeAttachment(const QString &pathOrUri, QString *err) {
QString s = pathOrUri;
if (s.startsWith(QLatin1String("file://")))
s = s.mid(7);
if (s.startsWith(QLatin1String("content://"))) {
if (err)
*err = QStringLiteral("that picker handed over a content:// URI this "
"desktop cannot open; pick the file by path "
"instead");
return QString();
}
return s;
}
/* Every desktop process reads the files its user can. */
bool hasAllFilesAccess() { return true; }
QString requestAllFilesAccess() { return QString(); }
/* A desktop window is not drawn under anything of the desktop's own: the bars
* a panel draws are the panel's, and nothing here can be asked for them. */
QString requestFullscreen() { return QString(); }
int platformRegisterLinux(AgentCore *core) {
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"message", "string", 1, "text of the notification"},
{"title", "string", 0, "title line (default: CST-agent)"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
memset(&g_notify, 0, sizeof(g_notify));
setMeta(&g_notify, "notification_send",
"Show a desktop notification (what the user sees outside the app).",
CST_TP_ASK, "notify", kDesktopOnly, notifyProbe);
memcpy(g_notify.params, params, sizeof(params));
g_notify.run = nullptr;
g_notify.run_ex = notifyRun;
g_notify.ud = nullptr;
g_notify.owner = "app:linux";
return core->registerTool(&g_notify) ? 1 : 0;
}
} // namespace app
+196
View File
@@ -0,0 +1,196 @@
/* Platform tools on Windows, implemented by the app (not by the engine): they
* exist exactly where the desktop service does, and the engine only ever sees
* the capability -- platforms + probe decide whether the tool is offered.
*
* The Linux file next door is the same shape; what differs is the service
* behind each call. A notification is the scripting host's popup (Wscript.Shell
* through PowerShell) because Windows has no notify-send and a toast needs the
* WinRT API; it carries the same two arguments and answers the same way. */
#include <QByteArray>
#include <QClipboard>
#include <QDesktopServices>
#include <QFileInfo>
#include <QGuiApplication>
#include <QProcess>
#include <QString>
#include <QStringList>
#include <QUrl>
#include <cstdio>
#include <cstring>
#include "core/AgentCore.h"
#include "core/ToolProvider.h"
namespace app {
namespace {
/* whereis-style check without a shell: PATH is split on the Windows separator
* and a name may need one of the executable suffixes. */
bool haveProgram(const char *name) {
const QByteArray path = qgetenv("PATH");
const QList<QByteArray> dirs = path.split(';');
const QList<QByteArray> exts = {QByteArray(), QByteArray(".exe"),
QByteArray(".cmd"), QByteArray(".bat")};
for (const QByteArray &d : dirs) {
if (d.isEmpty())
continue;
for (const QByteArray &ext : exts) {
const QString cand = QFileInfo(QString::fromLocal8Bit(d + "\\" + name +
ext))
.absoluteFilePath();
if (QFileInfo::exists(cand) && QFileInfo(cand).isExecutable())
return true;
}
}
return false;
}
/* 0 when notifications can be shown; -1 with the reason otherwise. */
int notifyProbe(char *why, size_t why_sz) {
if (haveProgram("powershell") || haveProgram("pwsh"))
return 0;
snprintf(why, why_sz, "no powershell on PATH to show a popup with");
return -1;
}
const char *argOf(const ctl_tool_call_t *call, const char *key) {
for (int i = 0; i < call->nargs; i++)
if (strcmp(call->args[i].key, key) == 0)
return call->args[i].value;
return nullptr;
}
/* Runs on the turn's worker thread: no GUI objects here. The popup is started
* detached -- it waits for its own timeout, and the turn must not. */
int notifyRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)ud;
const char *title = argOf(call, "title");
const char *message = argOf(call, "message");
if (!message || !message[0]) {
const char *msg = "error: notification_send needs a message";
r->out = strdup(msg);
r->out_len = r->out ? strlen(msg) : 0;
r->exit_code = 1;
return 0;
}
const QString shown =
title && title[0] ? QString::fromUtf8(title) : QStringLiteral("CST-agent");
/* The popup's own text is single-quoted for PowerShell; a quote inside it is
* doubled, which is how PowerShell escapes one. */
QString text = QString::fromUtf8(message);
text.replace(QLatin1Char('\''), QLatin1String("''"));
QString heading = shown;
heading.replace(QLatin1Char('\''), QLatin1String("''"));
const QString script =
QStringLiteral("$w = New-Object -ComObject Wscript.Shell; "
"$w.Popup('%1', 8, '%2', 64) | Out-Null")
.arg(text, heading);
const QString exe = haveProgram("pwsh") ? QStringLiteral("pwsh")
: QStringLiteral("powershell");
QStringList args;
args << QStringLiteral("-NoProfile") << QStringLiteral("-NonInteractive")
<< QStringLiteral("-Command") << script;
const bool started = QProcess::startDetached(exe, args);
const QByteArray out = started
? QByteArrayLiteral("notification shown")
: QByteArrayLiteral("could not start ") +
exe.toLocal8Bit();
r->out = strdup(out.constData());
r->out_len = r->out ? strlen(r->out) : 0;
r->exit_code = started ? 0 : 1;
return 0;
}
/* Registered once; the engine keeps a copy until the owner is unregistered. */
cst_tool_def_t g_notify;
} // namespace
/* A file card's "open": ShellExecute through QDesktopServices, so the file's
* own application comes up. */
QString openLocalFile(const QString &path, const QString &title,
QString *status) {
const QString name = title.isEmpty() ? QFileInfo(path).fileName() : title;
if (qEnvironmentVariableIsSet("CST_APP_NO_OPEN")) {
if (status)
*status = QStringLiteral("opened %1 (test mode)").arg(name);
return QString();
}
if (!QFileInfo::exists(path))
return QStringLiteral("the file is gone: %1").arg(name);
if (!QDesktopServices::openUrl(QUrl::fromLocalFile(path)))
return QStringLiteral("no application on this machine opens %1").arg(name);
if (status)
*status = QStringLiteral("opened %1").arg(name);
return QString();
}
/* No share sheet here: the path is what another program needs, so it goes to
* the clipboard. */
QString shareLocalFile(const QString &path, const QString &title,
QString *status) {
const QString name = title.isEmpty() ? QFileInfo(path).fileName() : title;
if (qEnvironmentVariableIsSet("CST_APP_NO_OPEN")) {
if (status)
*status = QStringLiteral("shared %1 (test mode)").arg(name);
return QString();
}
if (!QFileInfo::exists(path))
return QStringLiteral("the file is gone: %1").arg(name);
QGuiApplication::clipboard()->setText(path);
if (status)
*status = QStringLiteral("%1: the path is on the clipboard").arg(name);
return QString();
}
/* Windows does not freeze a process whose window is open, and the app's own
* window is what keeps it alive: nothing to hold. */
QString holdForeground(const QString &text) {
(void)text;
return QString();
}
void releaseForeground() {}
/* A native file dialog hands over a path, so there is nothing to turn into
* one: a file:// URL loses its scheme and anything else is taken as a path. */
QString materializeAttachment(const QString &pathOrUri, QString *err) {
(void)err;
QString s = pathOrUri;
if (s.startsWith(QLatin1String("file://")))
s = s.mid(7);
return s;
}
/* Every process on Windows reads the files its user can. */
bool hasAllFilesAccess() { return true; }
QString requestAllFilesAccess() { return QString(); }
/* A Windows window has its own frame; there is no system bar drawn over it. */
QString requestFullscreen() { return QString(); }
int platformRegisterWindows(AgentCore *core) {
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
{"message", "string", 1, "text of the notification"},
{"title", "string", 0, "title line (default: CST-agent)"},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr},
{nullptr, nullptr, 0, nullptr}};
memset(&g_notify, 0, sizeof(g_notify));
setMeta(&g_notify, "notification_send",
"Show a notification outside the window (a popup that goes away by "
"itself).",
CST_TP_ASK, "notify", kDesktopOnly, notifyProbe);
memcpy(g_notify.params, params, sizeof(params));
g_notify.run = nullptr;
g_notify.run_ex = notifyRun;
g_notify.ud = nullptr;
g_notify.owner = "app:windows";
return core->registerTool(&g_notify) ? 1 : 0;
}
} // namespace app
+65
View File
@@ -0,0 +1,65 @@
#include "ui/BackKey.h"
#include <QEvent>
#include <QKeyEvent>
#include <QMetaObject>
#include <QObject>
#include <QVariant>
namespace app {
namespace {
class BackKeyFilter : public QObject {
public:
BackKeyFilter(QObject *window, QObject *root)
: QObject(window), m_window(window), m_root(root) {}
protected:
bool eventFilter(QObject *watched, QEvent *event) override {
if (!m_root || watched != m_window ||
(event->type() != QEvent::KeyPress &&
event->type() != QEvent::KeyRelease))
return QObject::eventFilter(watched, event);
QKeyEvent *key = static_cast<QKeyEvent *>(event);
if (key->key() != Qt::Key_Back)
return QObject::eventFilter(watched, event);
/* The key is down and up: a press that was taken is followed by a release
* that goes with it, so the platform never sees half of a key it did not
* get. */
if (event->type() == QEvent::KeyRelease)
return m_tookPress ? (m_tookPress = false, true)
: QObject::eventFilter(watched, event);
QVariant layer;
if (!QMetaObject::invokeMethod(m_root, "backLayer",
Q_RETURN_ARG(QVariant, layer)))
return QObject::eventFilter(watched, event);
if (layer.toString().isEmpty())
return QObject::eventFilter(watched, event); /* nothing open: not ours */
/* One layer back, on the next turn of the event loop (the dialogs insist,
* see Main.qml's stepBack). The key is spent: the window stays. */
QMetaObject::invokeMethod(m_root, "stepBack");
m_tookPress = true;
return true;
}
private:
QObject *m_window; /* whose keys are read; outlives this filter */
QObject *m_root; /* the window's QML root */
bool m_tookPress = false;
};
} // namespace
void installBackKey(QObject *window, QObject *root) {
if (!window || !root)
return;
/* On the application, not on the window: a key press arrives here as an
* event sent to the window, but a filter installed on the window itself
* never sees one (measured -- a window-installed filter stayed silent while
* the same key closed the drawer through a QML Shortcut). The filter keeps
* to `window`'s own events, so nothing else in the process is touched. */
QCoreApplication::instance()->installEventFilter(
new BackKeyFilter(window, root));
}
} // namespace app
+33
View File
@@ -0,0 +1,33 @@
/* The phone's back key, read before anything else sees the event.
*
* Android hands its back button to the window as a Qt::Key_Back key press, and
* the platform leaves the activity (the window goes away) when nothing takes
* the key. What takes it here is one layer at a time -- the dialog on top,
* then the sliding sidebar -- and only while there is a layer: the window's
* own QML answers which (Main.qml's backLayer()) and closes it (stepBack()).
*
* This lives in C++ rather than in a QML Shortcut because a window-level
* shortcut never sees the key while a modal popup is up: the dialog keeps it
* (a desktop run that presses Back with the settings dialog open shows the
* shortcut does not fire, while the drawer -- no popup -- closes fine). A
* filter on the window runs before the shortcut map, the popup and the focused
* item, so the same key does the same thing on every platform; with nothing
* open the key is passed on untouched, which is what leaves the window on a
* phone and does nothing on a desktop.
*
* A window must not be given a second one: installBackKey() installs once. */
#ifndef CST_APP_BACK_KEY_H
#define CST_APP_BACK_KEY_H
class QObject;
namespace app {
/* `window` is the QQuickWindow (the object key events are sent to), `root` the
* QML root object of that window (the one carrying backLayer()/stepBack()).
* The filter is owned by the window. */
void installBackKey(QObject *window, QObject *root);
} // namespace app
#endif // CST_APP_BACK_KEY_H
+81
View File
@@ -0,0 +1,81 @@
#include "ui/SessionImages.h"
#include <QFileInfo>
#include <QImageReader>
#include <QQmlApplicationEngine>
#include "cst_attach.h"
namespace app {
namespace {
/* "img-1a2b3c4d.png?w=160": the stored name, then what the view asked for.
* The size comes from the QML side as sourceSize, which Qt passes in as
* requestedSize; the query string is accepted too, so a plain URL can ask. */
QString relOf(const QString &id) {
const int q = id.indexOf(QLatin1Char('?'));
return q < 0 ? id : id.left(q);
}
} // namespace
SessionImages::SessionImages()
: QQuickImageProvider(QQuickImageProvider::Image) {}
void SessionImages::setDir(const QString &dir) {
QMutexLocker lock(&m_mu);
m_dir = dir;
}
QImage SessionImages::requestImage(const QString &id, QSize *size,
const QSize &requestedSize) {
const QString rel = relOf(id);
if (!cst_attach_rel_ok(rel.toUtf8().constData()))
return QImage(); /* QML sees Image.Error and falls back to the name */
QString dir;
{
QMutexLocker lock(&m_mu);
dir = m_dir;
}
if (dir.isEmpty())
return QImage();
const QString path = dir + QLatin1Char('/') + rel;
if (!QFileInfo::exists(path))
return QImage();
QImageReader reader(path);
reader.setAutoTransform(true);
const QSize full = reader.size();
if (!full.isValid()) {
/* No size in the header (or not a picture at all): hand back what Qt
* makes of it and let the view scale it. */
const QImage img = reader.read();
if (size)
*size = img.size();
return img;
}
/* Shrink to what the view shows, never up: a screenshot is decoded at the
* size of its thumbnail instead of at 4K. */
const bool smaller = requestedSize.isValid() && requestedSize.width() > 0 &&
requestedSize.height() > 0 &&
(full.width() > requestedSize.width() ||
full.height() > requestedSize.height());
if (smaller) {
const QSize scaled = full.scaled(requestedSize, Qt::KeepAspectRatio);
reader.setScaledSize(scaled);
if (size)
*size = scaled;
} else if (size) {
*size = full;
}
return reader.read();
}
SessionImages *installSessionImages(QQmlApplicationEngine *engine) {
SessionImages *images = new SessionImages;
if (engine)
engine->addImageProvider(QStringLiteral("cstattach"), images);
return images;
}
} // namespace app
+45
View File
@@ -0,0 +1,45 @@
/* The session's stored images as a QML image provider:
*
* image://cstattach/<stored name> (see cst_attach.h: "img-1a2b3c4d.png")
*
* The files live in the current session's attachment directory, which is what
* AgentCore::attachmentDir() names. Only that directory is served, and only
* names that pass the engine's own cst_attach_rel_ok() -- a transcript can
* carry hand-edited JSON, and nothing in it may reach outside the store.
*
* requestImage() runs on Quick's render thread while setDir() comes from the
* window's thread, hence the mutex. */
#ifndef CST_APP_SESSION_IMAGES_H
#define CST_APP_SESSION_IMAGES_H
#include <QImage>
#include <QMutex>
#include <QQuickImageProvider>
#include <QString>
class QQmlApplicationEngine;
namespace app {
class SessionImages : public QQuickImageProvider {
public:
SessionImages();
/* The directory holding the current session's images; "" disables serving. */
void setDir(const QString &dir);
QImage requestImage(const QString &id, QSize *size,
const QSize &requestedSize) override;
private:
mutable QMutex m_mu;
QString m_dir;
};
/* Registers image://cstattach/ on the engine and hands the provider back, so
* the caller can keep its directory in step with the agent's session. */
SessionImages *installSessionImages(QQmlApplicationEngine *engine);
} // namespace app
#endif // CST_APP_SESSION_IMAGES_H
+136
View File
@@ -0,0 +1,136 @@
#include "ui/ThemeIcons.h"
#include <QDir>
#include <QGuiApplication>
#include <QIcon>
#include <QPainter>
#include <QQmlApplicationEngine>
#include <QScreen>
#include <QStandardPaths>
#include <QStringList>
#include <QUrl>
namespace app {
namespace {
/* What a usable theme has to have; every window in the app needs it. */
const char kProbe[] = "mail-attachment";
/* The desktop's own theme first (whatever the platform theme set), then
* Breeze: this window is dark, so the dark variant, and Breeze proper as
* Qt's fallback for the odd name that only lives there. Before any of that
* the search paths have to be filled in -- Qt only builds them from XDG once
* a theme name was set, and a shell that was started outside the desktop
* session (nix-shell) has no XDG_DATA_DIRS pointing at the icon packages,
* hence the system profile. */
void adoptIconTheme() {
const QStringList known = QStandardPaths::standardLocations(
QStandardPaths::GenericDataLocation);
QStringList paths;
for (const QString &d : known)
paths << d + QStringLiteral("/icons");
paths << QDir::homePath() + QStringLiteral("/.icons");
const QString system = QStringLiteral("/run/current-system/sw/share/icons");
if (!paths.contains(system) && QDir(system).exists())
paths << system;
paths << QStringLiteral(":/icons");
QIcon::setThemeSearchPaths(paths);
QStringList candidates;
if (!QIcon::themeName().isEmpty())
candidates << QIcon::themeName();
candidates << QStringLiteral("breeze-dark") << QStringLiteral("breeze")
<< QStringLiteral("hicolor");
for (const QString &name : candidates) {
QIcon::setThemeName(name);
if (QIcon::hasThemeIcon(QLatin1String(kProbe)))
return;
}
}
/* The bundled set: app/icons/*.svg, compiled in as :/cst-icons/<name>.svg by
* app/CMakeLists.txt. A machine without an icon theme -- Android, where the
* Qt theme lookup finds nothing and QML was left showing its glyph fallback,
* which the phone fonts cannot draw -- gets the same icons from here. */
QIcon bundledIcon(const QString &name) {
return QIcon(QStringLiteral(":/cst-icons/") + name + QStringLiteral(".svg"));
}
QIcon iconForName(const QString &name) {
const QIcon themed = QIcon::fromTheme(name);
if (!themed.isNull())
return themed;
return bundledIcon(name);
}
/* "?color=%23eff0f1": the tint, and nothing else so far. */
QColor colorOption(const QString &id, QString *name) {
QColor color;
*name = id;
const int q = id.indexOf(QLatin1Char('?'));
if (q < 0)
return color;
*name = id.left(q);
const QStringList options = id.mid(q + 1).split(QLatin1Char('&'));
for (const QString &opt : options) {
if (!opt.startsWith(QLatin1String("color=")))
continue;
const QColor c(QUrl::fromPercentEncoding(opt.mid(6).toUtf8()));
if (c.isValid())
color = c;
}
return color;
}
qreal targetRatio() {
if (const QScreen *s = QGuiApplication::primaryScreen())
return qMax<qreal>(1.0, s->devicePixelRatio());
return 1.0;
}
} // namespace
ThemeIconProvider::ThemeIconProvider()
: QQuickImageProvider(QQuickImageProvider::Image) {}
QImage ThemeIconProvider::requestImage(const QString &id, QSize *size,
const QSize &requestedSize) {
QString name;
const QColor color = colorOption(id, &name);
if (name.isEmpty())
return QImage();
const QIcon icon = iconForName(name);
if (icon.isNull())
return QImage(); /* QML shows its fallback glyph */
const int px = requestedSize.isValid() && requestedSize.width() > 0
? requestedSize.width()
: 22;
const qreal ratio = targetRatio();
QPixmap pm = icon.pixmap(QSize(px, px), ratio, QIcon::Normal, QIcon::Off);
if (pm.isNull())
return QImage();
if (color.isValid()) {
QPainter p(&pm);
p.setCompositionMode(QPainter::CompositionMode_SourceIn);
p.fillRect(pm.rect(), color);
}
QImage img = pm.toImage();
img.setDevicePixelRatio(ratio);
if (size)
*size = QSize(px, px);
return img;
}
void installThemeIcons(QQmlApplicationEngine *engine) {
adoptIconTheme();
if (engine)
engine->addImageProvider(QStringLiteral("csttheme"), new ThemeIconProvider);
}
QString iconThemeName() { return QIcon::themeName(); }
bool themeIconAvailable(const QString &name) { return !iconForName(name).isNull(); }
} // namespace app
+47
View File
@@ -0,0 +1,47 @@
/* Icons from the desktop's icon theme (Breeze on KDE).
*
* The window did its icons with unicode glyphs (a clip emoji for attach, a
* gear, a hamburger): they render in whatever font happens to cover them --
* colour emoji in a grey toolbar -- and on a machine without that glyph they
* are a box. Every other desktop app asks the icon theme instead, and Qt
* Quick has no image provider for it without Kirigami, so this is one:
*
* image://csttheme/<icon-name>?color=%23rrggbb
*
* The icon is looked up with QIcon::fromTheme() in the desktop's theme
* (breeze-dark on a KDE desktop, Breeze as fallback), tinted to the asked-for
* color and rendered at the requested size. An unknown name yields a null
* image, which QML sees as Image.Error -- that is the hook for a glyph
* fallback, used on a machine with no icon theme at all. */
#ifndef CST_APP_THEMEICONS_H
#define CST_APP_THEMEICONS_H
#include <QImage>
#include <QQuickImageProvider>
#include <QString>
class QQmlApplicationEngine;
namespace app {
class ThemeIconProvider : public QQuickImageProvider {
public:
ThemeIconProvider();
QImage requestImage(const QString &id, QSize *size,
const QSize &requestedSize) override;
};
/* Points Qt at the desktop's icon theme and registers image://csttheme/.
* Call it on every engine that loads the window (main.cpp and --uitest). */
void installThemeIcons(QQmlApplicationEngine *engine);
/* The theme Qt was left on, for --selftest and the README. */
QString iconThemeName();
/* Whether the theme has this icon (what the fallback glyphs are for). */
bool themeIconAvailable(const QString &name);
} // namespace app
#endif /* CST_APP_THEMEICONS_H */
File diff suppressed because it is too large Load Diff
+20
View File
@@ -0,0 +1,20 @@
/* The --uitest entry point: see UiTest.cpp for what it drives. */
#ifndef CST_APP_UITEST_H
#define CST_APP_UITEST_H
#include <QString>
#include "core/AgentCore.h"
namespace app {
/* Loads the window, drives its controls with synthesized mouse/touch input
* (and a resize to the compact layout), prints one line per check and returns
* how many failed as the process exit code. `size` is the usual WxH string,
* empty for the default. */
int runUiTest(AgentCore &core, const QString &size);
} // namespace app
#endif /* CST_APP_UITEST_H */
+158
View File
@@ -0,0 +1,158 @@
/* The app's C smoke test: does the engine embed the way app/ needs it to?
*
* It links libcstcore.a (or the cstcore target) and runs without Qt, so the
* C side of the GUI stays verifiable on any machine -- including CI and the
* Android cross-build. `cst-agent-app --selftest` runs the same checks inside
* the real process. */
#define _POSIX_C_SOURCE 200809L
#include "cst_agent.h"
#include "cst_tools.h"
#include "os_compat.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <process.h>
#include <direct.h>
#define getpid _getpid
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
static int failures;
#define CHECK(cond, what) \
do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, what); \
failures++; \
} \
} while (0)
/* A tool the app would implement (the Linux build uses notify-send; here it
* only has to prove the plumbing). */
static int ctx_runs;
static int app_tool_run(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)call;
(void)ud;
ctx_runs++;
r->out = strdup("app tool ran");
r->out_len = r->out ? strlen(r->out) : 0;
r->exit_code = 0;
return 0;
}
static int probe_missing(char *why, size_t why_sz) {
snprintf(why, why_sz, "the desktop service is not running");
return -1;
}
int main(void) {
/* The scratch workspace goes where this host can actually write: /tmp on a
* desktop, the app's own directory on Android (where /tmp is off limits,
* so TMPDIR is pointed at it -- see app/src/main.cpp). */
char tmp[1024] = "";
if (os_temp_dir(tmp, sizeof(tmp)) != 0 || !tmp[0])
snprintf(tmp, sizeof(tmp), "%s", "/tmp");
char ws[1200];
snprintf(ws, sizeof(ws), "%s/cst-app-selftest-%d", tmp, (int)getpid());
#ifdef _WIN32
_mkdir(ws); /* the engine wants its workspace to exist */
#else
mkdir(ws, 0700);
#endif
cst_agent_config_t cfg;
memset(&cfg, 0, sizeof(cfg));
snprintf(cfg.workspace_root, sizeof(cfg.workspace_root), "%s", ws);
snprintf(cfg.session_path, sizeof(cfg.session_path), "%s/s.jsonl", ws);
snprintf(cfg.provider, sizeof(cfg.provider), "deepseek");
snprintf(cfg.model, sizeof(cfg.model), "deepseek-flash");
snprintf(cfg.api_base, sizeof(cfg.api_base), "https://api.deepseek.com/v1");
snprintf(cfg.api_key, sizeof(cfg.api_key), "test-key");
snprintf(cfg.mode, sizeof(cfg.mode), "general");
cfg.max_steps = 1;
cst_agent_t *a = cst_agent_create(&cfg);
CHECK(a != NULL, "the app can start an engine in its own process");
if (!a) {
fprintf(stderr, "cst-app-selftest: cannot start the engine\n");
return 1;
}
/* 1. a tool that exists here (no probe) is offered to the model */
cst_tool_def_t plain;
memset(&plain, 0, sizeof(plain));
plain.name = "app_ping";
plain.desc = "A tool the app provides.";
plain.perm = CST_TP_READ;
plain.run_ex = app_tool_run;
plain.owner = "app:selftest";
CHECK(cst_tool_register(&plain) == 0, "register an app tool");
const cst_tool_def_t *t = cst_tool_find("app_ping");
CHECK(t != NULL, "it is findable");
CHECK(t && cst_tool_active(cst_agent_config(a), t), "and it is offered");
ctl_tool_call_t call;
memset(&call, 0, sizeof(call));
snprintf(call.name, sizeof(call.name), "app_ping");
cst_tool_result_t res;
cst_tool_ctx_t ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.workspace_root = ws;
ctx.agent = a;
cst_tool_run(&ctx, &call, &res);
CHECK(ctx_runs == 1, "the app callback ran");
CHECK(res.out && strcmp(res.out, "app tool ran") == 0, "its result came back");
cst_tool_result_free(&res);
/* 2. a tool whose platform service is missing is never offered ... */
cst_tool_def_t missing;
memset(&missing, 0, sizeof(missing));
missing.name = "app_no_service";
missing.desc = "Needs a service that is not here.";
missing.perm = CST_TP_ASK;
missing.perm_name = "notify";
missing.available = probe_missing;
missing.run_ex = app_tool_run;
missing.owner = "app:selftest";
CHECK(cst_tool_register(&missing) == 0, "register a tool with a probe");
const cst_tool_def_t *mt = cst_tool_find("app_no_service");
char why[160] = "";
CHECK(mt && cst_tool_available(mt, why, sizeof(why)) != 0,
"the probe says it cannot run");
CHECK(strstr(why, "desktop service") != NULL, "and passes its reason on");
CHECK(mt && !cst_tool_active(cst_agent_config(a), mt),
"so it stays out of tools[] and the prompt");
snprintf(call.name, sizeof(call.name), "app_no_service");
cst_tool_run(&ctx, &call, &res);
CHECK(res.out && strstr(res.out, "cannot run here") != NULL,
"asking for it anyway is answered with the reason");
CHECK(ctx_runs == 1, "and its callback never ran");
cst_tool_result_free(&res);
/* 3. the app can drop its tools again */
CHECK(cst_tool_unregister_owner("app:selftest") == 2, "unregister both");
CHECK(cst_tool_find("app_ping") == NULL, "app_ping is gone");
CHECK(cst_tool_find("read_file") != NULL, "the built-ins are untouched");
cst_agent_destroy(a);
{
char cmd[1200];
snprintf(cmd, sizeof(cmd), "rm -rf %s", ws);
if (system(cmd) != 0)
fprintf(stderr, "note: could not clean %s\n", ws);
}
if (failures) {
fprintf(stderr, "cst-app-selftest: %d failure(s)\n", failures);
return 1;
}
printf("cst-app-selftest: OK\n");
return 0;
}
+5
View File
@@ -0,0 +1,5 @@
node_modules/
dist/
src-tauri/target/
.DS_Store
*.log
+57
View File
@@ -0,0 +1,57 @@
# Hermit Desktop (Tauri 2)
Cross-platform shell for Hermit. Visual layout follows DeepSeek Harness
(session rail · chat · tool timeline · composer); the agent engine is the
in-process C core (`libcstcore`), not a Cordis/plugin runtime.
## Stack
- **Tauri 2** + Rust host
- **React 19** + Vite + TypeScript UI
- FFI to `libcstcore` (same embed path as the legacy Qt app)
## Dependencies
| Platform | Needs |
|----------|--------|
| All | Rust (stable), Node 20+, `pnpm` or `npm` |
| Linux | `webkit2gtk-4.1`, `libgtk-3`, `librsvg`, `patchelf`, pkg-config, curl |
| Windows | WebView2 runtime |
| macOS | Xcode CLT |
Nix example:
```bash
nix-shell -p rustc cargo nodejs_22 pkg-config webkitgtk_4_1 gtk3 librsvg openssl curl
```
## Develop
```bash
cd apps/desktop
npm install
npm run tauri dev
```
Without a full engine link yet, the UI runs against the mock bridge
(`HERMIT_DESKTOP_MOCK=1` or automatic when FFI is unavailable).
## Build
```bash
npm run tauri build
```
Artifacts land in `src-tauri/target/release/bundle/`.
## Layout
```
apps/desktop/
src/ React UI (DSH-like)
src-tauri/ Rust + Tauri + FFI
README.md
```
The legacy Qt front end under `/app` is frozen and will be archived once
desktop feature parity lands.
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN" data-theme="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hermit</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+3584
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "hermit-desktop",
"private": true,
"version": "1.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2.1.1",
"@tauri-apps/plugin-dialog": "^2.2.0",
"@tauri-apps/plugin-shell": "^2.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^9.0.3",
"remark-gfm": "^4.0.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.1.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.0.3"
}
}
+4515
View File
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "hermit-desktop"
version = "1.1.0"
description = "Hermit desktop shell (Tauri 2)"
authors = ["WHC"]
edition = "2021"
[lib]
name = "hermit_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
cc = "1.2"
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-shell = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "sync", "macros", "time"] }
once_cell = "1"
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
# Link libcstcore from the repo (requires curl + built archive).
engine = []
+29
View File
@@ -0,0 +1,29 @@
fn main() {
// Optional: link a prebuilt libcstcore when HERMIT_CORE_LIB is set.
// Example:
// HERMIT_CORE_LIB=/path/to/libcstcore.a HERMIT_CORE_INCLUDE=/path/to/include
// cargo build --features engine
if std::env::var("CARGO_FEATURE_ENGINE").is_ok() {
if let Ok(lib) = std::env::var("HERMIT_CORE_LIB") {
let path = std::path::PathBuf::from(&lib);
if let Some(dir) = path.parent() {
println!("cargo:rustc-link-search=native={}", dir.display());
}
let stem = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("cstcore")
.trim_start_matches("lib");
println!("cargo:rustc-link-lib=static={}", stem);
println!("cargo:rustc-link-lib=curl");
println!("cargo:rustc-link-lib=pthread");
println!("cargo:rustc-link-lib=m");
println!("cargo:rerun-if-changed={}", lib);
}
if let Ok(inc) = std::env::var("HERMIT_CORE_INCLUDE") {
println!("cargo:rerun-if-env-changed=HERMIT_CORE_INCLUDE");
println!("cargo:rustc-env=HERMIT_CORE_INCLUDE={}", inc);
}
}
tauri_build::build()
}
@@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Default Hermit desktop capabilities",
"windows": ["main"],
"permissions": [
"core:default",
"shell:allow-open"
]
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"default":{"identifier":"default","description":"Default Hermit desktop capabilities","local":true,"windows":["main"],"permissions":["core:default","shell:allow-open"]}}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 682 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

+173
View File
@@ -0,0 +1,173 @@
//! Engine façade: mock by default; with `--features engine` + HERMIT_CORE_LIB
//! this module will grow real FFI around `cst_agent.h` (AgentCore parity).
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use tauri::{AppHandle, Emitter};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
pub id: String,
pub title: String,
pub updated_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum ChatItem {
#[serde(rename = "user")]
User { id: String, text: String },
#[serde(rename = "assistant")]
Assistant { id: String, text: String },
#[serde(rename = "thought")]
Thought { id: String, text: String },
#[serde(rename = "tool")]
Tool {
id: String,
name: String,
status: String,
detail: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
pub provider: String,
pub model: String,
pub approval: String,
pub workspace: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EngineEvent {
#[serde(rename = "assistant_delta")]
AssistantDelta { text: String },
#[serde(rename = "thought_delta")]
ThoughtDelta { text: String },
#[serde(rename = "tool_start")]
ToolStart {
id: String,
name: String,
detail: String,
},
#[serde(rename = "tool_end")]
ToolEnd {
id: String,
status: String,
detail: String,
},
#[serde(rename = "consent")]
Consent {
req: ConsentRequest,
},
#[serde(rename = "turn_end")]
TurnEnd { ok: bool },
#[serde(rename = "error")]
Error { message: String },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsentRequest {
pub id: String,
pub tool: String,
pub detail: String,
}
pub struct EngineState {
pub settings: Settings,
pub sessions: Vec<SessionInfo>,
busy: bool,
}
impl Default for EngineState {
fn default() -> Self {
let workspace = std::env::current_dir()
.ok()
.and_then(|p| p.to_str().map(|s| s.to_string()))
.unwrap_or_else(|| ".".into());
Self {
settings: Settings {
provider: "deepseek".into(),
model: "deepseek-flash".into(),
approval: "auto".into(),
workspace,
},
sessions: vec![SessionInfo {
id: "welcome".into(),
title: "Welcome".into(),
updated_at: chrono_now(),
}],
busy: false,
}
}
}
fn chrono_now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
pub type SharedEngine = Mutex<EngineState>;
pub fn list_sessions(state: &SharedEngine) -> Vec<SessionInfo> {
state.lock().unwrap().sessions.clone()
}
pub fn new_session(state: &SharedEngine) -> SessionInfo {
let mut g = state.lock().unwrap();
let s = SessionInfo {
id: format!("s{}", chrono_now()),
title: "New session".into(),
updated_at: chrono_now(),
};
g.sessions.insert(0, s.clone());
s
}
pub fn open_session(_state: &SharedEngine, _id: &str) -> Vec<ChatItem> {
// Real FFI will replay transcript from cst_agent_store_*.
Vec::new()
}
pub fn settings_get(state: &SharedEngine) -> Settings {
state.lock().unwrap().settings.clone()
}
pub async fn send_turn(app: AppHandle, state: &SharedEngine, text: String) {
{
let mut g = state.lock().unwrap();
if g.busy {
return;
}
g.busy = true;
}
// Placeholder stream until libcstcore FFI is wired (feature = "engine").
let _ = app.emit(
"hermit://event",
EngineEvent::ThoughtDelta {
text: "Rust host received turn; FFI bridge pending full AgentCore port."
.into(),
},
);
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let _ = app.emit(
"hermit://event",
EngineEvent::AssistantDelta {
text: format!("Echo (host): {}", text),
},
);
let _ = app.emit("hermit://event", EngineEvent::TurnEnd { ok: true });
state.lock().unwrap().busy = false;
}
pub fn cancel_turn(state: &SharedEngine) {
state.lock().unwrap().busy = false;
}
pub fn consent_answer(_id: &str, _answer: &str) {
// Real path: wake the worker blocked in consent hook.
}
+31
View File
@@ -0,0 +1,31 @@
//! Future FFI surface against `include/cst_agent.h` (AgentCore parity).
//!
//! Enable with:
//! make -C ../.. libcstcore.a # or cmake cstcore
//! HERMIT_CORE_LIB=$PWD/../../libcstcore.a \
//! HERMIT_CORE_INCLUDE=$PWD/../../include \
//! cargo build --features engine
//!
//! Mapping (Qt AgentCore → Tauri commands/events):
//! open / send / cancel → session_* / send_turn / cancel_turn
//! hooks.assistant_delta → hermit://event AssistantDelta
//! hooks.tool_* → ToolStart / ToolEnd
//! hooks.consent (blocking) → Consent event + consent_answer wakes waiter
//! settings / creds → settings_get (+ later settings_set)
#![allow(dead_code)]
#[cfg(feature = "engine")]
mod live {
// Bindings land here (cbindgen or manual extern "C").
}
#[cfg(not(feature = "engine"))]
pub fn engine_linked() -> bool {
false
}
#[cfg(feature = "engine")]
pub fn engine_linked() -> bool {
true
}
+14
View File
@@ -0,0 +1,14 @@
/* Placeholder for future cbindgen / manual FFI against include/cst_agent.h.
* Build with --features engine and HERMIT_CORE_LIB pointing at libcstcore.a.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/* Mirrors the subset AgentCore used; real symbols come from libcstcore. */
typedef struct cst_agent cst_agent_t;
#ifdef __cplusplus
}
#endif
+73
View File
@@ -0,0 +1,73 @@
mod engine;
mod ffi;
use engine::{SharedEngine, EngineState};
use std::sync::Mutex;
use tauri::Manager;
#[tauri::command]
fn session_list(state: tauri::State<'_, SharedEngine>) -> Vec<engine::SessionInfo> {
engine::list_sessions(&state)
}
#[tauri::command]
fn session_new(state: tauri::State<'_, SharedEngine>) -> engine::SessionInfo {
engine::new_session(&state)
}
#[tauri::command]
fn session_open(
state: tauri::State<'_, SharedEngine>,
id: String,
) -> Vec<engine::ChatItem> {
engine::open_session(&state, &id)
}
#[tauri::command]
fn settings_get(state: tauri::State<'_, SharedEngine>) -> engine::Settings {
engine::settings_get(&state)
}
#[tauri::command]
async fn send_turn(
app: tauri::AppHandle,
state: tauri::State<'_, SharedEngine>,
text: String,
) -> Result<(), String> {
engine::send_turn(app, &state, text).await;
Ok(())
}
#[tauri::command]
fn cancel_turn(state: tauri::State<'_, SharedEngine>) {
engine::cancel_turn(&state);
}
#[tauri::command]
fn consent_answer(id: String, answer: String) {
engine::consent_answer(&id, &answer);
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.manage(Mutex::new(EngineState::default()))
.invoke_handler(tauri::generate_handler![
session_list,
session_new,
session_open,
settings_get,
send_turn,
cancel_turn,
consent_answer
])
.setup(|app| {
if let Some(w) = app.get_webview_window("main") {
let _ = w.set_title("Hermit");
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running Hermit desktop");
}
+5
View File
@@ -0,0 +1,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
hermit_desktop_lib::run();
}
+53
View File
@@ -0,0 +1,53 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Hermit",
"version": "1.1.0",
"identifier": "xyz.whcself.hermit",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"label": "main",
"title": "Hermit",
"width": 1280,
"height": 840,
"minWidth": 880,
"minHeight": 560,
"resizable": true,
"fullscreen": false
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"linux": {
"deb": {
"depends": []
}
},
"macOS": {
"minimumSystemVersion": "12.0"
},
"windows": {
"nsis": {
"installMode": "currentUser"
}
}
}
}
+209
View File
@@ -0,0 +1,209 @@
import { useCallback, useEffect, useState } from "react";
import { Rail } from "@/components/Rail";
import { Transcript } from "@/components/Transcript";
import { Composer } from "@/components/Composer";
import { ConsentModal } from "@/components/ConsentModal";
import {
answerConsent,
cancelTurn,
getSettings,
listSessions,
newSession,
onEngineEvent,
openSession,
sendTurn,
type ChatItem,
type ConsentRequest,
type SessionInfo,
type Settings,
} from "@/lib/bridge";
import "@/styles/app.css";
export default function App() {
const [sessions, setSessions] = useState<SessionInfo[]>([]);
const [activeId, setActiveId] = useState<string | null>(null);
const [items, setItems] = useState<ChatItem[]>([]);
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(false);
const [query, setQuery] = useState("");
const [settings, setSettings] = useState<Settings>({
provider: "deepseek",
model: "deepseek-flash",
approval: "auto",
workspace: ".",
});
const [consent, setConsent] = useState<ConsentRequest | null>(null);
const [showSettings, setShowSettings] = useState(false);
const refreshSessions = useCallback(async () => {
setSessions(await listSessions());
}, []);
useEffect(() => {
void (async () => {
setSettings(await getSettings());
await refreshSessions();
})();
}, [refreshSessions]);
useEffect(() => {
let un: (() => void) | undefined;
void onEngineEvent((ev) => {
if (ev.type === "assistant_delta") {
setItems((prev) => {
const last = prev[prev.length - 1];
if (last && last.kind === "assistant") {
return [
...prev.slice(0, -1),
{ ...last, text: last.text + ev.text },
];
}
return [
...prev,
{ kind: "assistant", id: `a${Date.now()}`, text: ev.text },
];
});
} else if (ev.type === "thought_delta") {
setItems((prev) => {
const last = prev[prev.length - 1];
if (last && last.kind === "thought") {
return [
...prev.slice(0, -1),
{ ...last, text: last.text + "\n" + ev.text },
];
}
return [
...prev,
{ kind: "thought", id: `th${Date.now()}`, text: ev.text },
];
});
} else if (ev.type === "tool_start") {
setItems((prev) => [
...prev,
{
kind: "tool",
id: ev.id,
name: ev.name,
status: "running",
detail: ev.detail,
},
]);
} else if (ev.type === "tool_end") {
setItems((prev) =>
prev.map((it) =>
it.kind === "tool" && it.id === ev.id
? { ...it, status: ev.status, detail: ev.detail || it.detail }
: it,
),
);
} else if (ev.type === "consent") {
setConsent(ev.req);
} else if (ev.type === "turn_end") {
setBusy(false);
} else if (ev.type === "error") {
setBusy(false);
setItems((prev) => [
...prev,
{
kind: "assistant",
id: `err${Date.now()}`,
text: `Error: ${ev.message}`,
},
]);
}
}).then((u) => {
un = u;
});
return () => un?.();
}, []);
const open = async (id: string) => {
setActiveId(id);
setItems(await openSession(id));
};
const onNew = async () => {
const s = await newSession();
await refreshSessions();
setActiveId(s.id);
setItems([]);
};
const onSend = async () => {
const text = draft.trim();
if (!text || busy) return;
setDraft("");
setBusy(true);
setItems((prev) => [
...prev,
{ kind: "user", id: `u${Date.now()}`, text },
]);
await sendTurn(text);
};
return (
<div className="app">
<Rail
sessions={sessions}
activeId={activeId}
workspace={settings.workspace}
query={query}
onQuery={setQuery}
onNew={() => void onNew()}
onOpen={(id) => void open(id)}
onSettings={() => setShowSettings(true)}
/>
<section className="main">
<header className="topbar">
<h1>
{sessions.find((s) => s.id === activeId)?.title ?? "New session"}
</h1>
<div className="chips">
<span className="chip ok">engine ready</span>
<span className="chip">
<strong>{settings.model}</strong>
</span>
</div>
</header>
<Transcript items={items} />
<Composer
value={draft}
busy={busy}
settings={settings}
onChange={setDraft}
onSend={() => void onSend()}
onStop={() => void cancelTurn()}
/>
</section>
{consent ? (
<ConsentModal
req={consent}
onAnswer={(a) => {
void answerConsent(consent.id, a);
setConsent(null);
}}
/>
) : null}
{showSettings ? (
<div className="consent" onClick={() => setShowSettings(false)}>
<div
className="consent-card"
onClick={(e) => e.stopPropagation()}
>
<h3>Settings</h3>
<pre>{JSON.stringify(settings, null, 2)}</pre>
<div className="consent-actions">
<button
type="button"
className="primary"
onClick={() => setShowSettings(false)}
>
Close
</button>
</div>
</div>
</div>
) : null}
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { useEffect, useRef } from "react";
import type { Settings } from "@/lib/bridge";
type Props = {
value: string;
busy: boolean;
settings: Settings;
onChange: (v: string) => void;
onSend: () => void;
onStop: () => void;
};
export function Composer({
value,
busy,
settings,
onChange,
onSend,
onStop,
}: Props) {
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
el.style.height = "0px";
el.style.height = Math.min(200, el.scrollHeight) + "px";
}, [value]);
return (
<div className="composer-wrap">
<div className="composer">
<textarea
ref={ref}
rows={2}
placeholder="Describe what you want to build, / commands, @ files…"
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
if (!busy && value.trim()) onSend();
}
}}
/>
<div className="composer-bar">
<div className="composer-left">
<span className="chip">
<strong>{settings.model}</strong>
</span>
<span className="chip">
{settings.provider} · {settings.approval}
</span>
</div>
{busy ? (
<button type="button" className="send stop" onClick={onStop}>
Stop
</button>
) : (
<button
type="button"
className="send"
disabled={!value.trim()}
onClick={onSend}
>
Send
</button>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,31 @@
import type { ConsentRequest } from "@/lib/bridge";
type Props = {
req: ConsentRequest;
onAnswer: (a: "deny" | "once" | "always_tool" | "always_prefix") => void;
};
export function ConsentModal({ req, onAnswer }: Props) {
return (
<div className="consent">
<div className="consent-card">
<h3>Allow {req.tool}?</h3>
<pre>{req.detail}</pre>
<div className="consent-actions">
<button type="button" onClick={() => onAnswer("deny")}>
Deny
</button>
<button type="button" onClick={() => onAnswer("always_prefix")}>
Always prefix
</button>
<button type="button" onClick={() => onAnswer("always_tool")}>
Always tool
</button>
<button type="button" className="primary" onClick={() => onAnswer("once")}>
Allow once
</button>
</div>
</div>
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More