feat: web chat runs /refresh, /spec, /refine, /preview, /speed; TUI argument menus name their default #74

Merged
kreato merged 39 commits from taha/web-commands into main 2026-11-16 08:30:18 +00:00 AGit
Contributor

Stacked on #73 (review-followups, head 8bac5367): until #73 merges, this PR also lists #73's commits; only the last two are new. WEB COMMANDS (f88445db): /refresh, /spec, /refine and /preview move from terminal-only to WebAction and run in the daemon through commands.run (internal/app/command_web.go) with the existing text/notice results. /refresh reuses models.refresh and the caller's context; /spec mirrors the TUI grammar (spec.user reads, command.execute changes); /refine keeps a bounded per-session proposal cache and applies the session filter to undo with and without an id. /preview reads a file in the session's project only: local execution endpoints only, path resolved against the session cwd and refused when its real path leaves it or lands in a credential store (secretpaths), opened O_NOFOLLOW|O_NONBLOCK with fstat identity against the checked path, regular files only, binaries refused, 64 KiB shown. commands.run refuses plugin callers. /speed is a page command toggling the usage bar's tok/s reading (browser-local). /share, /traces, /update, /nightly, /import, /quit, /exit, /back, /fullscreen stay terminal-only. Docs: docs/web-commands.md (new), docs/remote.md. TUI ARGUMENT MENUS (2ee8db7e): every argument menu lists the bare command's action first and highlighted: new verbs /remote start, /fullscreen toggle, /speed toggle, /tier panel, /acp list; existing options reused (list for /mcp and /plugins, status for /traces, /nightly, /sandbox, /autonomous, /heartbeat, /spec). Handlers accept the new verbs with exactly the bare behaviour; Enter on a fresh menu still runs the default, Tab cycles. Docs: docs/tui-completion.md. REVIEW: a security review of the web commands (endpoint bypass, check-then-open race, credential paths, plugin caller) found 4 issues, all fixed with red-before-fix tests. CHECKS: go build, go vet ./internal/... (and darwin for internal/app), gofmt, plugin API unchanged; go test for internal/commands, internal/tui2/..., internal/remoteui and the internal/app command/preview/refine/spec/refresh/web/plugin tests pass (remoteui port and tui2/term tty timing flaked once under load, pass on rerun); web svelte-check 0 errors, 439 tests, assets rebuilt. The full scripts/check.sh was not run to completion for this PR (build/vet/gofmt/plugin-API/web-stamp steps passed). BEHAVIOUR CHANGES: commands.run now refuses plugin callers; the web chat can read project files via /preview (local sessions, project only, credential stores refused).

Stacked on #73 (review-followups, head 8bac5367): until #73 merges, this PR also lists #73's commits; only the last two are new. WEB COMMANDS (f88445db): /refresh, /spec, /refine and /preview move from terminal-only to WebAction and run in the daemon through commands.run (internal/app/command_web.go) with the existing text/notice results. /refresh reuses models.refresh and the caller's context; /spec mirrors the TUI grammar (spec.user reads, command.execute changes); /refine keeps a bounded per-session proposal cache and applies the session filter to undo with and without an id. /preview reads a file in the session's project only: local execution endpoints only, path resolved against the session cwd and refused when its real path leaves it or lands in a credential store (secretpaths), opened O_NOFOLLOW|O_NONBLOCK with fstat identity against the checked path, regular files only, binaries refused, 64 KiB shown. commands.run refuses plugin callers. /speed is a page command toggling the usage bar's tok/s reading (browser-local). /share, /traces, /update, /nightly, /import, /quit, /exit, /back, /fullscreen stay terminal-only. Docs: docs/web-commands.md (new), docs/remote.md. TUI ARGUMENT MENUS (2ee8db7e): every argument menu lists the bare command's action first and highlighted: new verbs /remote start, /fullscreen toggle, /speed toggle, /tier panel, /acp list; existing options reused (list for /mcp and /plugins, status for /traces, /nightly, /sandbox, /autonomous, /heartbeat, /spec). Handlers accept the new verbs with exactly the bare behaviour; Enter on a fresh menu still runs the default, Tab cycles. Docs: docs/tui-completion.md. REVIEW: a security review of the web commands (endpoint bypass, check-then-open race, credential paths, plugin caller) found 4 issues, all fixed with red-before-fix tests. CHECKS: go build, go vet ./internal/... (and darwin for internal/app), gofmt, plugin API unchanged; go test for internal/commands, internal/tui2/..., internal/remoteui and the internal/app command/preview/refine/spec/refresh/web/plugin tests pass (remoteui port and tui2/term tty timing flaked once under load, pass on rerun); web svelte-check 0 errors, 439 tests, assets rebuilt. The full scripts/check.sh was not run to completion for this PR (build/vet/gofmt/plugin-API/web-stamp steps passed). BEHAVIOUR CHANGES: commands.run now refuses plugin callers; the web chat can read project files via /preview (local sessions, project only, credential stores refused).
Taha added 36 commits 2026-11-15 21:03:29 +00:00
Follow-up to the final review of PR #72:
- mkdirSSHDirReplace checked the directories top-down, but writeAtomic then
  resolved the path by name again, so a worker that swapped a directory for
  a symlink between the check and the write (two sessions of one workspace
  share the sandbox home) redirected ssh_proxy.py, the ssh config and the
  wrappers elsewhere - the host's ~/.ssh included. Every daemon write into
  the sandbox home (the ssh transport files, the copied ssh files, the
  generated git config and signer) now walks from the home with directory
  descriptors: openat with O_NOFOLLOW per component, mkdirat when missing,
  unlinkat and mkdirat for a link or a non-directory, and files written with
  openat O_CREAT|O_EXCL|O_NOFOLLOW, fsync and renameat. Unix only; other
  platforms keep the previous path.
- lowerHostPattern took an escaped \] inside a character class for its end,
  so [\]A-Z] matched lower case; classes are parsed the way path.Match does.

TestWriteAtomicReplacesADirSwappedAfterTheCheck,
TestWriteGitConfigReplacesADirSwappedAfterTheCheck and
TestNetworkHostPatternParsesEscapedClassMembersLikePathMatch fail on the old
code.
Follow-up to the final review of PR #72:
- A plugin generation cancelled or failed during start, never published,
  kept the bindings its plugins made with events.subscribe, so a live plugin
  could change the MCP override of a session it never declared. reloadPlugins
  forgets the bindings of every generation it staged but did not publish.
- mcp.connect, mcp.reconnect and mcp.verify restarted the shared client
  behind a session's runtime disable, as mcp.reload did; they refuse for a
  disabled lineage now.
- The startup grant sweep could delete the live session grants of another
  daemon sharing the state directory with a different database (grants carry
  no database identity). It sweeps nothing while another daemon is live there
  (a connectable socket or a held lock); stale artifacts do not block it.
- docs/plugin-api.json still advertised mcp.add, mcp.update, mcp.remove,
  mcp.set_global_server and mcp.flush_settings to plugins with the admin
  grant, which the daemon refuses. They are client-only in the generator's
  tables now; the surface is regenerated (5 exposure fields; the Python SDK
  is unchanged).

plugin_generation_unpublished_test.go, mcp_runtime_disabled_restart_test.go,
grant_sweep_shared_state_test.go and the surface exposure test fail on the
old code.
A sandboxed command can now reach a docker daemon on macOS: docker build,
docker run and docker compose work once the user approves the daemon's unix
socket with a device grant. The docker socket is root-equivalent on the VM,
so nothing is on by default.

- The device permission is enforced on Seatbelt for exactly one existing unix
  socket (or a symlink to one, such as Docker Desktop's /var/run/docker.sock).
  The profile gets a network-outbound unix-socket rule for that path, read
  access to the CLI bundle behind the docker symlink, and DOCKER_HOST is
  pinned to the approved socket.
- Socket paths are validated once when the grant is compiled and the profile
  is frozen at worker build; a later symlink swap is denied, not redirected.
  A planted non-socket fails the grant closed; a missing path stays inert.
- The daemon's state dir, its control socket at a custom --socket or
  YAZI_SOCKET_PATH, the SSH agent socket and the git sign-broker socket can
  never be granted.
- scripts/smoke-seatbelt-cloud.sh gains opt-in SMOKE_DOCKER=1 probes.
- The agent's permission guide advises the session scope for device on
  Seatbelt, as for network.private.
clipboard.Read collapsed every failure into "no image, no error", so a
missing helper, a file-manager copy, an unsupported format, an oversized
payload or a timeout all did nothing and showed nothing.

- Every failure now returns an explanatory error that the composer shows.
- wl-paste reads the default target and sniffs magic bytes; xclip probes every
  offered type; text/uri-list, gnome-copied-files and plain paths resolve to
  image files; TIFF and BMP convert to PNG; macOS gains an osascript fallback.
- Image files are read only when they are regular files, opened non-blocking,
  checked on the opened descriptor, read through a size limit and bounded by
  the caller's deadline, so a FIFO or /dev/zero cannot hang or exhaust memory.
- clipboard.Text backs a text fallback for the paste chord.
- Ctrl+V joins Alt+V as a default paste-image chord.

- flake.nix: vendorHash updated; the non-blocking open imports golang.org/x/sys/unix, which the vendored module set did not contain yet.
- New package internal/tui2/widgets/mermaid renders flowchart/graph blocks
  (TD/TB/LR/BT/RL, node shapes, solid/dotted/thick edges with labels, chains,
  &, subgraphs) as box-drawing text with a layered layout. Anything it cannot
  draw, or that does not fit, falls back to the source as a code block.
- OpenUI blocks with small syntax errors no longer lose their menu: statements
  are salvaged one by one, reflowed lines are rejoined, quotes and brackets
  repaired, and only @ToAssistant revives a button action. What cannot be
  read is shown as raw text, never dropped. The agent's OpenUI prompt lists
  the common pitfalls.
- Tables: a wide (emoji/CJK) glyph in a column shrunk below its width
  overflowed the row and clipped the last column, which looked empty. Columns
  keep at least their widest grapheme; pipes inside code spans no longer split
  cells.
- Code lines wrap at the width instead of being clipped; continuation rows
  carry a soft-wrap marker on render.Cell so copy can rejoin them.
A mermaid fence in an assistant message renders as an SVG diagram through
the mermaid package (12.3.0, MIT), loaded lazily so the main bundle grows by
about 6 kB. securityLevel strict and htmlLabels off keep model-written diagram
text from injecting markup; the CSP is unchanged. Diagrams follow the light
and dark theme, an unfinished fence shows its source while streaming, and a
diagram that fails to render falls back to the source with a note.
Subagent completions, process wakes and other prompts the harness queues
rendered like the user's own messages. The queue item's origin and a short
label now travel with the stored notice to the TUI transcript and the web
chat, which show a compact "harness" row instead. The model still receives
the same prompt text.

- Old sessions: only entries stored as notices use the legacy prefix
  fallback; a user-typed message starting with "[subagent completed]" stays
  the user's.
- Labels strip control and bidi characters and cap the agent-chosen name, so
  a subagent cannot write a long trusted-looking headline.
- Accepting a command left a hold that suppressed the argument menu until
  the next letter; the menu now opens on the accepted space.
- Commands and arguments match fuzzily (filemention.Fuzzy), prefix and word
  boundary first. Tab and Shift+Tab cycle candidates with wraparound.
- Enter on a fresh argument menu runs the bare command; a typed, cycled or
  arrow-selected candidate is accepted first and the next Enter runs it.
- Shift+Tab with the @ file menu open panicked (index out of range); it now
  steps back through the files.
- Copying a wrapped code line joins its continuation rows without a newline
  or the layout inset, so a long command copies as the original line.
- A pasted image path becomes an attachment only into an empty draft;
  the paste-image chord inserts clipboard text when there is no image.
- Wires harness-notice events and the image paste into the root, rebuilds
  the web assets, and raises the TUI line budget (measured 48269).
On the Mac, docker run failed with "error getting credentials (-50)": the
credsStore "desktop" helper reads the macOS keychain, which the sandbox
denies. docker build failed writing ~/.docker/buildx/activity.

When the docker socket grant is active the worker now gets a generated
DOCKER_CONFIG in the sandbox home: the host config.json without credsStore,
credHelpers and auths, contexts copied (regular files, capped), and
cliPluginsExtraDirs naming the Docker.app and ~/.docker plugin directories the
profile can read. Pulls are anonymous and buildx state stays in the sandbox;
the keychain is never reachable. The copy keeps one empty auths entry for
the reserved host yazi-sandbox.invalid: with no credential entry at all the CLI
picks docker-credential-osxkeychain as a default store and fails the same way. Allowing the helper's keychain lookups was
rejected because it would expose every item the helper can read.

The macOS-only test failures came from /tmp vs /private/tmp spellings and the
104-byte sun_path limit; the tests now use short, resolved temp dirs.
A Finder Cmd+C puts a file URL on the pasteboard. The osascript type listing
failed on that clipboard and the file probe read only the legacy furl flavour,
so the paste was lost and the notice claimed the clipboard was empty.

The listing now also reports the file's POSIX path (each part in its own try,
scripting additions loaded), and the file probe always runs: legacy furl
first, then NSPasteboardTypeFileURL. The path goes through the same
regular-file, size and magic-byte checks as any pasted path. Notices now tell
an empty clipboard apart from one whose contents could not be listed.
Tab cycling and fuzzy matching belong to the argument menu. On the command
menu they made Tab hop between unrelated commands and pulled in names that
only contained the letters (/hs offered /hotkeys). Command names match by
prefix again, in the registry's order, and Tab completes the highlighted
command and opens its argument menu; Shift+Tab only moves the highlight.
Arguments keep fuzzy matching and Tab/Shift+Tab cycling.

Tests: TestCommandMatchingIsByPrefix and TestTabCompletesTheHighlightedCommand
replace the fuzzy command tests (both fail on the previous behaviour).
AssistantMarkdown breaks a 4+ column table out of the message column with a
negative margin-left and a matching padding-left. AssistantMessage's own
.md-table rule outranks it through Svelte's scope class, and its `margin: 16px
0` shorthand reset the negative margin while the padding stayed, so every wide
table started a full lead to the right of the text. The rule sets block
margins only now; a layout test pins that no .md-table rule there sets an
inline margin or padding (red on the shorthand). Web assets rebuilt.
Completing @direc to @directory/ set the same hold a file accept sets, so the
menu stayed closed until the next keystroke and the directory's entries could
not be picked with the arrows or another Tab. A directory is a step into it:
the terminal client refreshes the menu on its contents right away and the web
composer drops the hold (holdAfterAccept), so the listing appears at once. A
file accept keeps the hold, so the next Enter still sends.

Tests: TestTabOnADirectoryOpensItsContents (red: the menu was nil after Tab)
and the directory case in web/tests/mentions.test.ts. Web assets rebuilt.
A dependency chart with two subgraphs, a fan-in node and a <br/> label came
out garbled in the TUI:

- `Infra -.->|x| Core` created plain nodes named Infra and Core. An edge that
  names a subgraph now runs from its exit node to the other's entry node,
  across both borders, keeping its label and dotted style.
- Subgraph borders overwrote wires and labels ("│││", the label left as stray
  letters). Borders now join the wires they cross, gaps between subgraphs
  hold both borders (per nesting level) and the wire's channel, and labels
  are placed last on free cells, or the chart is refused.
- Every wire cell set all four directions at a run's ends, so turns became
  T-pieces and runs started one cell past the corner ("│──", "─┼"). Runs now
  share corner cells and set only the directions they use, so turns are
  corners and merges are junctions.
- <br/> became literal text; it now makes a multi-line box.
- Nested subgraphs were clamped onto each other at the grid edge; the drawing
  shifts instead. Boxes that would overlap or enclose a non-member are
  refused (the caller shows the source).
- A left-to-right chart wider than the terminal is drawn top-down instead of
  falling back to source.

The goldens are regenerated: the old ones froze the same junction bugs.
New tests (all red on the previous code): TestEdgeBetweenSubgraphsLinksTheBoxes,
TestLineBreakInALabelMakesATallerBox, TestFanInJoinsWithJunctions,
TestWideLeftToRightChartStacksTopDown; plus TestOverlappingSubgraphBoxesAreRefused.
FuzzRender: 45 s, 3.4M execs, no crashers. TUI line budget raised to 49300
(measured 48804).
The real dependency chart still showed only its source: APPS, a node outside
all subgraphs fed from inside Core, was placed in Core's layer column under
Core's nodes, so Core's box would have enclosed it and the render was
refused. Each top-level subgraph, and the group of outside nodes, now gets its
own cross-axis lane where their layers overlap (groups on disjoint layers
share a lane and stay aligned).

Also:
- An edge between boxes of different heights (a <br/> box next to a
  one-line box) jogged out of the taller box's centre ("──┐ └▶"); it now runs
  straight on a row both boxes share.
- A quoted dotted/pipe label (`-. "Makefile order" .->`) kept its quotes.

Tests (red on the previous commit): TestRealDependencyChartRenders (the
model's exact chart, at 400 and 228 columns) and
TestDifferentHeightBoxesConnectStraight. One golden lost a needless jog.
Large charts (a dependency graph with dozens of nodes) were unreadable at the
message column's width. A full-screen button in the diagram toolbar opens a
modal <dialog> with the diagram at its natural size, fitted to the window:
the wheel zooms around the pointer, a left or middle drag pans, a double
click switches between fit and 100%, + - 0 1 and the arrows do the same from
the keyboard, and Esc closes it. The toolbar shows the zoom level (10%-800%).

The keys are catalog rows in lib/keys.ts (so the shortcuts dialog lists them
and no component spells a key); the pan/zoom math is lib/panzoom.ts, pinned
by tests/panzoom.test.ts. Web assets rebuilt.
Review findings on the Seatbelt docker support:

- The generated docker configuration was written by path into the
  worker-writable sandbox home, so a planted symlink at .docker,
  config.json or contexts redirected the daemon's write outside the
  sandbox. It now goes through the same directory-descriptor helpers as
  the git and ssh files (mkdirHomeDir/writeHomeFile/writeHomeFileRel):
  every component is opened O_NOFOLLOW and a planted node is replaced.
- Only contexts/meta is copied. contexts/tls held a remote context's
  client key, which reached the worker on a socket approval alone. Each
  source file is opened O_NOFOLLOW and checked on the fd (regular, at
  most 64 KiB, read through a limit) so a swap after the walk cannot
  follow a link or bypass the cap.
- config.json is copied through an allowlist of non-secret CLI keys;
  HttpHeaders and proxies can embed credentials and are dropped.
- The daemon's live control socket (--socket or config socket_path) is
  handed to the backend and refused as a device grant, not only the
  YAZI_SOCKET_PATH spelling.
- The device scope is driven through the activation test, the non-unix
  home writer compiles, and the write loop retries on EINTR.

docs/sandbox.md describes the copy, the allowlist and when the socket is
re-validated.
- mcp.disconnect closes the shared client for every session but skipped
  the disabled-lineage gate the other restart verbs use. It is gated now,
  and the test covers all four verbs.
- A plugin could skip the gate by leaving session_id out (the lineage of
  no session allows everything). A plugin caller must now name a session
  for mcp.connect/reconnect/verify/disconnect; the user's session-less
  admin call is unchanged.
- subagentWakeDetail parses the wake template from its end and only
  accepts a real session id in the parentheses, so a subagent name cannot
  plant a fake id in a harness headline.
- TestQueuedMessageEndsPrecedeIdleSnapshot waits for the fourth message
  end instead of a 150 ms window, which failed under load.

New docs/mcp.md and docs/permissions.md describe the MCP write and
restart rules and the grant sweep (including the shared-state-dir skip);
docs/plugin-api.md no longer lists the client-only MCP writes as admin.
- Harness notices render by detail mode: Collapsed shows the headline
  only, Details the headline with a fold, Expanded the body as it was
  submitted (indentation and blank lines kept). Switching mode re-lays
  existing notices; a one-line notice is no longer clickable and the
  "more lines" count is right for combined wakes.
- An OpenUI block whose root statement fails no longer drops every
  statement that parsed, and salvaged bare-word actions keep '?' and '-'.
- The mermaid node cap returns its documented error instead of an
  internal failure, an empty nested subgraph draws no phantom box, and
  FuzzRender now sees a recovered panic.
- markdown.SetMermaid switches mermaid fences back to plain code blocks
  (used by the TUI setting in a following commit); Model.Relayout
  re-lays the transcript for such a renderer switch.

docs/harness-notices.md no longer lists heartbeats as notices (they are
prompts); the markdown docs no longer call the renderer a stub.
- On Linux a plain-text clipboard line naming an existing non-image path
  (a directory, a .txt) failed Ctrl+V with "not an image file". Such a
  path now pastes as text; a file-manager copy of a non-image keeps its
  clear error.
- Clipboard text is read with a 1 MiB limit instead of the 50 MiB image
  limit, one paste has an overall deadline, and a helper that never
  answers reports a timeout instead of "signal: killed".
- The fourth sandbox decision shape ("access recorded, not enforced")
  stays out of the transcript like the other three.

docs/pasting-images.md: plain-text image paths attach on Linux only, and
the overall bound is stated.
- Copying your own message did nothing when the splash header was on
  screen: in fullscreen the header scrolls with the transcript and the
  mouse mapping was off by the header height, so the drag landed on the
  bubble's blank padding row. The transcript origin is now recorded
  unclamped and a press on the banner anchors to the first row. A plain
  click on a short user bubble copies it; links in it still open first.
- A drag parked in the transcript's edge band repainted every 45 ms even
  when nothing could scroll (the flicker outside Expanded mode). The
  drag ticker now runs only while auto-scroll actually moves.
- /model: the first effort change after picking a model was lost because
  the model switch (which clears the effort) and the effort write ran as
  two concurrent effects. They run in order now, the footer shows the
  applied level, and each model's last effort is remembered in the new
  model_efforts preference (ten entries) and restored when it is picked.
- Mermaid diagrams in the terminal can be turned off: a "Mermaid diagrams
  (terminal)" /settings row, config.json "mermaid" and the Nix option
  programs.yazi-agent.settings.mermaid (the stored /settings choice wins).
  The web UI always draws diagrams. The re-layout runs on the UI loop.

TUI line budgets raised with measurements in budget_test.go; settings
goldens regenerated for the new row.
- The composer takes pasted or dropped images (png, jpeg, gif, webp; 4
  MiB each, under the bridge's 8 MiB frame): a thumbnail chip and an
  [image #N] token like the TUI. Text goes in prompt and only images in
  parts; the bridge refuses text parts and validates image parts the way
  the daemon does, so a prompt's text is never sent twice.
- [image #N] in a user message shows the stored image (click for full
  size); image-only prompts are no longer blank. No CSP change.
- The Subagents pill and the usage strip rest on the composer's opaque
  surface, so transcript text behind them no longer makes them
  unreadable.
- Mermaid viewer: its copy gets its own element ids, a theme flip keeps
  the old diagram until the new one lands, htmlLabels is off for every
  diagram type, the canvas shows a focus ring, a failed copy says so,
  and the shortcuts dialog lists the viewer keys.

Web assets rebuilt.
- A mermaid block stayed on "rendering…" for ever (diagram visible, no
  toggle or full-screen button): the render effect read renderState to
  carry the previous SVG and then wrote it, so every write re-ran the
  effect, whose cleanup cancelled the render in flight. The carry is read
  through untrack, and the render states live in pure helpers in
  lib/mermaid.ts with a test that the effect never reads renderState.
- The usage strip painted its new opaque surface as an empty pill under
  the composer when it had nothing to show; it is not drawn then.
- [image #N] in the web composer behaves like the TUI's token: the caret
  never lands inside it, Backspace/Delete remove the token and its
  attachment, a partial selection grows to the whole token, and it is
  drawn as a pill. Copy and cut give the literal [image #N] (so it pastes
  into the TUI), pasting it back re-binds while the image is attached,
  and cut/paste moves it. Copying across a thumbnail in a sent message
  gives the token text; the thumbnail drags out as the image.

docs/remote.md describes the chip. Web assets rebuilt.
The web composer draws an [image #N] token as a pill reading "Image N"
with a picture icon. The textarea keeps the literal token, so caret
positions, copy, cut and the sent prompt are unchanged and the TUI sees
the same text: the highlight layer draws the draft and the textarea text
is transparent (the caret stays visible through caret-color), with the
pill laid over the token's own width so the caret never drifts. A sent
message without an image payload shows the same label and still copies
as [image #N].

Clicking the pill or the attachment chip opens the image full size in a
shared ImageLightbox dialog (also used by sent messages); Esc, the close
button or the backdrop close it and focus returns to the draft. A click
that does not rest on a token, or a drag selection, behaves as before.

docs/remote.md updated. Web assets rebuilt.
The "Image N" pills left "[" and "[i" visible and typed text after them
looked doubled. The rule meant to hide the textarea text used
`textarea.input`, but `input` is a hashed CSS-module class, so it never
matched and the textarea kept painting the raw text over the mirror. The
textarea now carries its own class with color and
-webkit-text-fill-color transparent and an explicit caret-color; the
mirror sits above it, copies the textarea's computed typography (font,
spacing, line height, padding, borders, wrapping) on mount, resize and
font load, and follows scrollTop and scrollLeft. The pill is the token
span itself, at the raw token's exact width, so nothing peeks out.

Deleting a token always drops its attachment chip, now also when it is
typed or pasted over (attachmentsAfterEdit), and the chip's close button
removes every occurrence of its token with a sensible caret
(removeAttachmentToken). Both directions are pinned by tests.

Web assets rebuilt.
- Text after an "Image N" pill drew one space to the right of the
  caret: the mirror's {#each}/{#if} markup was indented across lines,
  Svelte kept those newline text nodes, and under white-space: pre-wrap
  each painted as a space. The segments are emitted with no whitespace
  between them, and the token element inherits the textarea's text
  metrics with margin, padding and border reset.
- The pill and its label overhung the token by 5px on each side and hid
  the neighbouring letters. Both are inset 0 now, the label is 0.85em
  and degrades to icon + number when the run is too narrow.
- The full-screen mermaid viewer drew every node as a black box: the
  viewer copy's ids were rewritten but the SVG's own <style> selectors
  (#<id> .node rect ...) still named the old id, so no style applied.
  Selectors inside <style> are rewritten too, pinned by a styled sample
  SVG test.

Web assets rebuilt.
Deleting an [image #N] token (Backspace, Delete, cut, typing over it, or
the chip's close button in the web UI) detaches the image instead of
discarding it: it stays in the composer's memory, is not sent, and its
web chip is hidden. Undo, redo, or typing or pasting [image #N] again
re-attaches the same image. Only a successful send discards the images
the sent text no longer references; after that the user pastes the
image again. A detached image keeps its number, so N is never reused.

Web: attachments are derived from the draft on every input
(reconcileImages), and token deletes go through execCommand so the
textarea's undo stack records them; a refused send keeps the memory.
TUI: the composer already detached on delete and re-attached on undo and
retype; Sent now discards the detached payloads, so a retyped token after
the send no longer revives an image that was not sent.

docs/remote.md and docs/pasting-images.md describe the rule. Web assets
rebuilt.
An [image #N] token now means the same image in every client of a
session. Cutting a draft with images out of the web composer and pasting
it into the TUI (or the other way round) brings the images along.

- Daemon: three client-only methods. session.image_put stores a pasted
  image and allocates its number (per session, monotonic, seeded above
  the highest [image #N] in the session's stored user messages, so a new
  image never takes an old token's number); session.image_get returns an
  image by number; session.image_discard drops numbers. The cache is in
  memory (a daemon restart empties it), bounded at 64 images and 128 MiB
  per session with oldest-first eviction reported to the caller, and is
  dropped with the session. Plugins cannot reach the methods
  (CLIENT_EXACT); the plugin API surface is regenerated.
- Web: the bridge carries the three methods through useSession with the
  same media-type and size checks; the composer stores a pasted image in
  the cache and uses its number, fetches a token it does not know, and
  after a send discards only the images it had detached.
- TUI: the same through the host client; the fetch runs as an effect,
  never on the paint goroutine, and a result for another session is
  dropped. A token the cache does not hold is removed whole with the
  reason in the footer, as before.
- An older daemon without the methods keeps today's local numbering.

Review fixes folded in: a 512 MiB daemon-wide bound evicts the globally
oldest image; a cascaded or failed-spawn session delete drops its cache,
and a put re-checks the session under the cache lock so a racing delete
cannot resurrect one; the history seed is scanned outside the lock;
oversized or absurd token numbers are ignored; unknown fields are
refused and the encoded length is checked before decoding. The clients
key their fetch bookkeeping by session, treat only the daemon's
not_found as final (a transient error keeps the token and retries a
bounded number of times), and the TUI captures the session id on the UI
loop for its image effects.

docs/image-cache.md describes the cache; docs/remote.md and
docs/pasting-images.md link it. Web assets rebuilt.
The footer showed "4308 tok/s" after tool rounds. The per-round timing
was right (tool runs and tool output are never inside a call's window);
the quotient was not: a call's output count includes the reasoning
tokens a reasoning model never streams, divided by the window from the
first visible delta to the end, so a round that mostly thought read in
the thousands. A replayed burst after a mid-stream attach did the same
to the live estimate.

usage.MaxPlausibleOutputRate (1000 tok/s) is applied to the TUI's exact
sample, its live estimate, and the store's branch-rate summaries (which
feed the web usage bar and the TUI's fallback average): such a sample is
not shown and not averaged; token totals are unchanged.

docs/footer-statistics.md explains what the number measures.
Since 702a1288 a walk that cannot enumerate a pid's children refuses
(exit 45, ErrNotKilled). In an image without procps every kill of a live
tree then failed: round 1 walked the tree through the children file and
killed it, round 2 re-walked every seen pid, the dead ones had no /proc
entry, so the walk fell through to BLIND and the script refused a kill it
had completed. Five package tests failed on main for this reason.

- tree() treats a pid with no /proc entry that kill -0 also reports gone
  as having no children: a dead pid cannot fork, and every child it had
  was enumerated in an earlier round. Blind is now only declared for a
  live pid whose descendants no source can find.
- A third source between the children file and ps: one pass over
  /proc/[0-9]*/stat builds the parent map with shell builtins (the ppid
  is read after the LAST ')' of the line, so a comm with ')' and spaces
  cannot shift it). It needs nothing but /proc, so kernels without the
  children file and images without procps still kill whole trees.
- The walk's /proc root is a Manager field baked into the script text for
  tests, never read from the environment; identity and liveness always
  use the real /proc.

Tests: the stat scan kills a three-level tree with the children file and
ps unavailable (fixture comms attack the ppid parse), and a walk with no
usable /proc still refuses. docs/ops-safety.md describes the sources.
The footer's tok/s divided a call's whole output count, which includes
reasoning tokens a model never streams, by the window from the first
visible delta: a round that mostly thought read in the thousands. The
previous commit hid such samples behind a 1000 tok/s cap; this replaces
the cap with a rate whose numerator and window describe the same
interval.

- model.Usage gains ReasoningTokens, parsed where the provider reports a
  split: OpenAI chat completion_tokens_details, OpenAI Responses/Codex
  output_tokens_details, ACP thoughtTokens, plugin providers. Gemini's
  candidatesTokenCount already excludes thoughts and Anthropic/Bedrock
  stream thinking as deltas, so they keep 0.
- The daemon decides once per provider call (usage.SpeedSample):
  reasoning streamed -> Output over the first-any-delta window; reasoning
  hidden with a reported count -> Output-ReasoningTokens over the
  first-visible-delta window; otherwise Output over the first-output
  window; under the minimum span or with nothing to count -> no sample.
  The pair travels on the usage event and is stored (migration 030:
  reasoning_tokens, rate_tokens, rate_span_ms; NULL keeps the old rule
  for rows written before it). The TUI sample and the three store
  summaries only read it.
- MaxPlausibleOutputRate is gone. The 41670 tok/s live estimate came from
  events replayed before the first snapshot at attach; the host marks
  them Replay and the estimate ignores them.

docs/footer-statistics.md explains the rule per provider.
- Web: the composer caps the total image payload per message at 6 MiB
  (base64, under the bridge's 8 MiB frame): a refused image is announced,
  the draft and its chips stay, and the send guard covers undo-restored,
  fetched and pasted tokens. Two ~3 MiB screenshots used to overflow the
  frame and lose the draft. The bridge's refusal of text parts in
  session.prompt is documented (text goes in prompt).
- TUI: a plain click on the splash banner no longer copies the first
  message (the code comment said it never does); drags from the banner
  are unchanged.
- TUI: on a daemon that does not know the model_efforts preference the
  /model effort choice stops writing it after the first refusal instead
  of showing an error block on every selection; the effort still applies.
- Sandbox: the startup grant sweep resolves a relative YAZI_SOCKET_PATH,
  so a second daemon spelled that way is detected instead of its grants
  being left alone.
- Mermaid: subgraphs nested deeper than 64 levels fall back to the source
  rendering with the documented error, instead of spending seconds of CPU
  on pathological nesting.
- Line budget raised with measurements (50590→51100, app 22290→22520).
- docs/mcp.md: the disabled-lineage gate covers disconnect too;
  docs/mermaid-web.md's license sentence matches the real licenses of
  mermaid's dependencies (MIT, ISC, MPL-2.0, EPL-2.0);
  docs/permissions.md and docs/mermaid.md updated for the fixes above.
Review follow-up to b9240729.

- kill -0 fails the same way for a dead pid and for a live one whose
  signals are denied (EPERM); with its stat unreadable too (hidepid, an
  LSM), the "gone" rule read such a live descendant as dead and the
  script reported a kill that left it running. A pid is now treated as
  gone only if the script reached it itself: signalled it successfully,
  kill -0 answered for it, or its own stat was readable, recorded at the
  moment of contact (the walk emits "ok <pid>" markers, the stat map
  counts, and each pid is signalled on its own). Any other pid keeps the
  blind refusal.
- The /proc stat map is built once per round, before the walk, and only
  when some seen pid would take the stat branch; tree() reused to build
  it once per seen pid, a full /proc pass each.
- The children-file read goes through the procRoot seam like the branch
  test that picks it.

Tests: a gone pid the script never signalled refuses with exit 45, and
the stat map runs once per round. docs/ops-safety.md describes the rule;
docs/footer-statistics.md notes that rows written before migration 030
keep the old rate rule and that the Responses/Codex reasoning window is
approximate.
efc68411's message promised the web image total cap, the bridge text-part
documentation and the license sentence, but those changes never made it
into the commit. They are here, with the rest of the reviewer's findings.

- Web: the composer caps the total image payload of a message at 6 MiB
  (base64, under the bridge's 8 MiB frame). An image that would exceed it
  is refused with a notice and the draft and its chips stay; the send
  guard covers undo-restored, fetched and pasted tokens. Two ~3 MiB
  screenshots used to overflow the frame, drop the connection and lose
  the draft.
- docs/remote.md: the bridge refuses type:"text" parts in session.prompt;
  text goes in prompt, images in parts.
- Kill: the ps walk printed a root the ps table does not list as if it
  had no children, so the script exited 0 while a descendant of an
  invisible pid ran. Such a root is now blind (exit 45). The
  children-file read applies 2>/dev/null before the < redirection, so a
  missing file's open error no longer leaks into the ErrNotKilled text.
- TUI: a stream reset forgets the remembered model_efforts refusal, so a
  daemon restarted into a newer version is asked again.
- docs/mcp.md: a plugin must name session_id for mcp.connect, reconnect,
  disconnect and verify (the user's session-less call is unaffected).
- docs/mermaid-web.md: the dependency licenses are stated as they are
  (MIT, ISC, MPL-2.0/Apache-2.0, EPL-2.0/GPL-3.0), and the sanitizing
  sentence says what mermaid actually sanitizes.

Web assets rebuilt.
The web chat refused every built-in classified WebTerminal. The ones that
suit a browser now run there:

- /refresh, /spec, /refine and /preview are WebAction: the daemon runs
  them through commands.run (internal/app/command_web.go) and answers
  with the existing text/notice results. /refresh reuses models.refresh
  with the TUI's summary line and the caller's context; /spec mirrors the
  TUI grammar (reads through spec.user, changes through command.execute);
  /refine keeps a bounded per-session proposal cache, since a browser
  holds no client state, and /refine undo applies the session filter with
  and without an id.
- /preview reads a file in the session's project only: local execution
  endpoints only (an SSH session's cwd is remote), the path resolved
  against the session cwd and refused when its real path leaves it or
  lands in a credential store (secretpaths), opened O_NOFOLLOW|O_NONBLOCK
  and checked by fstat identity against the checked path (no symlink or
  FIFO swap between check and open), regular files only, binaries
  refused, 64 KiB shown.
- commands.run refuses plugin callers: it carries user authority the
  plugin surface refuses by name.
- /speed is a page command: it toggles the usage bar's tok/s reading,
  stored in the browser, and works against a daemon that still calls it
  terminal-only.

/share, /traces, /update, /nightly, /import, /quit, /exit, /back and
/fullscreen stay terminal-only. docs/web-commands.md (new) and
docs/remote.md list which commands the web runs. Web assets rebuilt.
/remote alone starts the server, but its menu offered only pair, stop,
devices and revoke, so the action Enter runs had no name. Each argument
menu now names what the bare command does and lists it first,
highlighted: new verbs where none existed (/remote start, /fullscreen
toggle, /speed toggle, /tier panel, /acp list), an existing option
otherwise (list for /mcp and /plugins; status for /traces, /nightly,
/sandbox, /autonomous, /heartbeat and /spec). The handlers accept the new
verbs with exactly the bare behaviour, and the bare command keeps
working. Enter on a fresh menu still runs the default; Tab still cycles.

docs/tui-completion.md lists the defaults.
A six-reviewer pass over PR #73 found blockers and majors; this fixes them,
each with a regression test proven red without the fix.

Blockers:
- B1: the shared-state grant-sweep tests bind sockets in short directories,
  so macOS's 104-byte sun_path no longer fails them every run.
- B2: TestKillRefusesWhenProcIsUnusable skips off Linux like its neighbours.
- B3: an OpenUI Table with missing arguments dereferenced nil on the paint
  path; renderOpenUI now guards it and recovers to the block's source.
- B4: the web bridge enforces its frame limit itself: an over-budget frame
  gets a frame_too_large error and is drained, so the socket survives; the
  composer measures the whole prompt frame, not only the image total.

Majors:
- M1: the kill script read a failed kill -0 as death before consulting
  /proc, so a live pid the sandbox may not signal counted as killed.
- M2: a device grant activation would refuse (e.g. /dev/kvm) is refused at
  request time and on permission.put.
- M3: the SSH agent socket is protected even without a host.ssh grant.
- M4: device grants are stored with session scope only.
- M5: a compact fork copies reasoning_tokens, rate_tokens, rate_span_ms.
- M6: MCP restart verbs call refuseForeignMCPRuntimeSession.
- M7: pending web images are bound to the session they were pasted in.
- M8: the bridge validates prompt parts before useSession.
- M9-M12: a stray trailing call no longer replaces the OpenUI root; table
  cells match backtick runs by length; the quote-repair lexer is linear;
  reference expansion is capped (depth 64, 4096 values).
- M13/M14: a whole-draft path paste replaces the path; replayed events
  wait for the boot snapshot instead of hiding the durable history.
- M15: plugin API counts re-read from the generator (212/101/39, 341).

Minors: own auth.json.lock and flock errors no longer read as a neighbour
daemon; an image of exactly MaxImageBytes is accepted; strict image method
schemas; image encode outside imageCacheMu; mermaid init and front-matter
config stripped; lightbox, IME, copy/cut and paste-caret fixes; TIFF/BMP
pixel bound; ImagePut errors reported; path paste deadline; rebind
catch-up marked Replay; rune-safe clip, C1 controls, subgraph cap and tab
width in the TUI renderers; Usage.reasoning_tokens in the Python SDK;
closeHomeDir deleted and the test-only survivors listed in dead-code.md;
two broken doc links. TUI line budget raised to 51650 (measured 51144).
Two reviewers attacked the previous commit and found gaps; each fix has a
regression test proven red without it.

- Device grants: one predicate, refuseUnstorableDeviceGrant (a unix socket
  resource and session scope on Seatbelt), now runs on every door that
  writes a grant: the request, resolve, permission.put and
  sandbox.permissions.replace_global, which stored /dev/kvm or a global
  docker-socket grant and wedged every later Seatbelt activation.
- Agent sockets: the protected-socket list takes every agent socket the
  host.ssh gate accepts (ssh_config IdentityAgent, 1Password, a relative
  SSH_AUTH_SOCK resolved against the daemon cwd), not only the live
  SSH_AUTH_SOCK, so a device grant cannot hand the sandbox the keys.
- Kill: a walked pid whose kill -0 fails and whose stat is unreadable is
  treated as alive, so the kill exits 45 instead of reporting success.
- Mermaid: front matter is recognised with mermaid 12.3's own matcher
  (indent, blanks after the fence, CRLF), so an indented block can no
  longer set the render config.
- Web bridge: exactly 24 MiB left in a frame is still drained; only more
  closes the socket, as docs/remote.md says.
- TUI: every host event waits for the boot snapshot, not only replayed
  ones, so a live delta cannot hide the durable history; a dead stream
  drops the held events; converting a pasted path removes only the
  pasted text and keeps what was typed meanwhile.
The final review of #74 found no blockers; this fixes its should-fix items
and nits, each behaviour change with a regression test proven red first.

- commands.run is CLIENT_EXACT in the generator: the surface advertised it
  to unsafe plugins while the handler refuses every plugin caller (a listed
  entry dispatch refuses is a bug). Surface regenerated; the pluginapi pins
  and docs/plugin-api.md, docs/plugin-platform-plan.md follow.
- The protected agent sockets take every IdentityAgent in the ssh config
  (all Host blocks and Includes), not only the first, so a live agent
  socket named in a second block cannot be granted as a device.
- The web /speed accepts toggle like the TUI.
- /refresh: the comment and docs/web-commands.md said 60 s; it is 30 s per
  provider (refreshDiscoveryTimeout) inside the bridge's 10 min admission
  budget. The command_run.go refusal rationale now says what the surface
  really holds, pinned by a test.
- TestKillStatMapRunsOncePerRound counted fifo opens, which a loaded run
  inflated, against an absolute bound; it now paces the writer and bounds
  passes per round (failed 15/20 under load before).
- A test pins /acp's menu opening on list; doc and comment in present tense.
- /refine keeps its proposal until refine.apply succeeds, and a deleted
  session's proposal is dropped.
- commands.list refuses a malformed payload instead of decoding it with
  `_ =` into a session-less list (from #73).
- The bridge's frame-id fallback takes only the top-level id.
- docs: the /preview parent-directory symlink residual, and the grant
  sweep on filesystems without flock (docs/sandbox.md).
kreato merged commit 565f62b3ba into main 2026-11-16 08:30:18 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
kreato/yazi!74
No description provided.