Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat: improve desktop customization, streaming and performance diagnostics

Rach Pradhancecade4af411
diff --git a/README.md b/README.md
index 85ff4cb5..2788025b 100644
--- a/README.md
+++ b/README.md
@@ -35,79 +35,57 @@ curl -fsSL https://github.com/justrach/codegraff/releases/latest/download/instal
## The desktop app
-A native macOS window for graff: chat tabs, each backed by its own `graff acp`
-process, in a real app window instead of a browser tab. It is an AppKit
-`NSWindow` with a `WKWebView` in it, written in Zig against the ObjC runtime —
-no Electron.
-
-![The desktop app in a chat: workspace sidebar and chat history on the left, a transcript with collapsed thinking and tool rows in the middle, and a pinned-element strip above the composer](docs/images/native-chat.jpg)
-
-The sidebar holds workspaces and the chat library; the footer shows the graff
-session name so you can resume the same conversation from the CLI. Thinking and
-tool calls collapse into single rows.
-
-![The browser pane open beside the chat in Annotate mode, with a button on the page pinned, labelled with its role and name, and a note attached to it](docs/images/native-browser-annotate.jpg)
-
-The browser pane (experimental) shows a live Chrome tab belonging to the chat.
-In Annotate mode you click an element to pin it; the pin carries the element's
-role, accessible name, selector and box, plus your note, and rides along with
-your next message. The pane is [Kuri](https://github.com/justrach/kuri)'s
-managed headless Chrome, so it needs Kuri installed or `KURI_BIN` pointed at
-it; nothing starts until a pane is opened, a browser that sees no requests for
-`GRAFF_BROWSER_IDLE_MINS` (default 20) is stopped again, and the tree is
-restarted when it passes `GRAFF_BROWSER_MAX_RSS_MB` (default 3072).
-
-**What it is, before you download it.** The app is a window, not a bundle of
-the product: `Contents/` holds the shell binary and an icon, and nothing else.
-It renders the local UI, and that UI spawns `graff acp` per chat tab. So you
-need two things running before the window shows anything: the UI
-(`npm install && npm run dev` in `apps/native`) and a graff binary at
-`zig-out/bin/graff` — `zig build` at the repo root — or `GRAFF_BIN` pointing at
-one. With no dev server up, double-clicking the app gives WebKit's
-cannot-connect page.
-
-**Download.** Grab `Codegraff-macos.zip` from the
-[latest release](https://github.com/justrach/codegraff/releases/latest), unzip
-it, and drag `Codegraff.app` to Applications. macOS 13 or newer, Apple Silicon —
-the shipped binary is `arm64`-only. It is signed with a Developer ID under the
-hardened runtime and notarized and stapled by Apple, so there is no
-unidentified-developer block and no right-click-Open workaround; a freshly
-downloaded copy still gets macOS's ordinary "downloaded from the Internet"
-confirmation on first open.
-
-Launched from Finder the app inherits no environment, so it looks for a dev
-server on 127.0.0.1:3777, then 3000. `GRAFF_NATIVE_URL` applies only when the
-binary is started from a shell.
-
-**Building the shell.** `zig build` at the repo root builds the CLI, not the
-window. The window is `apps/native/desktop/build-app.sh` (icon, `Info.plist`,
-signing; `NOTARIZE=1` submits it to Apple, `INSTALL=1` puts it in
-`/Applications`), or, for a loose binary with no bundle:
+The current desktop preview uses Electron and embedded Chromium, with native
+macOS window controls and SwiftUI Activity and computer-use panels. Coding
+continues in `graff acp`; the window is a client of the same harness used by
+the terminal.
+
+![CodeGraff desktop in its dark theme, with a conversation and composer](docs/images/desktop-chat-dark.png)
+
+Chat tabs, searchable model selection, effort and fast controls, collapsed tool
+activity, and explicit working/finished/interrupted states keep the conversation
+readable. Appearance includes White, Black, Website and the official CodeGraff
+palette. Mention `$gui-theme` or `@gui-theme` in the GUI to create a custom theme.
+
+![CodeGraff palette with a resizable Changes panel beside the conversation](docs/images/desktop-review-codegraff.png)
+
+**Changes** shows local staged, unstaged and untracked edits, diffs, worktrees
+and recent commits. Drag its divider to give the review more room. The browser
+pane renders directly in Chromium and supports navigation, find, zoom and element
+pins. Optional macOS computer use exposes native app inspection and input after
+the user enables it and grants the operating system permissions.
+
+*Screenshots show the current GUI with scripted demonstration content. No private
+conversation or workspace data is included.*
+
+**Build and launch the preview** on Apple Silicon macOS 14+ with Bun, Zig and
+Xcode command-line tools installed:
+
+```sh
+./script/build_and_run.sh
+```
+
+The development bundle contains the production UI, Chromium, Bun, graff and the
+native bridge, and starts its own local server. It does not need a separate dev
+server or Kuri. This Electron preview is signed locally; release notarization and
+an Electron updater are separate distribution work. Previously published desktop
+assets may still use the legacy shell; see the release notes before downloading.
+
+**Profile and test without a model.** The Performance menu and desktop profiler
+tool record bounded, local measurement reports. Startup paint timing, streaming
+responsiveness, process resources and acceleration status are measured separately.
+No reports are uploaded automatically. From `apps/native`:
```sh
-zig build-exe apps/native/desktop/main.zig -O ReleaseSmall \
- -femit-bin=zig-out/bin/graff-native \
- -framework AppKit -framework WebKit
+bun run build
+bun run test:desktop
+bun run test:visual
+bun run test:performance
```
-**It updates itself.** Shortly after the window opens, on its own thread, it
-asks GitHub for the newest release and compares that tag with its own stamped
-version numerically, so 0.0.10 is newer than 0.0.9. It installs only after the
-download passes `codesign --verify --deep --strict`, has a Team ID equal to the
-running app's own, and is accepted by `spctl -a -t install`; then it asks once,
-with "Later" and "Update and restart". Any failure abandons the update and
-leaves the installed app alone. Both the API call and the download are under
-the same 20-second network timeout. Setting `GRAFF_NATIVE_NO_UPDATE` disables
-the check — any value, including empty; `=1` is the readable way to write it.
-The mechanism depends on the release carrying an asset whose name starts with
-`Codegraff` and ends with `.zip`, uploaded from a Mac: the tag-triggered
-workflow cross-compiles on Linux and can neither sign nor notarize. A release
-without that asset means installed apps find nothing and do nothing.
-
-**macOS only today.** The shell is AppKit and WebKit — `NSWindow` and
-`WKWebView` — and the packaging path uses `iconutil`, `codesign` and
-`notarytool` from Xcode's command line tools. On other platforms the same
-binary only prints the URL. The CLI runs on macOS, Linux and Windows.
+The visual and performance scenarios use production GUI components with scripted
+inputs and block engine/model API calls. See the [desktop guide](apps/native/electron/README.md)
+and [visual test guide](apps/native/electron/VISUAL-TESTS.md) for scope and limitations.
## What can I ask it?
diff --git a/TUI/engine.zig b/TUI/engine.zig
index 4ebc8771..42fd4ab5 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const builtin = @import("builtin");
+const types = @import("engine_types.zig");
const events_mod = @import("events.zig");
@@ -13,172 +14,31 @@ pub const Status = events_mod.Status;
pub const ModelChanged = events_mod.ModelChanged;
pub const Cost = events_mod.Cost;
-pub const Effort = enum { low, medium, high, xhigh, max, ultra };
-
-/// The session's permission policy. This is ENGINE state, not a badge: the
-/// turn backend maps it onto the harness's plan gate and approval policy
-/// (repl_glue.replTurnCb). Before #551 round 2 the TUI kept its own copy and
-/// the engine was never told, so a footer reading "Plan" sat over a turn that
-/// was writing files.
-pub const Mode = enum { normal, plan, always_approve };
-
-pub const Turn = struct {
- role: Role,
- text: []const u8,
- pub const Role = enum { user, assistant };
-};
-
-pub const Params = struct {
- effort: Effort = .medium,
- fast: bool = false,
- thinking: bool = false,
- ultracode: bool = false,
- /// Permission policy for this turn (Shift+Tab, Ctrl+O, /plan).
- mode: Mode = .normal,
- /// /strict — selects the strict system prompt on the turn's agent.
- strict: bool = false,
- goal: []const u8 = "",
-};
-
-/// Lock-free single-writer / single-reader preview buffer (same contract as
-/// the zigzag REPL stream). Overflow drops live bytes only.
-pub const StreamBuf = struct {
- buf: []u8 = &.{},
- len: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
-
- pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {
- const cur = self.len.load(.monotonic);
- if (cur >= self.buf.len) return;
- var n = @min(bytes.len, self.buf.len - cur);
- // Overflow drops the tail for good, so a clip must not land INSIDE a
- // codepoint: the missing bytes never arrive and the live row would
- // paint replacement garbage that persists for the rest of the turn.
- if (n < bytes.len) n = utf8Floor(bytes, n);
- if (n == 0) return;
- @memcpy(self.buf[cur .. cur + n], bytes[0..n]);
- self.len.store(cur + n, .release);
- }
-
- /// Largest k <= n where `s[0..k]` ends on a whole UTF-8 codepoint.
- fn utf8Floor(s: []const u8, n: usize) usize {
- if (n == 0 or n >= s.len) return n;
- var k = n;
- while (k > 0) : (k -= 1) {
- const b = s[k - 1];
- if (b < 0x80) return k; // ASCII byte ends a codepoint
- if (b >= 0xc0) { // lead byte: does its whole sequence fit?
- const len = std.unicode.utf8ByteSequenceLength(b) catch return k - 1;
- return if (k - 1 + len <= n) n else k - 1;
- }
- }
- return 0; // all continuation bytes: nothing whole to keep
- }
-
- pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {
- const n = self.len.load(.acquire);
- if (n == 0) return null;
- return gpa.dupe(u8, self.buf[0..n]) catch null;
- }
-};
-
-/// A turn backend gets the live text buffer AND the typed event queue (#551):
-/// prose streams into `stream` for the pending row's tail view, while every
-/// structured moment (tool call, outcome, refusal, notice, failover) is PUSHED
-/// as an event. The TUI used to recover the second kind by parsing the first,
-/// which is the defect this seam removes.
-pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf, events: *events_mod.Queue) ?[]const u8;
-/// How a seat is PAID FOR. The TUI never derives this — src/billing.zig owns
-/// the rule and the engine hands the answer over with the catalog, the same
-/// way it hands over the model names themselves.
-pub const CostClass = enum {
- plan,
- credits,
- api,
- local,
-
- pub fn badge(self: CostClass) []const u8 {
- return switch (self) {
- .plan => "plan",
- .credits => "credits",
- .api => "api",
- .local => "local",
- };
- }
-};
-
-/// One row of the model catalog. A bare name was ambiguous: the same model
-/// served by codex (a ChatGPT plan), codegraff (gateway credits) and openai (a
-/// metered key) drew three identical rows, and picking one resolved the
-/// provider by first-name-match rather than by the row the user chose.
-pub const ModelEntry = struct {
- name: []const u8,
- provider: []const u8 = "",
- /// False when this provider has no credential in this session. The row
- /// stays — knowing the seat EXISTS is the point — but it is dimmed.
- has_key: bool = false,
- cost: CostClass = .api,
-};
-
-/// What a switch actually landed on. The provider travels back with the model
-/// so the current-row marker can tell two same-named seats apart.
-pub const Picked = struct { model: []const u8, provider: []const u8 = "" };
-
-/// Switch to `name` ON `provider`. An empty `provider` means "the caller does
-/// not know one" (a hand-typed `/model <name>`) and asks the engine to route
-/// by name, which is what the picker used to be stuck doing for every pick.
-pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?Picked;
-pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
-/// Fill dest with a staged image path (return >0) or an error line (return <0).
-pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;
-/// Run a user-typed `!` shell line; return combined output (caller frees), the
-/// gate's refusal, or null when the harness could not produce either. `params`
-/// carries the session's policy because `!` goes through the same gate the
-/// model's bash tool does — a `!` under /plan must be refused (#551).
-pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, params: Params) ?[]const u8;
-/// Newline-joined repo-relative paths for @-search (caller frees), or null.
-pub const FilesFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
-/// Copy text to the system clipboard; true on success.
-pub const CopyFn = *const fn (turn_ctx: ?*anyopaque, text: []const u8) bool;
-/// Engine-owned history compaction. Fills `out` with gpa-owned note + turns
-/// (caller frees). Returns false when history is unchanged.
-pub const CompactOut = struct {
- note: []const u8 = "",
- turns: []Turn = &.{},
-};
-pub const CompactFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, out: *CompactOut) bool;
-
-/// The frontend just discarded part of its transcript. The engine owns the
-/// conversation the model actually sees (#551), so it has to be told: without
-/// this, /new left the whole old session in the request body and /rewind left
-/// a prompt the user had taken back.
-pub const HistoryOp = enum { reset, rewind };
-pub const HistoryFn = *const fn (turn_ctx: ?*anyopaque, op: HistoryOp) void;
-
-/// Host-side `/goal` verb. `.none` is a snapshot (strict/ultracode/rename):
-/// the host must not re-apply or mint a goal. Typed TUI `/goal` is the same
-/// retirable lifecycle as the line REPL — never a standing `--goal` (#716).
-pub const GoalOp = enum { none, set, clear, pause, unpause };
-
-pub const SessionState = struct {
- session_name: []const u8 = "",
- goal: []const u8 = "",
- strict: bool = false,
- ultracode: bool = false,
- goal_op: GoalOp = .none,
-};
-pub const StateFn = *const fn (turn_ctx: ?*anyopaque, state: SessionState) void;
-
-pub const ResumeOut = struct {
- turns: []Turn = &.{},
- session_name: []const u8 = "",
- goal: []const u8 = "",
- strict: bool = false,
- ultracode: bool = false,
- note: []const u8 = "",
-};
-pub const ResumeFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, spec: []const u8, out: *ResumeOut) bool;
-/// Newline-joined saved-session rows (`base\tlabel\tdesc`) for `/resume` (caller frees), or null.
-pub const SessionsFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
+pub const Effort = types.Effort;
+pub const Mode = types.Mode;
+pub const Turn = types.Turn;
+pub const Params = types.Params;
+pub const StreamBuf = types.StreamBuf;
+pub const TurnFn = types.TurnFn;
+pub const CostClass = types.CostClass;
+pub const ModelEntry = types.ModelEntry;
+pub const Picked = types.Picked;
+pub const ModelFn = types.ModelFn;
+pub const CancelFn = types.CancelFn;
+pub const PasteFn = types.PasteFn;
+pub const BashFn = types.BashFn;
+pub const FilesFn = types.FilesFn;
+pub const CopyFn = types.CopyFn;
+pub const CompactOut = types.CompactOut;
+pub const CompactFn = types.CompactFn;
+pub const HistoryOp = types.HistoryOp;
+pub const HistoryFn = types.HistoryFn;
+pub const GoalOp = types.GoalOp;
+pub const SessionState = types.SessionState;
+pub const StateFn = types.StateFn;
+pub const ResumeOut = types.ResumeOut;
+pub const ResumeFn = types.ResumeFn;
+pub const SessionsFn = types.SessionsFn;
pub const Job = struct {
thread: std.Thread = undefined,
@@ -351,32 +211,3 @@ pub fn jobRun(job: *Job) void {
job.result = reply;
job.done.store(true, .release);
}
-
-test "StreamBuf: append then snapshot, overflow is silent" {
- var buf: [8]u8 = undefined;
- var s: StreamBuf = .{ .buf = &buf };
- s.appendBytes("hello");
- const snap = s.snapshot(std.testing.allocator).?;
- defer std.testing.allocator.free(snap);
- try std.testing.expectEqualStrings("hello", snap);
- s.appendBytes(" world!!!!");
- try std.testing.expectEqual(@as(usize, 8), s.len.load(.acquire));
-}
-
-test "StreamBuf: an overflow clip lands on a codepoint boundary" {
- // The dropped tail never arrives, so a clip inside 🚀 would leave the live
- // row painting replacement garbage for the rest of the turn.
- var buf: [8]u8 = undefined;
- var s: StreamBuf = .{ .buf = &buf };
- s.appendBytes("ab");
- s.appendBytes("🚀🚀"); // 8 bytes: only the first fits whole
- const snap = s.snapshot(std.testing.allocator).?;
- defer std.testing.allocator.free(snap);
- try std.testing.expect(std.unicode.utf8ValidateSlice(snap));
- try std.testing.expectEqualStrings("ab🚀", snap);
- // A chunk that cannot contribute even one whole glyph writes nothing.
- var tiny: [2]u8 = undefined;
- var t: StreamBuf = .{ .buf = &tiny };
- t.appendBytes("日");
- try std.testing.expectEqual(@as(usize, 0), t.len.load(.acquire));
-}
diff --git a/TUI/engine_types.zig b/TUI/engine_types.zig
new file mode 100644
index 00000000..2ff1db35
--- /dev/null
+++ b/TUI/engine_types.zig
@@ -0,0 +1,199 @@
+//! Turn-backend value types and streaming buffer; no mutable frontend callbacks.
+const std = @import("std");
+const events_mod = @import("events.zig");
+
+pub const Effort = enum { low, medium, high, xhigh, max, ultra };
+
+/// The session's permission policy. This is ENGINE state, not a badge: the
+/// turn backend maps it onto the harness's plan gate and approval policy
+/// (repl_glue.replTurnCb). Before #551 round 2 the TUI kept its own copy and
+/// the engine was never told, so a footer reading "Plan" sat over a turn that
+/// was writing files.
+pub const Mode = enum { normal, plan, always_approve };
+
+pub const Turn = struct {
+ role: Role,
+ text: []const u8,
+ pub const Role = enum { user, assistant };
+};
+
+pub const Params = struct {
+ effort: Effort = .medium,
+ fast: bool = false,
+ thinking: bool = false,
+ ultracode: bool = false,
+ /// Permission policy for this turn (Shift+Tab, Ctrl+O, /plan).
+ mode: Mode = .normal,
+ /// /strict — selects the strict system prompt on the turn's agent.
+ strict: bool = false,
+ goal: []const u8 = "",
+};
+
+/// Lock-free single-writer / single-reader preview buffer (same contract as
+/// the zigzag REPL stream). Overflow drops live bytes only.
+pub const StreamBuf = struct {
+ buf: []u8 = &.{},
+ len: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
+
+ pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {
+ const cur = self.len.load(.monotonic);
+ if (cur >= self.buf.len) return;
+ var n = @min(bytes.len, self.buf.len - cur);
+ // Overflow drops the tail for good, so a clip must not land INSIDE a
+ // codepoint: the missing bytes never arrive and the live row would
+ // paint replacement garbage that persists for the rest of the turn.
+ if (n < bytes.len) n = utf8Floor(bytes, n);
+ if (n == 0) return;
+ @memcpy(self.buf[cur .. cur + n], bytes[0..n]);
+ self.len.store(cur + n, .release);
+ }
+
+ /// Largest k <= n where `s[0..k]` ends on a whole UTF-8 codepoint.
+ fn utf8Floor(s: []const u8, n: usize) usize {
+ if (n == 0 or n >= s.len) return n;
+ var k = n;
+ while (k > 0) : (k -= 1) {
+ const b = s[k - 1];
+ if (b < 0x80) return k; // ASCII byte ends a codepoint
+ if (b >= 0xc0) { // lead byte: does its whole sequence fit?
+ const len = std.unicode.utf8ByteSequenceLength(b) catch return k - 1;
+ return if (k - 1 + len <= n) n else k - 1;
+ }
+ }
+ return 0; // all continuation bytes: nothing whole to keep
+ }
+
+ pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {
+ const n = self.len.load(.acquire);
+ if (n == 0) return null;
+ return gpa.dupe(u8, self.buf[0..n]) catch null;
+ }
+};
+
+/// A turn backend gets the live text buffer AND the typed event queue (#551):
+/// prose streams into `stream` for the pending row's tail view, while every
+/// structured moment (tool call, outcome, refusal, notice, failover) is PUSHED
+/// as an event. The TUI used to recover the second kind by parsing the first,
+/// which is the defect this seam removes.
+pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf, events: *events_mod.Queue) ?[]const u8;
+/// How a seat is PAID FOR. The TUI never derives this — src/billing.zig owns
+/// the rule and the engine hands the answer over with the catalog, the same
+/// way it hands over the model names themselves.
+pub const CostClass = enum {
+ plan,
+ credits,
+ api,
+ local,
+
+ pub fn badge(self: CostClass) []const u8 {
+ return switch (self) {
+ .plan => "plan",
+ .credits => "credits",
+ .api => "api",
+ .local => "local",
+ };
+ }
+};
+
+/// One row of the model catalog. A bare name was ambiguous: the same model
+/// served by codex (a ChatGPT plan), codegraff (gateway credits) and openai (a
+/// metered key) drew three identical rows, and picking one resolved the
+/// provider by first-name-match rather than by the row the user chose.
+pub const ModelEntry = struct {
+ name: []const u8,
+ provider: []const u8 = "",
+ /// False when this provider has no credential in this session. The row
+ /// stays — knowing the seat EXISTS is the point — but it is dimmed.
+ has_key: bool = false,
+ cost: CostClass = .api,
+};
+
+/// What a switch actually landed on. The provider travels back with the model
+/// so the current-row marker can tell two same-named seats apart.
+pub const Picked = struct { model: []const u8, provider: []const u8 = "" };
+
+/// Switch to `name` ON `provider`. An empty `provider` means "the caller does
+/// not know one" (a hand-typed `/model <name>`) and asks the engine to route
+/// by name, which is what the picker used to be stuck doing for every pick.
+pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?Picked;
+pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
+/// Fill dest with a staged image path (return >0) or an error line (return <0).
+pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;
+/// Run a user-typed `!` shell line; return combined output (caller frees), the
+/// gate's refusal, or null when the harness could not produce either. `params`
+/// carries the session's policy because `!` goes through the same gate the
+/// model's bash tool does — a `!` under /plan must be refused (#551).
+pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, params: Params) ?[]const u8;
+/// Newline-joined repo-relative paths for @-search (caller frees), or null.
+pub const FilesFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
+/// Copy text to the system clipboard; true on success.
+pub const CopyFn = *const fn (turn_ctx: ?*anyopaque, text: []const u8) bool;
+/// Engine-owned history compaction. Fills `out` with gpa-owned note + turns
+/// (caller frees). Returns false when history is unchanged.
+pub const CompactOut = struct {
+ note: []const u8 = "",
+ turns: []Turn = &.{},
+};
+pub const CompactFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, out: *CompactOut) bool;
+
+/// The frontend just discarded part of its transcript. The engine owns the
+/// conversation the model actually sees (#551), so it has to be told: without
+/// this, /new left the whole old session in the request body and /rewind left
+/// a prompt the user had taken back.
+pub const HistoryOp = enum { reset, rewind };
+pub const HistoryFn = *const fn (turn_ctx: ?*anyopaque, op: HistoryOp) void;
+
+/// Host-side `/goal` verb. `.none` is a snapshot (strict/ultracode/rename):
+/// the host must not re-apply or mint a goal. Typed TUI `/goal` is the same
+/// retirable lifecycle as the line REPL — never a standing `--goal` (#716).
+pub const GoalOp = enum { none, set, clear, pause, unpause };
+
+pub const SessionState = struct {
+ session_name: []const u8 = "",
+ goal: []const u8 = "",
+ strict: bool = false,
+ ultracode: bool = false,
+ goal_op: GoalOp = .none,
+};
+pub const StateFn = *const fn (turn_ctx: ?*anyopaque, state: SessionState) void;
+
+pub const ResumeOut = struct {
+ turns: []Turn = &.{},
+ session_name: []const u8 = "",
+ goal: []const u8 = "",
+ strict: bool = false,
+ ultracode: bool = false,
+ note: []const u8 = "",
+};
+pub const ResumeFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, spec: []const u8, out: *ResumeOut) bool;
+/// Newline-joined saved-session rows (`base\tlabel\tdesc`) for `/resume` (caller frees), or null.
+pub const SessionsFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
+
+test "StreamBuf: append then snapshot, overflow is silent" {
+ var buf: [8]u8 = undefined;
+ var s: StreamBuf = .{ .buf = &buf };
+ s.appendBytes("hello");
+ const snap = s.snapshot(std.testing.allocator).?;
+ defer std.testing.allocator.free(snap);
+ try std.testing.expectEqualStrings("hello", snap);
+ s.appendBytes(" world!!!!");
+ try std.testing.expectEqual(@as(usize, 8), s.len.load(.acquire));
+}
+
+test "StreamBuf: an overflow clip lands on a codepoint boundary" {
+ // The dropped tail never arrives, so a clip inside 🚀 would leave the live
+ // row painting replacement garbage for the rest of the turn.
+ var buf: [8]u8 = undefined;
+ var s: StreamBuf = .{ .buf = &buf };
+ s.appendBytes("ab");
+ s.appendBytes("🚀🚀"); // 8 bytes: only the first fits whole
+ const snap = s.snapshot(std.testing.allocator).?;
+ defer std.testing.allocator.free(snap);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(snap));
+ try std.testing.expectEqualStrings("ab🚀", snap);
+ // A chunk that cannot contribute even one whole glyph writes nothing.
+ var tiny: [2]u8 = undefined;
+ var t: StreamBuf = .{ .buf = &tiny };
+ t.appendBytes("日");
+ try std.testing.expectEqual(@as(usize, 0), t.len.load(.acquire));
+}
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index a26ec7dd..b52d3eb4 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -7,6 +7,7 @@ import { NextRequest } from "next/server";
import type { AcpCommand } from "@/lib/acp";
import { AcpTransport } from "@/lib/acp-transport";
import { defaultRoot, resolveRoot } from "@/lib/server-root";
+import { prepareGuiPrompt } from "@/lib/gui-skill-context";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -259,13 +260,15 @@ export async function POST(req: NextRequest) {
return Response.json({ ok: true });
}
if (method === "session/prompt") {
+ if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });
+ const promptParams = await prepareGuiPrompt(body.params);
if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });
slot.streaming = true;
const encoder = new TextEncoder();
let cancelled = false;
const stream = new ReadableStream({
start(controller) {
- void slot.transport.request("session/prompt", { ...body.params, sessionId: slot.sessionId }, 24 * 60 * 60 * 1000,
+ void slot.transport.request("session/prompt", { ...promptParams, sessionId: slot.sessionId }, 24 * 60 * 60 * 1000,
line => { if (!cancelled) controller.enqueue(encoder.encode(`${line}\n`)); })
.then(() => { if (!cancelled) { cancelled = true; controller.close(); } })
.catch(error => { if (!cancelled) { cancelled = true; controller.error(error); } })
diff --git a/apps/native/app/api/fs/route.ts b/apps/native/app/api/fs/route.ts
index 0bde0a28..68b793bc 100644
--- a/apps/native/app/api/fs/route.ts
+++ b/apps/native/app/api/fs/route.ts
@@ -1,6 +1,8 @@
import { spawn } from "node:child_process";
-import { readdirSync, readFileSync, statSync } from "node:fs";
+import { readdirSync, createReadStream, statSync } from "node:fs";
import path from "node:path";
+import { Readable } from "node:stream";
+import { filePreview } from "@/lib/file-preview";
import { NextRequest } from "next/server";
import { resolveRoot } from "@/lib/server-root";
@@ -10,7 +12,6 @@ export const dynamic = "force-dynamic";
/** Heavy or generated trees that only bury the folders people navigate to. */
const HIDDEN = new Set([".git", "node_modules", ".next", ".zig-cache", "zig-out", ".DS_Store"]);
-const MAX_TEXT = 256 * 1024;
const IMAGE_TYPES: Record<string, string> = {
".png": "image/png",
@@ -126,25 +127,11 @@ export async function GET(req: NextRequest) {
// ?raw=1 streams the bytes themselves — how the pane shows images.
if (req.nextUrl.searchParams.get("raw")) {
const type = IMAGE_TYPES[path.extname(target).toLowerCase()] ?? "application/octet-stream";
- const bytes = readFileSync(target);
- return new Response(new Uint8Array(bytes), {
+ return new Response(Readable.toWeb(createReadStream(target)) as ReadableStream, {
headers: { "content-type": type, "cache-control": "no-store" },
});
}
- const buf = readFileSync(target);
- const head = buf.subarray(0, 8192);
- const binary = head.includes(0);
- const truncated = buf.length > MAX_TEXT;
- return Response.json({
- ok: true,
- root,
- path: relPath,
- dir: false,
- size: buf.length,
- binary,
- truncated,
- text: binary ? "" : buf.subarray(0, MAX_TEXT).toString("utf8"),
- });
+ return Response.json({ ok: true, root, path: relPath, dir: false, ...await filePreview(target) });
} catch (err) {
return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 404 });
}
diff --git a/apps/native/app/api/themes/route.ts b/apps/native/app/api/themes/route.ts
new file mode 100644
index 00000000..73d2dda5
--- /dev/null
+++ b/apps/native/app/api/themes/route.ts
@@ -0,0 +1,17 @@
+import { listThemes, saveTheme } from "@/lib/theme-files";
+import { themeLimit } from "@/lib/custom-themes";
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+export async function GET() {
+ try { return Response.json(await listThemes(), { headers: { "cache-control": "no-store" } }); }
+ catch { return Response.json({ error: "Could not read your themes folder." }, { status: 500 }); }
+}
+export async function POST(request: Request) {
+ const reader = request.body?.getReader(); if (!reader) return Response.json({ error: "Choose a theme JSON file." }, { status: 400 });
+ try {
+ let size = 0; const chunks: Uint8Array[] = [];
+ while (true) { const { done, value } = await reader.read(); if (done) break; size += value.length; if (size > themeLimit) { await reader.cancel(); return Response.json({ error: "Theme exceeds 16 KiB." }, { status: 413 }); } chunks.push(value); }
+ return Response.json(await saveTheme(JSON.parse(Buffer.concat(chunks).toString("utf8"))));
+ } catch (error) { return Response.json({ error: error instanceof Error ? error.message : "Could not import theme." }, { status: 400 }); }
+ finally { reader.releaseLock(); }
+}
diff --git a/apps/native/app/appearance.css b/apps/native/app/appearance.css
new file mode 100644
index 00000000..d6e6a8f0
--- /dev/null
+++ b/apps/native/app/appearance.css
@@ -0,0 +1,53 @@
+/* CodeGraff website palette. White and Black retain the neutral desktop tokens. */
+:root[data-theme="website"] {
+ --page: #fafaf8;
+ --canvas: #f1f3ef;
+ --surface: #ffffff;
+ --inset: #f5f6f2;
+ --hover: #edf1eb;
+ --hover-2: #e3eae2;
+ --ink: #18231e;
+ --ink-2: #526157;
+ --ink-3: #737f75;
+ --line: #e0e6de;
+ --line-strong: #cbd6cb;
+ --field: #f0f3ed;
+ --stripe: #18231e0d;
+ --stripe-bg: #f4f5f0;
+ --accent: #059669;
+ --accent-ink: #047857;
+ --accent-tint: #e3f3e9;
+ --green: #047857;
+ --green-tint: #e6f2e8;
+ --red: #b54735;
+ --red-tint: #f9ece6;
+}
+
+/* Official palette: paper, rice, ink, cobalt, coral and gold. */
+:root[data-theme="codegraff"] {
+ --page: #f6eedf;
+ --canvas: #eee4d3;
+ --surface: #fffaf0;
+ --inset: #f2e8d8;
+ --hover: #eae0cf;
+ --hover-2: #e0d4c1;
+ --ink: #1b1714;
+ --ink-2: #51483f;
+ --ink-3: #74685b;
+ --line: #d7cbb8;
+ --line-strong: #bbae99;
+ --field: #eee4d3;
+ --stripe: #1b17140d;
+ --stripe-bg: #f6eedf;
+ --accent: #2654d9;
+ --accent-ink: #2147b7;
+ --accent-tint: #e3e7f5;
+ --green: #486841;
+ --green-tint: #e4ebd9;
+ --red: #a83f2d;
+ --red-tint: #f2ddd2;
+ --orange: #96601c;
+ --orange-tint: #f9e5c2;
+ --brand-coral: #d45a43;
+ --brand-gold: #f7a63b;
+}
diff --git a/apps/native/app/layout.tsx b/apps/native/app/layout.tsx
index dfeac9d2..46e13b79 100644
--- a/apps/native/app/layout.tsx
+++ b/apps/native/app/layout.tsx
@@ -1,26 +1,27 @@
import type { Metadata } from "next";
-import { Inter, JetBrains_Mono } from "next/font/google";
+import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
+import "./appearance.css";
+import { appearanceScript } from "@/lib/appearance";
import { ThemeSync } from "@/components/site/ThemeSync";
import DesktopTitlebar from "@/components/site/DesktopTitlebar";
import { BrowserWarm } from "@/components/site/BrowserWarm";
-const inter = Inter({
+const inter = Geist({
subsets: ["latin"],
variable: "--font-inter",
});
-const mono = JetBrains_Mono({
+const mono = Geist_Mono({
subsets: ["latin"],
variable: "--font-mono-face",
});
export const metadata: Metadata = {
title: "Codegraff",
- description: "Native graff harness — Beautiful UI primitives in a merjs desktop shell.",
+ description: "CodeGraff desktop workspace.",
};
-const themeScript = `(function(){try{var t=localStorage.getItem("bui-theme");document.documentElement.classList.toggle("dark",t!=="light")}catch(e){document.documentElement.classList.add("dark")}})()`;
export default function RootLayout({
children,
@@ -28,7 +29,7 @@ export default function RootLayout({
return (
<html lang="en" suppressHydrationWarning>
<head>
- <script dangerouslySetInnerHTML={{ __html: themeScript }} />
+ <script dangerouslySetInnerHTML={{ __html: appearanceScript }} />
</head>
<body className={`${inter.variable} ${mono.variable} font-sans`}>
<ThemeSync />
diff --git a/apps/native/app/visual-tests/page.tsx b/apps/native/app/visual-tests/page.tsx
new file mode 100644
index 00000000..43bfb258
--- /dev/null
+++ b/apps/native/app/visual-tests/page.tsx
@@ -0,0 +1,7 @@
+import { notFound } from "next/navigation";
+import TurnFixture from "./turn-fixture";
+export const dynamic = "force-dynamic";
+export default function VisualTests() {
+ if (process.env.GRAFF_VISUAL_TESTS !== "1") notFound();
+ return <TurnFixture />;
+}
diff --git a/apps/native/app/visual-tests/turn-fixture.tsx b/apps/native/app/visual-tests/turn-fixture.tsx
new file mode 100644
index 00000000..ffa65422
--- /dev/null
+++ b/apps/native/app/visual-tests/turn-fixture.tsx
@@ -0,0 +1,29 @@
+"use client";
+import { useState } from "react";
+import { AssistantBody } from "@/components/site/ChatBubbles";
+import { emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
+import { applyAppearance, type Appearance } from "@/lib/appearance";
+export const cases = ["starting", "thinking", "writing", "running", "waiting", "done", "stopped", "error", "missing-result"] as const;
+function fixture(name: typeof cases[number]): AssistantTurn {
+ const now = Date.now();
+ const turn: AssistantTurn = { ...emptyTurn(), startedAt: now - 40000, lastUpdateAt: now, connected: name !== "starting", text: "Preparing a theme preview with readable text and a distinct accent.", status: "streaming", tools: [] };
+ if (name === "starting" || name === "thinking") { turn.text = ""; turn.status = "thinking"; turn.activityKind = "agent_thought_chunk"; }
+ if (name === "writing") turn.activityKind = "agent_message_chunk";
+ if (["running", "waiting", "missing-result", "error"].includes(name)) turn.tools = [{ id: "fixture-tool", name: "Check palette", icon: "run", chip: "palette.json", status: name === "waiting" ? "ok" : "running", detail: [{ text: "Scripted tool output" }], atChars: 0, startedAt: now - 5000 }];
+ if (name === "waiting") turn.lastUpdateAt = now - 25000;
+ if (name === "error") return finishAcpTurn({ ...turn, status: "error", error: "The connection ended before the turn completed." });
+ if (name === "stopped") return finishAcpTurn({ ...turn, stopReason: "cancelled" });
+ return name === "done" || name === "missing-result" ? finishAcpTurn(turn) : turn;
+}
+export default function TurnFixture() {
+ const [name, setName] = useState<typeof cases[number]>("starting");
+ const [turn, setTurn] = useState(() => fixture("starting"));
+ return <main className="flex h-screen flex-col bg-page text-ink" data-visual-fixture>
+ <nav aria-label="Fixture scenarios" className="flex flex-wrap gap-2 border-b border-line p-3">
+ {cases.map(value => <button key={value} data-case={value} onClick={() => { setName(value); setTurn(fixture(value)); }} className="rounded bg-field px-2 py-1 text-xs">{value}</button>)}
+ {(["light", "dark", "codegraff"] as Appearance[]).map(theme => <button key={theme} data-theme-choice={theme} onClick={() => applyAppearance(theme)} className="rounded bg-field px-2 py-1 text-xs">{theme}</button>)}
+ </nav>
+ <div className="min-h-0 flex-1 overflow-auto px-6 py-8"><div className="mx-auto max-w-[720px]" data-fixture-transcript><AssistantBody key={name} turn={turn} following={false} /></div></div>
+ <div data-fixture-composer className="mx-auto mb-5 w-[calc(100%-48px)] max-w-[720px] rounded-xl border border-line bg-surface p-4 text-sm text-ink-3">{turn.status === "streaming" || turn.status === "thinking" ? "Queue a follow-up…" : "Follow up"}</div>
+ </main>;
+}
diff --git a/apps/native/components/primitives/EffortPicker.module.css b/apps/native/components/primitives/EffortPicker.module.css
index 78ac1f6f..81e2963a 100644
--- a/apps/native/components/primitives/EffortPicker.module.css
+++ b/apps/native/components/primitives/EffortPicker.module.css
@@ -14,7 +14,7 @@
.fill {
height: 100%;
border-radius: inherit;
- background: #3783fa;
+ background: var(--accent);
}
.stops {
position: absolute;
@@ -64,6 +64,6 @@
border: 1px solid rgb(0 0 0 / 10%);
box-shadow: 0 1px 3px rgb(0 0 0 / 12%);
}
-.range:focus-visible { outline: 2px solid #3783fa; outline-offset: 4px; }
+.range:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
.slider:has(.range:disabled) { opacity: .5; }
.range:disabled { cursor: wait; }
diff --git a/apps/native/components/primitives/ModelEffortButtons.tsx b/apps/native/components/primitives/ModelEffortButtons.tsx
index 984837f9..cedd112f 100644
--- a/apps/native/components/primitives/ModelEffortButtons.tsx
+++ b/apps/native/components/primitives/ModelEffortButtons.tsx
@@ -55,9 +55,9 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo
const progress = levels.length > 1 ? draft / (levels.length - 1) : 0;
const displayName = model.name.replace(/^gpt-/i, "GPT-").replace(/-(astra|sol|terra|luna)$/i, (_, name: string) => ` ${name[0].toUpperCase()}${name.slice(1)}`);
return <div className={`flex min-w-0 items-center gap-0.5 ${wide ? "col-start-2 row-start-2 justify-self-start" : "col-start-3 row-start-1"}`}>
- <button ref={buttonRef} type="button" aria-expanded={modelOpen} aria-label="Choose model" disabled={saving} onClick={openModel}
+ <button ref={buttonRef} type="button" aria-expanded={modelOpen} aria-label="Choose model" disabled={saving || busy} onClick={openModel}
className={`flex h-7 min-w-0 items-center gap-1 px-1.5 text-[12px] font-medium text-ink-2 hover:bg-hover hover:text-ink ${pill ? "rounded-full" : "rounded-lg"}`}>
- {model.fast && model.fastSupported && <span className="text-blue-500 [&_svg]:size-3.5" aria-label="Fast mode enabled"><Bolt filled /></span>}
+ {model.fast && model.fastSupported && <span className="text-accent [&_svg]:size-3.5" aria-label="Fast mode enabled"><Bolt filled /></span>}
<span className="truncate">{displayName}</span><Chevron />
</button>
{levels.length > 0 && <button ref={effortButton} type="button" aria-label="Select effort" aria-expanded={open} onClick={show}
@@ -68,8 +68,8 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo
<button type="button" aria-label="Fast mode" aria-pressed={!!model.fast} disabled={blocked || !model.fastSupported}
title={model.fastSupported ? "Priority service for lower latency; may use more of your allowance" : "Fast mode is available for Codex models"}
onClick={() => void change(`/fast ${model.fast ? "off" : "on"}`)}
- className={`flex size-8 shrink-0 items-center justify-center rounded-[10px] transition-colors disabled:opacity-30 ${model.fast ? "bg-blue-500/10 text-blue-500" : "text-ink-3 hover:bg-hover"}`}><Bolt filled={!!model.fast} /></button>
- <div className="min-w-0 text-center"><div className="text-[17px] font-medium leading-6 text-blue-500">{labels[levels[draft]] ?? levels[draft]}</div><div className="mt-0.5 truncate text-[13px] leading-5 text-ink-3">{saving ? <span role="status">Saving…</span> : displayName}</div></div>
+ className={`flex size-8 shrink-0 items-center justify-center rounded-[10px] transition-colors disabled:opacity-30 ${model.fast ? "bg-accent-tint text-accent" : "text-ink-3 hover:bg-hover"}`}><Bolt filled={!!model.fast} /></button>
+ <div className="min-w-0 text-center"><div className="text-[17px] font-medium leading-6 text-accent">{labels[levels[draft]] ?? levels[draft]}</div><div className="mt-0.5 truncate text-[13px] leading-5 text-ink-3">{saving ? <span role="status">Saving…</span> : displayName}</div></div>
<button type="button" aria-label="Reset effort to medium" title="Reset effort to medium" disabled={blocked || !levels.includes("medium")} onClick={() => { setDraft(levels.indexOf("medium")); void change("/effort medium"); }} className="flex size-8 shrink-0 items-center justify-center rounded-lg text-ink-3 hover:bg-hover disabled:opacity-30"><svg aria-hidden="true" width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M4 10a8 8 0 1 1 0 5M4 4v6h6" /></svg></button>
</div>
<div className={styles.slider}>
@@ -79,7 +79,7 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo
onChange={event => setDraft(Number(event.target.value))} onPointerUp={apply} onKeyUp={apply}
className={styles.range} />
</div>
- {error && <p role="alert" className="mt-2 text-xs text-red-500">{error}</p>}
+ {error && <p role="alert" className="mt-2 text-xs text-red">{error}</p>}
</div>, document.body)}
</div>;
}
diff --git a/apps/native/components/primitives/ModelPicker.tsx b/apps/native/components/primitives/ModelPicker.tsx
new file mode 100644
index 00000000..7f306b9a
--- /dev/null
+++ b/apps/native/components/primitives/ModelPicker.tsx
@@ -0,0 +1,88 @@
+"use client";
+import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
+import { createPortal } from "react-dom";
+import type { ModelChoice } from "@/lib/acp-client";
+
+type Props = {
+ models: ModelChoice[]; selected: ModelChoice; anchor: RefObject<HTMLButtonElement | null>;
+ onSelect(model: ModelChoice): void; onClose(): void;
+};
+export default function ModelPicker({ models, selected, anchor, onSelect, onClose }: Props) {
+ const [query, setQuery] = useState("");
+ const [active, setActive] = useState(0);
+ const [position, setPosition] = useState<{ left: number; top: number; width: number; height: number } | null>(null);
+ const panel = useRef<HTMLDivElement>(null);
+ const list = useRef<HTMLDivElement>(null);
+ const search = useRef<HTMLInputElement>(null);
+ const keyboard = useRef(false);
+ const focused = useRef(false);
+ const id = useId();
+ const callbacks = useRef({ onSelect, onClose }); callbacks.current = { onSelect, onClose };
+ const shown = useMemo(() => {
+ const terms = query.toLowerCase().trim().split(/\s+/).filter(Boolean);
+ if (terms.length) return models.filter(model => terms.every(term => `${model.name} ${model.tag ?? ""} ${model.provider ?? ""}`.toLowerCase().includes(term)));
+ // The current choice is immediately visible; other models retain graff's order.
+ return [selected, ...models.filter(model => model.key !== selected.key)];
+ }, [models, query, selected]);
+ useLayoutEffect(() => {
+ const place = () => {
+ const rect = anchor.current?.getBoundingClientRect(); if (!rect) return;
+ const margin = 12, safeTop = document.documentElement.dataset.desktop === "true" ? 48 : margin;
+ const width = Math.min(360, window.innerWidth - margin * 2);
+ const above = Math.max(0, rect.top - safeTop - 8), below = Math.max(0, window.innerHeight - rect.bottom - margin - 8);
+ const up = above >= Math.min(420, below);
+ const maxHeight = Math.min(420, up ? above : below);
+ const height = Math.min(maxHeight, 125 + Math.max(1, models.length) * 44);
+ setPosition({ left: Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin)),
+ top: up ? Math.max(safeTop, rect.top - height - 8) : rect.bottom + 8, width, height });
+ };
+ place();
+ const scroll = (event: Event) => { if (!panel.current?.contains(event.target as Node)) place(); };
+ window.addEventListener("resize", place); document.addEventListener("scroll", scroll, true);
+ return () => { window.removeEventListener("resize", place); document.removeEventListener("scroll", scroll, true); };
+ }, [anchor, models.length]);
+ useLayoutEffect(() => { if (position && !focused.current) { search.current?.focus({ preventScroll: true }); focused.current = true; } }, [position]);
+ useEffect(() => {
+ const outside = (event: PointerEvent) => {
+ if (!panel.current?.contains(event.target as Node) && !anchor.current?.contains(event.target as Node)) callbacks.current.onClose();
+ };
+ document.addEventListener("pointerdown", outside);
+ return () => document.removeEventListener("pointerdown", outside);
+ }, [anchor]);
+ useLayoutEffect(() => {
+ if (!keyboard.current) return;
+ keyboard.current = false;
+ const viewport = list.current, row = viewport?.children[active] as HTMLElement | undefined;
+ if (!viewport || !row) return;
+ if (row.offsetTop < viewport.scrollTop) viewport.scrollTop = row.offsetTop;
+ else if (row.offsetTop + row.offsetHeight > viewport.scrollTop + viewport.clientHeight) viewport.scrollTop = row.offsetTop + row.offsetHeight - viewport.clientHeight;
+ }, [active]);
+ const close = () => { callbacks.current.onClose(); anchor.current?.focus({ preventScroll: true }); };
+ return createPortal(<div ref={panel} role="dialog" aria-label="Choose a model" className="fixed z-[200] flex flex-col overflow-hidden rounded-xl border border-line bg-surface shadow-overlay"
+ style={{ ...position, visibility: position ? "visible" : "hidden" }} onKeyDown={event => {
+ event.stopPropagation();
+ if (event.key === "Escape") { event.preventDefault(); close(); }
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); keyboard.current = true; setActive(index => Math.max(0, Math.min(shown.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)))); }
+ if (event.key === "Enter" && event.target === search.current && shown[active]) { event.preventDefault(); callbacks.current.onSelect(shown[active]); }
+ if (event.key === "Tab") {
+ const buttons = [search.current, ...Array.from(panel.current?.querySelectorAll<HTMLButtonElement>('button:not([role="option"])') ?? [])].filter(Boolean) as HTMLElement[];
+ const index = buttons.indexOf(document.activeElement as HTMLElement);
+ event.preventDefault(); buttons[(index + (event.shiftKey ? buttons.length - 1 : 1)) % buttons.length]?.focus();
+ }
+ }}>
+ <div className="flex shrink-0 items-center justify-between px-3 pt-2.5 pb-2"><strong className="text-xs font-medium">Model</strong><button aria-label="Close model picker" onClick={close} className="flex size-6 items-center justify-center rounded text-ink-3 hover:bg-hover">×</button></div>
+ <div className="shrink-0 border-b border-line px-3 pb-2.5"><input ref={search} role="combobox" aria-label="Filter models" aria-expanded="true" aria-controls={`${id}-list`} aria-activedescendant={shown[active] ? `${id}-${active}` : undefined} aria-autocomplete="list"
+ placeholder="Search models or providers…" value={query} onChange={event => { setQuery(event.target.value); setActive(0); if (list.current) list.current.scrollTop = 0; }}
+ className="h-8 w-full rounded-md border border-line bg-field px-2.5 text-xs text-ink outline-accent placeholder:text-ink-3" /></div>
+ <div ref={list} id={`${id}-list`} role="listbox" aria-label="Available models" className="relative min-h-0 flex-1 overflow-y-auto overscroll-contain p-1.5">
+ {shown.map((model, index) => <button id={`${id}-${index}`} key={model.key} role="option" aria-selected={model.key === selected.key} tabIndex={-1}
+ title={`${model.name}${model.tag ? ` · ${model.tag}` : ""}`} onPointerMove={() => setActive(index)} onMouseDown={event => event.preventDefault()} onClick={() => callbacks.current.onSelect(model)}
+ className={`flex min-h-11 w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left ${index === active ? "bg-hover" : "hover:bg-hover"}`}>
+ <span className="min-w-0 flex-1"><span className="block truncate text-[13px] font-medium text-ink">{model.name}</span><span className="block truncate text-[10px] text-ink-3">{model.tag ?? model.provider ?? "Available"}</span></span>
+ {model.key === selected.key && <span className="shrink-0 text-[10px] text-accent-ink">Current ✓</span>}
+ </button>)}
+ {!shown.length && <p role="status" className="px-3 py-6 text-center text-xs text-ink-3">No matching models. Try another name or provider.</p>}
+ </div>
+ <div className="flex shrink-0 justify-between border-t border-line px-3 py-2 text-[10px] text-ink-3"><span>{shown.length} {shown.length === 1 ? "model" : "models"}</span><span>↑↓ to browse · Enter to select</span></div>
+ </div>, document.body);
+}
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index 13267765..9296c5eb 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -1,5 +1,8 @@
"use client";
+import { parseComposerToken as parseToken, guiSkillRows } from "@/lib/gui-skills";
+import { Icon, GLYPHS, BRANDS, SOURCES, DEMO_COMMANDS, MODELS, FILES, DICTATION, AUTO_STEPS } from "./prompt-demo";
+import ModelPicker from "./ModelPicker";
import ModelEffortButtons from "./ModelEffortButtons";
import type { ModelChoice } from "@/lib/acp-client";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -34,134 +37,6 @@ const RAINBOW = accentChain([
* Variants: Rounded (card radius) · Pill (full radius).
* ───────────────────────────────────────────────────────── */
-function Icon({ children, size = 15, strokeWidth = 1.8 }: { children: React.ReactNode; size?: number; strokeWidth?: number }) {
- return (
- <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
- {children}
- </svg>
- );
-}
-
-const GLYPHS: Record<string, React.ReactNode> = {
- clip: <path d="m21.4 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48" />,
- chart: <path d="M4 20V10M10 20V4M16 20v-7M22 20H2" />,
- layers: <g><path d="M12 2 2 7l10 5 10-5-10-5z" /><path d="M2 17l10 5 10-5M2 12l10 5 10-5" /></g>,
- globe: <g><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></g>,
- file: <g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></g>,
-};
-
-/* real product marks, inline so the file stays self-contained */
-const BRANDS: Record<string, React.ReactNode> = {
- figma: (
- <svg width="11" height="16" viewBox="0 0 38 57" aria-hidden="true">
- <path d="M9.5 57A9.5 9.5 0 0 0 19 47.5V38H9.5a9.5 9.5 0 0 0 0 19z" fill="#0ACF83" />
- <path d="M0 28.5A9.5 9.5 0 0 1 9.5 19H19v19H9.5A9.5 9.5 0 0 1 0 28.5z" fill="#A259FF" />
- <path d="M0 9.5A9.5 9.5 0 0 1 9.5 0H19v19H9.5A9.5 9.5 0 0 1 0 9.5z" fill="#F24E1E" />
- <path d="M19 0h9.5a9.5 9.5 0 1 1 0 19H19V0z" fill="#FF7262" />
- <path d="M38 28.5a9.5 9.5 0 1 1-19 0 9.5 9.5 0 0 1 19 0z" fill="#1ABCFE" />
- </svg>
- ),
- slack: (
- <svg width="15" height="15" viewBox="0 0 127 127" aria-hidden="true">
- <path d="M27.2 80c0 7.3-5.9 13.2-13.2 13.2C6.7 93.2.8 87.3.8 80c0-7.3 5.9-13.2 13.2-13.2h13.2V80zm6.6 0c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2v33c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V80z" fill="#E01E5A" />
- <path d="M47 27.2c-7.3 0-13.2-5.9-13.2-13.2C33.8 6.7 39.7.8 47 .8c7.3 0 13.2 5.9 13.2 13.2v13.2H47zm0 6.7c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H13.9C6.6 60.3.7 54.4.7 47.1c0-7.3 5.9-13.2 13.2-13.2H47z" fill="#36C5F0" />
- <path d="M99.9 47.1c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H99.9V47.1zm-6.6 0c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V13.9C66.9 6.6 72.8.7 80.1.7c7.3 0 13.2 5.9 13.2 13.2v33.2z" fill="#2EB67D" />
- <path d="M80.1 99.8c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V99.8h13.2zm0-6.6c-7.3 0-13.2-5.9-13.2-13.2 0-7.3 5.9-13.2 13.2-13.2h33.1c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H80.1z" fill="#ECB22E" />
- </svg>
- ),
- gmail: (
- <svg width="15" height="12" viewBox="0 0 256 193" aria-hidden="true">
- <path d="M58.182 192.05V93.14L27.507 65.077 0 49.504v125.091c0 9.658 7.825 17.455 17.455 17.455h40.727Z" fill="#4285F4" />
- <path d="M197.818 192.05h40.727c9.659 0 17.455-7.826 17.455-17.455V49.505l-31.156 17.837-27.026 25.798v98.91Z" fill="#34A853" />
- <path d="m58.182 93.14-4.174-38.647 4.174-36.989L128 69.868l69.818-52.364 4.669 34.992-4.669 40.644L128 145.504 58.182 93.14Z" fill="#EA4335" />
- <path d="M197.818 17.504V93.14L256 49.504V26.231c0-21.585-24.64-33.89-41.89-20.945l-16.292 12.218Z" fill="#FBBC04" />
- <path d="m0 49.504 26.759 20.07L58.182 93.14V17.504L41.89 5.286C24.61-7.66 0 4.646 0 26.23v23.273Z" fill="#C5221F" />
- </svg>
- ),
-};
-
-type Source = {
- key: string;
- name: string;
- desc: string;
- glyph?: string;
- brand?: string;
- attach?: boolean;
- connect?: boolean;
-};
-
-const SOURCES: Source[] = [
- { key: "attach", name: "Add photos & files", desc: "Upload from your computer", glyph: "clip", attach: true },
- { key: "scoop", name: "Scoop Data", desc: "Sales & churn metrics", glyph: "chart" },
- { key: "flavors", name: "Flavor records", desc: "26 makers, tags, links", glyph: "layers" },
- { key: "web", name: "Web search", desc: "Real-time news and info", glyph: "globe" },
- { key: "figma", name: "Figma", desc: "Design-to-code workflows", brand: "figma" },
- { key: "slack", name: "Slack", desc: "Read and manage Slack", brand: "slack" },
- { key: "gmail", name: "Gmail", desc: "Read and manage Gmail", brand: "gmail", connect: true },
-];
-
-/* The self-running walkthrough types "/" and glides through rows, so it
- * needs something to show. A live surface is handed the agent's real set and
- * never falls back to these — an invented command must not reach a console
- * where someone could run it. */
-const DEMO_COMMANDS: AcpCommand[] = [
- { name: "compare", description: "Flavor vs. last summer" },
- { name: "churn-plan", description: "Draft a churn schedule" },
- { name: "restock", description: "Build a reorder list" },
- { name: "draft-email", description: "Write a supplier email" },
- { name: "summarize", description: "Digest the thread so far" },
-];
-
-const MODELS = [
- { key: "sprinkles-5", name: "Sprinkles 5", tag: "Flagship" },
- { key: "vanilla-1", name: "Vanilla 1", tag: "Basic" },
- { key: "freezer-burn", name: "Freezer Burn 0.4", tag: "Stale" },
-];
-
-const FILES = ["flavor-chart.png", "summer-menu.pdf", "pos-export.csv"];
-const DICTATION = "Compare pistachio weekends to last summer";
-
-/* self-running demo: walk the @ menu, then the / menu, and repeat.
- * Any pointer or key interaction hands control to the user. */
-const AUTO_STEPS: {
- draft: string;
- active?: number;
- connect?: boolean;
- modelOpen?: boolean;
- model?: string;
- hold: number;
-}[] = [
- { draft: "", connect: false, model: "vanilla-1", hold: 1100 },
- { draft: "@", active: 0, hold: 900 },
- { draft: "@", active: 1, hold: 620 },
- { draft: "@", active: 4, hold: 620 },
- { draft: "@", active: 6, hold: 700 },
- { draft: "@", active: 6, connect: true, hold: 1000 },
- { draft: "", hold: 700 },
- { draft: "/", active: 0, hold: 900 },
- { draft: "/", active: 1, hold: 620 },
- { draft: "/", active: 3, hold: 1000 },
- { draft: "", hold: 800 },
- // open the model picker and upgrade to the flagship → rainbow sweep
- { draft: "", modelOpen: true, hold: 1200 },
- { draft: "", model: "sprinkles-5", hold: 2400 },
- { draft: "", hold: 900 },
-];
-
-/* The last @word or /word being typed, if any. An @ query may carry path
- * separators and dots, because narrowing by directory is how anyone finds a
- * file in a large tree; a slash command never contains either. */
-function parseToken(draft: string): { kind: "at" | "slash"; query: string; start: number } | null {
- const match = /(^|\s)(?:@([\w./-]*)|\/([\w-]*))$/.exec(draft);
- if (!match) return null;
- const at = match[2] !== undefined;
- return {
- kind: at ? "at" : "slash",
- query: (at ? match[2] : match[3]).toLowerCase(),
- start: match.index + match[1].length,
- };
-}
-
export type PromptModel = ModelChoice;
export default function PromptBar({
@@ -228,6 +103,7 @@ export default function PromptBar({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [modelKey, models]);
const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [uploads, setUploads] = useState(0);
const [attachError, setAttachError] = useState<string | null>(null);
const [dragging, setDragging] = useState(false);
/* Workspace files matching the current @ query — live surfaces only. */
@@ -241,20 +117,12 @@ export default function PromptBar({
const wide = expanded || tall;
const [rowBox, setRowBox] = useState<{ top: number; height: number } | null>(null);
const [engaged, setEngaged] = useState(false);
- const [modelBox, setModelBox] = useState<{ top: number; height: number } | null>(null);
- const [modelHovered, setModelHovered] = useState<number | null>(null);
- const [modelQuery, setModelQuery] = useState("");
- const [modelMenuLeft, setModelMenuLeft] = useState(0);
- const [modelMenuBottom, setModelMenuBottom] = useState(0);
- const [modelMenuMaxH, setModelMenuMaxH] = useState(560);
- const composerAnchorRef = useRef<HTMLDivElement>(null);
const controlsRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const measureRef = useRef<HTMLSpanElement>(null);
const modelRef = useRef<HTMLButtonElement>(null);
const rowRefs = useRef<(HTMLButtonElement | null)[]>([]);
- const modelRowRefs = useRef<(HTMLButtonElement | null)[]>([]);
const glimmRef = useRef<HTMLCanvasElement>(null);
const shaderRef = useRef<ReturnType<typeof createShader> | null>(null);
const sweepingRef = useRef(false);
@@ -273,7 +141,7 @@ export default function PromptBar({
}, [commands, demo]);
const token = dismissed ? null : parseToken(draft);
- const menu: "at" | "slash" | null = plusOpen ? "at" : token?.kind ?? null;
+ const menu: "at" | "slash" | "skill" | null = plusOpen ? "at" : token?.kind ?? null;
const query = plusOpen ? "" : token?.query ?? "";
/* The @ picker searches the workspace. Debounced, and every in-flight
@@ -315,10 +183,10 @@ export default function PromptBar({
* an invented data source is worse than an empty menu. */
const atRows = demo
? SOURCES.filter((s) => s.name.toLowerCase().includes(query))
- : [SOURCES[0], ...fileRows];
+ : [...guiSkillRows(query), SOURCES[0], ...fileRows];
const rows: { key: string; name: string; desc: string }[] =
- menu === "at"
+ menu === "skill" ? guiSkillRows(query) : menu === "at"
? atRows
: menu === "slash"
? slashRows.filter((c) => c.name.slice(1).startsWith(query))
@@ -336,46 +204,6 @@ export default function PromptBar({
if (target) setRowBox({ top: target.offsetTop, height: target.offsetHeight });
}, [menu, query, active, connected, rows.length]);
- /* same gliding highlight in the model menu — floats to the hovered
- * row, falling back to the currently-selected model */
- const modelFilter = modelQuery.trim().toLowerCase();
- const shownModels = modelFilter
- ? catalog.filter(
- (m) => m.name.toLowerCase().includes(modelFilter) || (m.tag ?? "").toLowerCase().includes(modelFilter),
- )
- : catalog;
- const modelIndex = shownModels.findIndex((m) => m.key === model.key);
- useLayoutEffect(() => {
- if (!modelOpen) return;
- const target = modelRowRefs.current[modelHovered ?? modelIndex];
- if (target) {
- setModelBox({ top: target.offsetTop, height: target.offsetHeight });
- /* 40+ authenticated models: opening far from the current selection
- * hid it off-screen — bring it into view, but never fight the mouse */
- if (modelHovered === null) target.scrollIntoView({ block: "nearest" });
- }
- }, [modelOpen, modelHovered, modelIndex, modelFilter]);
-
- /* The menu is outside the clipped composer, so align it to the model
- * trigger by measurement instead of pinning it to the far-right edge. */
- useLayoutEffect(() => {
- if (!modelOpen || !composerAnchorRef.current || !modelRef.current) return;
- const anchorRect = composerAnchorRef.current.getBoundingClientRect();
- const triggerRect = modelRef.current.getBoundingClientRect();
- setModelMenuLeft(Math.max(0, Math.min(triggerRect.left - anchorRect.left, anchorRect.width - 176)));
- setModelMenuBottom(anchorRect.bottom - triggerRect.top + 8);
- // The menu grows upward from the trigger; without this cap a 40-model
- // list runs past the viewport top and clips its own filter input.
- setModelMenuMaxH(Math.max(220, Math.min(560, triggerRect.top - 20)));
- }, [modelOpen, wide, model.name]);
-
- useEffect(() => {
- if (!modelOpen) {
- setModelHovered(null);
- setModelQuery("");
- }
- }, [modelOpen]);
-
/* Build the shader with a pinned hue phase. createShader seeds its
* internal hueShift from Math.random(), which made the sweep a different
* colour on every reload — pin it so the rainbow is identical each time. */
@@ -438,7 +266,7 @@ export default function PromptBar({
const selectModel = (next: PromptModel) => {
setModel(next);
setModelOpen(false);
- onModelChange?.(next.key);
+ if (next.key !== model.key) onModelChange?.(next.key);
if (next.key === "sprinkles-5") celebrate();
};
@@ -458,18 +286,17 @@ export default function PromptBar({
return () => clearTimeout(t);
}, [auto, autoStep]);
- /* dictation resolves after a beat, like a real transcript landing */
+ /* The simulated transcript is confined to the component demo. */
useEffect(() => {
- if (!listening) return;
+ if (!demo || !listening) return;
const t = setTimeout(() => {
setDraft((current) => (current ? `${current.trimEnd()} ${DICTATION}` : DICTATION));
setListening(false);
inputRef.current?.focus();
}, 2200);
return () => clearTimeout(t);
- }, [listening]);
+ }, [demo, listening]);
- /* Move wrapped text above the controls, then grow to a compact maximum. */
useLayoutEffect(() => {
const input = inputRef.current;
const controls = controlsRef.current;
@@ -502,16 +329,15 @@ export default function PromptBar({
/* clicking anywhere outside the composer closes the open menus */
useEffect(() => {
- if (!modelOpen && !plusOpen) return;
+ if (!plusOpen) return;
const close = (event: PointerEvent) => {
if (!(event.target as Element).closest("[data-promptbar]")) {
- setModelOpen(false);
setPlusOpen(false);
}
};
document.addEventListener("pointerdown", close);
return () => document.removeEventListener("pointerdown", close);
- }, [modelOpen, plusOpen]);
+ }, [plusOpen]);
const closeMenus = () => {
setPlusOpen(false);
@@ -528,6 +354,8 @@ export default function PromptBar({
fileInputRef.current?.click();
}
setDraft(before);
+ } else if (row.key.startsWith("gui-skill:")) {
+ setDraft(`${before}$${row.key.slice(10)} `);
} else if (row.key.startsWith("file:")) {
/* The harness reads `@[path]` out of the prompt text: an image becomes
* a native vision block, anything else stays a path it opens itself. */
@@ -542,18 +370,16 @@ export default function PromptBar({
inputRef.current?.focus();
};
- /* Bytes from a paste, a drop or the file picker. Uploaded one at a time so
- * one refusal cannot take the others down with it. */
const attachFiles = async (files: File[]) => {
if (demo || files.length === 0) return;
- setAttachError(null);
+ setAttachError(null); setUploads(count => count + files.length);
for (const file of files) {
try {
const attachment = await uploadAttachment(file);
setAttachments((current) => [...current, attachment]);
} catch (err) {
setAttachError(err instanceof Error ? err.message : String(err));
- }
+ } finally { setUploads(count => count - 1); }
}
inputRef.current?.focus();
};
@@ -565,7 +391,7 @@ export default function PromptBar({
});
};
- const canSend = !disabled && (draft.trim().length > 0 || attachments.length > 0);
+ const canSend = !disabled && uploads === 0 && (draft.trim().length > 0 || attachments.length > 0);
const showStop = busy && !canSend;
const send = () => {
if (!canSend) return;
@@ -606,7 +432,7 @@ export default function PromptBar({
onKeyDownCapture={takeOver}
>
{/* composer is the anchor — menus grow up from its top edge */}
- <div ref={composerAnchorRef} className="relative">
+ <div className="relative">
{/* ── @ / slash menu ─────────────────────────────── */}
{menu && (
<div
@@ -679,89 +505,17 @@ export default function PromptBar({
</div>
)}
<div className="mt-1 border-t border-line px-2 pt-1.5 pb-1 text-[11px] text-ink-3">
- {menu !== "at"
+ {menu === "skill" ? "GUI skills · ↑↓ then Enter to select" : menu !== "at"
? "Type to search commands"
: demo
? "Type to search sources & files"
- : "Type to search this workspace — or paste, drop and attach files"}
+ : "Search files or GUI skills · use $ for skills only"}
</div>
</div>
)}
- {/* ── model menu ─────────────────────────────────── */}
- {modelOpen && (
- <div
- className="absolute z-10 flex w-64 flex-col rounded-[10px] bg-surface p-1 shadow-raised"
- style={{ left: modelMenuLeft, bottom: modelMenuBottom, maxHeight: modelMenuMaxH, animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both", transformOrigin: "bottom left" }}
- >
- {/* a real install lists 40+ authenticated seats — filter beats scrolling */}
- {catalog.length > 8 && (
- <input
- autoFocus
- value={modelQuery}
- onChange={(event) => {
- setModelQuery(event.target.value);
- setModelHovered(null);
- }}
- onKeyDown={(event) => {
- if (event.key === "Escape") {
- setModelOpen(false);
- inputRef.current?.focus();
- }
- if (event.key === "Enter" && shownModels.length > 0) {
- selectModel(shownModels[0]);
- inputRef.current?.focus();
- }
- }}
- placeholder="Filter models…"
- aria-label="Filter models"
- className="mb-1 h-7 shrink-0 rounded-[6px] bg-field px-2 text-[12px] text-ink shadow-hairline outline-none placeholder:text-ink-3"
- />
- )}
- <div
- onMouseLeave={() => setModelHovered(null)}
- className="relative min-h-0 flex-1 overflow-y-auto"
- >
- {/* single gliding highlight — floats to the hovered / selected row */}
- <span
- aria-hidden
- className="pointer-events-none absolute inset-x-0 rounded-[6px] bg-hover"
- style={{
- top: modelBox?.top ?? 0,
- height: modelBox?.height ?? 0,
- opacity: modelBox && modelHovered !== null ? 1 : 0,
- transition:
- "top 220ms cubic-bezier(0.23,1,0.32,1), height 220ms cubic-bezier(0.23,1,0.32,1), opacity 150ms ease",
- }}
- />
- {shownModels.map((m, i) => (
- <button
- key={m.key}
- type="button"
- ref={(el) => {
- modelRowRefs.current[i] = el;
- }}
- onMouseDown={(event) => event.preventDefault()}
- onMouseEnter={() => setModelHovered(i)}
- onClick={() => {
- selectModel(m);
- inputRef.current?.focus();
- }}
- className="relative z-10 flex h-7.5 w-full items-center gap-2 rounded-[6px] px-2 text-left"
- >
- <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-ink">{m.name}</span>
- <span className="shrink-0 text-[11px] text-ink-3">{m.tag}</span>
- <span className={`shrink-0 text-ink ${m.key === model.key ? "" : "invisible"}`}>
- <Icon size={13} strokeWidth={2.5}><path d="M20 6L9 17l-5-5" /></Icon>
- </span>
- </button>
- ))}
- {shownModels.length === 0 && (
- <div className="px-2 py-2 text-[12px] text-ink-3">No models match “{modelQuery.trim()}”</div>
- )}
- </div>
- </div>
- )}
+ {modelOpen && <ModelPicker models={catalog} selected={model} anchor={modelRef} onClose={() => setModelOpen(false)}
+ onSelect={next => { selectModel(next); inputRef.current?.focus({ preventScroll: true }); }} />}
{/* ── composer ───────────────────────────────────── */}
<div
@@ -791,7 +545,6 @@ export default function PromptBar({
pill ? (attachments.length > 0 || wide ? "rounded-[24px]" : "rounded-full") : tall ? "rounded-[22px]" : "rounded-[14px]"
}`}
>
- {/* The @ menu's attach row and the + button both open this. */}
<input
ref={fileInputRef}
type="file"
@@ -853,6 +606,7 @@ export default function PromptBar({
</div>
)}
+ {uploads > 0 && <p role="status" className="px-2 text-xs text-ink-3">Adding {uploads} {uploads === 1 ? "file" : "files"}…</p>}
{attachError && (
<div className={`text-[11.5px] text-red ${pill ? "px-2" : "px-1"}`} role="status">
{attachError}
@@ -939,9 +693,9 @@ export default function PromptBar({
<button
type="button"
aria-label={listening ? "Stop dictation" : "Start dictation"}
- aria-pressed={listening}
+ aria-pressed={listening} disabled={!demo} title={demo ? "Demo dictation" : "Dictation is not available yet"}
onClick={() => setListening((current) => !current)}
- className={`flex size-7 shrink-0 items-center justify-center transition-[background-color,color,transform] duration-150 active:scale-[0.94] ${
+ className={`flex size-7 shrink-0 items-center justify-center disabled:opacity-30 disabled:cursor-not-allowed transition-[background-color,color,transform] duration-150 active:scale-[0.94] ${
pill ? "rounded-full" : "rounded-[8px]"
} ${listening ? "bg-accent-tint text-accent-ink" : "text-ink-3 hover:bg-hover hover:text-ink"} ${wide ? "col-start-4 row-start-2" : "col-start-4 row-start-1"}`}
>
@@ -967,7 +721,7 @@ export default function PromptBar({
aria-label={showStop ? "Stop" : "Send"}
disabled={showStop ? !onStop : !canSend}
onClick={showStop ? onStop : send}
- className={`flex size-7 shrink-0 items-center justify-center transition-[background-color,color,transform] duration-200 enabled:active:scale-[0.94] ${
+ className={`flex size-7 shrink-0 items-center justify-center disabled:opacity-30 disabled:cursor-not-allowed transition-[background-color,color,transform] duration-200 enabled:active:scale-[0.94] ${
pill ? "rounded-full" : "rounded-[8px]"
} ${wide ? "col-start-5 row-start-2" : "col-start-5 row-start-1"}`}
style={{
diff --git a/apps/native/components/primitives/ToolChips.tsx b/apps/native/components/primitives/ToolChips.tsx
index 0522418a..3b4c3c76 100644
--- a/apps/native/components/primitives/ToolChips.tsx
+++ b/apps/native/components/primitives/ToolChips.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
/* ─────────────────────────────────────────────────────────
@@ -93,7 +93,7 @@ export type LiveToolRow = {
/** Workspace file this call touched; makes the chip a jump target. */
path?: string;
/** Live call state — running rows get a spinner so the turn visibly moves. */
- status?: "running" | "ok" | "error";
+ status?: "running" | "ok" | "error" | "interrupted";
startedAt?: number;
elapsedMs?: number;
};
@@ -129,25 +129,17 @@ export default function ToolChips({
? Object.fromEntries((liveDiffs ?? []).map((d) => [d.file, d.lines ?? []]))
: DIFF_LINES;
const [step, setStep] = useState(0);
- const [open, setOpen] = useState(true);
- const userToggled = useRef(false);
+ const [open, setOpen] = useState(!live);
/* tick once a second while any live row runs, so its timer counts up */
const [, setClock] = useState(0);
const anyRunning = live && rows.some((r) => "status" in r && r.status === "running");
useEffect(() => {
- if (!anyRunning) return;
+ if (!anyRunning || !open) return;
const t = setInterval(() => setClock((c) => c + 1), 1000);
return () => clearInterval(t);
- }, [anyRunning]);
- /* A batch of reads should not be a wall sitting on the answer. Expand
- * while something is running so the live call is visible; fold the rest
- * into the summary once they settle — unless the reader opened it. */
- useEffect(() => {
- if (!live || userToggled.current) return;
- if (anyRunning) setOpen(true);
- else if (rows.length > 1) setOpen(false);
- }, [live, anyRunning, rows.length]);
- const showHeader = !live || rows.length > 1;
+ }, [anyRunning, open]);
+ // Disclosure belongs to the reader. New calls and completion never change it.
+ const showHeader = true;
const [openRows, setOpenRows] = useState<Set<string>>(new Set());
/* Rendered in a body portal so animated/translated reply wrappers cannot
* redefine the fixed-position coordinate system. */
@@ -193,9 +185,8 @@ export default function ToolChips({
{showHeader && (
<button
type="button"
- aria-expanded={open}
+ data-tool-summary aria-expanded={open}
onClick={() => {
- userToggled.current = true;
setOpen((current) => !current);
}}
className="-mx-1.5 flex w-fit items-center gap-1.5 rounded-control px-1.5 py-1 text-[12.5px] text-ink-2 transition-colors duration-100 hover:bg-hover-2"
@@ -216,6 +207,8 @@ export default function ToolChips({
if (other > 0) parts.push(`${other} other`);
const liveN = rows.filter((r) => "status" in r && r.status === "running").length;
if (liveN) parts.push(liveN === 1 ? "running" : `${liveN} running`);
+ const interrupted = rows.filter(row => "status" in row && row.status === "interrupted").length;
+ if (interrupted) parts.push(`${interrupted} interrupted`);
return parts.join(" · ") || `${rows.length} steps`;
})()
: "4 tool calls, 2 messages"}
@@ -224,7 +217,7 @@ export default function ToolChips({
)}
{/* tool call rows */}
- <div className="grid transition-[grid-template-rows,opacity] duration-300" style={{ gridTemplateRows: !showHeader || open ? "1fr" : "0fr", opacity: !showHeader || open ? 1 : 0 }}>
+ <div inert={!open} aria-hidden={!open} className="grid transition-[grid-template-rows,opacity] duration-300" style={{ gridTemplateRows: !showHeader || open ? "1fr" : "0fr", opacity: !showHeader || open ? 1 : 0 }}>
{/* -mx-1 + px-1.5 keeps content at the same x while giving the
row hover pills room inside this overflow-hidden clip box */}
<div className="-mx-1 overflow-hidden px-1.5 pb-1">
diff --git a/apps/native/components/primitives/prompt-demo.tsx b/apps/native/components/primitives/prompt-demo.tsx
new file mode 100644
index 00000000..d94e13cf
--- /dev/null
+++ b/apps/native/components/primitives/prompt-demo.tsx
@@ -0,0 +1,114 @@
+import type { AcpCommand } from "@/lib/acp";
+export function Icon({ children, size = 15, strokeWidth = 1.8 }: { children: React.ReactNode; size?: number; strokeWidth?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
+ {children}
+ </svg>
+ );
+}
+
+export const GLYPHS: Record<string, React.ReactNode> = {
+ clip: <path d="m21.4 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48" />,
+ chart: <path d="M4 20V10M10 20V4M16 20v-7M22 20H2" />,
+ layers: <g><path d="M12 2 2 7l10 5 10-5-10-5z" /><path d="M2 17l10 5 10-5M2 12l10 5 10-5" /></g>,
+ globe: <g><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></g>,
+ file: <g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></g>,
+};
+
+/* real product marks, inline so the file stays self-contained */
+export const BRANDS: Record<string, React.ReactNode> = {
+ figma: (
+ <svg width="11" height="16" viewBox="0 0 38 57" aria-hidden="true">
+ <path d="M9.5 57A9.5 9.5 0 0 0 19 47.5V38H9.5a9.5 9.5 0 0 0 0 19z" fill="#0ACF83" />
+ <path d="M0 28.5A9.5 9.5 0 0 1 9.5 19H19v19H9.5A9.5 9.5 0 0 1 0 28.5z" fill="#A259FF" />
+ <path d="M0 9.5A9.5 9.5 0 0 1 9.5 0H19v19H9.5A9.5 9.5 0 0 1 0 9.5z" fill="#F24E1E" />
+ <path d="M19 0h9.5a9.5 9.5 0 1 1 0 19H19V0z" fill="#FF7262" />
+ <path d="M38 28.5a9.5 9.5 0 1 1-19 0 9.5 9.5 0 0 1 19 0z" fill="#1ABCFE" />
+ </svg>
+ ),
+ slack: (
+ <svg width="15" height="15" viewBox="0 0 127 127" aria-hidden="true">
+ <path d="M27.2 80c0 7.3-5.9 13.2-13.2 13.2C6.7 93.2.8 87.3.8 80c0-7.3 5.9-13.2 13.2-13.2h13.2V80zm6.6 0c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2v33c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V80z" fill="#E01E5A" />
+ <path d="M47 27.2c-7.3 0-13.2-5.9-13.2-13.2C33.8 6.7 39.7.8 47 .8c7.3 0 13.2 5.9 13.2 13.2v13.2H47zm0 6.7c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H13.9C6.6 60.3.7 54.4.7 47.1c0-7.3 5.9-13.2 13.2-13.2H47z" fill="#36C5F0" />
+ <path d="M99.9 47.1c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H99.9V47.1zm-6.6 0c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V13.9C66.9 6.6 72.8.7 80.1.7c7.3 0 13.2 5.9 13.2 13.2v33.2z" fill="#2EB67D" />
+ <path d="M80.1 99.8c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V99.8h13.2zm0-6.6c-7.3 0-13.2-5.9-13.2-13.2 0-7.3 5.9-13.2 13.2-13.2h33.1c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H80.1z" fill="#ECB22E" />
+ </svg>
+ ),
+ gmail: (
+ <svg width="15" height="12" viewBox="0 0 256 193" aria-hidden="true">
+ <path d="M58.182 192.05V93.14L27.507 65.077 0 49.504v125.091c0 9.658 7.825 17.455 17.455 17.455h40.727Z" fill="#4285F4" />
+ <path d="M197.818 192.05h40.727c9.659 0 17.455-7.826 17.455-17.455V49.505l-31.156 17.837-27.026 25.798v98.91Z" fill="#34A853" />
+ <path d="m58.182 93.14-4.174-38.647 4.174-36.989L128 69.868l69.818-52.364 4.669 34.992-4.669 40.644L128 145.504 58.182 93.14Z" fill="#EA4335" />
+ <path d="M197.818 17.504V93.14L256 49.504V26.231c0-21.585-24.64-33.89-41.89-20.945l-16.292 12.218Z" fill="#FBBC04" />
+ <path d="m0 49.504 26.759 20.07L58.182 93.14V17.504L41.89 5.286C24.61-7.66 0 4.646 0 26.23v23.273Z" fill="#C5221F" />
+ </svg>
+ ),
+};
+
+type Source = {
+ key: string;
+ name: string;
+ desc: string;
+ glyph?: string;
+ brand?: string;
+ attach?: boolean;
+ connect?: boolean;
+};
+
+export const SOURCES: Source[] = [
+ { key: "attach", name: "Add photos & files", desc: "Upload from your computer", glyph: "clip", attach: true },
+ { key: "scoop", name: "Scoop Data", desc: "Sales & churn metrics", glyph: "chart" },
+ { key: "flavors", name: "Flavor records", desc: "26 makers, tags, links", glyph: "layers" },
+ { key: "web", name: "Web search", desc: "Real-time news and info", glyph: "globe" },
+ { key: "figma", name: "Figma", desc: "Design-to-code workflows", brand: "figma" },
+ { key: "slack", name: "Slack", desc: "Read and manage Slack", brand: "slack" },
+ { key: "gmail", name: "Gmail", desc: "Read and manage Gmail", brand: "gmail", connect: true },
+];
+
+/* The self-running walkthrough types "/" and glides through rows, so it
+ * needs something to show. A live surface is handed the agent's real set and
+ * never falls back to these — an invented command must not reach a console
+ * where someone could run it. */
+export const DEMO_COMMANDS: AcpCommand[] = [
+ { name: "compare", description: "Flavor vs. last summer" },
+ { name: "churn-plan", description: "Draft a churn schedule" },
+ { name: "restock", description: "Build a reorder list" },
+ { name: "draft-email", description: "Write a supplier email" },
+ { name: "summarize", description: "Digest the thread so far" },
+];
+
+export const MODELS = [
+ { key: "sprinkles-5", name: "Sprinkles 5", tag: "Flagship" },
+ { key: "vanilla-1", name: "Vanilla 1", tag: "Basic" },
+ { key: "freezer-burn", name: "Freezer Burn 0.4", tag: "Stale" },
+];
+
+export const FILES = ["flavor-chart.png", "summer-menu.pdf", "pos-export.csv"];
+export const DICTATION = "Compare pistachio weekends to last summer";
+
+/* self-running demo: walk the @ menu, then the / menu, and repeat.
+ * Any pointer or key interaction hands control to the user. */
+export const AUTO_STEPS: {
+ draft: string;
+ active?: number;
+ connect?: boolean;
+ modelOpen?: boolean;
+ model?: string;
+ hold: number;
+}[] = [
+ { draft: "", connect: false, model: "vanilla-1", hold: 1100 },
+ { draft: "@", active: 0, hold: 900 },
+ { draft: "@", active: 1, hold: 620 },
+ { draft: "@", active: 4, hold: 620 },
+ { draft: "@", active: 6, hold: 700 },
+ { draft: "@", active: 6, connect: true, hold: 1000 },
+ { draft: "", hold: 700 },
+ { draft: "/", active: 0, hold: 900 },
+ { draft: "/", active: 1, hold: 620 },
+ { draft: "/", active: 3, hold: 1000 },
+ { draft: "", hold: 800 },
+ // open the model picker and upgrade to the flagship → rainbow sweep
+ { draft: "", modelOpen: true, hold: 1200 },
+ { draft: "", model: "sprinkles-5", hold: 2400 },
+ { draft: "", hold: 900 },
+];
diff --git a/apps/native/components/site/ChangesPane.module.css b/apps/native/components/site/ChangesPane.module.css
new file mode 100644
index 00000000..fb0752eb
--- /dev/null
+++ b/apps/native/components/site/ChangesPane.module.css
@@ -0,0 +1,15 @@
+.panel { container-type: inline-size; }
+.resize { position: absolute; z-index: 20; inset: 0 auto 0 -10px; width: 10px; cursor: col-resize; touch-action: none; outline: none; }
+.resize::after { content: ""; position: absolute; top: 12px; bottom: 12px; left: 4px; width: 2px; border-radius: 2px; background: transparent; transition: background 120ms; }
+.resize:hover::after, .resize:focus-visible::after, .resize[data-dragging]::after { background: var(--accent); }
+.body { display: flex; min-height: 0; flex: 1; }
+.files { width: 180px; flex-shrink: 0; overflow: auto; border-right: 1px solid var(--line); padding: 6px; }
+@container (max-width: 540px) {
+ .body { flex-direction: column; }
+ .files { width: 100%; max-height: 150px; border-right: 0; border-bottom: 1px solid var(--line); }
+}
+.chatbar { container: chatbar / inline-size; }
+@container chatbar (max-width: 650px) {
+ .actions { gap: 2px; padding-left: 4px; }
+ .actions [data-toolbar-label] { display: none; }
+}
diff --git a/apps/native/components/site/ChangesPane.tsx b/apps/native/components/site/ChangesPane.tsx
index 89d55c78..41c1df44 100644
--- a/apps/native/components/site/ChangesPane.tsx
+++ b/apps/native/components/site/ChangesPane.tsx
@@ -1,19 +1,16 @@
"use client";
import { useEffect, useRef, useState } from "react";
import type { ReviewState, ReviewScope } from "@/lib/git-review";
-function Diff({ text }: { text: string }) {
- let old = 0, next = 0;
- return <div className="min-w-max py-2 font-mono text-[11px] leading-5">{text.split("\n").slice(0, 12000).map((line, index) => {
- const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)/.exec(line);
- if (hunk) { old = Number(hunk[1]); next = Number(hunk[2]); return <div key={index} className="sticky left-0 my-2 bg-hover px-3 text-ink-3">{line}</div>; }
- if (/^(diff --git|index |---|\+\+\+)/.test(line)) return null;
- const added = line.startsWith("+"), removed = line.startsWith("-");
- const left = added ? "" : old++, right = removed ? "" : next++;
- return <div key={index} className={`flex whitespace-pre ${added ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400" : removed ? "bg-red-500/10 text-red-600 dark:text-red-400" : "text-ink-2"}`}>
- <span className="w-10 shrink-0 select-none px-1 text-right text-ink-3">{left || ""}</span><span className="mr-2 w-10 shrink-0 select-none px-1 text-right text-ink-3">{right || ""}</span><span className="pr-4">{line || " "}</span>
- </div>;
- })}</div>;
+import ReviewActions from "./ReviewActions";
+import ReviewDiff from "./ReviewDiff";
+import { reviewLines } from "@/lib/review-lines";
+import styles from "./ChangesPane.module.css";
+import ResizableReviewPane from "./ResizableReviewPane";
+function Icon({ kind }: { kind: "close" | "files" | "up" | "down" | "history" | "refresh" }) {
+ const paths = { close: "M6 6l12 12M6 18 18 6", files: "M8 6h12M8 12h12M8 18h12M3 6h.01M3 12h.01M3 18h.01", up: "m6 14 6-6 6 6", down: "m6 10 6 6 6-6", history: "M3 10a9 9 0 1 1 1 7M3 4v6h6M12 7v5l3 2", refresh: "M4 10a8 8 0 1 1 0 5M4 4v6h6" };
+ return <svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d={paths[kind]} /></svg>;
}
+const button = "flex size-7 shrink-0 items-center justify-center rounded-md text-ink-3 hover:bg-hover hover:text-ink disabled:opacity-30";
export default function ChangesPane({ root, onClose }: { root?: string; onClose(): void }) {
const [workspace, setWorkspace] = useState(root);
const [scope, setScope] = useState<ReviewScope>("all");
@@ -23,9 +20,15 @@ export default function ChangesPane({ root, onClose }: { root?: string; onClose(
const [diff, setDiff] = useState("");
const [error, setError] = useState("");
const [history, setHistory] = useState(false);
+ const [showFiles, setShowFiles] = useState(false);
+ const viewport = useRef<HTMLElement>(null);
+ const [filter, setFilter] = useState("");
+ const [wrap, setWrap] = useState(true);
+ const [revision, setRevision] = useState(0);
const [loading, setLoading] = useState(true);
useEffect(() => { setWorkspace(root); setSelected(""); }, [root]);
useEffect(() => {
+ setLoading(true);
let stopped = false, timer: ReturnType<typeof setTimeout>;
const refresh = async () => {
if (document.visibilityState === "hidden") { timer = setTimeout(refresh, 5000); return; }
@@ -45,27 +48,52 @@ export default function ChangesPane({ root, onClose }: { root?: string; onClose(
finally { if (!stopped) { setLoading(false); timer = setTimeout(refresh, 5000); } }
};
void refresh(); return () => { stopped = true; clearTimeout(timer); };
- }, [workspace, scope, selected]);
- const index = state?.files.findIndex(file => file.path === selected) ?? -1;
- return <aside aria-label="Workspace changes" className="flex w-[650px] max-w-[60%] shrink-0 flex-col overflow-hidden rounded-xl border border-line bg-page">
- <header className="flex h-11 items-center gap-2 border-b border-line px-3"><strong className="flex-1 text-sm">Changes <span className="font-normal text-ink-3">· {state?.branch ?? "Git"}</span></strong><span className="text-[10px] text-emerald-600">Live · 5s</span><button aria-label="Close changes" onClick={onClose}>×</button></header>
- <div className="flex items-center gap-2 border-b border-line p-2 text-xs">
- <select aria-label="Review worktree" value={workspace ?? state?.root ?? ""} onChange={e => { setWorkspace(e.target.value); setSelected(""); }} className="min-w-0 flex-1 rounded bg-field p-1">
- {(state?.worktrees.length ? state.worktrees : [{ path: workspace ?? "", branch: "Current workspace" }]).map(tree => <option key={tree.path} value={tree.path}>{tree.branch} · {tree.path.split('/').pop()}</option>)}
- </select>
- <select aria-label="Changes scope" value={scope} onChange={e => setScope(e.target.value as ReviewScope)} className="rounded bg-field p-1"><option value="all">All changes</option><option value="staged">Staged</option><option value="unstaged">Unstaged</option></select>
- <button aria-pressed={history} onClick={() => setHistory(!history)} className="rounded px-2 py-1 hover:bg-hover">History</button>
+ }, [workspace, scope, selected, revision]);
+ const files = state?.files ?? [];
+ const filteredFiles = files.filter(file => file.path.toLowerCase().includes(filter.toLowerCase()));
+ const index = files.findIndex(file => file.path === selected);
+ const file = files[index];
+ const rows = reviewLines(diff);
+ const added = rows.filter(row => row.kind === "add").length;
+ const removed = rows.filter(row => row.kind === "remove").length;
+ const newFiles = files.filter(file => file.untracked).length;
+ const choose = (path: string) => { setSelected(path); setDiff(""); };
+ return <ResizableReviewPane><aside aria-label="Workspace changes" className={`${styles.panel} flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page`}>
+ <header className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-3">
+ <strong className="text-[13px] font-medium">Changes</strong>
+ <span className="rounded-md bg-hover px-1.5 py-0.5 text-[10px] tabular-nums text-ink-3">{files.length}</span>
+ <div className="min-w-0 flex-1 truncate pl-1 text-[11px] text-ink-3" title={state?.branch}>{state?.branch}</div>
+ <span className="size-1.5 shrink-0 rounded-full bg-green/70" title="Refreshes every five seconds while visible" aria-label="Live updates" />
+ <button className={button} title="Refresh changes" aria-label="Refresh changes" onClick={() => setRevision(value => value + 1)}><Icon kind="refresh" /></button>
+ <button className={button} title="Close changes" aria-label="Close changes" onClick={onClose}><Icon kind="close" /></button>
+ </header>
+ {state && state.worktrees.length > 1 && <div className="border-b border-line px-3 py-2"><select aria-label="Review worktree" value={workspace ?? state.root} onChange={e => { setWorkspace(e.target.value); choose(""); }} className="w-full rounded-md bg-field px-2 py-1 text-xs">{state.worktrees.map(tree => <option key={tree.path} value={tree.path}>{tree.branch} · {tree.path.split('/').pop()}</option>)}</select></div>}
+ <div className="flex shrink-0 items-center gap-2 border-b border-line px-3 py-2">
+ <div role="group" aria-label="Changes scope" className="flex rounded-lg bg-hover/60 p-0.5">{(["all", "staged", "unstaged"] as const).map(value => <button key={value} aria-pressed={scope === value} onClick={() => { setScope(value); choose(""); }} className={`rounded-md px-2.5 py-1 text-[11px] transition-colors ${scope === value ? "bg-page text-ink shadow-sm" : "text-ink-3 hover:text-ink"}`}>{value === "all" ? "All" : value === "staged" ? "Staged" : "Unstaged"}</button>)}</div>
+ <div className="flex min-w-0 flex-1 items-center justify-end gap-1.5 text-[10px] tabular-nums">
+ {!!state?.totalAdd && <span title="Added lines in tracked files" className="text-green">+{state.totalAdd}</span>}
+ {!!state?.totalDel && <span title="Removed lines in tracked files" className="text-red">−{state.totalDel}</span>}
+ {!!newFiles && <span className="whitespace-nowrap text-ink-3">{newFiles} new</span>}
+ </div>
+ <button aria-label="Show recent commits" title="Recent commits" aria-pressed={history} onClick={() => setHistory(!history)} className={`${button} ${history ? "bg-hover text-ink" : ""}`}><Icon kind="history" /></button>
</div>
- <p className="border-b border-line px-3 py-2 text-[11px] text-ink-3">Shared working tree · edits from you and every agent. <span className="text-emerald-600">+{state?.totalAdd ?? 0}</span> <span className="text-red-500">−{state?.totalDel ?? 0}</span></p>
- {error && <p role="alert" className="p-3 text-xs text-red-500">{error}</p>}
- {history && <div className="max-h-44 overflow-auto border-b border-line p-2">{state?.commits.map(commit => <div key={commit.hash} className="flex gap-2 py-1 text-xs"><code className="text-ink-3">{commit.hash}</code><span className="min-w-0 flex-1 truncate">{commit.subject}</span><span className="text-ink-3">{commit.author}</span></div>)}</div>}
- <div className="flex min-h-0 flex-1">
- <nav aria-label="Changed files" className="w-44 shrink-0 overflow-auto border-r border-line p-1">{state?.files.map(file => <button key={file.path} onClick={() => { setSelected(file.path); setDiff(""); }} title={file.path}
- className={`flex w-full items-center gap-1 rounded px-2 py-2 text-left text-xs ${file.path === selected ? "bg-hover" : "hover:bg-hover"}`}><span className="text-ink-3">{file.untracked ? "+" : file.status.trim()}</span><span className="min-w-0 flex-1 truncate">{file.path}</span></button>)}</nav>
- <section className="flex min-w-0 flex-1 flex-col"><div className="flex h-9 shrink-0 items-center gap-2 border-b border-line px-2 text-xs"><span className="min-w-0 flex-1 truncate" title={selected}>{selected || (loading ? "Loading…" : "Working tree is clean")}</span>
- <button aria-label="Previous changed file" disabled={index <= 0} onClick={() => setSelected(state!.files[index - 1].path)}>↑</button><button aria-label="Next changed file" disabled={!state || index >= state.files.length - 1} onClick={() => setSelected(state!.files[index + 1].path)}>↓</button></div>
- <div className="min-h-0 flex-1 overflow-auto">{diff ? <Diff text={diff} /> : <p className="p-4 text-xs text-ink-3">{selected ? "Loading diff, or no text diff available." : "Changes appear here as files are edited."}</p>}</div>
+ {error && <p role="alert" className="border-b border-line px-3 py-2 text-xs text-red">{error}</p>}
+ {history && <div className="max-h-44 shrink-0 overflow-auto border-b border-line px-3 py-2">{state?.commits.length ? state.commits.map(commit => <div key={commit.hash} className="py-1.5 text-xs"><div className="truncate text-ink-2" title={commit.subject}>{commit.subject}</div><div className="mt-0.5 text-[10px] text-ink-3"><code>{commit.hash}</code> · {commit.author}</div></div>) : <p className="py-2 text-xs text-ink-3">No commits yet.</p>}</div>}
+ {files.length > 0 && <div className="flex h-11 shrink-0 items-center gap-1.5 border-b border-line px-2">
+ <button className={`${button} ${showFiles ? "bg-hover" : ""}`} title="Toggle file list" aria-label="Toggle changed file list" aria-pressed={showFiles} onClick={() => setShowFiles(!showFiles)}><Icon kind="files" /></button>
+ <select aria-label="Changed file" title={selected} value={selected} onChange={e => choose(e.target.value)} className="min-w-0 flex-1 truncate rounded-md bg-transparent py-1 text-xs text-ink-2">{files.map(file => <option key={file.path} value={file.path}>{file.path}</option>)}</select>
+ {file?.untracked && <span className="rounded bg-hover px-1.5 py-0.5 text-[9px] text-ink-3">NEW</span>}
+ {!!added && <span className="text-[10px] tabular-nums text-green">+{added}</span>}{!!removed && <span className="text-[10px] tabular-nums text-red">−{removed}</span>}
+ <button aria-label="Wrap long lines" aria-pressed={wrap} title="Wrap long lines" onClick={() => setWrap(!wrap)} className={`rounded px-1.5 py-1 text-[10px] ${wrap ? "bg-hover text-ink-2" : "text-ink-3"}`}>Wrap</button>
+ <button className={button} aria-label="Previous changed file" disabled={index <= 0} onClick={() => choose(files[index - 1].path)}><Icon kind="up" /></button>
+ <button className={button} aria-label="Next changed file" disabled={index >= files.length - 1} onClick={() => choose(files[index + 1].path)}><Icon kind="down" /></button>
+ </div>}
+ <div className={styles.body}>
+ {showFiles && files.length > 0 && <nav aria-label="Changed files" className={styles.files}><input aria-label="Filter changed files" placeholder="Find a file…" value={filter} onChange={event => setFilter(event.target.value)} className="mb-2 w-full rounded-md border border-line bg-field px-2 py-1.5 text-xs outline-accent" />{!filteredFiles.length && <p className="px-2 py-3 text-xs text-ink-3">No matching files.</p>}{filteredFiles.map(file => <button key={file.path} onClick={() => choose(file.path)} title={file.path} className={`mb-0.5 flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-xs ${file.path === selected ? "bg-hover text-ink" : "text-ink-3 hover:bg-hover"}`}><span className="min-w-0 flex-1"><span className="block truncate">{file.path.split('/').pop()}</span>{file.path.includes("/") && <span className="mt-0.5 block truncate font-mono text-[9px] text-ink-3">{file.path.slice(0, file.path.lastIndexOf("/"))}</span>}</span><span className="text-[9px]">{file.untracked ? "NEW" : file.status.trim()}</span></button>)}</nav>}
+ <section ref={viewport} aria-label="File diff" aria-busy={loading} className="min-h-0 min-w-0 flex-1 overflow-auto">
+ {rows.length ? <ReviewDiff rows={rows} wrap={wrap} /> : <div className="flex min-h-40 h-full flex-col items-center justify-center gap-2 px-8 text-center"><span className="text-sm text-ink-2">{loading ? "Loading changes…" : selected ? "No text changes to display" : "Working tree is clean"}</span><p className="max-w-60 text-xs leading-relaxed text-ink-3">{loading ? "" : selected ? "Binary files and metadata-only changes have no line diff." : "Edits in this workspace will appear here automatically."}</p></div>}
</section>
</div>
- </aside>;
+ {selected && <ReviewActions diff={diff} path={selected} root={workspace} viewport={viewport} count={rows.slice(0, 12000).filter(row => row.kind === "hunk").length} />}
+ </aside></ResizableReviewPane>;
}
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index 4c9a418f..6ccb2c11 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -4,6 +4,7 @@ import { memo, useEffect, useRef, useState, type RefObject } from "react";
import Markdown from "@/components/primitives/Markdown";
import ThinkingState from "@/components/primitives/ThinkingState";
import ToolChips from "@/components/primitives/ToolChips";
+import TurnActivity from "./TurnActivity";
import { pinScrollerTail } from "@/lib/follow-scroll";
import { turnBlocks, type AssistantTurn } from "@/lib/acp";
@@ -123,14 +124,10 @@ export const AssistantBody = memo(function AssistantBody({
const lastTextIndex = blocks.reduce((acc, b, i) => (b.kind === "text" ? i : acc), -1);
const lastBlock = blocks[blocks.length - 1];
- const waitingOnTools =
- turn.status === "streaming" &&
- !lastTextBody &&
- (lastBlock?.kind === "tools" || blocks.length === 0);
return (
- <article className="min-w-0" style={{ overflowAnchor: "none", animation: "fade-in 280ms ease both" }}>
- {(thinking || reasoningRows.length > 0 || (turn.thoughtMs ?? 0) >= 1500) && (
+ <article data-turn-status={turn.status} aria-busy={live} className="min-w-0" style={{ overflowAnchor: "none", animation: "fade-in 280ms ease both" }}>
+ {((thinking && turn.activityKind === "agent_thought_chunk") || reasoningRows.length > 0 || (turn.thoughtMs ?? 0) >= 1500) && (
<ThinkingState
variant="Reasoning"
rows={reasoningRows.length ? reasoningRows : [{ primary: "Waiting on the model…", shimmer: true }]}
@@ -152,28 +149,15 @@ export const AssistantBody = memo(function AssistantBody({
<div key={`text-${i}`} className="mt-3 max-w-[630px]">
<Markdown
text={i === lastTextIndex ? smoothText : block.text}
- streaming={i === lastTextIndex && (draining || turn.status === "streaming" || turn.status === "thinking")}
+ streaming={i === lastTextIndex && live && draining}
onOpenPath={onOpenPath}
/>
</div>
),
)}
- {waitingOnTools && (
- <div className="mt-4">
- <span
- className="bg-clip-text text-[13px] font-medium whitespace-nowrap text-transparent"
- style={{
- backgroundImage: "linear-gradient(90deg, var(--ink-3) 35%, var(--ink) 50%, var(--ink-3) 65%)",
- backgroundSize: "200% 100%",
- animation: "shimmer-text 1.4s linear infinite",
- }}
- >
- {turn.tools.some((tool) => tool.status === "running") ? "Running tools…" : "Writing…"}
- </span>
- </div>
- )}
+ <TurnActivity turn={turn} />
{turn.error && (
- <p className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>
+ <p role="alert" className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>
)}
{turn.recap && turn.status === "done" && !draining && (
<p className="mt-3 text-[12px] text-ink-3">{turn.recap}</p>
diff --git a/apps/native/components/site/ConversationsPane.tsx b/apps/native/components/site/ConversationsPane.tsx
index d56a84b8..65c3b47e 100644
--- a/apps/native/components/site/ConversationsPane.tsx
+++ b/apps/native/components/site/ConversationsPane.tsx
@@ -47,11 +47,12 @@ export default function ConversationsPane({
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const sentinelRef = useRef<HTMLDivElement>(null);
+ const generation = useRef(0);
const q = useDebounced(query);
useEffect(() => {
- let cancelled = false;
- setLoading(true);
+ let cancelled = false; generation.current++;
+ setLoading(true); setLoadingMore(false);
setError(null);
void listSessionsPage({ limit: PAGE, q, scope, root })
.then((page) => {
@@ -77,12 +78,14 @@ export default function ConversationsPane({
const io = new IntersectionObserver(
(entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
- if (loadingMore || loading) return;
+ if (loadingMore || loading || error) return;
const next = cursor;
if (!next) return;
+ const request = generation.current;
setLoadingMore(true);
void listSessionsPage({ limit: PAGE, cursor: next, q, scope, root })
.then((page) => {
+ if (request !== generation.current) return;
setRows((current) => {
const seen = new Set(current.map((r) => r.name));
return [...current, ...page.sessions.filter((r) => !seen.has(r.name))];
@@ -90,14 +93,14 @@ export default function ConversationsPane({
setCursor(page.nextCursor);
setTotal(page.total);
})
- .catch(() => undefined)
- .finally(() => setLoadingMore(false));
+ .catch(() => { if (request === generation.current) setError("Could not load more conversations. Choose Retry to try again."); })
+ .finally(() => { if (request === generation.current) setLoadingMore(false); });
},
{ rootMargin: "160px" },
);
io.observe(el);
return () => io.disconnect();
- }, [cursor, loading, loadingMore, q, scope]);
+ }, [cursor, loading, loadingMore, q, scope, root, error]);
const groups = groupSessions(rows);
const empty = !loading && rows.length === 0;
@@ -161,7 +164,7 @@ export default function ConversationsPane({
<div className="min-h-0 flex-1 overflow-y-auto">
<div className="mx-auto flex w-full max-w-[720px] flex-col gap-6 px-5 py-5 sm:px-8">
- {error && <p className="text-[13px] text-orange">{error}</p>}
+ {error && <p role="alert" className="text-[13px] text-orange">{error}{rows.length > 0 && <button className="ml-2 underline" onClick={() => setError(null)}>Retry</button>}</p>}
{empty && (
<div className="flex flex-col items-center justify-center gap-1 rounded-[14px] bg-inset px-6 py-16 text-center">
<span className="text-[14px] font-medium text-ink">
diff --git a/apps/native/components/site/CustomThemes.tsx b/apps/native/components/site/CustomThemes.tsx
new file mode 100644
index 00000000..dcf6e1e9
--- /dev/null
+++ b/apps/native/components/site/CustomThemes.tsx
@@ -0,0 +1,47 @@
+"use client";
+import { useEffect, useRef, useState } from "react";
+import { parseTheme, themeWarnings, themeLimit, type CustomTheme } from "@/lib/custom-themes";
+import { selectCustomTheme, type Appearance } from "@/lib/appearance";
+
+export default function CustomThemes({ selected }: { selected: Appearance }) {
+ const [themes, setThemes] = useState<CustomTheme[]>([]), [issues, setIssues] = useState<string[]>([]), [error, setError] = useState("");
+ const upload = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ const controller = new AbortController(); let timer: ReturnType<typeof setTimeout>;
+ const refresh = async () => {
+ try {
+ if (document.visibilityState === "hidden") return;
+ const response = await fetch("/api/themes", { signal: controller.signal, cache: "no-store" });
+ const data = await response.json(); if (!response.ok) throw Error(data.error);
+ setThemes(data.themes.map(parseTheme)); setIssues(data.issues); setError("");
+ } catch (error) { if (!controller.signal.aborted) setError(error instanceof Error ? error.message : "Could not load themes."); }
+ finally { if (!controller.signal.aborted) timer = setTimeout(refresh, 2000); }
+ };
+ void refresh(); return () => { controller.abort(); clearTimeout(timer); };
+ }, []);
+ return <section className="mt-3 border-t border-line pt-3" aria-label="Custom themes">
+ <div className="flex items-center justify-between"><strong className="text-xs font-medium">My themes</strong><button className="rounded px-2 py-1 text-[11px] text-accent-ink hover:bg-hover" onClick={() => upload.current?.click()}>Import theme</button></div>
+ <p className="mt-1 text-[11px] leading-4 text-ink-3">Type <code>$gui-theme</code> or <code>@gui-theme</code> in chat to create your own with Graff.</p>
+ <input ref={upload} type="file" accept="application/json,.json" className="hidden" aria-label="Import theme file" onChange={async event => {
+ const file = event.target.files?.[0]; event.target.value = ""; if (!file) return;
+ try {
+ if (file.size > themeLimit) throw Error("Theme exceeds 16 KiB.");
+ const theme = parseTheme(JSON.parse(await file.text()));
+ if (themes.some(current => current.id === theme.id)) throw Error("That theme id already exists. Give the imported theme a new id first.");
+ const response = await fetch("/api/themes", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(theme) });
+ const data = await response.json(); if (!response.ok) throw Error(data.error);
+ setThemes(current => [...current.filter(item => item.id !== theme.id), theme]); setError("");
+ } catch (error) { setError(error instanceof Error ? error.message : "Could not import theme."); }
+ }} />
+ <div className="mt-2 grid grid-cols-2 gap-2">{themes.map(theme => {
+ const warnings = themeWarnings(theme);
+ return <button key={theme.id} aria-label={`Use theme ${theme.name}`} aria-pressed={selected === `custom:${theme.id}`} title={warnings.join("\n") || theme.name}
+ onClick={() => { try { selectCustomTheme(theme); } catch { setError("Could not save the theme preference."); } }}
+ className={`rounded-lg border p-2 text-left hover:bg-hover ${selected === `custom:${theme.id}` ? "border-accent" : "border-line"}`}>
+ <span className="mb-1 flex h-10 items-center gap-1 rounded p-2" style={{ background: theme.colors.page, color: theme.colors.ink }}><span className="size-4 rounded-full" style={{ background: theme.colors.accent }} /><span className="rounded px-1 text-[10px]" style={{ background: theme.colors.surface }}>Aa</span></span>
+ <span className="block truncate text-[11px] font-medium">{theme.name}</span>{warnings.length > 0 && <span className="text-[10px] text-orange">Check text contrast</span>}
+ </button>;
+ })}</div>
+ {(error || issues.length > 0) && <p role="alert" className="mt-2 text-[11px] text-red">{error || issues.join(" ")}</p>}
+ </section>;
+}
diff --git a/apps/native/components/site/ElectronBrowserPane.tsx b/apps/native/components/site/ElectronBrowserPane.tsx
index 0c68427a..9e136aa7 100644
--- a/apps/native/components/site/ElectronBrowserPane.tsx
+++ b/apps/native/components/site/ElectronBrowserPane.tsx
@@ -9,7 +9,7 @@ type Props = { chat: string; pins: BrowserPin[]; onPinsChange(pins: BrowserPin[]
export default function ElectronBrowserPane({ chat, pins, onPinsChange, onAsk, onClose, initialUrl, memoryKey }: Props) {
const [url, setUrl] = useState(initialUrl || "");
- const [info, setInfo] = useState<PageInfo | null>(null);
+ const [info, setInfo] = useState<(PageInfo & { canGoBack?: boolean; canGoForward?: boolean }) | null>(null);
const [error, setError] = useState("");
const [picking, setPicking] = useState(false);
const [width, setWidth] = useState(520);
@@ -74,21 +74,21 @@ export default function ElectronBrowserPane({ chat, pins, onPinsChange, onAsk, o
onPointerMove={e => { if (e.currentTarget.hasPointerCapture(e.pointerId)) setWidth(Math.max(320, Math.min(900, window.innerWidth - e.clientX - 24))); }}
onPointerUp={e => e.currentTarget.releasePointerCapture(e.pointerId)} />
<header className="flex h-11 items-center gap-2 border-b border-line px-3">
- <span className="min-w-0 flex-1 truncate text-sm font-medium">{info?.title || "Browser"}</span>
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{info?.ready === "loading" ? "Loading page…" : info?.title || "Browser"}</span>
<button className={button} aria-pressed={picking} disabled={!info || info.ready === "suspended"} onClick={() => { setPicking(!picking); void command("pick", { enabled: !picking }); }}>{picking ? "Cancel pin" : "Pin element"}</button>
<button className={button} aria-label="Activity" onClick={() => void desktop()!.activity()}>Activity</button>
<button className={button} aria-label="Close browser" onClick={() => { void desktop()!.browser(chat, "close"); onClose(); }}>×</button>
</header>
<form className="flex h-10 items-center gap-1 border-b border-line px-2" onSubmit={e => { e.preventDefault(); void command("open", { url }); }}>
- <button type="button" className={button} aria-label="Back" onClick={() => void command("back")}>←</button>
- <button type="button" className={button} aria-label="Forward" onClick={() => void command("forward")}>→</button>
+ <button type="button" className={button} aria-label="Back" disabled={!info?.canGoBack} onClick={() => void command("back")}>←</button>
+ <button type="button" className={button} aria-label="Forward" disabled={!info?.canGoForward} onClick={() => void command("forward")}>→</button>
<button type="button" className={button} aria-label="Reload" onClick={() => void command("open", { url })}>↻</button>
<input ref={address} className="h-7 min-w-0 flex-1 rounded-md bg-field px-2 text-xs outline-none" aria-label="Address" placeholder="Enter a URL" value={url} onChange={e => setUrl(e.target.value)} onFocus={e => e.currentTarget.select()} />
<button className={button}>Go</button>
</form>
<div className="flex h-9 items-center gap-1 border-b border-line px-2">
<input aria-label="Find in page" placeholder="Find in page" className="h-6 min-w-0 flex-1 rounded bg-field px-2 text-xs" value={find}
- onChange={e => setFind(e.target.value)} onKeyDown={e => { if (e.key === "Enter" && find) void command("find", { text: find }); }} />
+ onChange={e => { setFind(e.target.value); if (!e.target.value && info) void command("find", { text: "" }); }} onKeyDown={e => { if (e.key === "Enter" && find) void command("find", { text: find }); }} />
<button className={button} disabled={!info || !find} onClick={() => void command("find", { text: find })}>Find</button>
<button className={button} aria-label="Zoom out" disabled={!info || zoom <= 0.5} onClick={() => { const factor = Math.max(0.5, zoom - 0.1); setZoom(factor); void command("zoom", { factor }); }}>−</button>
<button className={button} aria-label="Reset zoom" disabled={!info} onClick={() => { setZoom(1); void command("zoom", { factor: 1 }); }}>{Math.round(zoom * 100)}%</button>
diff --git a/apps/native/components/site/FilesPane.tsx b/apps/native/components/site/FilesPane.tsx
index e1049f2a..e309b527 100644
--- a/apps/native/components/site/FilesPane.tsx
+++ b/apps/native/components/site/FilesPane.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import Markdown from "@/components/primitives/Markdown";
import {
formatSize,
@@ -143,6 +143,7 @@ export default function FilesPane({
requested?: { path: string; n: number; changes?: boolean } | null;
onClose: () => void;
}) {
+ const navigation = useRef(0);
const [dir, setDir] = useState<FsDir | null>(null);
const [file, setFile] = useState<FsFile | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -166,8 +167,10 @@ export default function FilesPane({
}, [loadChanges]);
const show = useCallback(async (path: string, keepView = false) => {
+ const request = ++navigation.current;
try {
const res = await fsStat(path, root);
+ if (request !== navigation.current) return;
setError(null);
if (!keepView) {
setView("files");
@@ -180,7 +183,7 @@ export default function FilesPane({
setFile(res);
}
} catch (err) {
- setError(err instanceof Error ? err.message : String(err));
+ if (request === navigation.current) setError(err instanceof Error ? err.message : String(err));
}
}, [root]);
@@ -190,6 +193,7 @@ export default function FilesPane({
// workspace switch re-runs this (new `show`) and lands on its root.
setFile(null);
void show("", true);
+ return () => { navigation.current++; };
}, [show]);
useEffect(() => {
@@ -215,7 +219,7 @@ export default function FilesPane({
return (
<aside
- className="hidden w-[400px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"
+ className="flex w-[400px] max-w-[55%] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page"
style={{ animation: "fade-in 300ms ease both" }}
>
{/* header: workspace root + close */}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index d215fa68..7fc4e5fd 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -1,6 +1,8 @@
"use client";
+import { createTurnPainter } from "@/lib/turn-painter";
import { useQuietSettings } from "./useQuietSettings";
+import reviewStyles from "./ChangesPane.module.css";
import ChangesPane from "./ChangesPane";
import { useBrowserVisibility } from "./useBrowserVisibility";
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
@@ -380,7 +382,7 @@ export default function GraffHarness() {
messages: [
...c.messages,
{ id: userId, role: "user", text: trimmed },
- { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: spawnModel } },
+ { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: spawnModel, startedAt: Date.now() } },
],
},
),
@@ -401,37 +403,29 @@ export default function GraffHarness() {
wire = `${trimmed}\n\n${annotationsBlock(pins, handle)}`;
setPins(chatId, []);
}
- let turn: AssistantTurn = { ...emptyTurn(), model: spawnModel };
+ let turn: AssistantTurn = { ...emptyTurn(), model: spawnModel, startedAt: Date.now() };
+ const painter = createTurnPainter<AssistantTurn>(next => patchAssistant(chatId, asstId, next));
const startedAt = Date.now();
try {
const id = await requireSession(chatId);
- // Paint at most once per frame. ACP text/tool events can arrive dozens
- // of times per 16ms; each setChats used to re-parse every settled
- // markdown block in the thread.
- let paint = 0;
- const turnRef = { current: turn };
+ turn = { ...turn, connected: true, lastUpdateAt: Date.now() };
+ painter.update(turn);
for await (const update of prompt(handleOf(chatId), id, wire)) {
turn = applyAcpUpdate(turn, update);
if (turn.thoughtMs === undefined && turn.status !== "thinking") turn = { ...turn, thoughtMs: Date.now() - startedAt };
- turnRef.current = turn;
- if (!paint) {
- paint = requestAnimationFrame(() => {
- paint = 0;
- patchAssistant(chatId, asstId, turnRef.current);
- });
- }
+ painter.update(turn);
}
- if (paint) cancelAnimationFrame(paint);
// The turn carried pins, so the agent most likely changed the page:
// reload the chat's tab so the pane shows the result without a click.
if (pins.length > 0) void browserNav(handleOf(chatId), "reload").catch(() => undefined);
if (/^\/(effort|reasoning|fast)(?:\s|$)/.test(trimmed)) void adoptCatalog(chatId);
turn = finishAcpTurn(turn);
- patchAssistant(chatId, asstId, turn);
+ painter.finish(turn);
} catch (err) {
- turn = { ...turn, error: err instanceof Error ? err.message : String(err), status: "error" };
- patchAssistant(chatId, asstId, turn);
+ turn = finishAcpTurn({ ...turn, error: err instanceof Error ? err.message : String(err), status: "error" });
+ painter.finish(turn);
} finally {
+ painter.dispose();
runningRef.current.delete(chatId);
setBusyFor(chatId, false);
void refreshStored();
@@ -889,11 +883,8 @@ export default function GraffHarness() {
};
const tabBar = (
- <div className="flex h-11 shrink-0 items-center border-b border-line px-2">
- {/* The tabs scroll on their own. They used to share this row's scroller
- * with the toolbar, so a handful of open chats pushed the split,
- * workspace and browser controls off the edge — and with the scrollbar
- * hidden, they were simply gone. */}
+ <div className={`${reviewStyles.chatbar} flex h-11 shrink-0 items-center border-b border-line px-2`}>
+ {/* Tabs scroll independently; toolbar labels collapse in narrow panes. */}
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{chats.map((c) => (
<div
@@ -946,7 +937,7 @@ export default function GraffHarness() {
</svg>
</button>
</div>
- <div className="flex shrink-0 items-center gap-2 pl-2 pr-1">
+ <div className={`${reviewStyles.actions} flex shrink-0 items-center gap-2 pl-2 pr-1`}>
<button
type="button"
aria-pressed={conversationsOpen}
@@ -957,7 +948,7 @@ export default function GraffHarness() {
}`}
>
<IconChat size={14} />
- <span className="hidden sm:inline">Chats</span>
+ <span data-toolbar-label className="hidden sm:inline">Chats</span>
</button>
<button
type="button"
@@ -987,7 +978,7 @@ export default function GraffHarness() {
}`}
>
<IconFolder size={14} />
- <span className="max-w-40 truncate font-mono text-[11.5px]">{workspaceName}</span>
+ <span data-toolbar-label className="max-w-40 truncate font-mono text-[11.5px]">{workspaceName}</span>
</button>
<button
type="button"
@@ -1000,7 +991,7 @@ export default function GraffHarness() {
<path d="M6 9l6 6 6-6" />
</svg>
</button>
- <button type="button" onClick={openChanges} className="rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover" aria-label="Review workspace changes">Changes</button>
+ <button type="button" onClick={openChanges} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover" aria-label="Review workspace changes" title="Review workspace changes"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M5 5h14v14H5zM8 9h8M8 12h8M8 15h4" /></svg><span data-toolbar-label>Changes</span></button>
<button
type="button"
aria-pressed={browserOpen}
@@ -1014,7 +1005,7 @@ export default function GraffHarness() {
}`}
>
<IconGlobe size={14} />
- <span className="text-[11.5px]">Browser</span>
+ <span data-toolbar-label className="text-[11.5px]">Browser</span>
{pinCount > 0 && (
<span className="rounded-full bg-accent px-1.5 text-[10px] font-semibold text-white tabular-nums">{pinCount}</span>
)}
diff --git a/apps/native/components/site/ResizableReviewPane.tsx b/apps/native/components/site/ResizableReviewPane.tsx
new file mode 100644
index 00000000..02705bc7
--- /dev/null
+++ b/apps/native/components/site/ResizableReviewPane.tsx
@@ -0,0 +1,65 @@
+"use client";
+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import styles from "./ChangesPane.module.css";
+
+const storageKey = "graff.changes.width";
+const defaultWidth = 650;
+export default function ResizableReviewPane({ children }: { children: ReactNode }) {
+ const frame = useRef<HTMLDivElement>(null);
+ const drag = useRef<{ x: number; width: number } | null>(null);
+ const [preferred, setPreferred] = useState(defaultWidth);
+ const [maximum, setMaximum] = useState(defaultWidth);
+ const [dragging, setDragging] = useState(false);
+ const minimum = Math.min(300, maximum);
+ const width = Math.max(minimum, Math.min(maximum, preferred));
+ const save = (value: number) => {
+ setPreferred(value);
+ try { localStorage.setItem(storageKey, String(value)); } catch { /* Optional preference. */ }
+ };
+ useLayoutEffect(() => {
+ try { const saved = Number(localStorage.getItem(storageKey)); if (Number.isFinite(saved) && saved >= 200) setPreferred(saved); } catch { /* Use default. */ }
+ const parent = frame.current?.parentElement;
+ if (!parent) return;
+ const measure = () => {
+ const available = parent.clientWidth;
+ setMaximum(Math.max(0, available - Math.min(320, available / 2) - 10));
+ };
+ measure();
+ const observer = new ResizeObserver(measure); observer.observe(parent);
+ return () => observer.disconnect();
+ }, []);
+ useLayoutEffect(() => {
+ if (!dragging) return;
+ const { cursor, userSelect } = document.body.style;
+ document.body.style.cursor = "col-resize"; document.body.style.userSelect = "none";
+ return () => { document.body.style.cursor = cursor; document.body.style.userSelect = userSelect; };
+ }, [dragging]);
+ return <div ref={frame} className="relative flex min-h-0 min-w-0 shrink-0" style={{ width }}>
+ <div role="separator" aria-label="Resize changes panel" aria-orientation="vertical" tabIndex={0}
+ aria-valuemin={Math.round(minimum)} aria-valuemax={Math.round(maximum)} aria-valuenow={Math.round(width)}
+ title="Drag to resize · Double-click to reset" className={styles.resize} data-dragging={dragging || undefined}
+ onPointerDown={event => {
+ if (event.button !== 0) return;
+ event.preventDefault(); event.currentTarget.focus({ preventScroll: true });
+ drag.current = { x: event.clientX, width };
+ event.currentTarget.setPointerCapture(event.pointerId); setDragging(true);
+ }}
+ onPointerMove={event => {
+ if (drag.current) setPreferred(Math.max(minimum, Math.min(maximum, drag.current.width + drag.current.x - event.clientX)));
+ }}
+ onPointerUp={event => {
+ if (!drag.current) return;
+ const next = Math.max(minimum, Math.min(maximum, drag.current.width + drag.current.x - event.clientX));
+ drag.current = null; setDragging(false); save(next);
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }}
+ onLostPointerCapture={() => { drag.current = null; setDragging(false); }}
+ onPointerCancel={() => { drag.current = null; setDragging(false); }}
+ onDoubleClick={() => save(defaultWidth)}
+ onKeyDown={event => {
+ const next = event.key === "ArrowLeft" ? width + 20 : event.key === "ArrowRight" ? width - 20 : event.key === "Home" ? minimum : event.key === "End" ? maximum : null;
+ if (next !== null) { event.preventDefault(); save(Math.max(minimum, Math.min(maximum, next))); }
+ }} />
+ {children}
+ </div>;
+}
diff --git a/apps/native/components/site/ReviewActions.tsx b/apps/native/components/site/ReviewActions.tsx
new file mode 100644
index 00000000..aec5f673
--- /dev/null
+++ b/apps/native/components/site/ReviewActions.tsx
@@ -0,0 +1,40 @@
+"use client";
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+export default function ReviewActions({ diff, path, root, viewport, count }: {
+ count: number; diff: string; path: string; root?: string; viewport: RefObject<HTMLElement | null>;
+}) {
+ const [hunk, setHunk] = useState(-1);
+ const [copied, setCopied] = useState(false);
+ const [error, setError] = useState("");
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ useEffect(() => { setHunk(-1); setCopied(false); setError(""); clearTimeout(timer.current); return () => clearTimeout(timer.current); }, [diff, path]);
+ const jump = (direction: number) => {
+ const nodes = viewport.current?.querySelectorAll<HTMLElement>("[data-diff-hunk]");
+ if (!nodes?.length) return;
+ const next = hunk < 0 ? (direction > 0 ? 0 : nodes.length - 1) : (hunk + direction + nodes.length) % nodes.length;
+ nodes[next].scrollIntoView({ block: "start", behavior: "auto" }); setHunk(next);
+ };
+ const copy = async () => {
+ try { await navigator.clipboard.writeText(diff); setError(""); setCopied(true); clearTimeout(timer.current); timer.current = setTimeout(() => setCopied(false), 1800); }
+ catch { setError("Couldn't copy the diff. Try again."); }
+ };
+ const reveal = async () => {
+ try {
+ const reply = await fetch("/api/fs", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action: "reveal", path, root }) });
+ if (!reply.ok) throw Error(); setError("");
+ } catch { setError("Couldn't reveal this file in Finder."); }
+ };
+ const button = "rounded-[6px] px-2 py-1 text-[11px] text-ink-3 hover:bg-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-30";
+ return <footer className="shrink-0 border-t border-line bg-inset px-2 py-1.5">
+ <div className="flex flex-wrap items-center gap-0.5">
+ <button className={button} disabled={!count} aria-label="Previous changed section" onClick={() => jump(-1)}>↑</button>
+ <span className="px-1 font-mono text-[10px] tabular-nums text-ink-3" aria-live="polite">{count ? `${hunk < 0 ? "–" : hunk + 1} / ${count} sections` : "No sections"}</span>
+ <button className={button} disabled={!count} aria-label="Next changed section" onClick={() => jump(1)}>↓</button>
+ <span className="flex-1" />
+ <button className={button} disabled={!diff} onClick={() => void copy()}>{copied ? "Copied" : "Copy diff"}</button>
+ <button className={button} disabled={!path} title="Reveal selected file in Finder" onClick={() => void reveal()}>Reveal</button>
+ </div>
+ {error && <p role="alert" className="px-2 py-1 text-xs text-red">{error}</p>}
+ </footer>;
+}
diff --git a/apps/native/components/site/ReviewDiff.tsx b/apps/native/components/site/ReviewDiff.tsx
new file mode 100644
index 00000000..6ef488fb
--- /dev/null
+++ b/apps/native/components/site/ReviewDiff.tsx
@@ -0,0 +1,13 @@
+import type { ReviewLine } from "@/lib/review-lines";
+export default function ReviewDiff({ rows, wrap }: { rows: ReviewLine[]; wrap: boolean }) {
+ return <div className={`py-2 font-mono text-[11px] leading-[1.8] ${wrap ? "min-w-0" : "min-w-max"}`}>
+ {rows.slice(0, 12000).map((line, i) => line.kind === "hunk"
+ ? <div key={i} data-diff-hunk className="my-1 flex gap-2 border-y border-line/50 bg-hover/40 px-4 py-1.5 text-[10px] text-ink-3"><span>Lines {line.next || line.old}</span>{line.text && <span className="truncate">· {line.text}</span>}</div>
+ : <div key={i} className={`grid grid-cols-[34px_34px_18px_minmax(0,1fr)] pr-4 text-ink-2 ${line.kind === "add" ? "bg-green-tint/60" : line.kind === "remove" ? "bg-red-tint/60" : ""}`}>
+ <span className="select-none pr-2 text-right text-ink-3/60">{line.old}</span><span className="select-none pr-2 text-right text-ink-3/60">{line.next}</span>
+ <span className={`select-none ${line.kind === "add" ? "text-green" : "text-red"}`}>{line.kind === "add" ? "+" : line.kind === "remove" ? "−" : ""}</span>
+ <span className={wrap ? "whitespace-pre-wrap [overflow-wrap:anywhere]" : "whitespace-pre"}>{line.text || " "}</span>
+ </div>)}
+ {rows.length > 12000 && <p className="px-4 py-3 text-ink-3">Showing the first 12,000 diff rows.</p>}
+ </div>;
+}
diff --git a/apps/native/components/site/ThemeSync.tsx b/apps/native/components/site/ThemeSync.tsx
index c6baf470..8dd4ac15 100644
--- a/apps/native/components/site/ThemeSync.tsx
+++ b/apps/native/components/site/ThemeSync.tsx
@@ -1,19 +1,13 @@
"use client";
-
import { useEffect } from "react";
+import { appearanceEvent, appearanceKey, customThemeKey, applyAppearance, readAppearance } from "@/lib/appearance";
-/* React 19 reconciles <html>'s className during hydration, wiping the class
- * the pre-paint head script set. This re-applies the stored theme the moment
- * hydration finishes, on every page. */
export function ThemeSync() {
useEffect(() => {
- try {
- const theme = localStorage.getItem("bui-theme");
- document.documentElement.classList.toggle("dark", theme !== "light");
- } catch {
- document.documentElement.classList.add("dark");
- }
+ const sync = () => applyAppearance(readAppearance());
+ const storage = (event: StorageEvent) => { if (event.key === appearanceKey || event.key === customThemeKey || event.key === null) sync(); };
+ sync(); window.addEventListener(appearanceEvent, sync); window.addEventListener("storage", storage);
+ return () => { window.removeEventListener(appearanceEvent, sync); window.removeEventListener("storage", storage); };
}, []);
-
return null;
}
diff --git a/apps/native/components/site/ThemeToggle.tsx b/apps/native/components/site/ThemeToggle.tsx
index 9065dd69..bd81442d 100644
--- a/apps/native/components/site/ThemeToggle.tsx
+++ b/apps/native/components/site/ThemeToggle.tsx
@@ -1,69 +1,64 @@
"use client";
+import { useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import CustomThemes from "./CustomThemes";
+import { appearanceEvent, appearanceKey, applyAppearance, readAppearance, type Appearance } from "@/lib/appearance";
-import { useEffect, useState } from "react";
+const themes = [
+ { id: "codegraff", name: "CodeGraff", detail: "Official · Japanese palette", bg: "#f6eedf", surface: "#fffaf0", ink: "#1b1714", accent: "#2654d9" },
+ { id: "light", name: "White", detail: "Light and minimal", bg: "#fafafa", surface: "#ffffff", ink: "#25272b", accent: "#3785fa" },
+ { id: "dark", name: "Black", detail: "Quiet charcoal", bg: "#17181b", surface: "#24262a", ink: "#f4f4f5", accent: "#5b9cf7" },
+ { id: "website", name: "Website", detail: "CodeGraff emerald", bg: "#fafaf8", surface: "#ffffff", ink: "#18231e", accent: "#059669" },
+] as const;
-/** Sun/moon segmented pill from the refs. */
export function ThemeToggle() {
- const [dark, setDark] = useState<boolean | null>(null);
-
+ const [theme, setTheme] = useState<Appearance>("dark");
+ const [position, setPosition] = useState<{ top: number; right: number } | null>(null);
+ const trigger = useRef<HTMLButtonElement>(null);
+ const panel = useRef<HTMLDivElement>(null);
useEffect(() => {
- /* localStorage is the source of truth — the html class can be stale
- * for a moment around hydration (see ThemeSync). */
- try {
- setDark(localStorage.getItem("bui-theme") !== "light");
- } catch {
- setDark(document.documentElement.classList.contains("dark"));
- }
+ const sync = () => setTheme(readAppearance());
+ sync(); window.addEventListener(appearanceEvent, sync); window.addEventListener("storage", sync);
+ return () => { window.removeEventListener(appearanceEvent, sync); window.removeEventListener("storage", sync); };
}, []);
-
- function apply(next: boolean) {
- if (next === dark) return;
- setDark(next);
- /* freeze all transitions while every token flips, so the theme change
- * is one clean swap instead of hundreds of mismatched color fades */
- const root = document.documentElement;
- root.classList.add("theme-switching");
- root.classList.toggle("dark", next);
- requestAnimationFrame(() => requestAnimationFrame(() => root.classList.remove("theme-switching")));
- try {
- localStorage.setItem("bui-theme", next ? "dark" : "light");
- } catch {}
- }
-
- return (
- <div className="relative inline-grid h-9 grid-cols-2 items-center rounded-full bg-field p-0.5">
- <span
- aria-hidden
- className="absolute inset-y-0.5 left-0.5 w-8 rounded-full bg-surface shadow-btn
- transition-transform duration-200"
- style={{
- transform: dark ? "translateX(32px)" : "translateX(0)",
- transitionTimingFunction: "cubic-bezier(0.23, 1, 0.32, 1)",
- opacity: dark === null ? 0 : 1,
- }}
- />
- <button
- aria-label="Light mode"
- onClick={() => apply(false)}
- className={`relative z-10 flex size-8 items-center justify-center rounded-full
- transition-colors duration-150 ${dark ? "text-ink-3 hover:text-ink-2" : "text-ink"}`}
- >
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
- <circle cx="12" cy="12" r="4" fill="currentColor" stroke="none" />
- <path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
- </svg>
- </button>
- <button
- aria-label="Dark mode"
- onClick={() => apply(true)}
- className={`relative z-10 flex size-8 items-center justify-center rounded-full
- transition-colors duration-150 ${dark ? "text-ink" : "text-ink-3 hover:text-ink-2"}`}
- >
- <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
- <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
- </svg>
- </button>
-
- </div>
- );
+ useEffect(() => {
+ if (!position) return;
+ panel.current?.querySelector<HTMLButtonElement>('[aria-pressed="true"]')?.focus();
+ const outside = (event: PointerEvent) => { if (!panel.current?.contains(event.target as Node) && !trigger.current?.contains(event.target as Node)) setPosition(null); };
+ const keys = (event: KeyboardEvent) => {
+ if (event.key === "Escape") { event.stopPropagation(); setPosition(null); trigger.current?.focus(); }
+ if (event.key === "Tab") {
+ const buttons = Array.from(panel.current?.querySelectorAll<HTMLButtonElement>("button") ?? []);
+ const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
+ if (index >= 0) { event.preventDefault(); buttons[(index + (event.shiftKey ? buttons.length - 1 : 1)) % buttons.length]?.focus(); }
+ }
+ };
+ const close = () => setPosition(null);
+ document.addEventListener("pointerdown", outside); document.addEventListener("keydown", keys);
+ window.addEventListener("resize", close);
+ return () => { document.removeEventListener("pointerdown", outside); document.removeEventListener("keydown", keys); window.removeEventListener("resize", close); };
+ }, [position]);
+ const choose = (next: Appearance) => {
+ document.documentElement.classList.add("theme-switching");
+ applyAppearance(next); setTheme(next);
+ try { localStorage.setItem(appearanceKey, next); } catch {}
+ window.dispatchEvent(new Event(appearanceEvent));
+ requestAnimationFrame(() => requestAnimationFrame(() => document.documentElement.classList.remove("theme-switching")));
+ };
+ return <>
+ <button ref={trigger} aria-label="Appearance" title="Appearance" aria-haspopup="dialog" aria-expanded={!!position} onClick={() => {
+ const rect = trigger.current!.getBoundingClientRect();
+ setPosition(position ? null : { top: Math.max(48, Math.min(rect.bottom + 8, window.innerHeight - 420)), right: Math.max(8, window.innerWidth - rect.right) });
+ }} className="flex size-8 shrink-0 items-center justify-center rounded-lg text-ink-3 hover:bg-hover hover:text-ink">
+ <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="12" r="8" /><path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none" /></svg>
+ </button>
+ {position && createPortal(<div ref={panel} role="dialog" aria-label="Appearance" aria-modal="true" className="fixed z-[200] w-[310px] max-w-[calc(100vw-16px)] overflow-y-auto rounded-xl border border-line bg-surface p-3 shadow-overlay" style={{ ...position, maxHeight: `calc(100dvh - ${position.top + 12}px)` }}>
+ <div className="mb-3 flex items-center justify-between"><strong className="text-xs font-medium">Appearance</strong><button aria-label="Close appearance" onClick={() => { setPosition(null); trigger.current?.focus(); }} className="rounded px-1.5 text-ink-3 hover:bg-hover">×</button></div>
+ <div className="grid grid-cols-2 gap-2">{themes.map(option => <button key={option.id} aria-pressed={theme === option.id} onClick={() => choose(option.id)} className={`rounded-lg border p-1.5 text-left focus-visible:outline-2 focus-visible:outline-accent ${theme === option.id ? "border-accent bg-accent-tint" : "border-line hover:bg-hover"}`}>
+ <span aria-hidden="true" className="mb-2 flex h-14 gap-1 overflow-hidden rounded p-1.5" style={{ background: option.bg }}><span className="w-3 rounded-sm" style={{ background: option.id === "codegraff" ? "#d45a43" : option.accent, opacity: .35 }} /><span className="flex flex-1 flex-col gap-1 rounded p-1" style={{ background: option.surface }}><span className="h-1 w-5 rounded" style={{ background: option.ink, opacity: .45 }} /><span className="h-1 w-8 rounded" style={{ background: option.ink, opacity: .15 }} /><span className="mt-auto h-1.5 w-4 rounded" style={{ background: option.accent }} /></span></span>
+ <span className="block text-[11px] font-medium text-ink">{option.name}</span><span className="block text-[9px] leading-4 text-ink-3">{option.detail}</span>
+ </button>)}</div>
+ <CustomThemes selected={theme} />
+ </div>, document.body)}
+ </>;
}
diff --git a/apps/native/components/site/TurnActivity.tsx b/apps/native/components/site/TurnActivity.tsx
new file mode 100644
index 00000000..d1503249
--- /dev/null
+++ b/apps/native/components/site/TurnActivity.tsx
@@ -0,0 +1,24 @@
+"use client";
+import { useEffect, useState } from "react";
+import type { AssistantTurn } from "@/lib/acp";
+import { turnActivity } from "@/lib/turn-activity";
+export default function TurnActivity({ turn }: { turn: AssistantTurn }) {
+ const [now, setNow] = useState(Date.now);
+ const active = turn.status === "thinking" || turn.status === "streaming";
+ useEffect(() => {
+ if (!active) { setNow(Date.now()); return; }
+ let timer: ReturnType<typeof setInterval> | undefined;
+ const sync = () => {
+ clearInterval(timer); setNow(Date.now());
+ if (document.visibilityState !== "hidden") timer = setInterval(() => setNow(Date.now()), 1000);
+ };
+ sync(); document.addEventListener("visibilitychange", sync);
+ return () => { clearInterval(timer); document.removeEventListener("visibilitychange", sync); };
+ }, [active]);
+ if (!turn.startedAt && !active && !turn.error) return null;
+ const activity = turnActivity(turn, now);
+ return <div data-turn-activity={activity.state} className={`mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] ${activity.state === "error" ? "text-red" : activity.live ? "text-ink-2" : "text-ink-3"}`}>
+ {activity.live ? <span aria-hidden="true" className="size-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-r-transparent motion-reduce:animate-none" /> : <span aria-hidden="true">{activity.state === "error" ? "!" : activity.label === "Stopped" ? "■" : "✓"}</span>}
+ <span role="status" aria-live="polite">{activity.label}</span><span aria-hidden="true">·</span><span data-activity-detail className="tabular-nums">{activity.detail}</span>
+ </div>;
+}
diff --git a/apps/native/electron/README.md b/apps/native/electron/README.md
index a8d3aa50..ab3ac001 100644
--- a/apps/native/electron/README.md
+++ b/apps/native/electron/README.md
@@ -114,3 +114,11 @@ The macOS window keeps native close/minimize/full-screen controls in a reserved
draggable titlebar. For smoke runs while using another app, set
`GRAFF_SMOKE_SKIP_INPUT=1` to skip native keyboard injection; the report records
that omission.
+
+The v2 profiler adds document LCP/FCP, maximum observed interaction duration,
+recording-period layout shift, renderer heap and DOM size, GPU-process CPU/RSS
+and allowlisted Chromium acceleration status. Unavailable metrics remain null.
+It does not claim GPU utilization, dedicated VRAM, field INP/CLS or a Lighthouse
+score. Chromium chooses its supported GPU backend; no forced driver flags or
+custom Metal pipeline are needed for the current DOM-based interface.
+See [repeatable performance scenarios](VISUAL-TESTS.md) for the model-free runner.
diff --git a/apps/native/electron/VISUAL-TESTS.md b/apps/native/electron/VISUAL-TESTS.md
new file mode 100644
index 00000000..004bbdf3
--- /dev/null
+++ b/apps/native/electron/VISUAL-TESTS.md
@@ -0,0 +1,51 @@
+# Desktop visual tests
+
+From `apps/native`, run `bun run build`, then `bun run test:visual`.
+This opens an isolated Electron window, renders scripted turn states, and
+checks visible progress, layout, disclosure state, completion and interruption
+in White, Black and CodeGraff themes. PNGs and results go to
+`zig-out/visual-tests`; set `GRAFF_VISUAL_OUTPUT` to use another directory.
+
+No engine binary, model account, MCP server or model request is used. Requests
+to API routes are blocked and fail the test. The fixture page is unavailable
+unless the test server sets `GRAFF_VISUAL_TESTS=1`. Tests use the production
+transcript components, with deterministic input data rather than model output.
+
+`bun run test:desktop` also covers transport parsing, turn-state decisions and
+the deferred-render race. The packaged Electron smoke suite exercises the
+composer and scripted streaming path in addition to its engine integration.
+
+## Repeatable performance and README captures
+
+`bun run test:performance` runs the visual suite followed by a synthetic full-GUI
+workload: startup, a reply, Appearance changes, review, and a longer streamed
+transcript. It writes `performance.json` and `desktop-*.png` beside the visual
+results. Its fetch adapter supplies fixed demonstration content before hydration;
+the runner blocks any API request that escapes the adapter. No credentials,
+workspace contents, engine process or model is needed.
+
+The baseline phase covers startup and controls; the candidate phase covers
+streaming. These are different workloads, **not** an optimization A/B result.
+Compare the same phase across repeated runs on the same machine and app build.
+The test window disables background throttling to make off-focus test runs
+reliable; the normal application still throttles hidden windows. Run visual
+runners one at a time, without rebuilding the UI during a run.
+
+The profile includes document LCP/FCP, peak observed interaction duration, summed
+layout shift during recording, renderer JS heap/DOM size, process-tree RSS/CPU,
+main-loop delay and GPU-process CPU/RSS. LCP is a startup metric; it does not
+measure streamed replies. Scripted `.click()` calls are not trusted user input
+and may produce no Event Timing samples. Missing values stay null. This report
+is neither a Lighthouse score nor field INP/CLS. GPU utilization/VRAM are not
+available through these metrics; GPU-process memory overlaps process-tree RSS.
+
+For a live agent-driven profile, use the desktop `profiler` tool's `start`,
+`mark` (baseline/candidate), `report` and `stop` operations. Reload the window
+while recording to collect fresh startup timings, then reproduce the same
+interaction in each phase. Observers and samples stop when recording stops;
+recording is off by default and capped at ten minutes. Export via the Performance
+menu when a local feedback artifact is wanted.
+
+To refresh the README, inspect the synthetic `desktop-*.png` files, then copy
+selected captures into `docs/images`. Keep test reports and real-user screenshots
+out of public documentation.
diff --git a/apps/native/electron/browser-actions.cjs b/apps/native/electron/browser-actions.cjs
index 46d765db..14656ad9 100644
--- a/apps/native/electron/browser-actions.cjs
+++ b/apps/native/electron/browser-actions.cjs
@@ -29,7 +29,7 @@ async function browserAction(browser, chat, method, params = {}) {
wc.sendInputEvent({ type: 'keyDown', keyCode: params.key, modifiers });
wc.sendInputEvent({ type: 'keyUp', keyCode: params.key, modifiers }); return { ok: true };
}
- if (method === 'find') { wc.findInPage(String(params.text || ''), { forward: params.forward !== false }); return { ok: true }; }
+ if (method === 'find') { const text = String(params.text || ''); if (text) wc.findInPage(text, { forward: params.forward !== false }); else wc.stopFindInPage('clearSelection'); return { ok: true }; }
if (method === 'zoom') { const factor = Number(params.factor); if (!Number.isFinite(factor) || factor < 0.5 || factor > 2) throw new Error('Zoom must be 0.5 to 2'); wc.setZoomFactor(factor); return { factor }; }
throw new Error('Unsupported browser action');
}
diff --git a/apps/native/electron/browser-actions.test.cjs b/apps/native/electron/browser-actions.test.cjs
new file mode 100644
index 00000000..872de356
--- /dev/null
+++ b/apps/native/electron/browser-actions.test.cjs
@@ -0,0 +1,13 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { browserAction } = require('./browser-actions.cjs');
+test('empty Find clears Chromium highlights and navigation does not need a rendered page', async () => {
+ const calls = [];
+ const browser = { tabs: new Map([['chat', { view: { webContents: {
+ findInPage: text => calls.push(text), stopFindInPage: mode => calls.push(mode),
+ } } }]]) };
+ await browserAction(browser, 'chat', 'find', { text: 'word' });
+ await browserAction(browser, 'chat', 'find', { text: '' });
+ assert.deepEqual(calls, ['word', 'clearSelection']);
+ await assert.rejects(browserAction(browser, 'closed', 'find', { text: 'word' }), /closed or suspended/);
+});
diff --git a/apps/native/electron/browser-tabs.cjs b/apps/native/electron/browser-tabs.cjs
index cdedee94..c3a4c766 100644
--- a/apps/native/electron/browser-tabs.cjs
+++ b/apps/native/electron/browser-tabs.cjs
@@ -16,7 +16,8 @@ class BrowserTabs {
const wc = tab.view?.webContents;
return { tabId: tab.chat, url: wc?.getURL() || tab.url, title: wc?.getTitle() || '',
width: tab.rect?.width || 0, height: tab.rect?.height || 0,
- ready: wc ? 'complete' : 'suspended', suspended: !wc };
+ ready: wc ? (wc.isLoading() ? 'loading' : 'complete') : 'suspended', suspended: !wc,
+ canGoBack: wc?.navigationHistory.canGoBack() ?? false, canGoForward: wc?.navigationHistory.canGoForward() ?? false };
}
notify(tab) { this.emit({ chat: tab.chat, type: 'info', info: this.info(tab) }); }
create(chat) {
@@ -36,7 +37,7 @@ class BrowserTabs {
tab.view = view;
const wc = view.webContents;
let navigationStarted = 0;
- wc.on('did-start-loading', () => { navigationStarted = performance.now(); this.profiler?.record('page-navigation'); });
+ wc.on('did-start-loading', () => { navigationStarted = performance.now(); this.profiler?.record('page-navigation'); this.notify(tab); });
wc.on('did-finish-load', () => { this.profiler?.record('page-loaded', performance.now() - navigationStarted); wc.send('profile-enabled', !!this.profiler?.active); });
wc.setWindowOpenHandler(({ url }) => {
void this.navigate(chat, url).catch(() => {}); return { action: 'deny' };
@@ -64,8 +65,9 @@ class BrowserTabs {
attach(tab) {
if (this.visible && this.visible !== tab.chat) this.hide(this.visible);
this.visible = tab.chat; clearTimeout(tab.timer);
- if (tab.view && tab.rect) { tab.view.setBounds(tab.rect); tab.view.setVisible(tab.rect.width > 0 && tab.rect.height > 0); }
+ if (tab.view && tab.rect) { tab.view.setBounds(tab.rect); tab.view.setVisible(!this.overlay && tab.rect.width > 0 && tab.rect.height > 0); }
}
+ setOverlay(blocked) { this.overlay = blocked; const tab = this.tabs.get(this.visible); if (tab) this.attach(tab); }
setBounds(chat, rect) {
let tab = this.tabs.get(chat);
const size = this.window.getContentBounds();
diff --git a/apps/native/electron/build.sh b/apps/native/electron/build.sh
index f1abc471..fe1bfe07 100644
--- a/apps/native/electron/build.sh
+++ b/apps/native/electron/build.sh
@@ -11,7 +11,13 @@ bun install --frozen-lockfile
if [[ ! -f node_modules/electron/path.txt ]]; then bun node_modules/electron/install.js; fi
bun run --bun build
cd "$root"
-zig build graff -Doptimize=ReleaseFast -Dversion="$version"
+# GUI-only iteration can reuse the already-built engine without rebuilding its cache.
+if [[ "${GRAFF_REUSE_ENGINE:-0}" != "1" ]]; then
+ zig build graff -Doptimize=ReleaseFast -Dversion="$version"
+elif [[ ! -x "$root/zig-out/bin/graff" ]]; then
+ echo "No built graff executable to reuse. Run without GRAFF_REUSE_ENGINE." >&2
+ exit 1
+fi
mkdir -p "$out"
# This directory is an isolated build artifact, never the installed application.
rm -rf "$bundle"
diff --git a/apps/native/electron/external-links.cjs b/apps/native/electron/external-links.cjs
new file mode 100644
index 00000000..a785031d
--- /dev/null
+++ b/apps/native/electron/external-links.cjs
@@ -0,0 +1,14 @@
+// Only normal web links can leave the app; never hand arbitrary schemes to the OS.
+function externalURL(raw) {
+ try { const url = new URL(raw); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? url.href : null; }
+ catch { return null; }
+}
+function installExternalLinks(contents, origin, open = url => require('electron').shell.openExternal(url)) {
+ const launch = raw => { const url = externalURL(raw); if (url) void Promise.resolve(open(url)).catch(() => {}); };
+ contents.on('will-navigate', (event, url) => {
+ if (new URL(url).origin === origin) return;
+ event.preventDefault(); launch(url);
+ });
+ contents.setWindowOpenHandler(({ url }) => { launch(url); return { action: 'deny' }; });
+}
+module.exports = { externalURL, installExternalLinks };
diff --git a/apps/native/electron/external-links.test.cjs b/apps/native/electron/external-links.test.cjs
new file mode 100644
index 00000000..402ddda6
--- /dev/null
+++ b/apps/native/electron/external-links.test.cjs
@@ -0,0 +1,15 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { EventEmitter } = require('node:events');
+const { externalURL, installExternalLinks } = require('./external-links.cjs');
+test('clicked web links leave the shell; executable schemes cannot reach the OS', () => {
+ const contents = new EventEmitter(); let popup; const opened = [];
+ contents.setWindowOpenHandler = handler => { popup = handler; };
+ installExternalLinks(contents, 'http://127.0.0.1:3788', url => opened.push(url));
+ let prevented = false;
+ contents.emit('will-navigate', { preventDefault() { prevented = true; } }, 'https://example.com/docs');
+ assert.equal(prevented, true); assert.deepEqual(opened, ['https://example.com/docs']);
+ popup({ url: 'https://example.com/help' }); popup({ url: 'file:///etc/passwd' });
+ assert.equal(opened.length, 2);
+ for (const url of ['javascript:alert(1)', 'data:text/html,hi', 'https://user:[email protected]', 'not a URL']) assert.equal(externalURL(url), null);
+});
diff --git a/apps/native/electron/gallery-fixture.cjs b/apps/native/electron/gallery-fixture.cjs
new file mode 100644
index 00000000..1d8c11da
--- /dev/null
+++ b/apps/native/electron/gallery-fixture.cjs
@@ -0,0 +1,41 @@
+// Synthetic content for reproducible screenshots; never reads the user's workspace.
+function installGalleryFixture() {
+ const original = window.fetch;
+ localStorage.setItem('graff.native.browser.open', '0');
+ const root = '/demo/field-notes';
+ const catalog = { result: { current: { model: 'Graff', provider: '', effort: 'medium', fast: false, effortLevels: ['low', 'medium', 'high'] }, models: [{ name: 'Graff', provider: '', context: 128000, authenticated: true, cost: 'local', current: true }] } };
+ const json = body => new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });
+ const delta = text => ({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'demo', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } } });
+ window.fetch = async (input, options) => {
+ const url = new URL(typeof input === 'string' ? input : input.url, location.origin);
+ if (!url.pathname.startsWith('/api/')) return original(input, options);
+ if (url.pathname === '/api/models') return json(catalog);
+ if (url.pathname === '/api/sessions') return json({ cwd: root, sessions: [], total: 0, nextCursor: null });
+ if (url.pathname === '/api/themes') return json({ themes: [], issues: [] });
+ if (url.pathname === '/api/title') return json({ title: 'A calmer workspace' });
+ if (url.pathname === '/api/git') {
+ if (options?.method === 'POST') return json({ diff: 'diff --git a/palette.css b/palette.css\n--- a/palette.css\n+++ b/palette.css\n@@ -1,5 +1,6 @@\n :root {\n- --paper: #ffffff;\n- --ink: #000000;\n+ --paper: #f6eedf;\n+ --ink: #211e19;\n+ --accent: #567568;\n --radius: 12px;\n }\n' });
+ return json({ root, branch: 'main', files: [{ path: 'palette.css', add: 3, del: 2, untracked: false, status: ' M', binary: false }], totalAdd: 3, totalDel: 2, commits: [], worktrees: [{ path: root, branch: 'main' }] });
+ }
+ if (url.pathname === '/api/acp') {
+ if (!options?.body) return json({ ok: true, cwd: root, home: '/demo' });
+ const body = JSON.parse(options.body);
+ if (body.method === 'bootstrap') return json({ sessionId: 'demo', commands: [] });
+ if (body.method === 'graff/models') return json(catalog);
+ if (body.method === 'session/prompt') {
+ const text = window.galleryBenchmark ? ('A responsive workspace keeps the conversation readable as updates arrive.\n\n').repeat(80) : 'The workspace now has a softer palette and a clearer review flow.\n\n### Ready to explore\n\n- **Appearance:** switch between White, Black, Website and CodeGraff, or add your own theme.\n- **Changes:** review edits beside the conversation and drag the divider to make room.\n- **Browser:** open a page, pin an element and ask Graff to work with it.\n\nEverything is ready for your review.';
+ return new Response(new ReadableStream({ start(controller) {
+ let index = 0;
+ const send = value => controller.enqueue(new TextEncoder().encode(JSON.stringify(value) + '\n'));
+ const timer = setInterval(() => {
+ send(delta(text.slice(index, index + 24))); index += 24;
+ if (index >= text.length) { clearInterval(timer); send({ jsonrpc: '2.0', id: 1, result: { stopReason: 'end_turn' } }); controller.close(); }
+ }, window.galleryBenchmark ? 25 : 5);
+ }}), { headers: { 'content-type': 'application/x-ndjson' } });
+ }
+ return json({ result: {} });
+ }
+ return new Response('{}', { status: 404 });
+ };
+}
+module.exports = { installGalleryFixture };
diff --git a/apps/native/electron/hardware-profile.cjs b/apps/native/electron/hardware-profile.cjs
new file mode 100644
index 00000000..bd9acc66
--- /dev/null
+++ b/apps/native/electron/hardware-profile.cjs
@@ -0,0 +1,11 @@
+const FEATURES = ['gpu_compositing', 'rasterization', 'opengl', 'webgl', 'webgl2', 'webgpu', 'video_decode', 'video_encode'];
+const STATES = new Set(['enabled', 'enabled_on', 'enabled_force', 'enabled_readback', 'disabled_off', 'disabled_software', 'disabled_off_ok', 'unavailable_off', 'unavailable_software', 'unavailable_off_ok']);
+function accelerationStatus(raw = {}) {
+ return Object.fromEntries(FEATURES.map(key => [key, STATES.has(raw[key]) ? raw[key] : 'unknown']));
+}
+function chromiumSample(rows = []) {
+ const gpu = rows.filter(row => row.type === 'GPU');
+ return { gpuProcessCpuPercent: gpu.reduce((n, row) => n + (Number.isFinite(row.cpu?.percentCPUUsage) ? row.cpu.percentCPUUsage : 0), 0),
+ gpuProcessRssMiB: gpu.reduce((n, row) => n + (Number.isFinite(row.memory?.workingSetSize) ? row.memory.workingSetSize / 1024 : 0), 0) };
+}
+module.exports = { accelerationStatus, chromiumSample };
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index c5fabd64..3859fde2 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -4,17 +4,21 @@ const { randomBytes } = require('node:crypto');
const { treeSample, intervalSampler } = require('./process-metrics.cjs');
const { BrowserTabs } = require('./browser-tabs.cjs');
const { startAutomation } = require('./automation.cjs');
+const { installExternalLinks } = require('./external-links.cjs');
const { startServer } = require('./server.cjs');
const { ComputerUse } = require('./computer.cjs');
const { desktopConfig } = require('./desktop-config.cjs');
const { browserAction } = require('./browser-actions.cjs');
const { Profiler } = require('./profiler.cjs');
+const { rendererSample } = require('./renderer-profile.cjs');
+const { chromiumSample } = require('./hardware-profile.cjs');
const fs = require('node:fs/promises');
const root = process.env.GRAFF_CWD || app.getPath('home');
const resources = process.env.GRAFF_ELECTRON_RESOURCES || process.resourcesPath;
app.setName('Codegraff');
-app.setPath('userData', path.join(app.getPath('appData'), 'Codegraff Electron'));
+app.setPath('userData', process.env.GRAFF_ELECTRON_SMOKE ? path.join(require('node:os').tmpdir(), `codegraff-smoke-${process.pid}`) : path.join(app.getPath('appData'), 'Codegraff Electron'));
+if (process.env.GRAFF_ELECTRON_SMOKE) process.env.GRAFF_THEMES_DIR = path.join(app.getPath('userData'), 'themes');
let win, browser, backend, automation, computer, profiler;
let quitting = false;
@@ -49,20 +53,26 @@ app.whenReady().then(async () => {
win = new BrowserWindow({ width: 1440, height: 920, minWidth: 900, minHeight: 600,
title: 'Codegraff', titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 14, y: 11 }, backgroundColor: '#fafaf9', show: false,
webPreferences: { preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:app',
- contextIsolation: true, sandbox: true, nodeIntegration: false, backgroundThrottling: true } });
+ contextIsolation: true, sandbox: true, nodeIntegration: false, backgroundThrottling: !process.env.GRAFF_ELECTRON_SMOKE } });
browser = new BrowserTabs(win, message => { if (!win.isDestroyed()) win.webContents.send('browser-event', message); });
win.on('close', () => browser.closeAll());
win.webContents.on('did-start-navigation', (_event, _url, inPlace, mainFrame) => {
if (mainFrame && !inPlace) browser.closeAll();
});
computer = new ComputerUse(resources, win);
- profiler = new Profiler(intervalSampler(process.pid, () => browser.liveCount), enabled => {
+ const sampleTree = intervalSampler(process.pid, () => browser.liveCount);
+ profiler = new Profiler(async () => {
+ const [tree, renderer] = await Promise.all([sampleTree(), rendererSample(win.webContents).catch(() => ({}))]);
+ return { ...tree, ...renderer, ...chromiumSample(app.getAppMetrics()) };
+ }, enabled => {
+ if (!enabled) void rendererSample(win.webContents, false).catch(() => {});
if (win.isDestroyed()) return;
for (const contents of [win.webContents, ...[...browser.tabs.values()].map(tab => tab.view?.webContents).filter(Boolean)]) {
if (!contents.isDestroyed()) contents.send('profile-enabled', enabled);
}
- });
+ }, () => app.getGPUFeatureStatus());
browser.profiler = profiler;
+ win.webContents.on('did-finish-load', () => win.webContents.send('profile-enabled', !!profiler.active));
win.webContents.on('render-process-gone', () => profiler.record('renderer-crash'));
ipcMain.on('profile-longtask', (event, duration) => {
const owned = event.sender === win.webContents || [...browser.tabs.values()].some(tab => tab.view?.webContents === event.sender);
@@ -87,14 +97,14 @@ app.whenReady().then(async () => {
if (!['open', 'navigate', 'back', 'forward', 'reload', 'info', 'bounds', 'hide', 'close', 'stop', 'pick', 'find', 'zoom'].includes(method)) throw new Error('Unknown action');
return ['find', 'zoom'].includes(method) ? browserAction(browser, chat, method, params) : browser.command(chat, method, params);
});
+ ipcMain.on('browser-overlay', (event, blocked) => { trusted(event); browser.setOverlay(blocked === true); });
ipcMain.handle('activity', event => { trusted(event); return activity(); });
ipcMain.on('browser-pin', (event, pin) => {
const tab = [...browser.tabs.values()].find(t => t.view?.webContents === event.sender);
if (!tab || event.senderFrame !== event.sender.mainFrame || !pin?.element || JSON.stringify(pin).length > 16000) return;
win.webContents.send('browser-event', { chat: tab.chat, type: 'pin', pin });
});
- win.webContents.on('will-navigate', (event, url) => { if (new URL(url).origin !== backend.origin) event.preventDefault(); });
- win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ installExternalLinks(win.webContents, backend.origin);
win.on('minimize', () => { if (browser.visible) browser.hide(browser.visible); });
win.on('restore', () => win.webContents.send('browser-event', { type: 'layout' }));
Menu.setApplicationMenu(Menu.buildFromTemplate([
diff --git a/apps/native/electron/performance-scenarios.cjs b/apps/native/electron/performance-scenarios.cjs
new file mode 100644
index 00000000..b2f9818c
--- /dev/null
+++ b/apps/native/electron/performance-scenarios.cjs
@@ -0,0 +1,78 @@
+const fs = require('node:fs');
+const path = require('node:path');
+const { app, BrowserWindow, ipcMain } = require('electron');
+const { Profiler } = require('./profiler.cjs');
+const { intervalSampler } = require('./process-metrics.cjs');
+const { rendererSample } = require('./renderer-profile.cjs');
+const { chromiumSample } = require('./hardware-profile.cjs');
+const { installGalleryFixture } = require('./gallery-fixture.cjs');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function runPerformance({ win: fixtureWindow, origin, output }) {
+ const win = new BrowserWindow({ width: 1440, height: 920, show: true, titleBarStyle: 'hiddenInset',
+ webPreferences: { preload: path.join(__dirname, 'preload.cjs'), sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ fixtureWindow.destroy();
+ await win.loadURL('about:blank');
+ ipcMain.handle('browser', () => null);
+ // The gallery uses the real desktop preload but no engine or browser backends.
+
+ const wc = win.webContents, js = code => wc.executeJavaScript(code);
+ wc.on('console-message', event => { if (/Error|error|Illegal/.test(event.message || '')) console.error('Fixture renderer:', event.message); });
+ const wait = async expression => { for (let n = 0; n < 300; n++) { if (await js(expression)) return; await sleep(50); } throw Error(`Scenario timeout: ${expression}; ${await js("JSON.stringify({state:document.querySelector('[data-turn-activity]')?.textContent,text:document.querySelector('article')?.textContent,visibility:document.visibilityState})")}`); };
+ wc.debugger.attach('1.3');
+ await wc.debugger.sendCommand('Page.enable');
+ await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `(${installGalleryFixture.toString()})()` });
+ win.setSize(1440, 920); win.show(); win.focus();
+ const sampleTree = intervalSampler(process.pid, () => 0);
+ const profiler = new Profiler(async () => ({ ...await sampleTree(), ...await rendererSample(wc), ...chromiumSample(app.getAppMetrics()) }), enabled => { wc.send('profile-enabled', enabled); }, () => app.getGPUFeatureStatus());
+ const longTask = (event, duration) => { if (event.sender === wc && Number.isFinite(duration)) profiler.record('renderer-long-task', duration); };
+ ipcMain.on('profile-longtask', longTask);
+ try {
+ console.log('Performance: loading desktop fixture');
+ await wc.loadURL(origin);
+ console.log('Performance: desktop loaded');
+ await wait(`document.querySelector('[aria-label="Appearance"]') && document.querySelector('textarea[aria-label="Prompt"]')`);
+ console.log('Performance: recording');
+ await profiler.start(); await sleep(2200); await profiler.capture(0);
+ const send = async text => {
+ await js(`(()=>{const input=document.querySelector('textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(input,${JSON.stringify(text)});input.dispatchEvent(new Event('input',{bubbles:true}));})()`);
+ await wait(`!document.querySelector('[aria-label="Send"]').disabled`);
+ await js(`document.querySelector('[aria-label="Send"]').click()`);
+ await wait(`!!document.querySelector('article[aria-busy="true"]')`);
+ await wait(`!document.querySelector('article[aria-busy="true"]')`);
+ };
+ console.log('Performance: first reply');
+ await send('Make this workspace feel calm and easy to use.');
+ await js('document.fonts.ready.then(()=>true)');
+ const click = async selector => {
+ const point = await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
+ wc.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ wc.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
+ };
+ const capture = async name => {
+ console.log('Performance: capture', name);
+ await js(`document.activeElement?.blur(); document.querySelector('button[title^="graff session "] span').textContent='Demo workspace'`);
+ await js(`Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{}))).then(()=>true)`);
+ await sleep(200);
+ fs.writeFileSync(path.join(output, name), (await wc.capturePage()).toPNG());
+ };
+ for (const [label, name] of [['Black', 'desktop-chat-dark.png'], ['CodeGraff', 'desktop-chat-codegraff.png']]) {
+ await click('[aria-label="Appearance"]');
+ await wait(`!!document.querySelector('[aria-label="Close appearance"]')`);
+ await js(`[...document.querySelectorAll('[role="dialog"] button')].find(b=>b.textContent.startsWith(${JSON.stringify(label)})).click(); document.querySelector('[aria-label="Close appearance"]').click()`);
+ await capture(name);
+ }
+ await js(`document.querySelector('[aria-label="Review workspace changes"]').click()`);
+ await wait(`document.querySelector('[aria-label="File diff"]')?.getAttribute('aria-busy')==='false'`);
+ await capture('desktop-review-codegraff.png');
+ await js(`document.querySelector('[aria-label="Close changes"]').click(); window.galleryBenchmark=true`);
+ console.log('Performance: stream');
+ profiler.mark('candidate');
+ await send('Stream the demonstration transcript.');
+ await profiler.capture(0); profiler.stop();
+ const report = profiler.report();
+ report.scenario = 'Synthetic full GUI: baseline startup and controls; candidate streamed transcript. Different workloads, not a before/after optimization claim. No engine or model calls.';
+ fs.writeFileSync(path.join(output, 'performance.json'), JSON.stringify(report, null, 2));
+ console.log(JSON.stringify({ baseline: report.baseline, streaming: report.candidate, acceleration: report.acceleration }));
+ } finally { profiler.stop(); await rendererSample(wc, false); wc.debugger.detach(); ipcMain.removeHandler('browser'); ipcMain.removeListener('profile-longtask', longTask); win.destroy(); }
+}
+module.exports = { runPerformance };
diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjs
index 3e759c8a..5c473ef0 100644
--- a/apps/native/electron/preload.cjs
+++ b/apps/native/electron/preload.cjs
@@ -18,3 +18,28 @@ ipcRenderer.on('profile-enabled', (_event, enabled) => {
});
longTasks.observe({ type: 'longtask', buffered: false });
});
+
+// Native web views sit above HTML, so app dialogs need their page temporarily hidden.
+window.addEventListener('DOMContentLoaded', () => {
+ const selector = '[role="dialog"],[role="menu"],[role="listbox"]';
+ const overlays = new Set(document.querySelectorAll(selector));
+ let scheduled = false, previous = false;
+ const update = () => {
+ scheduled = false;
+ for (const element of overlays) if (!element.isConnected || !element.matches(selector)) overlays.delete(element);
+ const blocked = [...overlays].some(element => element.checkVisibility());
+ if (blocked !== previous) { previous = blocked; ipcRenderer.send('browser-overlay', blocked); }
+ };
+ new MutationObserver(records => {
+ for (const record of records) {
+ if (record.type === 'attributes' && record.target.matches(selector)) overlays.add(record.target);
+ for (const node of record.addedNodes) if (node instanceof Element) {
+ if (node.matches(selector)) overlays.add(node);
+ for (const element of node.querySelectorAll(selector)) overlays.add(element);
+ }
+ }
+ // Streaming text changes never rescan the entire growing transcript.
+ if (!scheduled && (overlays.size || previous)) { scheduled = true; queueMicrotask(update); }
+ }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['hidden', 'aria-hidden', 'role'] });
+ update();
+});
diff --git a/apps/native/electron/profiler.cjs b/apps/native/electron/profiler.cjs
index 8cc27e0b..6daea5d9 100644
--- a/apps/native/electron/profiler.cjs
+++ b/apps/native/electron/profiler.cjs
@@ -1,8 +1,10 @@
const { performance } = require('node:perf_hooks');
+const { accelerationStatus } = require('./hardware-profile.cjs');
+const OPTIONAL = ['lcpMs', 'fcpMs', 'interactionMaxMs', 'layoutShift', 'rendererHeapMiB', 'domNodes', 'gpuProcessCpuPercent', 'gpuProcessRssMiB'];
const EVENTS = new Set(['ui-ready', 'page-navigation', 'page-loaded', 'renderer-crash', 'browser-action', 'computer-action', 'action-failed', 'renderer-long-task']);
const finite = value => Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
class Profiler {
- constructor(sample, notify = () => {}) { this.sample = sample; this.notify = notify; this.timer = null; this.samples = []; this.events = []; this.phase = 'baseline'; this.started = 0; this.busy = false; }
+ constructor(sample, notify = () => {}, hardware = () => ({})) { this.sample = sample; this.hardware = hardware; this.notify = notify; this.timer = null; this.samples = []; this.events = []; this.phase = 'baseline'; this.started = 0; this.busy = false; this.generation = 0; }
async start() {
this.stop(); this.samples = []; this.events = []; this.started = performance.now(); this.phase = 'baseline';
this.active = true; this.notify(true); this.expected = performance.now() + 2000;
@@ -12,18 +14,19 @@ class Profiler {
}, 2000);
this.timer.unref(); await this.capture(0); return this.status();
}
- stop() { clearInterval(this.timer); this.timer = null; this.active = false; this.notify(false); return this.status(); }
+ stop() { this.generation++; clearInterval(this.timer); this.timer = null; this.active = false; this.notify(false); return this.status(); }
status() { return { active: !!this.active, phase: this.phase, samples: this.samples.length, events: this.events.length, maxDurationSeconds: 600 }; }
async capture(lag) {
if (this.busy || !this.active) return;
- this.busy = true;
+ this.busy = true; const generation = this.generation, phase = this.phase;
try {
const raw = await this.sample();
- if (!this.active) return;
+ if (!this.active || generation !== this.generation) return;
// Construct every field explicitly. Never serialize process names, URLs or raw metrics objects.
- this.samples.push({ elapsedMs: finite(performance.now() - this.started), phase: this.phase,
+ this.samples.push({ elapsedMs: finite(performance.now() - this.started), phase,
rssMiB: finite(raw.rssMiB), cpuPercent: finite(raw.cpuPercent), processes: finite(raw.processes),
- browsers: finite(raw.browsers), mainLoopLagMs: finite(lag) });
+ browsers: finite(raw.browsers), mainLoopLagMs: finite(lag),
+ ...Object.fromEntries(OPTIONAL.map(key => [key, Number.isFinite(raw[key]) ? Math.max(0, finite(raw[key])) : null])) });
if (this.samples.length > 300) this.samples.shift();
} catch { this.record('action-failed', 0); } finally { this.busy = false; }
}
@@ -37,11 +40,12 @@ class Profiler {
const summary = phase => {
const rows = this.samples.filter(s => s.phase === phase);
const mean = key => finite(rows.reduce((n, row) => n + row[key], 0) / (rows.length || 1));
- return { samples: rows.length, meanRssMiB: mean('rssMiB'), meanCpuPercent: mean('cpuPercent'), maxMainLoopLagMs: Math.max(0, ...rows.map(r => r.mainLoopLagMs)) };
+ return { samples: rows.length, meanRssMiB: mean('rssMiB'), meanCpuPercent: mean('cpuPercent'), maxMainLoopLagMs: Math.max(0, ...rows.map(r => r.mainLoopLagMs)),
+ peaks: Object.fromEntries(OPTIONAL.map(key => { const values = rows.map(row => row[key]).filter(Number.isFinite); return [key, values.length ? Math.max(...values) : null]; })) };
};
const baseline = summary('baseline'), candidate = summary('candidate');
- return { schema: 'codegraff-performance-v1', privacy: 'Measurements only; no content, paths, URLs, identifiers, screenshots or free-form text.',
- measurement: 'RSS sums the app process tree and may count shared pages twice. CPU is interval process-tree CPU time; short-lived exited children can be missed and the first sample is zero. Main loop lag is timer delay; renderer long tasks are durations only.',
+ return { schema: 'codegraff-performance-v2', acceleration: accelerationStatus(this.hardware()), gpuUtilizationPercent: null, privacy: 'Measurements only; no content, paths, URLs, identifiers, screenshots or free-form text.',
+ measurement: 'RSS sums the app process tree and may count shared pages twice. CPU is interval process-tree CPU time; short-lived exited children can be missed and the first sample is zero. Main loop lag is timer delay; renderer long tasks are durations only. Paint timings are document-relative (reload during recording for a fresh LCP); interactionMaxMs is the slowest observed interaction, not INP. Layout shift sums recording entries, not session-window CLS. GPU process CPU/RSS are host resources, not GPU utilization or VRAM; shared Apple Silicon memory overlaps RSS. Missing measurements are null.',
status: this.status(), baseline, candidate,
comparison: baseline.samples && candidate.samples ? { meanRssMiBDelta: finite(candidate.meanRssMiB - baseline.meanRssMiB), meanCpuPercentDelta: finite(candidate.meanCpuPercent - baseline.meanCpuPercent) } : null,
samples: this.samples.map(row => ({ ...row })), events: this.events.map(row => ({ ...row })) };
diff --git a/apps/native/electron/profiler.test.cjs b/apps/native/electron/profiler.test.cjs
index c41e5b61..95c22165 100644
--- a/apps/native/electron/profiler.test.cjs
+++ b/apps/native/electron/profiler.test.cjs
@@ -24,3 +24,45 @@ test('CPU time parser preserves fractions and hour fields', () => {
assert.equal(cpuMilliseconds('2:01.50'), 121500);
assert.equal(cpuMilliseconds('1:02:03.25'), 3723250);
});
+test('restarting a recording cannot import an in-flight sample from the previous recording', async () => {
+ let finish;
+ const p = new Profiler(() => new Promise(resolve => { finish = resolve; }));
+ const old = p.start();
+ p.stop(); await p.start();
+ finish({ rssMiB: 900 }); await old;
+ assert.equal(p.report().samples.length, 0); p.stop();
+});
+test('hardware and renderer reporting never exports device identity or unsupported metrics as zero', async () => {
+ const { chromiumSample } = require('./hardware-profile.cjs');
+ assert.deepEqual(chromiumSample([{ type: 'GPU', cpu: { percentCPUUsage: 4 }, memory: { workingSetSize: 2048 }, name: 'PRIVATE' }]), { gpuProcessCpuPercent: 4, gpuProcessRssMiB: 2 });
+ const p = new Profiler(async () => ({ lcpMs: 120, interactionMaxMs: null, rendererHeapMiB: 12, domNodes: 90 }), () => {}, () => ({ gpu_compositing: 'enabled', webgpu: 'SECRET', renderer: 'PRIVATE' }));
+ await p.start(); p.stop(); const report = p.report();
+ assert.equal(report.acceleration.gpu_compositing, 'enabled');
+ assert.equal(report.acceleration.webgpu, 'unknown');
+ assert.equal(report.baseline.peaks.interactionMaxMs, null);
+ assert.equal(report.baseline.peaks.lcpMs, 120);
+ assert.equal(report.gpuUtilizationPercent, null);
+ assert.doesNotMatch(JSON.stringify(report), /SECRET|PRIVATE/);
+});
+test('renderer observers stay off until recording and disconnect on stop', () => {
+ const { collectRendererMetrics } = require('./renderer-profile.cjs');
+ const originalObserver = globalThis.PerformanceObserver, originalDocument = globalThis.document;
+ const observers = [];
+ globalThis.PerformanceObserver = class {
+ static supportedEntryTypes = ['largest-contentful-paint', 'paint', 'event', 'layout-shift'];
+ constructor(callback) { this.callback = callback; observers.push(this); }
+ observe(options) { this.options = options; }
+ disconnect() { this.disconnected = true; }
+ };
+ globalThis.document = { getElementsByTagName: () => Array(20) };
+ try {
+ collectRendererMetrics(false); assert.equal(observers.length, 0);
+ collectRendererMetrics(true); assert.equal(observers.length, 4);
+ observers[0].callback({ getEntries: () => [{ startTime: 150, url: 'SECRET', element: 'PRIVATE' }] });
+ observers[2].callback({ getEntries: () => [{ duration: 48, interactionId: 1, target: 'PRIVATE' }] });
+ const metrics = collectRendererMetrics(true);
+ assert.equal(metrics.lcpMs, 150); assert.equal(metrics.interactionMaxMs, 48);
+ assert.equal(observers.length, 4); assert.doesNotMatch(JSON.stringify(metrics), /SECRET|PRIVATE/);
+ collectRendererMetrics(false); assert.ok(observers.every(observer => observer.disconnected));
+ } finally { collectRendererMetrics(false); globalThis.PerformanceObserver = originalObserver; globalThis.document = originalDocument; }
+});
diff --git a/apps/native/electron/renderer-profile.cjs b/apps/native/electron/renderer-profile.cjs
new file mode 100644
index 00000000..bc69b45c
--- /dev/null
+++ b/apps/native/electron/renderer-profile.cjs
@@ -0,0 +1,31 @@
+// Executes in an isolated Chromium world. Only numeric measurements leave it.
+function collectRendererMetrics(enabled) {
+ const key = '__graffPerformance';
+ let state = globalThis[key];
+ if (!enabled) {
+ state?.observers.forEach(observer => observer.disconnect());
+ delete globalThis[key]; return null;
+ }
+ if (!state) {
+ state = globalThis[key] = { observers: [], lcpMs: null, fcpMs: null, interactionMaxMs: null, layoutShift: 0 };
+ const observe = (type, callback, options = {}) => {
+ if (!PerformanceObserver.supportedEntryTypes.includes(type)) return;
+ const observer = new PerformanceObserver(list => list.getEntries().forEach(callback));
+ observer.observe({ type, ...options }); state.observers.push(observer);
+ };
+ // Paint timings are document-relative; interaction/shift measurements start with recording.
+ observe('largest-contentful-paint', entry => { state.lcpMs = entry.startTime; }, { buffered: true });
+ for (const entry of performance.getEntriesByType('paint')) if (entry.name === 'first-contentful-paint') state.fcpMs = entry.startTime;
+ observe('paint', entry => { if (entry.name === 'first-contentful-paint') state.fcpMs = entry.startTime; });
+ observe('event', entry => { if (entry.interactionId) state.interactionMaxMs = Math.max(state.interactionMaxMs || 0, entry.duration); }, { durationThreshold: 16 });
+ observe('layout-shift', entry => { if (!entry.hadRecentInput) state.layoutShift += entry.value; });
+ }
+ return { lcpMs: state.lcpMs, fcpMs: state.fcpMs, interactionMaxMs: state.interactionMaxMs,
+ layoutShift: state.layoutShift, rendererHeapMiB: performance.memory ? performance.memory.usedJSHeapSize / 1048576 : null,
+ domNodes: document.getElementsByTagName('*').length };
+}
+async function rendererSample(contents, enabled = true) {
+ if (!contents || contents.isDestroyed()) return {};
+ return contents.executeJavaScriptInIsolatedWorld(997, [{ code: `(${collectRendererMetrics.toString()})(${enabled})` }]);
+}
+module.exports = { collectRendererMetrics, rendererSample };
diff --git a/apps/native/electron/smoke-gui-customization.cjs b/apps/native/electron/smoke-gui-customization.cjs
new file mode 100644
index 00000000..84747040
--- /dev/null
+++ b/apps/native/electron/smoke-gui-customization.cjs
@@ -0,0 +1,35 @@
+const assert = require('node:assert/strict');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function smokeGuiCustomization({ win, backend }) {
+ const js = source => win.webContents.executeJavaScript(source);
+ const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(100); } throw Error(`Customization check timed out: ${source}`); };
+ const type = text => js(`(()=>{const input=document.querySelector('textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(input,${JSON.stringify(text)});input.dispatchEvent(new Event('input',{bubbles:true}));})()`);
+ for (const prefix of ['$', '@']) {
+ await type(`${prefix}gui-th`);
+ await wait(`!![...document.querySelectorAll('button')].find(b=>b.textContent.includes('GUI skill ·'))`);
+ await js(`[...document.querySelectorAll('button')].find(b=>b.textContent.includes('GUI skill ·')).click()`);
+ await wait(`document.querySelector('textarea[aria-label="Prompt"]').value==='$gui-theme '`);
+ }
+ // No model request: verify the composer inserts a reviewable draft, then clear it.
+ await type('');
+ const fixture = { version: 1, id: 'smoke-ocean', name: 'Smoke Ocean', base: 'dark', colors: { page: '#112233', surface: '#172d43', ink: '#f0f7ff', 'ink-2': '#d0e0f0', 'ink-3': '#bdcddd', accent: '#89d6ed', 'accent-ink': '#a0dfff', 'accent-tint': '#21425a' }, font: 'serif', corners: 4 };
+ assert.equal(await js(`fetch('/api/themes',{method:'POST',headers:{'content-type':'application/json'},body:${JSON.stringify(JSON.stringify(fixture))}}).then(r=>r.status)`), 200);
+ await js(`document.querySelector('[aria-label="Appearance"]').click()`);
+ await wait(`!!document.querySelector('[aria-label="Use theme Smoke Ocean"]')`);
+ await js(`document.querySelector('[aria-label="Use theme Smoke Ocean"]').click()`);
+ assert.equal(await js(`getComputedStyle(document.documentElement).getPropertyValue('--page').trim()`), '#112233');
+ assert.equal(await js('document.documentElement.classList.contains("dark")'), true);
+ assert.equal(await js('document.body.style.fontFamily.includes("Georgia")'), true);
+ await win.loadURL(backend.origin);
+ await wait(`!!document.querySelector('[aria-label="Appearance"]')`);
+ assert.equal(await js(`getComputedStyle(document.documentElement).getPropertyValue('--page').trim()`), '#112233');
+ await js(`document.querySelector('[aria-label="Appearance"]').click()`);
+ await wait(`!!document.querySelector('[aria-label="Close appearance"]')`);
+ await js(`[...document.querySelectorAll('[role="dialog"] button')].find(b=>b.textContent.includes('Official · Japanese palette')).click()`);
+ assert.equal(await js('document.documentElement.style.getPropertyValue("--page")'), '');
+ assert.equal(await js('document.body.style.fontFamily'), '');
+ assert.equal(await js('document.documentElement.style.getPropertyValue("--radius-control")'), '');
+ await js(`document.querySelector('[aria-label="Close appearance"]').click()`);
+ return 'both skill mention menus, editable draft, theme import, selection, reload persistence and complete built-in reset';
+}
+module.exports = { smokeGuiCustomization };
diff --git a/apps/native/electron/smoke-model-picker.cjs b/apps/native/electron/smoke-model-picker.cjs
new file mode 100644
index 00000000..ad8cb369
--- /dev/null
+++ b/apps/native/electron/smoke-model-picker.cjs
@@ -0,0 +1,49 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function smokeModelPicker({ win }) {
+ const js = async source => { try { return await win.webContents.executeJavaScript(source); } catch (error) { throw Error(`UI fixture failed (${source.slice(0, 160)}): ${error.message}`); } };
+ const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(100); } throw Error(`Picker check timed out: ${source}`); };
+ const click = source => js(`document.querySelector(${JSON.stringify(source)}).click()`);
+ const type = value => js(`(()=>{const el=document.querySelector('[aria-label="Filter models"]');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(el,${JSON.stringify(value)});el.dispatchEvent(new Event('input',{bubbles:true}));})()`);
+ const bounds = () => js(`(()=>{const rect=document.querySelector('[aria-label="Choose a model"]').getBoundingClientRect(), search=document.querySelector('[aria-label="Filter models"]').getBoundingClientRect();return {top:rect.top,bottom:rect.bottom,left:rect.left,right:rect.right,width:innerWidth,height:innerHeight,searchTop:search.top,searchBottom:search.bottom}})()`);
+ const [width, height] = win.getSize();
+ try {
+ win.setSize(900, 600); await sleep(250);
+ await wait(`!!document.querySelector('[aria-label="Choose model"]')`);
+ await click('[aria-label="Choose model"]');
+ await wait(`!!document.querySelector('[aria-label="Choose a model"]')`);
+ let rect = await bounds();
+ assert.ok(rect.top >= 47 && rect.bottom <= rect.height - 8 && rect.left >= 8 && rect.right <= rect.width - 8, JSON.stringify(rect));
+ assert.equal(await js(`document.activeElement.getAttribute('aria-label')`), 'Filter models');
+ assert.equal(await js(`document.querySelector('[role=option]').getAttribute('aria-selected')`), 'true');
+ const current = await js(`document.querySelector('[role=option]').textContent`);
+ const before = await js(`document.querySelector('[aria-label="Filter models"]').getBoundingClientRect().top`);
+ await js(`document.querySelector('[aria-label="Available models"]').scrollTop=10000`);
+ assert.equal(await js(`document.querySelector('[aria-label="Filter models"]').getBoundingClientRect().top`), before);
+ await type('no-model-matches-this');
+ await wait(`document.querySelectorAll('[role=option]').length===0`);
+ rect = await bounds(); assert.ok(rect.top >= 47 && rect.bottom <= rect.height - 8, JSON.stringify(rect));
+ assert.equal(rect.searchTop, before, 'filtering keeps the search field in place');
+ await type('');
+ await wait(`document.querySelectorAll('[role=option]').length>0`);
+ assert.equal(await js(`document.querySelector('[aria-label="Available models"]').scrollTop`), 0);
+ await js(`document.querySelector('[aria-label="Filter models"]').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true}))`);
+ assert.equal(await js(`document.activeElement.getAttribute('aria-activedescendant')===document.querySelectorAll('[role=option]')[1].id`), true);
+ // Click the current choice through real mouse events; it must stay clickable in the portal.
+ const point = await js(`(()=>{const r=document.querySelector('[role=option]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
+ win.webContents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ win.webContents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
+ await wait(`!document.querySelector('[aria-label="Choose a model"]')`);
+ await click('[aria-label="Choose model"]');
+ await wait(`!!document.querySelector('[aria-label="Choose a model"]')`);
+ assert.equal(await js(`document.querySelector('[role=option]').textContent`), current);
+ await sleep(150);
+ if (process.env.GRAFF_MODEL_PICKER_SCREENSHOT) fs.writeFileSync(process.env.GRAFF_MODEL_PICKER_SCREENSHOT, (await win.webContents.capturePage()).toPNG());
+ await js(`document.querySelector('[aria-label="Filter models"]').dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}))`);
+ await wait(`!document.querySelector('[aria-label="Choose a model"]')`);
+ assert.equal(await js(`document.activeElement.getAttribute('aria-label')`), 'Choose model');
+ return 'minimum-window bounds, current-first order, fixed search, filtering, keyboard navigation, mouse selection and focus restoration';
+ } finally { win.setSize(width, height); }
+}
+module.exports = { smokeModelPicker };
diff --git a/apps/native/electron/smoke-review-resize.cjs b/apps/native/electron/smoke-review-resize.cjs
new file mode 100644
index 00000000..4de1036f
--- /dev/null
+++ b/apps/native/electron/smoke-review-resize.cjs
@@ -0,0 +1,26 @@
+const assert = require('node:assert/strict');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function smokeReviewResize({ win }) {
+ const js = source => win.webContents.executeJavaScript(source);
+ const paneWidth = () => js(`document.querySelector('[aria-label="Workspace changes"]').getBoundingClientRect().width`);
+ const original = await paneWidth();
+ const point = await js(`(()=>{const r=document.querySelector('[aria-label="Resize changes panel"]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+100)}})()`);
+ win.webContents.sendInputEvent({ type: 'mouseMove', ...point });
+ win.webContents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ win.webContents.sendInputEvent({ type: 'mouseMove', x: point.x + 90, y: point.y, button: 'left' });
+ await sleep(100);
+ win.webContents.sendInputEvent({ type: 'mouseUp', x: point.x + 90, y: point.y, button: 'left', clickCount: 1 });
+ await sleep(100);
+ const resized = await paneWidth();
+ assert.ok(Math.abs(original - resized - 90) < 3, `drag changed width ${original} → ${resized}`);
+ await js(`document.querySelector('[aria-label="Close changes"]').click()`); await sleep(100);
+ await js(`document.querySelector('[aria-label="Review workspace changes"]').click()`); await sleep(150);
+ assert.ok(Math.abs(await paneWidth() - resized) < 2, 'width survives reopening');
+ await js(`document.querySelector('[aria-label="Resize changes panel"]').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowLeft',bubbles:true}))`); await sleep(100);
+ assert.ok(Math.abs(await paneWidth() - resized - 20) < 2, 'keyboard expands pane');
+ await js(`document.querySelector('[aria-label="Resize changes panel"]').dispatchEvent(new MouseEvent('dblclick',{bubbles:true}))`); await sleep(100);
+ assert.ok(Math.abs(await paneWidth() - original) < 2, 'double-click restores default');
+ assert.equal(await js('document.body.style.cursor'), '');
+ return 'mouse drag, reopen persistence, keyboard adjustment and double-click reset';
+}
+module.exports = { smokeReviewResize };
diff --git a/apps/native/electron/smoke-tool-disclosure.cjs b/apps/native/electron/smoke-tool-disclosure.cjs
new file mode 100644
index 00000000..1aa56d2d
--- /dev/null
+++ b/apps/native/electron/smoke-tool-disclosure.cjs
@@ -0,0 +1,46 @@
+const assert = require('node:assert/strict');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function smokeToolDisclosure({ win, backend }) {
+ const js = async source => { try { return await win.webContents.executeJavaScript(source); } catch (error) { throw Error(`UI fixture failed (${source.slice(0, 160)}): ${error.message}`); } };
+ const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(100); } throw Error(`Tool disclosure check timed out: ${source}; state=${await js("JSON.stringify({visibility:document.visibilityState,headers:[...document.querySelectorAll('[data-tool-summary]')].map(e=>e.textContent)})")}`); };
+ // Script the transport inside this isolated smoke profile. No model turn or file write.
+ const setup = await js(`(async()=>{try {
+ const catalog=await fetch('/api/models').then(r=>r.json()); const original=window.fetch;
+ const json=body=>new Response(JSON.stringify(body),{headers:{'content-type':'application/json'}});
+ window.fetch=(url,options)=>{
+ if(url==='/api/title')return Promise.resolve(json({title:'Disclosure fixture'}));
+ if(url==='/api/acp' && options?.body){const body=JSON.parse(options.body);
+ if(body.method==='bootstrap')return Promise.resolve(json({sessionId:'disclosure-fixture',commands:[]}));
+ if(body.method==='graff/models')return Promise.resolve(json(catalog));
+ if(body.method==='session/prompt')return Promise.resolve(new Response(new ReadableStream({start(controller){window.disclosureEmit=update=>controller.enqueue(new TextEncoder().encode(JSON.stringify({jsonrpc:'2.0',method:'session/update',params:{sessionId:'disclosure-fixture',update}})+'\\n'));window.disclosureDone=()=>{controller.enqueue(new TextEncoder().encode(JSON.stringify({jsonrpc:'2.0',id:1,result:{stopReason:'end_turn'}})+'\\n'));controller.close()}}}),{headers:{'content-type':'application/x-ndjson'}}));
+ }
+ return original(url,options);
+ };
+ const input=document.querySelector('textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(input,'Check the disclosure fixture');input.dispatchEvent(new Event('input',{bubbles:true}));
+ } catch (error) { return error.stack; } })()`);
+ assert.equal(setup, undefined);
+ await wait(`!document.querySelector('[aria-label="Send"]').disabled`);
+ await js(`document.querySelector('[aria-label="Send"]').click()`);
+ await wait(`!!window.disclosureEmit`);
+ const tool = index => js(`window.disclosureEmit({sessionUpdate:'tool_call',toolCallId:'fixture-${index}',title:'fixture-${index}.txt',kind:'read',status:'pending',rawInput:{path:'fixture-${index}.txt'}})`);
+ await tool(1);
+ await wait(`!!document.querySelector('[data-tool-summary]')`);
+ assert.equal(await js(`document.querySelector('[data-tool-summary]').getAttribute('aria-expanded')`), 'false');
+ for (let i = 2; i <= 7; i++) await tool(i);
+ await wait(`document.querySelector('[data-tool-summary]').textContent.includes('7')`);
+ assert.equal(await js(`document.querySelector('[data-tool-summary]').getAttribute('aria-expanded')`), 'false');
+ await js(`document.querySelector('[data-tool-summary]').click()`);
+ await wait(`document.querySelector('[data-tool-summary]').getAttribute('aria-expanded')==='true'`);
+ await tool(8); await sleep(100);
+ assert.equal(await js(`document.querySelector('[data-tool-summary]').getAttribute('aria-expanded')`), 'true');
+ await js(`document.querySelector('[data-tool-summary]').click()`);
+ await tool(9); await sleep(100);
+ assert.equal(await js(`document.querySelector('[data-tool-summary]').getAttribute('aria-expanded')`), 'false');
+ await js(`window.disclosureDone()`);
+ await sleep(200);
+ assert.equal(await js(`document.querySelector('[data-tool-summary]').getAttribute('aria-expanded')`), 'false');
+ await win.loadURL(backend.origin);
+ await wait(`!!document.querySelector('[aria-label="Appearance"]')`);
+ return 'single and batched tools start collapsed; new updates and completion preserve the reader selection';
+}
+module.exports = { smokeToolDisclosure };
diff --git a/apps/native/electron/smoke-ui.cjs b/apps/native/electron/smoke-ui.cjs
new file mode 100644
index 00000000..624c64fc
--- /dev/null
+++ b/apps/native/electron/smoke-ui.cjs
@@ -0,0 +1,71 @@
+const assert = require('node:assert/strict');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function smokeUI({ win, browser, backend }) {
+ require('electron').app.focus({ steal: true }); win.show(); win.focus();
+ const js = expression => win.webContents.executeJavaScript(expression);
+ const wait = async expression => {
+ for (let n = 0; n < 100; n++) { if (await js(expression)) return; await sleep(100); }
+ throw Error(`UI did not reach: ${expression}; visible=${await js('document.visibilityState')}`);
+ };
+ const click = async selector => {
+ await wait(`!!document.querySelector(${JSON.stringify(selector)})`);
+ await js(`document.querySelector(${JSON.stringify(selector)}).click()`); await sleep(100);
+ };
+ await wait(`!!document.querySelector('[aria-label="Appearance"]')`);
+ await click('[aria-label="Appearance"]');
+ await wait(`!!document.querySelector('[role="dialog"][aria-label="Appearance"]')`);
+ for (const [name, expected] of [['White', 'light'], ['Black', 'dark'], ['Website', 'website'], ['CodeGraff', 'codegraff']]) {
+ await js(`[...document.querySelectorAll('[role="dialog"] button')].find(b=>b.textContent.includes(${JSON.stringify(name)})).click()`);
+ await wait(`document.documentElement.dataset.theme===${JSON.stringify(expected)}`);
+ assert.equal(await js(`document.documentElement.classList.contains('dark')`), expected === 'dark');
+ }
+ await click('[aria-label="Close appearance"]');
+ await win.loadURL(backend.origin);
+ await wait(`!!document.querySelector('[aria-label="Appearance"]')`);
+ assert.equal(await js('document.documentElement.dataset.theme'), 'codegraff');
+ assert.equal(await js(`document.querySelector('[aria-label="Start dictation"]').disabled`), true);
+
+ const customization = await require('./smoke-gui-customization.cjs').smokeGuiCustomization({ win, backend });
+ const modelPicker = await require('./smoke-model-picker.cjs').smokeModelPicker({ win });
+
+ const toolDisclosure = await require('./smoke-tool-disclosure.cjs').smokeToolDisclosure({ win, backend });
+
+ // Composer upload delay: sending must remain disabled until all bytes are staged.
+ await js(`window.auditFetch=window.fetch; window.fetch=(url,...args)=>url==='/api/attach'?new Promise(resolve=>{window.auditFinishUpload=()=>resolve(new Response(JSON.stringify({path:'/tmp/audit-fixture.txt',name:'audit-fixture.txt'}),{headers:{'content-type':'application/json'}}))}):window.auditFetch(url,...args);
+ const input=document.querySelector('input[type=file]'), data=new DataTransfer(); data.items.add(new File(['fixture'],'audit-fixture.txt',{type:'text/plain'})); input.files=data.files; input.dispatchEvent(new Event('change',{bubbles:true}));`);
+ await wait(`!!window.auditFinishUpload`);
+ assert.equal(await js(`document.querySelector('[aria-label="Send"]').disabled`), true);
+ await js('window.auditFinishUpload(); window.fetch=window.auditFetch; void 0');
+ await wait(`!document.querySelector('[aria-label="Send"]').disabled`);
+ // No prompt is sent. Reload discards this synthetic attachment.
+ await win.loadURL(backend.origin);
+ await click('[aria-label="Review workspace changes"]');
+ await wait(`!!document.querySelector('[aria-label="File diff"]')`);
+ await wait(`document.querySelector('[aria-label="File diff"]').getAttribute('aria-busy')==='false'`);
+ assert.ok(await js(`document.querySelector('[aria-label="Workspace changes"]').textContent.includes('Changes')`));
+ const reviewResize = await require('./smoke-review-resize.cjs').smokeReviewResize({ win });
+ const hasFiles = await js(`!!document.querySelector('[aria-label="Toggle changed file list"]')`);
+ if (hasFiles) {
+ await click('[aria-label="Toggle changed file list"]');
+ await js(`const input=document.querySelector('[aria-label="Filter changed files"]'); Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(input,'no-file-with-this-name'); input.dispatchEvent(new Event('input',{bubbles:true}));`);
+ await wait(`document.querySelector('[aria-label="Changed files"]').textContent.includes('No matching files')`);
+ await click('[aria-label="Next changed section"]');
+ }
+ await click('[aria-label="Close changes"]');
+
+ // A native page must yield to an HTML modal and return without losing its state.
+ browser.setBounds('overlay-fixture', { x: 700, y: 150, width: 300, height: 300 });
+ await browser.navigate('overlay-fixture', 'about:blank');
+ await click('[aria-label="Appearance"]');
+ await wait(`!!document.querySelector('[role="dialog"][aria-label="Appearance"]')`);
+ for (let n = 0; n < 30 && !browser.overlay; n++) await sleep(50);
+ assert.equal(browser.overlay, true, await js(`JSON.stringify({visibility:document.visibilityState,dialogs:[...document.querySelectorAll('[role=dialog]')].map(el=>({label:el.getAttribute('aria-label'),visible:el.checkVisibility()}))})`));
+ assert.equal(browser.tabs.get('overlay-fixture').view.getVisible(), false);
+ await click('[aria-label="Close appearance"]');
+ for (let n = 0; n < 30 && browser.overlay; n++) await sleep(50);
+ assert.equal(browser.tabs.get('overlay-fixture').view.getVisible(), true);
+ browser.close('overlay-fixture');
+ const result = { customization, modelPicker, toolDisclosure, reviewResize, themes: 'four choices and reload persistence', composer: 'demo dictation disabled and upload blocks send', review: hasFiles ? 'file filter, section navigation, close' : 'empty review and close', overlays: 'native page hidden and restored around app dialog' };
+ return result;
+}
+module.exports = { smokeUI };
diff --git a/apps/native/electron/smoke.cjs b/apps/native/electron/smoke.cjs
index 29cc3f11..69ecc0a0 100644
--- a/apps/native/electron/smoke.cjs
+++ b/apps/native/electron/smoke.cjs
@@ -19,6 +19,7 @@ async function run({ win, browser, automation, backend, metrics, activity, compu
await win.loadURL(backend.origin);
await sleep(1500);
assert.equal(browser.liveCount, 0);
+ report.ui = await require('./smoke-ui.cjs').smokeUI({ win, browser, backend });
const catalog = await win.webContents.executeJavaScript(`fetch('/api/models').then(r=>r.json())`);
assert.ok(catalog.result.current.model); assert.ok(catalog.result.models.length > 0);
assert.ok(catalog.result.current.effortLevels.length > 0);
diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjs
new file mode 100644
index 00000000..e7637a33
--- /dev/null
+++ b/apps/native/electron/visual-tests.cjs
@@ -0,0 +1,69 @@
+const { app, BrowserWindow } = require('electron');
+const { spawn } = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
+const os = require('node:os');
+const net = require('node:net');
+const assert = require('node:assert/strict');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-visual-'));
+app.setPath('userData', path.join(temporary, 'profile'));
+let server, win;
+const deadline = setTimeout(() => { console.error('Visual run exceeded 120 seconds'); finish(1); }, 120000);
+app.whenReady().then(async () => {
+ const root = path.resolve(__dirname, '..'), output = process.env.GRAFF_VISUAL_OUTPUT || path.resolve(root, '../../zig-out/visual-tests');
+ fs.mkdirSync(output, { recursive: true });
+ assert.ok(fs.existsSync(path.join(root, '.next/BUILD_ID')), 'Run bun run build before visual tests.');
+ const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve));
+ const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
+ const origin = `http://127.0.0.1:${port}`;
+ const log = fs.openSync(path.join(output, 'server.log'), 'w');
+ server = spawn(process.env.GRAFF_TEST_BUN || 'bun', ['node_modules/next/dist/bin/next', 'start', '--port', String(port), '--hostname', '127.0.0.1'], { cwd: root, env: { ...process.env, GRAFF_VISUAL_TESTS: '1', GRAFF_DESKTOP_TOKEN: '', NEXT_TELEMETRY_DISABLED: '1' }, detached: true, stdio: ['ignore', log, log] });
+ fs.closeSync(log);
+ for (let i = 0; i < 100; i++) { try { if ((await fetch(`${origin}/visual-tests`)).ok) break; } catch {} if (i === 99) throw Error('Visual fixture server did not start'); await sleep(100); }
+ win = new BrowserWindow({ width: 900, height: 600, show: true, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ app.focus({ steal: true }); win.show(); win.focus();
+ const apiRequests = [];
+ win.webContents.session.webRequest.onBeforeRequest((details, callback) => {
+ const url = new URL(details.url);
+ if (url.origin === origin && url.pathname.startsWith('/api/')) apiRequests.push(url.pathname);
+ callback({ cancel: !details.url.startsWith(origin) && !details.url.startsWith('data:') || url.pathname.startsWith('/api/') });
+ });
+ await win.loadURL(`${origin}/visual-tests`);
+ const js = source => win.webContents.executeJavaScript(source);
+ const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(50); } throw Error(`Visual check timed out: ${source}`); };
+ await wait(`!!document.querySelector('[data-case="waiting"]')`);
+ await js('document.fonts.ready.then(()=>true)');
+ const cases = { starting: 'Starting Graff…', thinking: 'Thinking…', writing: 'Writing response…', running: 'Running 1 tool…', waiting: 'Waiting for Graff…', done: 'Turn finished', stopped: 'Stopped', error: 'Response interrupted', 'missing-result': 'Turn finished' };
+ const results = [];
+ for (const theme of ['light', 'dark', 'codegraff']) {
+ await js(`document.querySelector('[data-theme-choice="${theme}"]').click()`);
+ for (const [name, label] of Object.entries(cases)) {
+ console.log('Visual:', theme, name);
+ await js(`document.querySelector('[data-case="${name}"]').click()`);
+ await wait(`document.querySelector('[data-turn-activity]')?.textContent.includes(${JSON.stringify(label)})`);
+ await js(`Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{}))).then(()=>true)`);
+ await js('new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))');
+ assert.equal(await js(`getComputedStyle(document.querySelector('article')).opacity`), '1');
+ const rect = await js(`(()=>{const a=document.querySelector('[data-turn-activity]').getBoundingClientRect(),b=document.querySelector('[data-fixture-composer]').getBoundingClientRect();return {top:a.top,bottom:a.bottom,width:a.width,composer:b.top,viewport:innerHeight}})()`);
+ assert.ok(rect.width > 100 && rect.top > 0 && rect.bottom < rect.composer && rect.composer < rect.viewport, JSON.stringify(rect));
+ if (name === 'waiting') assert.match(await js(`document.querySelector('[data-activity-detail]').textContent`), /No update for/);
+ const summary = await js(`document.querySelector('[data-tool-summary]')?.getAttribute('aria-expanded')`);
+ if (summary !== undefined) assert.equal(summary, 'false', 'progress never auto-expands tool details');
+ if (['done', 'stopped', 'error', 'missing-result'].includes(name)) assert.equal(await js(`document.querySelector('article').getAttribute('aria-busy')`), 'false');
+ fs.writeFileSync(path.join(output, `${theme}-${name}.png`), (await win.webContents.capturePage()).toPNG());
+ results.push(`${theme}/${name}`);
+ }
+ }
+ if (process.env.GRAFF_PERFORMANCE_TESTS) await require('./performance-scenarios.cjs').runPerformance({ win, origin, output });
+ assert.deepEqual(apiRequests, [], 'Visual fixtures must not call the engine or model APIs');
+ fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: results, apiRequests }, null, 2));
+ console.log(`${results.length} visual scenarios passed. No engine or model API calls. Screenshots: ${output}`);
+}).then(() => finish(0)).catch(error => { console.error(error); finish(1); });
+function finish(code) {
+ clearTimeout(deadline);
+ if (win && !win.isDestroyed()) win.destroy();
+ if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}
+ app.once('quit', () => { fs.rmSync(temporary, { recursive: true, force: true }); });
+ app.exit(code);
+}
diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.ts
index beaaa9ed..ac5b24d2 100644
--- a/apps/native/lib/acp-client.ts
+++ b/apps/native/lib/acp-client.ts
@@ -119,6 +119,7 @@ export async function* prompt(
}
if ("result" in line) {
terminal = true;
+ yield { sessionUpdate: "gui_turn_end", stopReason: (line.result as { stopReason?: string } | null)?.stopReason ?? "end_turn" };
break;
}
}
diff --git a/apps/native/lib/acp.test.ts b/apps/native/lib/acp.test.ts
index cb71ec53..4be40609 100644
--- a/apps/native/lib/acp.test.ts
+++ b/apps/native/lib/acp.test.ts
@@ -116,7 +116,7 @@ describe("applyAcpUpdate", () => {
assert.equal(blocks[2]?.kind, "text");
});
- it("finishAcpTurn settles running chips", () => {
+ it("finishAcpTurn stops unresolved chips without inventing success", () => {
let turn = emptyTurn();
turn = applyAcpUpdate(turn, {
sessionUpdate: "tool_call",
@@ -127,6 +127,6 @@ describe("applyAcpUpdate", () => {
});
turn = finishAcpTurn(turn);
assert.equal(turn.status, "done");
- assert.equal(turn.tools[0]?.status, "ok");
+ assert.equal(turn.tools[0]?.status, "interrupted");
});
});
diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.ts
index 04d25962..b04b86d6 100644
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@ -222,11 +222,10 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
}
export function finishAcpTurn(turn: AssistantTurn): AssistantTurn {
- if (turn.status === "error") return turn;
return {
...turn,
- tools: turn.tools.map((t) => (t.status === "running" ? { ...t, status: "ok" as const } : t)),
- status: "done",
+ tools: turn.tools.map((t) => (t.status === "running" ? { ...t, status: "interrupted" as const, detail: [...t.detail, { text: "Turn ended before a result was received." }] } : t)),
+ status: turn.status === "error" ? "error" : "done",
};
}
@@ -259,7 +258,9 @@ export function turnBlocks(text: string, tools: ToolRow[]): TurnBlock[] {
}
export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): AssistantTurn {
+ turn = { ...turn, lastUpdateAt: Date.now(), activityKind: update.sessionUpdate, connected: true };
switch (update.sessionUpdate) {
+ case "gui_turn_end": return { ...turn, stopReason: typeof update.stopReason === "string" ? update.stopReason : "end_turn" };
case "agent_thought_chunk": {
const text = (update as { content?: AcpContent }).content?.text ?? "";
return {
diff --git a/apps/native/lib/appearance.ts b/apps/native/lib/appearance.ts
new file mode 100644
index 00000000..1c424b67
--- /dev/null
+++ b/apps/native/lib/appearance.ts
@@ -0,0 +1,39 @@
+import { colorTokens, fonts, parseTheme, type CustomTheme, type BuiltinAppearance } from "./custom-themes";
+export type Appearance = BuiltinAppearance | `custom:${string}`;
+export const customThemeKey = "bui-custom-theme";
+export const appearanceKey = "bui-theme";
+export const appearanceEvent = "graff-appearance";
+export function normalizeAppearance(value: string | null): Appearance {
+ if (value && /^custom:[a-z][a-z0-9-]{0,47}$/.test(value)) return value as Appearance;
+ return value === "light" || value === "website" || value === "codegraff" ? value : "dark";
+}
+export function readAppearance(): Appearance {
+ try { return normalizeAppearance(localStorage.getItem(appearanceKey)); }
+ catch { return normalizeAppearance(document.documentElement.dataset.theme ?? null); }
+}
+export function applyAppearance(theme: Appearance) {
+ const root = document.documentElement;
+ let custom: CustomTheme | null = null;
+ if (theme.startsWith("custom:")) try { const saved = parseTheme(JSON.parse(localStorage.getItem(customThemeKey) || "null")); if (`custom:${saved.id}` === theme) custom = saved; } catch {}
+ const base = custom?.base ?? (theme.startsWith("custom:") ? "dark" : theme);
+ root.classList.toggle("dark", base === "dark");
+ root.dataset.theme = base;
+ root.dataset.appearance = theme;
+ root.style.colorScheme = base === "dark" ? "dark" : "light";
+ for (const token of colorTokens) root.style.removeProperty(`--${token}`);
+ for (const token of ["chip", "control", "card"]) root.style.removeProperty(`--radius-${token}`);
+ if (document.body) document.body.style.fontFamily = "";
+ if (custom) {
+ for (const [token, color] of Object.entries(custom.colors)) root.style.setProperty(`--${token}`, color);
+ if (custom.corners !== undefined) for (const token of ["chip", "control", "card"]) root.style.setProperty(`--radius-${token}`, `${custom.corners}px`);
+ if (custom.font && document.body) document.body.style.fontFamily = fonts[custom.font];
+ }
+}
+export function selectCustomTheme(theme: CustomTheme) {
+ const valid = parseTheme(theme);
+ localStorage.setItem(customThemeKey, JSON.stringify(valid));
+ localStorage.setItem(appearanceKey, `custom:${valid.id}`);
+ applyAppearance(`custom:${valid.id}`); window.dispatchEvent(new Event(appearanceEvent));
+}
+// Run before paint as well as after hydration to avoid flashing the default theme.
+export const appearanceScript = `(()=>{const root=document.documentElement;let theme="dark",custom=null;try{theme=localStorage.getItem("${appearanceKey}")||"dark";if(theme.startsWith("custom:")){const c=JSON.parse(localStorage.getItem("${customThemeKey}")||"null");if(c&&theme==="custom:"+c.id&&["light","dark","website","codegraff"].includes(c.base)&&c.colors)custom=c}}catch{}const base=custom?custom.base:["light","website","codegraff"].includes(theme)?theme:"dark";root.dataset.theme=base;root.classList.toggle("dark",base==="dark");root.style.colorScheme=base==="dark"?"dark":"light";if(custom)for(const [key,value]of Object.entries(custom.colors))if(${JSON.stringify(colorTokens)}.includes(key)&&typeof value==="string"&&/^#[0-9a-f]{6}$/i.test(value))root.style.setProperty("--"+key,value)})()`;
diff --git a/apps/native/lib/custom-themes.test.ts b/apps/native/lib/custom-themes.test.ts
new file mode 100644
index 00000000..e3a7f496
--- /dev/null
+++ b/apps/native/lib/custom-themes.test.ts
@@ -0,0 +1,32 @@
+import { test, expect } from "bun:test";
+import { mkdtemp, rm, writeFile, symlink, readFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { parseTheme, contrast, themeWarnings } from "./custom-themes";
+import { listThemes, saveTheme } from "./theme-files";
+export const sampleTheme = { version: 1, id: "test-garden", name: "Test Garden", base: "dark", colors: { page: "#15201c", surface: "#1c2a23", ink: "#f1f7ee", "ink-2": "#c1d4c3", "ink-3": "#a3baa6", accent: "#a4d98c", "accent-ink": "#b5e79e", "accent-tint": "#2c422c" }, font: "system", corners: 10 };
+test("portable theme validates and keeps readable text", () => {
+ expect(parseTheme(sampleTheme).id).toBe("test-garden");
+ expect(themeWarnings(parseTheme(sampleTheme))).toEqual([]);
+ expect(contrast("#ffffff", "#000000")).toBe(21);
+});
+test("theme schema rejects executable values, unknown tokens and invalid identifiers", () => {
+ for (const patch of [{ id: "../outside" }, { version: 2 }, { base: "unknown" }, { font: ["system"] }, { corners: -1 }, { css: "body{}" }, { colors: { ...sampleTheme.colors, page: "url(https://example.com)" } }, { colors: { ...sampleTheme.colors, position: "#ffffff" } }, { colors: {} }]) expect(() => parseTheme({ ...sampleTheme, ...patch })).toThrow();
+});
+test("contrast warnings identify unreadable secondary text", () => {
+ expect(themeWarnings(parseTheme({ ...sampleTheme, colors: { ...sampleTheme.colors, "ink-3": "#15201c" } }))).toContain("ink-3 on page has low text contrast.");
+});
+test("theme import is atomic, lists valid files, and preserves duplicate ids", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "theme-files-"));
+ try {
+ await saveTheme(sampleTheme, directory);
+ await expect(saveTheme({ ...sampleTheme, name: "Overwrite" }, directory)).rejects.toThrow();
+ await writeFile(path.join(directory, "broken.json"), "{");
+ await writeFile(path.join(directory, "huge.json"), " ".repeat(20_000));
+ await symlink(path.join(directory, "test-garden.json"), path.join(directory, "link.json"));
+ const result = await listThemes(directory);
+ expect(result.themes.map(theme => theme.name)).toEqual(["Test Garden"]);
+ expect(result.issues).toHaveLength(3);
+ expect(JSON.parse(await readFile(path.join(directory, "test-garden.json"), "utf8")).name).toBe("Test Garden");
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
diff --git a/apps/native/lib/custom-themes.ts b/apps/native/lib/custom-themes.ts
new file mode 100644
index 00000000..0f02e4bd
--- /dev/null
+++ b/apps/native/lib/custom-themes.ts
@@ -0,0 +1,35 @@
+export const bases = ["light", "dark", "website", "codegraff"] as const;
+export type BuiltinAppearance = typeof bases[number];
+export const colorTokens = ["page", "canvas", "surface", "inset", "hover", "hover-2", "ink", "ink-2", "ink-3", "line", "line-strong", "field", "stripe", "stripe-bg", "accent", "accent-ink", "accent-tint", "green", "green-tint", "red", "red-tint", "orange", "orange-tint", "brand-coral", "brand-gold"] as const;
+export const fonts = { geist: 'var(--font-inter), system-ui, sans-serif', system: '-apple-system, BlinkMacSystemFont, sans-serif', serif: 'Georgia, "Times New Roman", serif' };
+export type CustomTheme = { version: 1; id: string; name: string; base: BuiltinAppearance; colors: Partial<Record<typeof colorTokens[number], string>>; font?: keyof typeof fonts; corners?: number };
+export const themeLimit = 16 * 1024;
+const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
+export function parseTheme(value: unknown): CustomTheme {
+ if (!record(value) || value.version !== 1) throw Error("Use theme version 1.");
+ if (Object.keys(value).some(key => !["version", "id", "name", "base", "colors", "font", "corners"].includes(key))) throw Error("Theme contains an unknown setting.");
+ if (typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,47}$/.test(value.id)) throw Error("Theme id must be a lowercase name with letters, digits or hyphens (up to 48 characters).");
+ if (typeof value.name !== "string" || !value.name.trim() || value.name.length > 60 || /[\x00-\x1f]/.test(value.name)) throw Error("Give the theme a name of 1–60 characters.");
+ if (!bases.includes(value.base as BuiltinAppearance)) throw Error("Choose a base: light, dark, website or codegraff.");
+ if (!record(value.colors)) throw Error("Theme colors must be an object.");
+ const colors: CustomTheme["colors"] = {};
+ for (const [key, color] of Object.entries(value.colors)) {
+ if (!(colorTokens as readonly string[]).includes(key) || typeof color !== "string" || !/^#[0-9a-f]{6}$/i.test(color)) throw Error(`Invalid color: ${key}. Use a supported token and a six-digit hex color.`);
+ colors[key as keyof typeof colors] = color;
+ }
+ for (const key of ["page", "surface", "ink", "ink-2", "ink-3", "accent", "accent-ink", "accent-tint"] as const) if (!colors[key]) throw Error(`Missing color: ${key}.`);
+ if (value.font !== undefined && (typeof value.font !== "string" || !Object.hasOwn(fonts, value.font))) throw Error("Font must be geist, system or serif.");
+ if (value.corners !== undefined && (typeof value.corners !== "number" || !Number.isInteger(value.corners) || value.corners < 0 || value.corners > 20)) throw Error("Corners must be a whole number from 0 to 20.");
+ return { version: 1, id: value.id, name: value.name.trim(), base: value.base as BuiltinAppearance, colors, ...(value.font === undefined ? {} : { font: value.font as keyof typeof fonts }), ...(value.corners === undefined ? {} : { corners: value.corners as number }) };
+}
+export function contrast(a: string, b: string) {
+ const luminance = (hex: string) => [1, 3, 5].map(at => parseInt(hex.slice(at, at + 2), 16) / 255).map(c => c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4).reduce((sum, c, i) => sum + c * [.2126, .7152, .0722][i], 0);
+ const x = luminance(a), y = luminance(b); return (Math.max(x, y) + .05) / (Math.min(x, y) + .05);
+}
+export function themeWarnings(theme: CustomTheme): string[] {
+ const warnings: string[] = [];
+ for (const ink of ["ink", "ink-2", "ink-3", "accent-ink"] as const) {
+ for (const background of ["page", "surface"] as const) if (contrast(theme.colors[ink]!, theme.colors[background]!) < 4.5) warnings.push(`${ink} on ${background} has low text contrast.`);
+ }
+ return warnings;
+}
diff --git a/apps/native/lib/file-preview.test.ts b/apps/native/lib/file-preview.test.ts
new file mode 100644
index 00000000..79185eae
--- /dev/null
+++ b/apps/native/lib/file-preview.test.ts
@@ -0,0 +1,19 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { filePreview, MAX_PREVIEW } from "./file-preview";
+test("large previews are bounded and retain full file size; binary contents stay hidden", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'graff-preview-'));
+ try {
+ const name = path.join(root, 'large.log');
+ const fd = await open(name, 'w');
+ await fd.write(Buffer.alloc(MAX_PREVIEW, 65)); await fd.truncate(512 * 1024 * 1024); await fd.close();
+ const preview = await filePreview(name);
+ assert.equal(preview.size, 512 * 1024 * 1024);
+ assert.equal(preview.text.length, MAX_PREVIEW); assert.equal(preview.truncated, true);
+ await writeFile(name, Buffer.from([0, 1, 2]));
+ assert.equal((await filePreview(name)).text, '');
+ } finally { await rm(root, { recursive: true, force: true }); }
+});
diff --git a/apps/native/lib/file-preview.ts b/apps/native/lib/file-preview.ts
new file mode 100644
index 00000000..d9a06449
--- /dev/null
+++ b/apps/native/lib/file-preview.ts
@@ -0,0 +1,14 @@
+import { open } from "node:fs/promises";
+export const MAX_PREVIEW = 256 * 1024;
+/** Read only the displayed prefix, including for huge logs and sparse files. */
+export async function filePreview(path: string) {
+ const file = await open(path, "r");
+ try {
+ const { size } = await file.stat();
+ const buffer = Buffer.alloc(Math.min(size, MAX_PREVIEW));
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ const bytes = buffer.subarray(0, bytesRead);
+ const binary = bytes.subarray(0, 8192).includes(0);
+ return { size, binary, truncated: size > bytesRead, text: binary ? "" : bytes.toString("utf8") };
+ } finally { await file.close(); }
+}
diff --git a/apps/native/lib/git-review.test.ts b/apps/native/lib/git-review.test.ts
index 05c8d3eb..bcbd7e39 100644
--- a/apps/native/lib/git-review.test.ts
+++ b/apps/native/lib/git-review.test.ts
@@ -22,3 +22,26 @@ test("shared review includes staged, unstaged, new and deleted files without she
await assert.rejects(reviewDiff(root,'../private'), /relative workspace/);
} finally { rmSync(root,{recursive:true,force:true}); }
});
+test("a repository without commits displays both untracked and staged first files", async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'graff-review-first-'));
+ try {
+ execFileSync('git', ['init', '-q', root]);
+ writeFileSync(path.join(root, 'first.txt'), 'first line\n');
+ assert.match(await reviewDiff(root, 'first.txt'), /\+first line/);
+ assert.equal((await reviewState(root)).files.length, 1);
+ execFileSync('git', ['add', 'first.txt'], { cwd: root });
+ assert.match(await reviewDiff(root, 'first.txt'), /\+first line/);
+ assert.match(await reviewDiff(root, 'first.txt', 'staged'), /\+first line/);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
+test("numstat retains tabs in file names", async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'graff-review-tabs-'));
+ try {
+ execFileSync('git', ['init', '-q', root]);
+ writeFileSync(path.join(root, 'with\ttab.txt'), 'first\nsecond\n');
+ execFileSync('git', ['add', '.'], { cwd: root });
+ const state = await reviewState(root, 'staged');
+ assert.equal(state.files[0].path, 'with\ttab.txt');
+ assert.equal(state.totalAdd, 2);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
diff --git a/apps/native/lib/git-review.ts b/apps/native/lib/git-review.ts
index 084424ef..a0b4ecdb 100644
--- a/apps/native/lib/git-review.ts
+++ b/apps/native/lib/git-review.ts
@@ -15,13 +15,10 @@ export async function reviewDiff(root: string, file: string, scope: ReviewScope
const resolved = path.resolve(root, file);
if (!file || resolved === root || !resolved.startsWith(root + path.sep)) throw new Error("Expected a relative workspace file");
const base = ["diff", "--no-ext-diff", "--no-textconv"];
- try {
- const diff = await git(root, [...base, ...scopeArgs(scope), "--", file]);
- if (diff || scope === "staged") return diff;
- const tracked = await git(root, ["ls-files", "--", file]);
- return tracked ? diff : git(root, [...base, "--no-index", "--", "/dev/null", file], true);
- }
- catch (error) { if (scope !== "all") throw error; return git(root, [...base, "--cached", "--", file]); }
+ const untracked = await git(root, ["ls-files", "--others", "--exclude-standard", "--", file]);
+ if (untracked && scope !== "staged") return git(root, [...base, "--no-index", "--", "/dev/null", file], true);
+ const head = scope === "all" ? await git(root, ["rev-parse", "--verify", "HEAD"]).catch(() => "") : "";
+ return git(root, [...base, ...(scope === "all" && !head ? ["--cached"] : scopeArgs(scope)), "--", file]);
}
export async function reviewState(root: string, scope: ReviewScope = "all"): Promise<ReviewState> {
const [status, branch, log, worktreeText] = await Promise.all([
@@ -43,7 +40,7 @@ export async function reviewState(root: string, scope: ReviewScope = "all"): Pro
const stats = await git(root, ["diff", "--numstat", "-z", ...scopeArgs(scope)]).catch(() => git(root, ["diff", "--numstat", "-z", "--cached"]));
const parts = stats.split("\0");
for (let i = 0; i < parts.length; i++) {
- const [add, del, name] = parts[i].split("\t"); let file = name;
+ const [add, del, ...nameParts] = parts[i].split("\t"); const name = nameParts.join("\t"); let file = name;
if (name === "") { i++; file = parts[++i]; }
const entry = files.find(row => row.path === file);
if (entry) { entry.add = Number(add) || 0; entry.del = Number(del) || 0; entry.binary = add === "-"; }
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index 4b9d9c57..e641fb00 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -47,7 +47,7 @@ export type ToolRow = {
name: string;
icon: ToolIcon;
chip: string;
- status: "running" | "ok" | "error";
+ status: "running" | "ok" | "error" | "interrupted";
detail: { text: string; tone?: "add" }[];
path?: string;
/** Wall-clock bracket, measured client-side — rows tick while running. */
@@ -78,6 +78,11 @@ export type AskPrompt = {
export type TurnStatus = "thinking" | "streaming" | "ask" | "done" | "error";
export type AssistantTurn = {
+ startedAt?: number;
+ lastUpdateAt?: number;
+ activityKind?: string;
+ connected?: boolean;
+ stopReason?: string;
reasoning: string;
text: string;
tools: ToolRow[];
diff --git a/apps/native/lib/gui-skill-context.ts b/apps/native/lib/gui-skill-context.ts
new file mode 100644
index 00000000..6a847ecb
--- /dev/null
+++ b/apps/native/lib/gui-skill-context.ts
@@ -0,0 +1,20 @@
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { selectedGuiSkills, withGuiSkillContext } from "./gui-skills";
+import { themeDirectory } from "./theme-files";
+
+export async function prepareGuiPrompt(params: Record<string, unknown> | undefined) {
+ if (!Array.isArray(params?.prompt)) return params;
+ const selected = new Set<string>();
+ // Explicit mentions in user text only: attachments never activate a skill.
+ for (const block of params.prompt) if (block?.type === "text" && typeof block.text === "string") for (const skill of selectedGuiSkills(block.text)) selected.add(skill.id);
+ if (!selected.size) return params;
+ const instructions = await Promise.all([...selected].map(async id => {
+ const text = await readFile(path.join(process.cwd(), "skills", id, "SKILL.md"), "utf8");
+ return `GUI skill: ${id}\n${text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")}\nTheme directory for this desktop: ${JSON.stringify(themeDirectory())}`;
+ }));
+ const prompt = params.prompt.map(block => ({ ...block }));
+ const first = prompt.find(block => block.type === "text" && typeof block.text === "string");
+ first.text = withGuiSkillContext(first.text, instructions.join("\n\n"));
+ return { ...params, prompt };
+}
diff --git a/apps/native/lib/gui-skills.test.ts b/apps/native/lib/gui-skills.test.ts
new file mode 100644
index 00000000..e3b627f5
--- /dev/null
+++ b/apps/native/lib/gui-skills.test.ts
@@ -0,0 +1,28 @@
+import { test, expect } from "bun:test";
+import { guiSkillRows, parseComposerToken, selectedGuiSkills, withoutGuiSkillContext } from "./gui-skills";
+import { prepareGuiPrompt } from "./gui-skill-context";
+test("at and dollar discover GUI skills without stealing file or slash completion", () => {
+ expect(parseComposerToken("Try $gui-th")?.kind).toBe("skill");
+ expect(parseComposerToken("Try @gui-th")?.kind).toBe("at");
+ expect(parseComposerToken("@src/main.zig")?.query).toBe("src/main.zig");
+ expect(parseComposerToken("/effort")?.kind).toBe("slash");
+ expect(guiSkillRows("theme")[0].name).toBe("$gui-theme");
+});
+test("only explicit, unquoted GUI skill mentions activate context", () => {
+ expect(selectedGuiSkills("$gui-theme make it green @gui-theme")).toHaveLength(1);
+ for (const text of ["`$gui-theme`", "```\n@gui-theme\n```", "email@gui-theme", "@$gui-theme", "$gui-theme-old", "@[gui-theme]", "@gui-theme/file", "regular prompt"]) expect(selectedGuiSkills(text)).toEqual([]);
+});
+test("GUI skill instructions arrive through ACP while display text and other blocks survive", async () => {
+ const original = { sessionId: "fixture", prompt: [{ type: "text", text: "$gui-theme make a garden palette" }, { type: "image", data: "fixture" }] };
+ const prepared = await prepareGuiPrompt(original);
+ const blocks = prepared?.prompt as typeof original.prompt;
+ expect(blocks[0].text).toContain("GUI skill: gui-theme");
+ expect(blocks[0].text).toContain("Theme directory for this desktop:");
+ expect(withoutGuiSkillContext(blocks[0].text!)).toBe(original.prompt[0].text!);
+ expect(blocks[1]).toEqual(original.prompt[1]);
+ expect(original.prompt[0].text).toBe("$gui-theme make a garden palette");
+});
+test("ordinary prompts and file attachments do not load GUI skills", async () => {
+ const original = { prompt: [{ type: "text", text: "Read the project" }, { type: "resource_link", name: "$gui-theme", uri: "file:///fixture" }] };
+ expect(await prepareGuiPrompt(original)).toBe(original);
+});
diff --git a/apps/native/lib/gui-skills.ts b/apps/native/lib/gui-skills.ts
new file mode 100644
index 00000000..7b7d5ea4
--- /dev/null
+++ b/apps/native/lib/gui-skills.ts
@@ -0,0 +1,19 @@
+// This catalog belongs to the desktop composer, never the engine's skill registry.
+export const guiSkills = [{ id: "gui-theme", name: "GUI theme", description: "Create or adjust your desktop theme" }] as const;
+export function guiSkillRows(query: string) {
+ return guiSkills.filter(skill => `${skill.id} ${skill.description}`.toLowerCase().includes(query.toLowerCase())).map(skill => ({ key: `gui-skill:${skill.id}`, name: `$${skill.id}`, desc: `GUI skill · ${skill.description}` }));
+}
+export function selectedGuiSkills(text: string) {
+ const prose = text.replace(/```[\s\S]*?(?:```|$)|`[^`\n]*`/g, "");
+ return guiSkills.filter(skill => new RegExp(`(?:^|\\s)[@$]${skill.id}(?=$|\\s|[.,!?;:])`).test(prose));
+}
+export function parseComposerToken(draft: string): { kind: "at" | "slash" | "skill"; query: string; start: number } | null {
+ const match = /(^|\s)([@/$])([\w./-]*)$/.exec(draft);
+ return match ? { kind: match[2] === "@" ? "at" : match[2] === "$" ? "skill" : "slash", query: match[3].toLowerCase(), start: match.index + match[1].length } : null;
+}
+const start = "\n<graff-gui-skill-context>\n", end = "\n</graff-gui-skill-context>";
+export function withGuiSkillContext(text: string, instructions: string) { return `${text}${start}${instructions}${end}`; }
+export function withoutGuiSkillContext(text: string) {
+ const at = text.lastIndexOf(start);
+ return at >= 0 && text.endsWith(end) ? text.slice(0, at) : text;
+}
diff --git a/apps/native/lib/review-lines.test.ts b/apps/native/lib/review-lines.test.ts
new file mode 100644
index 00000000..3fc902a4
--- /dev/null
+++ b/apps/native/lib/review-lines.test.ts
@@ -0,0 +1,21 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { reviewLines } from "./review-lines";
+
+test("new-file metadata is hidden and only added content contributes to counts", () => {
+ const rows = reviewLines("diff --git a/new b/new\nnew file mode 100644\nindex 000..123\n--- /dev/null\n+++ b/new\n@@ -0,0 +1,2 @@\n+first\n+++ literal code\n\\ No newline at end of file\n");
+ assert.deepEqual(rows, [
+ { kind: "hunk", text: "", old: 0, next: 1 },
+ { kind: "add", text: "first", next: 1 },
+ { kind: "add", text: "++ literal code", next: 2 },
+ ]);
+});
+
+test("replacement hunks preserve separate old and new line numbers", () => {
+ const rows = reviewLines("@@ -10,2 +12,2 @@ function\n unchanged\n-old\n+new\n");
+ assert.deepEqual(rows.slice(1), [
+ { kind: "context", text: "unchanged", old: 10, next: 12 },
+ { kind: "remove", text: "old", old: 11 },
+ { kind: "add", text: "new", next: 13 },
+ ]);
+});
diff --git a/apps/native/lib/review-lines.ts b/apps/native/lib/review-lines.ts
new file mode 100644
index 00000000..99448500
--- /dev/null
+++ b/apps/native/lib/review-lines.ts
@@ -0,0 +1,18 @@
+export type ReviewLine = { kind: "hunk" | "add" | "remove" | "context"; text: string; old?: number; next?: number };
+export function reviewLines(diff: string): ReviewLine[] {
+ let old = 0, next = 0, inHunk = false;
+ const rows: ReviewLine[] = [];
+ for (const line of diff.split("\n")) {
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)/.exec(line);
+ if (hunk) {
+ old = Number(hunk[1]); next = Number(hunk[2]); inHunk = true;
+ rows.push({ kind: "hunk", text: hunk[3].trim(), old, next }); continue;
+ }
+ if (line.startsWith("diff --git")) inHunk = false;
+ if (!inHunk || !/^[ +\-]/.test(line)) continue;
+ if (line[0] === "+") rows.push({ kind: "add", text: line.slice(1), next: next++ });
+ else if (line[0] === "-") rows.push({ kind: "remove", text: line.slice(1), old: old++ });
+ else rows.push({ kind: "context", text: line.slice(1), old: old++, next: next++ });
+ }
+ return rows;
+}
diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.ts
index 552237e8..cb719ee4 100644
--- a/apps/native/lib/sessions.ts
+++ b/apps/native/lib/sessions.ts
@@ -1,3 +1,4 @@
+import { withoutGuiSkillContext } from "./gui-skills";
import {
chipFor,
emptyTurn,
@@ -230,7 +231,7 @@ export function transcriptFromMessages(raw: unknown[], model?: string): Transcri
? { role: "tool", tool_call_id: saved.call_id, content: saved.output }
: saved;
if (msg.role === "user") {
- const text = textOf(msg.content).trim();
+ const text = withoutGuiSkillContext(textOf(msg.content).trim());
if (!text) continue;
flush();
out.push({ role: "user", text });
@@ -277,7 +278,7 @@ export function transcriptFromMessages(raw: unknown[], model?: string): Transcri
const t = current();
const idx = t.tools.findIndex((row) => row.id === msg.tool_call_id);
if (idx < 0) continue;
- const text = textOf(msg.content).trim();
+ const text = withoutGuiSkillContext(textOf(msg.content).trim());
const failed = /^(error|failed|denied)\b/i.test(text);
t.tools = t.tools.map((row, i) =>
i === idx
diff --git a/apps/native/lib/theme-files.ts b/apps/native/lib/theme-files.ts
new file mode 100644
index 00000000..953cbd57
--- /dev/null
+++ b/apps/native/lib/theme-files.ts
@@ -0,0 +1,47 @@
+import { open, readdir, mkdir, link, rm } from "node:fs/promises";
+import { constants } from "node:fs";
+import path from "node:path";
+import os from "node:os";
+import { randomUUID } from "node:crypto";
+import { parseTheme, themeLimit, themeWarnings, type CustomTheme } from "./custom-themes";
+
+export const themeDirectory = () => process.env.GRAFF_THEMES_DIR || path.join(os.homedir(), ".graff", "themes");
+export async function readThemeFile(file: string) {
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > themeLimit) throw Error("Theme must be a JSON file smaller than 16 KiB.");
+ const buffer = Buffer.alloc(themeLimit + 1);
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
+ if (bytesRead > themeLimit) throw Error("Theme is too large.");
+ return parseTheme(JSON.parse(buffer.subarray(0, bytesRead).toString("utf8")));
+ } finally { await handle.close(); }
+}
+export async function listThemes(directory = themeDirectory()) {
+ const themes: CustomTheme[] = [], issues: string[] = [];
+ let files;
+ try { files = await readdir(directory, { withFileTypes: true }); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return { themes, issues }; throw error; }
+ const candidates = files.filter(file => file.name.endsWith(".json")).sort((a, b) => a.name.localeCompare(b.name));
+ if (candidates.length > 100) issues.push("Only the first 100 theme files are loaded.");
+ for (const file of candidates.slice(0, 100)) {
+ try {
+ const theme = await readThemeFile(path.join(directory, file.name));
+ if (file.name !== `${theme.id}.json`) throw Error("Filename must match the theme id.");
+ themes.push(theme);
+ } catch (error) { issues.push(`${file.name}: ${error instanceof Error ? error.message : "Could not read theme."}`); }
+ }
+ return { themes, issues };
+}
+export async function saveTheme(value: unknown, directory = themeDirectory()) {
+ const theme = parseTheme(value);
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ const file = path.join(directory, `${theme.id}.json`), temp = path.join(directory, `.${randomUUID()}.tmp`);
+ try {
+ const handle = await open(temp, "wx", 0o600);
+ try { await handle.writeFile(JSON.stringify(theme, null, 2) + "\n"); } finally { await handle.close(); }
+ // Import creates a new choice; it cannot overwrite an existing theme.
+ await link(temp, file);
+ } finally { await rm(temp, { force: true }); }
+ return { theme, warnings: themeWarnings(theme) };
+}
diff --git a/apps/native/lib/turn-activity.test.ts b/apps/native/lib/turn-activity.test.ts
new file mode 100644
index 00000000..7346e478
--- /dev/null
+++ b/apps/native/lib/turn-activity.test.ts
@@ -0,0 +1,48 @@
+import { test, expect } from "bun:test";
+import { emptyTurn, applyAcpUpdate, finishAcpTurn } from "./acp";
+import { turnActivity } from "./turn-activity";
+import { createTurnPainter } from "./turn-painter";
+test("commentary followed by silence stays visibly waiting", () => {
+ const turn = { ...emptyTurn(), status: "streaming" as const, text: "Preparing the change.", connected: true, startedAt: 1000, lastUpdateAt: 4000, activityKind: "agent_message_chunk" };
+ expect(turnActivity(turn, 25000)).toMatchObject({ live: true, label: "Waiting for Graff…", state: "waiting" });
+ expect(turnActivity(turn, 25000).detail).toContain("21s");
+});
+test("active tools remain visible after commentary, with completed details collapsed separately", () => {
+ let turn = applyAcpUpdate({ ...emptyTurn(), text: "Preparing the change." }, { sessionUpdate: "tool_call", toolCallId: "fixture", kind: "execute", status: "pending" });
+ expect(turnActivity(turn, Date.now()).label).toBe("Running 1 tool…");
+ turn = applyAcpUpdate(turn, { sessionUpdate: "tool_call_update", toolCallId: "fixture", status: "completed" });
+ expect(turnActivity(turn, Date.now()).label).toBe("Waiting for Graff…");
+});
+test("cancel and stream error settle pending tools without claiming success", () => {
+ const pending = applyAcpUpdate(emptyTurn(), { sessionUpdate: "tool_call", toolCallId: "fixture", status: "pending" });
+ const stopped = finishAcpTurn(applyAcpUpdate(pending, { sessionUpdate: "gui_turn_end", stopReason: "cancelled" }));
+ expect(turnActivity(stopped, Date.now()).label).toBe("Stopped");
+ expect(stopped.tools[0].status).toBe("interrupted");
+ const failed = finishAcpTurn({ ...pending, status: "error", error: "Disconnected" });
+ expect(turnActivity(failed, Date.now())).toMatchObject({ label: "Response interrupted", live: false });
+ expect(failed.tools[0].status).toBe("interrupted");
+});
+test("turn painter commits if animation frames stop, and stale callbacks cannot undo an error", () => {
+ const painted: string[] = [], frames: (() => void)[] = [], timers: (() => void)[] = [];
+ const painter = createTurnPainter<string>(value => painted.push(value), { frame(callback) { frames.push(callback); return frames.length; }, cancelFrame() {}, delay(callback) { timers.push(callback); return timers.length as unknown as ReturnType<typeof setTimeout>; }, cancelDelay() {} });
+ painter.update("first"); painter.update("latest");
+ timers[0](); expect(painted).toEqual(["latest"]);
+ frames[0](); expect(painted).toEqual(["latest"]);
+ painter.update("working"); painter.finish("error");
+ frames[1](); timers[1](); painter.update("late");
+ expect(painted).toEqual(["latest", "error"]);
+});
+test("default painter calls browser cancellation APIs without a scheduler receiver", () => {
+ const originalFrame = globalThis.requestAnimationFrame, originalCancel = globalThis.cancelAnimationFrame;
+ let next: FrameRequestCallback | undefined;
+ globalThis.requestAnimationFrame = callback => { next = callback; return 1; };
+ globalThis.cancelAnimationFrame = function (this: unknown) {
+ if (this !== undefined && this !== globalThis) throw new TypeError("Illegal invocation");
+ };
+ try {
+ const painted: string[] = [];
+ const painter = createTurnPainter<string>(value => painted.push(value));
+ painter.update("working"); next?.(0); painter.finish("done");
+ expect(painted).toEqual(["working", "done"]);
+ } finally { globalThis.requestAnimationFrame = originalFrame; globalThis.cancelAnimationFrame = originalCancel; }
+});
diff --git a/apps/native/lib/turn-activity.ts b/apps/native/lib/turn-activity.ts
new file mode 100644
index 00000000..c10bb2bd
--- /dev/null
+++ b/apps/native/lib/turn-activity.ts
@@ -0,0 +1,13 @@
+import type { AssistantTurn } from "./graff-events";
+export function turnActivity(turn: AssistantTurn, now: number) {
+ const live = turn.status === "thinking" || turn.status === "streaming";
+ const elapsed = Math.max(0, Math.floor((now - (turn.startedAt ?? now)) / 1000));
+ const idle = Math.max(0, Math.floor((now - (turn.lastUpdateAt ?? turn.startedAt ?? now)) / 1000));
+ const running = turn.tools.filter(tool => tool.status === "running").length;
+ const missing = turn.tools.filter(tool => tool.status === "interrupted").length;
+ if (turn.status === "error") return { state: "error", label: "Response interrupted", detail: "You can send a follow-up to continue.", live: false };
+ if (turn.status === "ask") return { state: "input", label: "Waiting for your answer", detail: "", live: false };
+ if (!live) return { state: "done", label: turn.stopReason === "cancelled" ? "Stopped" : "Turn finished", detail: missing ? `${missing} tool ${missing === 1 ? "result" : "results"} not received` : `${elapsed}s`, live: false };
+ const label = !turn.connected ? "Starting Graff…" : running ? `Running ${running} ${running === 1 ? "tool" : "tools"}…` : turn.activityKind === "agent_thought_chunk" ? "Thinking…" : turn.activityKind === "agent_message_chunk" && idle < 2 ? "Writing response…" : "Waiting for Graff…";
+ return { state: idle >= 15 ? "waiting" : "working", label, detail: idle >= 15 ? `No update for ${idle}s · You can stop this turn` : `${elapsed}s`, live: true };
+}
diff --git a/apps/native/lib/turn-painter.ts b/apps/native/lib/turn-painter.ts
new file mode 100644
index 00000000..572a3408
--- /dev/null
+++ b/apps/native/lib/turn-painter.ts
@@ -0,0 +1,19 @@
+type Scheduler = { frame(callback: () => void): number; cancelFrame(id: number): void; delay(callback: () => void): ReturnType<typeof setTimeout>; cancelDelay(id: ReturnType<typeof setTimeout>): void };
+export function createTurnPainter<T>(paint: (value: T) => void, scheduler: Scheduler = {
+ frame: callback => requestAnimationFrame(callback), cancelFrame: id => cancelAnimationFrame(id),
+ delay: callback => setTimeout(callback, 100), cancelDelay: id => clearTimeout(id),
+}) {
+ let frame: number | undefined, timer: ReturnType<typeof setTimeout> | undefined, latest: T, generation = 0, closed = false;
+ const cancel = () => { generation++; if (frame !== undefined) scheduler.cancelFrame(frame); if (timer !== undefined) scheduler.cancelDelay(timer); frame = undefined; timer = undefined; };
+ return {
+ update(value: T) {
+ if (closed) return;
+ latest = value; if (frame !== undefined || timer !== undefined) return;
+ const ticket = generation;
+ const commit = () => { if (closed || ticket !== generation) return; cancel(); paint(latest); };
+ frame = scheduler.frame(commit); timer = scheduler.delay(commit);
+ },
+ finish(value: T) { if (closed) return; cancel(); closed = true; paint(value); },
+ dispose() { cancel(); closed = true; },
+ };
+}
diff --git a/apps/native/next.config.ts b/apps/native/next.config.ts
index 237b7f48..a0411b5c 100644
--- a/apps/native/next.config.ts
+++ b/apps/native/next.config.ts
@@ -9,6 +9,7 @@ const nextConfig: NextConfig = {
// Without this the tracer walks up to the repository root and copies the
// Zig build outputs into the payload.
outputFileTracingRoot: __dirname,
+ outputFileTracingIncludes: { "/api/acp": ["./skills/*/SKILL.md"] },
// The app is opened at 127.0.0.1 (the desktop shell points there), which
// Next 16 treats as cross-origin for its dev resources unless it is
// listed here; without it hot reloading is refused.
diff --git a/apps/native/package.json b/apps/native/package.json
index b8604319..b6345914 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -12,7 +12,10 @@
"lint": "next lint",
"test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts",
"electron:build": "bash electron/build.sh",
- "test:electron": "bun test electron/policy.test.cjs"
+ "test:electron": "bun test electron/policy.test.cjs",
+ "test:desktop": "bun test lib ./electron/*.test.cjs",
+ "test:visual": "bun scripts/test-visual.mjs",
+ "test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs"
},
"dependencies": {
"@streamdown/code": "^1.1.1",
diff --git a/apps/native/scripts/test-visual.mjs b/apps/native/scripts/test-visual.mjs
new file mode 100644
index 00000000..d6c26aa0
--- /dev/null
+++ b/apps/native/scripts/test-visual.mjs
@@ -0,0 +1,6 @@
+import { createRequire } from 'node:module';
+import { spawn } from 'node:child_process';
+const require = createRequire(import.meta.url);
+const child = spawn(require('electron'), ['electron/visual-tests.cjs'], { stdio: 'inherit', env: { ...process.env, GRAFF_TEST_BUN: process.execPath } });
+child.on('error', error => { console.error(error.message); process.exitCode = 1; });
+child.on('exit', code => { process.exitCode = code ?? 1; });
diff --git a/apps/native/skills/gui-theme/SKILL.md b/apps/native/skills/gui-theme/SKILL.md
new file mode 100644
index 00000000..e629bc6d
--- /dev/null
+++ b/apps/native/skills/gui-theme/SKILL.md
@@ -0,0 +1,74 @@
+---
+name: gui-theme
+description: Create or adjust a CodeGraff desktop theme when selected with @gui-theme or $gui-theme in the GUI composer.
+---
+
+# GUI theme
+
+This skill is supplied by the GUI for this request. It is not an engine skill
+or a terminal theme. Use ordinary file tools to create a portable JSON theme;
+do not patch the app, engine, shell settings, or built-in palettes.
+
+Follow the requested mood, colors, and light/dark preference. If the user only
+invoked the skill, ask for their preferred look before creating anything.
+Otherwise make a coherent first version and iterate from feedback.
+
+## Theme file
+
+Save one JSON file in the theme directory supplied below these instructions
+(normally `~/.graff/themes`). The filename must match its `id`, for example
+`midnight-garden.json`. Inspect an existing file before replacing it; preserve
+other themes. A new id creates a separate choice in Appearance.
+
+```json
+{
+ "version": 1,
+ "id": "midnight-garden",
+ "name": "Midnight Garden",
+ "base": "dark",
+ "colors": {
+ "page": "#15201c",
+ "canvas": "#101914",
+ "surface": "#1c2a23",
+ "ink": "#f1f7ee",
+ "ink-2": "#c1d4c3",
+ "ink-3": "#a3baa6",
+ "accent": "#a4d98c",
+ "accent-ink": "#b5e79e",
+ "accent-tint": "#2c422c",
+ "line": "#3e5446",
+ "field": "#23342b"
+ },
+ "font": "system",
+ "corners": 10
+}
+```
+
+The schema is version 1, maximum 16 KiB. IDs use lowercase letters, digits and
+hyphens, start with a letter, and are at most 48 characters. Names are at most
+60 characters. Base is `light`, `dark`, `website`, or `codegraff`.
+
+Required colors: `page`, `surface`, `ink`, `ink-2`, `ink-3`, `accent`,
+`accent-ink`, `accent-tint`. All colors are six-digit hex strings.
+Optional colors: `canvas`, `inset`, `hover`, `hover-2`, `line`, `line-strong`,
+`field`, `stripe`, `stripe-bg`, `green`, `green-tint`, `red`, `red-tint`,
+`orange`, `orange-tint`, `brand-coral`, `brand-gold`.
+Unset tokens inherit from the base. For a coherent result, customize surfaces,
+borders and status colors too, while preserving recognizable success/error states.
+Optional `font`: `geist`, `system`, or `serif`; code retains its monospace font.
+Optional `corners`: integer 0–20 pixels for controls, chips and cards.
+No arbitrary CSS, URLs, scripts, external fonts, or executable assets.
+
+## Validate and deliver
+
+Parse the JSON after writing it. Check text contrast on both `page` and
+`surface`: aim for at least 4.5:1 for all ink tokens, including secondary text
+and `accent-ink`. Check selected states, input fields and error/success colors.
+Appearance reports schema errors and low-contrast warnings. Correct these
+before calling the theme finished.
+
+Tell the user to open Appearance and choose the new theme under My themes.
+The panel refreshes while open, without rebuilding or restarting the app.
+Selecting a built-in theme restores its defaults. Theme selection remains the
+user's choice: creating a file does not silently switch their theme.
+The JSON file is shareable using Import theme in another desktop installation.
diff --git a/docs/adr/0074-gui-skills-and-portable-themes.md b/docs/adr/0074-gui-skills-and-portable-themes.md
new file mode 100644
index 00000000..8d27a411
--- /dev/null
+++ b/docs/adr/0074-gui-skills-and-portable-themes.md
@@ -0,0 +1,26 @@
+# 0074. GUI skills and portable themes
+
+Status: accepted
+
+## Decision
+
+Desktop-specific skills live with the GUI. The composer offers them through
+explicit `@` and `$` mentions. The GUI's ACP adapter loads only the selected
+skill and appends its instructions to that request. The engine's built-in
+skills, terminal commands, and ordinary ACP clients remain unchanged.
+
+Theme files are versioned JSON palettes under the user's themes directory.
+The GUI validates bounded files and applies allowlisted color, font, and corner
+settings. Themes cannot supply scripts, arbitrary CSS, remote fonts or URLs.
+Appearance lists saved themes while open; selecting one stores a local
+preference. Creating a theme does not select it automatically. Built-in
+choices reset custom overrides, and imports cannot overwrite existing ids.
+
+## Consequences
+
+Agents can customize the desktop using ordinary file tools without editing
+or rebuilding the application. The skill and its schema ship with the GUI.
+The GUI owns discovery, validation, presentation and prompt context; the
+engine continues to own coding and tool execution. Cached theme values make
+the selected palette available before the first paint. No idle file polling
+is needed when Appearance is closed.
diff --git a/docs/adr/0075-acp-adapter-and-desktop-measurements.md b/docs/adr/0075-acp-adapter-and-desktop-measurements.md
new file mode 100644
index 00000000..27cf59df
--- /dev/null
+++ b/docs/adr/0075-acp-adapter-and-desktop-measurements.md
@@ -0,0 +1,28 @@
+# 0075. Separate ACP presentation adapters and measure desktop workloads
+
+Status: accepted
+
+## Decision
+
+The TUI backend value types live separately from the mutable callback registry.
+ACP transcript decoding lives separately from session lifecycle. In-process text
+chunks use the same normalized decoder operation as wire chunks, avoiding JSON
+allocation and parsing when both endpoints already share a process. Tool events
+retain their wire path. Parity tests cover reasoning visibility and Unicode.
+Coding and session policy remain in the harness; desktop rendering stays a client.
+
+Desktop profiling extends the bounded, opt-in measurement report (ADR 0072).
+Paint timings cover document startup; interaction latency, streaming, heap,
+process-tree resources and event-loop delay cover ongoing use. Unavailable
+measurements are null. GPU feature status is allowlisted; GPU-process CPU/RSS
+must never be presented as device utilization or dedicated video memory.
+Chromium chooses its supported hardware backend; no forced driver overrides or
+custom shader pipeline without a measured workload that benefits.
+
+## Consequences
+
+Synthetic GUI workloads can run without credentials or a model and generate
+public-safe demonstration images. Their measurements are lab evidence, not
+field percentiles or proof of faster real-model turns. Performance reports carry
+no transcript, device identifier or raw profiling trace. Screenshots are separate,
+explicit test artifacts. New optimizations require comparable before/after runs.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 30d23f1e..2528c99c 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -84,6 +84,8 @@ record only when you need the evidence or the edge cases.
| [0071](0071-desktop-tools-and-macos-computer-use.md) | Desktop MCP controls embedded Chromium and a user-enabled native macOS bridge; coding stays in graff. |
| [0072](0072-gui-profiler-exports-measurements-only.md) | GUI profiling is bounded and off by default; feedback exports contain allowlisted measurements with no automatic upload. |
| [0073](0073-acp-stream-and-shared-review.md) | One ACP stdout reader routes responses; shared review reads Git working trees without inferring edit authorship. |
+| [0074](0074-gui-skills-and-portable-themes.md) | Explicit desktop skills and validated themes live in the GUI; selected instructions travel over ACP. |
+| [0075](0075-acp-adapter-and-desktop-measurements.md) | ACP presentation decoding is separate from session lifecycle; desktop performance uses bounded workload measurements and default Chromium acceleration. |
## When to write one
diff --git a/docs/images/desktop-chat-dark.png b/docs/images/desktop-chat-dark.png
new file mode 100644
index 00000000..c9e41a1e
Binary files /dev/null and b/docs/images/desktop-chat-dark.png differ
diff --git a/docs/images/desktop-review-codegraff.png b/docs/images/desktop-review-codegraff.png
new file mode 100644
index 00000000..eaf3c9bf
Binary files /dev/null and b/docs/images/desktop-review-codegraff.png differ
diff --git a/src/main.zig b/src/main.zig
index c4c02e15..98429fa6 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -585,6 +585,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)
_ = @import("agent_request_search_tests.zig");
_ = @import("agent_ws_steer.zig"); // gpt-6-astra response.steer
+ _ = @import("tui_acp_updates.zig");
_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root
_ = @import("task_outcome.zig"); // goal-outcome telemetry events
_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here
diff --git a/src/tui_acp.zig b/src/tui_acp.zig
index ca925132..2ec388d4 100644
--- a/src/tui_acp.zig
+++ b/src/tui_acp.zig
@@ -50,100 +50,10 @@ pub fn cancel() void {
acp.handleLine(&s.dispatch, arena_state.allocator(), &w, "{\"jsonrpc\":\"2.0\",\"method\":\"session/cancel\"}") catch {};
}
-/// Maps one ACP `session/update` line onto the TUI stream / event queue.
-pub const Apply = struct {
- queue: *tui.EventQueue,
- stream: *repl.StreamBuf,
- show_thinking: bool = false,
- reasoning_open: bool = false,
- last_title: [160]u8 = undefined,
- last_title_len: usize = 0,
-};
-
-pub fn applyBuffered(a: *Apply, gpa: Allocator, bytes: []const u8) void {
- var it = std.mem.splitScalar(u8, bytes, '\n');
- while (it.next()) |line| applyLine(a, gpa, line);
-}
-
-pub fn applyLine(a: *Apply, gpa: Allocator, line: []const u8) void {
- const trimmed = std.mem.trim(u8, line, " \t\r\n");
- if (trimmed.len == 0) return;
- var parsed = std.json.parseFromSlice(Value, gpa, trimmed, .{}) catch return;
- defer parsed.deinit();
- if (parsed.value != .object) return;
- const method = util.strFieldObj(parsed.value.object, "method") orelse return;
- if (!std.mem.eql(u8, method, "session/update")) return;
- const params = parsed.value.object.get("params") orelse return;
- if (params != .object) return;
- const update = params.object.get("update") orelse return;
- if (update != .object) return;
- const kind = util.strFieldObj(update.object, "sessionUpdate") orelse return;
- if (std.mem.eql(u8, kind, "agent_thought_chunk")) {
- const text = contentText(update.object) orelse return;
- if (text.len == 0 or !a.show_thinking) return;
- a.reasoning_open = true;
- a.stream.appendBytes(text);
- return;
- }
- if (std.mem.eql(u8, kind, "agent_message_chunk")) {
- const text = contentText(update.object) orelse return;
- if (text.len == 0) return;
- if (a.reasoning_open) {
- a.reasoning_open = false;
- a.stream.appendBytes("\n");
- }
- a.stream.appendBytes(text);
- return;
- }
- if (std.mem.eql(u8, kind, "tool_call")) {
- const title = util.strFieldObj(update.object, "title") orelse "tool";
- const name = util.strFieldObj(update.object, "name") orelse title;
- rememberTitle(a, name);
- if (label.skipTranscript(name)) return;
- a.queue.push(.{ .tool_started = .{ .name = name, .detail = cap(title, 160) } });
- return;
- }
- if (std.mem.eql(u8, kind, "tool_call_update")) {
- if (tui.rawStream()) |raw| raw.len.store(0, .release);
- const title = a.last_title[0..a.last_title_len];
- if (title.len == 0 or label.skipTranscript(title)) return;
- const status = util.strFieldObj(update.object, "status") orelse "completed";
- const failed = std.mem.eql(u8, status, "failed");
- const text = updateText(update.object);
- a.queue.push(.{ .tool_finished = .{
- .name = title,
- .detail = cap(text, 80),
- .is_error = failed,
- } });
- }
-}
-
-fn contentText(update: std.json.ObjectMap) ?[]const u8 {
- const content = update.get("content") orelse return null;
- if (content != .object) return null;
- return util.strFieldObj(content.object, "text");
-}
-
-fn updateText(update: std.json.ObjectMap) []const u8 {
- const content = update.get("content") orelse return "";
- if (content != .array or content.array.items.len == 0) return "";
- const first = content.array.items[0];
- if (first != .object) return "";
- const inner = first.object.get("content") orelse return "";
- if (inner != .object) return "";
- return util.strFieldObj(inner.object, "text") orelse "";
-}
-
-fn rememberTitle(a: *Apply, title: []const u8) void {
- const n = @min(title.len, a.last_title.len);
- @memcpy(a.last_title[0..n], title[0..n]);
- a.last_title_len = n;
-}
-
-fn cap(s: []const u8, n: usize) []const u8 {
- const line = if (std.mem.indexOfScalar(u8, s, '\n')) |i| s[0..i] else s;
- return line[0..@min(line.len, n)];
-}
+const updates = @import("tui_acp_updates.zig");
+pub const Apply = updates.Apply;
+pub const applyLine = updates.applyLine;
+pub const applyBuffered = updates.applyBuffered;
fn toolTitle(name: []const u8, input: Value) []const u8 {
if (input == .object) {
@@ -164,6 +74,13 @@ const transcript_vt: engine_sink.VTable = .{ .emit = transcriptEmit, .durable =
fn transcriptEmit(ctx: *anyopaque, ev: engine_sink.Stamped) void {
const t: *Transcript = @ptrCast(@alignCast(ctx));
+ // Text carries no JSON-only fields. Use the decoder's normalized path,
+ // avoiding a writer allocation + JSON parse for each in-process chunk.
+ switch (ev.event) {
+ .reasoning_delta => |d| return updates.applyChunk(t.apply, true, d.text),
+ .text_delta, .tool_arg_delta => |d| return updates.applyChunk(t.apply, false, d.text),
+ else => {},
+ }
var aw: Io.Writer.Allocating = .init(t.gpa);
defer aw.deinit();
writeUpdate(&aw.writer, t.session_id, ev.event) catch return;
@@ -288,7 +205,7 @@ fn dispatchTurn(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]
fn liveStream(stream: *tui.StreamBuf) *repl.StreamBuf {
comptime {
if (@sizeOf(tui.StreamBuf) != @sizeOf(repl.StreamBuf) or
- @offsetOf(tui.StreamBuf, "buf") != @offsetOf(tui.StreamBuf, "buf") or
+ @offsetOf(tui.StreamBuf, "buf") != @offsetOf(repl.StreamBuf, "buf") or
@offsetOf(tui.StreamBuf, "len") != @offsetOf(repl.StreamBuf, "len"))
@compileError("tui.StreamBuf and repl.StreamBuf must stay layout-identical");
}
@@ -405,38 +322,6 @@ fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const
return std.fmt.allocPrint(arena, "echo:{s}", .{text});
}
-test "applyLine: thought then text land on the live tail" {
- var q: tui.EventQueue = .{};
- q.attach(std.testing.allocator);
- defer q.deinit();
- var buf: [128]u8 = undefined;
- var stream: repl.StreamBuf = .{ .buf = &buf };
- var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };
- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"type\":\"text\",\"text\":\"why\"}}}}");
- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"hi\"}}}}");
- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;
- defer std.testing.allocator.free(snap);
- try std.testing.expectEqualStrings("why\nhi", snap);
-}
-
-test "applyLine: tool_call then tool_call_update become typed rows" {
- var q: tui.EventQueue = .{};
- q.attach(std.testing.allocator);
- defer q.deinit();
- var buf: [32]u8 = undefined;
- var stream: repl.StreamBuf = .{ .buf = &buf };
- var a: Apply = .{ .queue = &q, .stream = &stream };
- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call\",\"name\":\"read_file\",\"title\":\"note.txt\",\"kind\":\"read\",\"status\":\"in_progress\"}}}");
- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call_update\",\"status\":\"completed\",\"content\":[{\"type\":\"content\",\"content\":{\"type\":\"text\",\"text\":\"ok\\nmore\"}}]}}}");
- const evs = q.drain();
- defer q.free(evs);
- try std.testing.expectEqual(@as(usize, 2), evs.len);
- try std.testing.expectEqualStrings("read_file", evs[0].tool_started.name);
- try std.testing.expectEqualStrings("note.txt", evs[0].tool_started.detail);
- try std.testing.expectEqualStrings("ok", evs[1].tool_finished.detail);
- try std.testing.expect(!evs[1].tool_finished.is_error);
-}
-
test "transcript sink: tool_call keeps the catalog name, title is the path" {
var q: tui.EventQueue = .{};
q.attach(std.testing.allocator);
diff --git a/src/tui_acp_updates.zig b/src/tui_acp_updates.zig
new file mode 100644
index 00000000..5946c481
--- /dev/null
+++ b/src/tui_acp_updates.zig
@@ -0,0 +1,162 @@
+//! ACP transcript decoding, independent of live session and Agent lifecycle.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const tui = @import("tui");
+const repl = @import("repl.zig");
+const util = @import("util.zig");
+const label = @import("agent_tool_label.zig");
+
+/// Maps one ACP `session/update` line onto the TUI stream / event queue.
+pub const Apply = struct {
+ queue: *tui.EventQueue,
+ stream: *repl.StreamBuf,
+ show_thinking: bool = false,
+ reasoning_open: bool = false,
+ last_title: [160]u8 = undefined,
+ last_title_len: usize = 0,
+};
+
+pub fn applyBuffered(a: *Apply, gpa: Allocator, bytes: []const u8) void {
+ var it = std.mem.splitScalar(u8, bytes, '\n');
+ while (it.next()) |line| applyLine(a, gpa, line);
+}
+
+pub fn applyLine(a: *Apply, gpa: Allocator, line: []const u8) void {
+ const trimmed = std.mem.trim(u8, line, " \t\r\n");
+ if (trimmed.len == 0) return;
+ var parsed = std.json.parseFromSlice(Value, gpa, trimmed, .{}) catch return;
+ defer parsed.deinit();
+ if (parsed.value != .object) return;
+ const method = util.strFieldObj(parsed.value.object, "method") orelse return;
+ if (!std.mem.eql(u8, method, "session/update")) return;
+ const params = parsed.value.object.get("params") orelse return;
+ if (params != .object) return;
+ const update = params.object.get("update") orelse return;
+ if (update != .object) return;
+ const kind = util.strFieldObj(update.object, "sessionUpdate") orelse return;
+ if (std.mem.eql(u8, kind, "agent_thought_chunk") or std.mem.eql(u8, kind, "agent_message_chunk")) {
+ applyChunk(a, std.mem.eql(u8, kind, "agent_thought_chunk"), contentText(update.object) orelse return);
+ return;
+ }
+ if (std.mem.eql(u8, kind, "tool_call")) {
+ const title = util.strFieldObj(update.object, "title") orelse "tool";
+ const name = util.strFieldObj(update.object, "name") orelse title;
+ rememberTitle(a, name);
+ if (label.skipTranscript(name)) return;
+ a.queue.push(.{ .tool_started = .{ .name = name, .detail = cap(title, 160) } });
+ return;
+ }
+ if (std.mem.eql(u8, kind, "tool_call_update")) {
+ if (tui.rawStream()) |raw| raw.len.store(0, .release);
+ const title = a.last_title[0..a.last_title_len];
+ if (title.len == 0 or label.skipTranscript(title)) return;
+ const status = util.strFieldObj(update.object, "status") orelse "completed";
+ const failed = std.mem.eql(u8, status, "failed");
+ const text = updateText(update.object);
+ a.queue.push(.{ .tool_finished = .{
+ .name = title,
+ .detail = cap(text, 80),
+ .is_error = failed,
+ } });
+ }
+}
+
+fn contentText(update: std.json.ObjectMap) ?[]const u8 {
+ const content = update.get("content") orelse return null;
+ if (content != .object) return null;
+ return util.strFieldObj(content.object, "text");
+}
+
+fn updateText(update: std.json.ObjectMap) []const u8 {
+ const content = update.get("content") orelse return "";
+ if (content != .array or content.array.items.len == 0) return "";
+ const first = content.array.items[0];
+ if (first != .object) return "";
+ const inner = first.object.get("content") orelse return "";
+ if (inner != .object) return "";
+ return util.strFieldObj(inner.object, "text") orelse "";
+}
+
+fn rememberTitle(a: *Apply, title: []const u8) void {
+ const n = @min(title.len, a.last_title.len);
+ @memcpy(a.last_title[0..n], title[0..n]);
+ a.last_title_len = n;
+}
+
+fn cap(s: []const u8, n: usize) []const u8 {
+ const line = if (std.mem.indexOfScalar(u8, s, '\n')) |i| s[0..i] else s;
+ return line[0..@min(line.len, n)];
+}
+
+/// The in-process transport can pass text directly; wire clients decode into this same path.
+pub fn applyChunk(a: *Apply, thinking: bool, text: []const u8) void {
+ if (text.len == 0 or (thinking and !a.show_thinking)) return;
+ if (thinking) {
+ a.reasoning_open = true;
+ } else if (a.reasoning_open) {
+ a.reasoning_open = false;
+ a.stream.appendBytes("\n");
+ }
+ a.stream.appendBytes(text);
+}
+
+test "applyLine: thought then text land on the live tail" {
+ var q: tui.EventQueue = .{};
+ q.attach(std.testing.allocator);
+ defer q.deinit();
+ var buf: [128]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &buf };
+ var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };
+ applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"type\":\"text\",\"text\":\"why\"}}}}");
+ applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"hi\"}}}}");
+ const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;
+ defer std.testing.allocator.free(snap);
+ try std.testing.expectEqualStrings("why\nhi", snap);
+}
+
+test "applyLine: tool_call then tool_call_update become typed rows" {
+ var q: tui.EventQueue = .{};
+ q.attach(std.testing.allocator);
+ defer q.deinit();
+ var buf: [32]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &buf };
+ var a: Apply = .{ .queue = &q, .stream = &stream };
+ applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call\",\"name\":\"read_file\",\"title\":\"note.txt\",\"kind\":\"read\",\"status\":\"in_progress\"}}}");
+ applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call_update\",\"status\":\"completed\",\"content\":[{\"type\":\"content\",\"content\":{\"type\":\"text\",\"text\":\"ok\\nmore\"}}]}}}");
+ const evs = q.drain();
+ defer q.free(evs);
+ try std.testing.expectEqual(@as(usize, 2), evs.len);
+ try std.testing.expectEqualStrings("read_file", evs[0].tool_started.name);
+ try std.testing.expectEqualStrings("note.txt", evs[0].tool_started.detail);
+ try std.testing.expectEqualStrings("ok", evs[1].tool_finished.detail);
+ try std.testing.expect(!evs[1].tool_finished.is_error);
+}
+
+test "direct chunks match ACP wire decoding without allocations" {
+ var q: tui.EventQueue = .{};
+ var direct_buf: [128]u8 = undefined;
+ var wire_buf: [128]u8 = undefined;
+ var direct: repl.StreamBuf = .{ .buf = &direct_buf };
+ var wire: repl.StreamBuf = .{ .buf = &wire_buf };
+ var a: Apply = .{ .queue = &q, .stream = &direct, .show_thinking = true };
+ var b: Apply = .{ .queue = &q, .stream = &wire, .show_thinking = true };
+ applyChunk(&a, true, "why日");
+ applyChunk(&a, false, "hello🚀");
+ applyLine(&b, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"text\":\"why日\"}}}}");
+ applyLine(&b, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"text\":\"hello🚀\"}}}}");
+ try std.testing.expectEqualStrings(wire.buf[0..wire.len.load(.acquire)], direct.buf[0..direct.len.load(.acquire)]);
+ try std.testing.expectEqual(b.reasoning_open, a.reasoning_open);
+}
+
+test "hidden reasoning and empty chunks do not alter transcript" {
+ var q: tui.EventQueue = .{};
+ var buf: [64]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &buf };
+ var a: Apply = .{ .queue = &q, .stream = &stream };
+ applyChunk(&a, true, "hidden");
+ applyChunk(&a, false, "");
+ applyChunk(&a, false, "visible");
+ try std.testing.expectEqualStrings("visible", stream.buf[0..stream.len.load(.acquire)]);
+ try std.testing.expect(!a.reasoning_open);
+}