Compare commits

...
Author SHA1 Message Date
Mohamed Boudra b2ca56ee73 chore(release): cut 0.17.2 2026-11-22 12:46:24 +01:00
Mohamed Boudra 59f19e4e5e docs(changelog): add 0.17.2 release notes 2026-11-22 12:38:49 +01:00
Mohamed Boudra 884adbcc2f Archive the open workspace from the mobile workspace actions menu (#10507)
* feat(app): add Archive workspace to the mobile workspace actions menu

The compact header's actions menu had no way to archive the open workspace; it
was only reachable from the sidebar row or the keyboard shortcut. The route-keyed
archive logic behind the shortcut now lives in useActiveWorkspaceArchive so the
menu and the shortcut share one path (confirmation, undo toast, redirect).

* fix(app): redirect after archive from where you are now, not where the header was

The archive starts after the host check and confirmation. The header that began
it can be gone by then, and its last-rendered route would still match the
archived workspace, replacing the workspace you had since opened. Read the
current selection from the navigation owner when the archive starts.

* fix(app): skip the post-archive redirect when you have left workspace routes

The last-remembered workspace selection survives opening Settings, so an archive
that finished while Settings was open still redirected away from it. Read the
focused route instead, which is null on any non-workspace screen.
2026-11-22 18:25:55 +07:00
Mohamed Boudra 91247c8218 fix(app): keep turn timing inside the footer (#10510)
The Turn stats button narrows the timing column. On web, preserved spaces at soft wraps extend the timing text range past the button. Collapse wrapping spaces for the timing labels and include Turn stats in the existing hover stability check.
2026-11-22 18:01:18 +07:00
Mohamed Boudra 2d09c47672 Show provider session and turn metrics (#10496)
* feat(providers): let providers report session and turn metrics

Providers know things about a session and a turn that Paseo cannot derive:
timing, token flow, cache use, cost, the model that answered. They can now
report them as label/value rows that Paseo carries to clients unchanged, so
each provider decides which metrics make sense and how they read.

Session metrics live on the agent record and snapshot. Turn metrics are
stamped on the turn's footer row (last assistant message, else last tool
call) so they survive reload, pagination and a daemon restart, and so the
live turn_completed event and a later timeline fetch agree. Provider history
replay restores both.

Metrics are sanitized once where they enter the agent manager. The wire
schemas validate whole messages, so one malformed row from a provider would
otherwise make clients drop an entire snapshot, turn event or timeline page.

A live completed turn with no Model metric gets the agent's model, so every
provider shows model attribution before it is instrumented. Replayed turns do
not: they may have run on a different model than the agent has now.

Plugin providers publish session metrics behind a negotiated
`session.metrics` capability because an older daemon closes a connection
that sends an event type it does not know. Turn metrics ride an existing
event that older daemons strip, so they need no gate.

The wire additions are optional fields on existing schemas only.

* feat(providers): report session and turn metrics from OpenCode, OMP, Pi and Claude

Each provider now attaches metrics to turn_completed and emits
session_metrics_updated, live and when history is replayed.

- Live turns end on the adapter's clock. A provider's message timestamps
  can come from another clock.
- Tool time merges overlapping runs, so parallel tools count once.
- A total that is missing any part is hidden, so a partial total is
  never shown.
- Replayed history reports metrics only for turns that finished, which
  matches live, where failed and interrupted turns report none.
- Claude reports cost as a running total for each query(). A resumed
  query starts that total from a saved one, so a turn's cost is the
  change since the previous result of the same query. The first turn of
  a query shows no cost.
- Claude transcripts do not record result messages, so replayed Claude
  history has no turn metrics.
- Session metrics come from each provider's own cumulative counters. The
  cache hit is the last reply's or the last turn's, because a session-wide
  figure blends prompts from before and after compactions.

* feat(app): show provider session and turn metrics

Session metrics appear in the context window details, between the context summary and the
account usage cards. A provider-reported Cost row replaces the app's own session cost line.

Each completed turn with metrics gets a stats button in its footer: a hover card on web, a
press-opened tooltip on native wide screens, and a sheet on compact screens. The context window
sheet becomes a shared DetailsSheet so both use the same content-sized sheet.

Metrics ride on the row that hosts the turn's footer (the turn's last assistant message, else its
last tool call), the same row the daemon stamps. Live turn_completed events and timeline pages
both stamp that row, so a refetch agrees with what the live event showed.

The daemon updates session metrics without bumping updatedAt, like usage, so a stale buffered
upsert may still carry the newest metrics and is accepted for that field.

* fix(app): keep a turn's stats after the cached timeline reloads

The local timeline cache dropped turnMetrics when it saved a turn's footer row. After a page
reload the cached rows painted without the stats icon, and the catch-up fetch had no new
entries to stamp them from.

* fix(providers): keep imported session stats and never count a steered turn short

Importing a Pi, Oh My Pi or OpenCode v2 session dropped the stats the provider returned with its
history, so imported chats showed none until a forced replay. Import now carries them the way
replay does.

Replaying a Pi or Oh My Pi transcript read a prompt that steered a running turn as the start of a
new turn, so the steered turn's stats counted only the steps after the steer. A turn that follows
one ending on tools now reports no total, because the transcript reads the same as a stop and a
new prompt.

* fix(providers): keep stats through merged messages and plugin imports, start Pi first-token timing at the request

A message the timeline merges from several chunks keeps the stats stamped on its last chunk. Plugin session imports carry the stats the plugin replayed, through the same history reader the other providers use. Steers queued together after an unclear turn stay unclear instead of attributing the final reply to the wrong turn. Pi measures time to first token from the request, not the first reply header.

* fix(providers): carry a turn's stats onto the message the timeline merges from text chunks

The previous change put the carry-over in the reasoning merge. The assistant message merge dropped the stats of its last chunk, so an imported reply of two text blocks lost its Turn stats button.

* fix(providers): carry a turn's stats onto the tool card the timeline merges from updates

An imported turn that ends on a tool call stamps the stats on the tool's last update. The tool merge kept the first update's fields, so the stats were lost.

* fix(opencode): replay no session stats for a session that has none

An empty OpenCode session replayed a session stats event with no metrics, which broke the empty-history check in the versioned runtime test.
2026-11-22 16:43:56 +07:00
Mohamed Boudra 52377f595a Enable sidebar usage summary by default and move source toggles to a dedicated Sources list (#10491)
* feat(usage): enable sidebar usage summary by default and add dedicated Sources list

Show the sidebar Usage summary by default instead of requiring opt-in in
Appearance settings, while honoring explicit off preferences and continuing
to hide the row when no enabled source has pinned windows.

Let usage sources declare optional provider hints (`providers` on the
registration and `provider` on discovered accounts) so the daemon can mark
reports `defaultEnabled: false` when their hinted providers are neither
enabled nor installed, keeping usage sources decoupled from agent providers
while avoiding clutter from leftover credentials.

Move per-source show/hide controls out of individual card headers into a
dedicated `Sources` submenu inside Usage Settings (with tri-state
`cardVisibility` preferences migrating legacy `cardsOff`) so disabled
sources stay out of the main card list.

* fix(usage): resolve provider hints per report, refresh on forceRefresh, and clarify inactive copy

Resolve each usage report's provider activity hint in parallel with its
fetch and enforce a real timeout deadline in `isProviderActiveForUsage` so
a slow provider probe never holds back unrelated reports or hangs past the
deadline on non-abortable plugin RPCs.

Give the availability hint a 5-minute freshness TTL and re-probe when
`forceRefresh` is requested, retaining the fresher probe result across
subsequent normal reads until a newer snapshot or TTL expiry supersedes it.

Rename the default-off Sources sublabel from "Provider not installed" to
"Provider inactive" across all locales so it accurately covers both
disabled and unavailable providers.

* fix(usage): share provider availability reading across snapshot publishes and usage probes

Record both `ready` and `unavailable` global snapshot publications into
`usageActivityCache` so `isProviderActiveForUsage` reads one timestamped
availability cache instead of relying on `fetchedAt` (which unavailable
snapshot entries do not carry).

* fix(app): add MenuCheckboxItem so Usage Sources toggles expose checked state to screen readers

Introduce `MenuCheckboxItem` / `DropdownMenuCheckboxItem` backed by
`accessibilityRole="checkbox"` so toggleable menu rows expose their checked
state in Chromium's accessibility tree and native screen readers while
leaving existing `MenuItem` roles unchanged.

* fix(app): keep compact menu sheet rows in Tab order and activate on Space

Use `tabIndex={0}` for `MenuRow` in `sheet` presentation (leaving
popover roving arrow-key navigation at `tabIndex={-1}`) and handle Space
in web sheet rows since React Native Web only activates Space for
`role="button"`, not `menuitem` or `checkbox`.

* test(usage): include provider hint in claude-usage-source keychain and stores assertions
2026-11-22 16:43:11 +07:00
Mohamed Boudra 9cb521dda2 perf(ci): speed up server tests, Playwright shards, desktop/website E2E, and apt cache (#10504)
* perf(ci): cut PR CI wall-clock time across server tests, Playwright shards, and workflow setup

* fix(ci): guard empty apt cache copy, use 100% Vitest workers in CI, revert Playwright to 2 workers with built supervisor
2026-11-22 16:42:52 +07:00
Mohamed Boudra 234ddf8dd7 Simplify setup across supported provider docs (#10502)
* docs(providers): simplify setup across supported provider pages

Lead each supported provider page with the official CLI/protocol Paseo uses and the simplest default setup path, removing config.json snippets from Getting started on Antigravity and Oh My Pi. Fixes the outdated Settings path on Codex and keeps all Chinese translations in sync.

* docs(providers): address review feedback on Antigravity, Codex, Muse, and Pi
2026-11-22 15:22:12 +07:00
Mohamed Boudra 3914893aa1 Troubleshoot providers from their settings page, and tidy provider settings (#10487)
* feat(providers): add docs links, sign-in facts and a tidier provider page

A user whose Antigravity models looked stale had no way to find out why
without asking in chat. agy 1.5.14 picks its sign-in from the
environment: with SSH_CONNECTION, SSH_CLIENT or SSH_TTY set it reads a
token file, otherwise the OS keyring
(google-antigravity/antigravity-cli#1336). The daemon is often started
outside SSH while the user tests agy over SSH, so the two can be signed
in to different accounts and list different models.

- The Antigravity status reports whether agy runs in an SSH session, and
  the diagnostic report for plugin providers now includes the resolved
  command, path and version like built-in providers do.
- Providers carry an optional docsUrl (protocol field, plugin SDK
  registration, built-in definitions). The provider page links it from
  Troubleshooting, and the Antigravity page documents the sign-in
  mismatch.
- Provider and project settings get a breadcrumb title. Refresh moves to
  the Models header, the model list scrolls inside a fixed height with a
  full-width search, and section headers keep one spacing whether or not
  they hold an action.
- A switch no longer makes its row taller than the track, and every
  settings row is at least as tall as one with a switch, so a switch row
  and a text row line up.

* fix(providers): report Antigravity's sign-in when ACP does not start

A sign-in problem can be what stops agy's ACP server from starting, so
the diagnostic report now shows the SSH session rows in that case too.

The plugin provider diagnostic test no longer compares the daemon PATH
and shell rows, which differ per host (Windows reports ComSpec).

* fix(server): show the same provider version in the report and Installation

The plugin diagnostic read the version by calling the provider's
inspect itself with a 10s deadline, while the Installation row reads it
through the installation service with a 20s deadline and a cache. A
version check between 10 and 20 seconds showed in Installation and as
an error in the report.

The snapshot manager now hands getDiagnostic an inspectInstallation
that reads through the installation service, so both show one answer
and agy --version runs once for both.

* feat(app): give rows that open something the same height as other rows

Detail rows and collapsible row headers reserved a button's height so a
list where only some rows held a switch kept one height. Now that every
settings row is at least as tall as a switch row, that reserve only made
rows like Diagnostic report and Docs taller than their neighbours.

* test(app): compare rows that open something with text and switch rows

* feat(app): size the provider icon to the page title

* fix(app): scale the provider title icon with the interface size
2026-11-22 15:13:31 +07:00
Mohamed BoudraandClaude ede181d39a Refresh enabled provider catalogues in the background every 30 minutes (#10481)
* Refresh enabled provider catalogues in the background every 30 minutes

A long-running daemon cached discovered models until a manual Refresh or a
restart, so a server-side model rollout stayed invisible. The daemon now
refreshes each enabled provider about every 30 minutes, one provider per
staggered slot. A recent refresh pushes the next one back. Background
refreshes join discovery already in flight, publish only changed
catalogues, and keep a ready catalogue when a probe fails.

Co-Authored-By: Claude <noreply@anthropic.com>

* Keep background refresh slots independent and its probes soft

Ticks no longer wait for a refresh to settle, so one slow provider cannot
delay the others. A provider with a background refresh still running is
skipped. The due check uses a fixed one-second timer slack instead of half
a slot, so a manual refresh always pushes the next probe a full interval.
Background probes pass force: false so OpenCode keeps its shared server.
A result that is not ready keeps a ready catalogue, which covers plugin
status probes that report a failed startup as unavailable.

Co-Authored-By: Claude <noreply@anthropic.com>

* Keep a ready catalogue when a background refresh returns a partial one

Claude falls back to its curated list without discovery-gated models when
model discovery fails or times out. That result is ready, so a background
refresh published it and Mythos left the picker. Providers now mark such a
catalogue incomplete, and a background refresh keeps the ready catalogue it
would have replaced. A manual refresh still publishes it.

Co-Authored-By: Claude <noreply@anthropic.com>

* Kill OpenCode servers whose startup is pending at shutdown

A probe still allocating its port when the daemon stopped spawned its
OpenCode server after shutdown returned, and the process outlived the
daemon. Background refresh makes that overlap likelier. Shutdown now waits
for pending startups and kills the generations they produce.

Co-Authored-By: Claude <noreply@anthropic.com>

* Stop running probes before provider shutdown

A probe checking availability when the daemon stopped could still go on to
discovery and start an OpenCode server after provider cleanup returned.
The manager now aborts every running probe through its refresh signal when
it stops, and shutdown waits up to ten seconds for them to settle before it
shuts down provider clients.

Co-Authored-By: Claude <noreply@anthropic.com>

* Refuse OpenCode spawns from operations begun before shutdown

A rotation accepted before shutdown waited for the old server to stop and
then started a replacement after cleanup returned. The server manager now
counts shutdowns; every operation that can start a server records the
epoch it began in, and the spawn step refuses once a shutdown has passed.
Operations begun after shutdown still start, since the manager is a
process-wide singleton.

Co-Authored-By: Claude <noreply@anthropic.com>

* Keep manual refresh precedence over concurrent background refreshes

* Avoid eager provider snapshot downloads for unobserved directories

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-22 14:50:02 +07:00
Mohamed Boudra c28aa2570c docs(website): refresh sponsor page visitor and Discord member counts (#10498)
Homepage and docs visitors use the site-wide Plausible figure for the 30 complete days to 2026-11-21 (107,693), rounded down to 100,000. Discord members come from the live guild count (2,678). The README figure is unchanged because GitHub only exposes 14 days of traffic.
2026-11-22 14:29:02 +07:00
246 changed files with 9474 additions and 1156 deletions
+28 -5
View File
@@ -20,6 +20,8 @@ env:
# CI does not use the CUDA execution provider, and the onnxruntime-node
# postinstall download from NuGet is large enough to make npm ci flaky.
ONNXRUNTIME_NODE_INSTALL: skip
NPM_CONFIG_AUDIT: "false"
NPM_CONFIG_FUND: "false"
jobs:
changes:
@@ -165,8 +167,29 @@ jobs:
- name: Run website tests
run: npx vitest run packages/website/src --bail=1
# WebKit needs about 180 system packages (125 MB) from the Ubuntu mirror. The mirror
# sometimes serves them at under 100 kB/s, which turns a 1-minute step into 25 minutes.
# Keep the downloaded .deb files in the Actions cache so apt installs them without the mirror.
- name: Restore website browser system packages
uses: actions/cache@v4
with:
path: ~/website-browser-debs
key: website-browser-debs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: website-browser-debs-${{ runner.os }}-
- name: Install website test browsers
run: npx playwright install --with-deps chromium webkit
run: |
mkdir -p ~/website-browser-debs
shopt -s nullglob
cached_debs=(~/website-browser-debs/*.deb)
if (( ${#cached_debs[@]} > 0 )); then
sudo cp "${cached_debs[@]}" /var/cache/apt/archives/
fi
npx playwright install --with-deps chromium webkit
archive_debs=(/var/cache/apt/archives/*.deb)
if (( ${#archive_debs[@]} > 0 )); then
cp "${archive_debs[@]}" ~/website-browser-debs/
fi
- name: Verify website mockups
run: npm run test:e2e --workspace=@getpaseo/website
@@ -466,9 +489,9 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
E2E_WORKERS: "2"
# File groups are weighted by observed reporter durations.
# Share of the test list per shard, rebalanced from the Playwright step
# minutes of five eight-shard runs so the slowest and fastest shards meet.
PWTEST_SHARD_WEIGHTS: "85:94:117:128:91:103:127:85"
# Share of the test list per shard, rebalanced from main and PR eight-shard
# durations so the slowest and fastest shards meet.
PWTEST_SHARD_WEIGHTS: "90:114:100:104:108:112:112:90"
- name: Upload test artifacts
uses: actions/upload-artifact@v4
@@ -582,7 +605,7 @@ jobs:
# Source tests do not read PASEO_CLI_TEST_SHARD. Run them once, on the
# shortest E2E shard, after its runner has built the server stack.
- name: Run CLI source tests
if: ${{ env.PASEO_CLI_TEST_SHARD == '3' }}
if: ${{ env.PASEO_CLI_TEST_SHARD == '2' }}
run: npm run test:unit --workspace=@getpaseo/cli
# The dependency watchers write build outputs, so run them after the parallel CLI tests.
+24
View File
@@ -1,5 +1,29 @@
# Changelog
## 0.17.2 - 2026-11-22
- **Turn and session stats:** View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers. ([#10496](https://github.com/getpaseo/paseo/pull/10496), [#10510](https://github.com/getpaseo/paseo/pull/10510))
- **Automatic model list refresh:** Enabled providers refresh their model lists in the background every 30 minutes. ([#10481](https://github.com/getpaseo/paseo/pull/10481))
- **Sidebar usage by default:** The sidebar usage summary is enabled by default, sources for inactive providers start hidden, and source toggles move to a Sources list. ([#10491](https://github.com/getpaseo/paseo/pull/10491))
- **Agents can steer turns:** Agents can steer another agent's running turn alongside queueing or interrupting it, and receive delivery guidance in the response. ([#10483](https://github.com/getpaseo/paseo/pull/10483))
### Added
- Added Archive workspace to the mobile workspace actions menu ([#10507](https://github.com/getpaseo/paseo/pull/10507))
- Added provider docs links, fuller diagnostic reports, and a scrollable Models list with inline refresh to provider settings ([#10487](https://github.com/getpaseo/paseo/pull/10487))
### Changed
- Removed the "This chat uses OpenCode v2." info row from OpenCode v2 chats ([#10490](https://github.com/getpaseo/paseo/pull/10490))
### Fixed
- Fixed pressing Tab or Enter in the slash menu running a stale `/exit` choice and archiving the agent ([#10484](https://github.com/getpaseo/paseo/pull/10484) by [@3ae3ae](https://github.com/3ae3ae))
- Fixed busy host connections dropping to reconnect when multiple connections are saved ([#10395](https://github.com/getpaseo/paseo/pull/10395))
- Fixed retrying an edited New workspace form hitting a conflict error after a failed start, and unified composer error alerts ([#10482](https://github.com/getpaseo/paseo/pull/10482))
- Fixed Antigravity turns staying running after creating a recurring schedule ([#10469](https://github.com/getpaseo/paseo/pull/10469))
- Fixed daemon startup and plugin reloads leaving zombie child processes for local directory plugins ([#10470](https://github.com/getpaseo/paseo/pull/10470))
## 0.17.1 - 2026-11-21
- **Antigravity approvals and history:** Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires [Antigravity CLI 1.5.0 or later](https://paseo.sh/docs/supported-providers/antigravity). ([#10193](https://github.com/getpaseo/paseo/pull/10193))
+24
View File
@@ -1,5 +1,29 @@
# Changelog
## 0.17.2 - 2026-11-22
- **回合和会话统计**:查看 Claude、OpenCode v2、Pi、Oh My Pi 和插件 Provider 的单轮及会话耗时、token、缓存和费用指标。([#10496](https://github.com/getpaseo/paseo/pull/10496), [#10510](https://github.com/getpaseo/paseo/pull/10510))
- **自动刷新模型列表**:已启用的 Provider 每 30 分钟在后台刷新一次模型列表。([#10481](https://github.com/getpaseo/paseo/pull/10481))
- **默认显示侧边栏用量**:侧边栏用量摘要现在默认开启,未启用 Provider 的用量来源默认隐藏,来源开关移至“来源”列表。([#10491](https://github.com/getpaseo/paseo/pull/10491))
- **Agent 可引导进行中的轮次**:Agent 除了排队或中断外,现在可以引导另一个 Agent 正在运行的轮次,并在响应中收到投递指引。([#10483](https://github.com/getpaseo/paseo/pull/10483))
### 新增
- 在移动端工作区操作菜单中新增“归档工作区” ([#10507](https://github.com/getpaseo/paseo/pull/10507))
- 在 Provider 设置中新增文档链接、更完整的诊断报告,以及带内联刷新按钮的可滚动 Models 列表 ([#10487](https://github.com/getpaseo/paseo/pull/10487))
### 变更
- 移除 OpenCode v2 对话中的“This chat uses OpenCode v2.”提示行 ([#10490](https://github.com/getpaseo/paseo/pull/10490))
### 修复
- 修复在斜杠菜单中按 Tab 或 Enter 时误触发过期的 `/exit` 选项并归档 Agent 的问题 ([#10484](https://github.com/getpaseo/paseo/pull/10484),贡献者:[@3ae3ae](https://github.com/3ae3ae))
- 修复保存了多个主机连接时,繁忙的正常连接会断开重连的问题 ([#10395](https://github.com/getpaseo/paseo/pull/10395))
- 修复新建工作区启动失败后,修改表单再重试时出现冲突错误的问题,并统一了 Composer 错误提示 ([#10482](https://github.com/getpaseo/paseo/pull/10482))
- 修复 Antigravity 创建循环定时任务后轮次一直停留在运行状态的问题 ([#10469](https://github.com/getpaseo/paseo/pull/10469))
- 修复启动 daemon 和重载本地目录插件后遗留僵尸子进程的问题 ([#10470](https://github.com/getpaseo/paseo/pull/10470))
## 0.17.1 - 2026-11-21
- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批,以及导入或重新打开会话。需要 [Antigravity CLI 1.5.0 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity)。([#10193](https://github.com/getpaseo/paseo/pull/10193))
+1
View File
@@ -102,6 +102,7 @@ Each agent is stored as a separate JSON file, grouped by project directory.
| `config` | `SerializableConfig?` | Agent session configuration (see below) |
| `runtimeInfo` | `RuntimeInfo?` | Live runtime state (see below) |
| `features` | `AgentFeature[]?` | Provider-reported features (toggles/selects) |
| `sessionMetrics` | `AgentMetric[]?` | Provider-reported session metrics, already formatted for display; the latest report replaces the list |
| `persistence` | `PersistenceHandle?` | Handle for resuming sessions |
| `lastError` | `string?` (nullable) | Last error message, if any |
| `requiresAttention` | `boolean?` | Whether the agent needs user attention |
+2 -2
View File
@@ -78,7 +78,7 @@ In the composer, the first glyph's ink starts on the text column's edge, and the
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
A `<Pressable>` wrapping a `<Text>` is a sixth variant. It is wrong. `<Button>` accepts `style`, `textStyle`, `leftIcon`, `disabled`, `size`, and `variant`.
@@ -134,7 +134,7 @@ A section or group explains itself through the `info` prop on `<SettingsSection>
Cards inside a section sit closer than sections. Rows inside a card touch — only the divider separates them. The rhythm is page → spacious; section → spacious; card → tight.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. A row that opens something (`<SettingsDetailRow>`, a collapsible row's header) is at least as tall as one holding a default control, so a list where only some of those rows carry a switch keeps one row height. Other rows take their content's height. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Every row is at least as tall as one holding a switch, so text rows, switch rows and rows that open something (`<SettingsDetailRow>`, a collapsible row's header) line up. A row holding a button or a select is taller. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
+23 -2
View File
@@ -221,11 +221,32 @@ Plugin callbacks follow the same contract; see [plugin providers](plugins.md#con
`ProviderSnapshotManager` owns one refresh deadline per provider. The deadline starts before the
availability check and covers that check plus the complete catalog probe. Providers that make
multiple catalog requests must not apply this deadline separately to each request. The manager
aborts the shared refresh signal at the deadline. Providers name active catalog operations and
aborts the shared refresh signal at the deadline, and when it stops. Shutdown waits for running
probes to settle before it shuts down provider clients, so a probe cannot start provider work,
such as an OpenCode server, after its client has cleaned up. Providers name active catalog operations and
finish subprocess, server, or session cleanup before rejecting. Timeout errors list the operations
that were still active when the deadline expired.
Catalogue results stay cached by identity until explicit refresh or a change to that provider's configuration.
Catalogue results stay cached by identity until a refresh or a change to that provider's configuration.
Providers change their model lists on the server without a CLI update, so the daemon refreshes
each enabled provider about every 30 minutes (`ProviderRefreshSchedule`). One timer ticks
`30 min / enabled providers` apart, and each tick starts at most one refresh: the provider refreshed
longest ago, if that was a full interval ago. Ticks do not wait for refreshes, so a provider that
probes many workspace targets does not delay the others, and provider CLIs never start in a burst.
Any forced refresh, configuration change, or newly enabled provider counts as a refresh and pushes
that provider's next one back a full interval.
The background refresh takes the settings refresh path for one provider, with these differences:
- It joins discovery already in flight.
- It passes `force: false`, because providers treat `force` as a requested hard refresh. OpenCode
rotates its shared server on it.
- An unchanged catalogue keeps the published record and its `fetchedAt`, so idle clients receive
no update.
- A result that is not ready, or a catalogue the provider marks `incomplete`, keeps a ready
catalogue. Plugin status probes report a failed startup as unavailable, so that counts as
transient. Set `ProviderCatalog.incomplete` when discovery fails and you fall back to a partial
list, as Claude does when model discovery times out. A manual refresh still publishes all three.
Keys are resolved on each read so project configuration can select a different cached catalogue.
Selector opening may read a loading or stale query, but does not force provider probing.
@@ -0,0 +1,5 @@
- Turn and session stats: View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers.
- Automatic model list refresh: Enabled providers refresh their model lists in the background every 30 minutes.
- Sidebar usage by default: The sidebar usage summary is enabled by default, sources for inactive providers start hidden, and source toggles move to a Sources list.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Turn and session stats: View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers.
- Automatic model list refresh: Enabled providers refresh their model lists in the background every 30 minutes.
- Sidebar usage by default: The sidebar usage summary is enabled by default, sources for inactive providers start hidden, and source toggles move to a Sources list.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Turn and session stats: View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers.
- Automatic model list refresh: Enabled providers refresh their model lists in the background every 30 minutes.
- Sidebar usage by default: The sidebar usage summary is enabled by default, sources for inactive providers start hidden, and source toggles move to a Sources list.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,5 @@
- Turn and session stats: View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers.
- Automatic model list refresh: Enabled providers refresh their model lists in the background every 30 minutes.
- Sidebar usage by default: The sidebar usage summary is enabled by default, sources for inactive providers start hidden, and source toggles move to a Sources list.
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-qZCOSeT264mXP2RcV+eD7lEkc3WAH1re6NjTtbQOHqY=
sha256-vtzoUMnKaAdBFd/hhnk9p2WwHGgL70RXh26vkkyRIH0=
+28 -28
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.1",
"version": "0.17.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.1",
"version": "0.17.2",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37477,7 +37477,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.1",
"version": "0.17.2",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39647,13 +39647,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/server": "0.17.1",
"@getpaseo/client": "0.17.2",
"@getpaseo/protocol": "0.17.2",
"@getpaseo/server": "0.17.2",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39900,11 +39900,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.1",
"@getpaseo/relay": "0.17.1",
"@getpaseo/protocol": "0.17.2",
"@getpaseo/relay": "0.17.2",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39916,7 +39916,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40159,7 +40159,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.1",
"version": "0.17.2",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40205,7 +40205,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40235,7 +40235,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40243,8 +40243,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/client": "0.17.2",
"@getpaseo/protocol": "0.17.2",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40254,8 +40254,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/client": "0.17.2",
"@getpaseo/protocol": "0.17.2",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40277,7 +40277,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40305,7 +40305,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40527,17 +40527,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.1",
"version": "0.17.2",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.17.1",
"@getpaseo/highlight": "0.17.1",
"@getpaseo/plugin": "0.17.1",
"@getpaseo/protocol": "0.17.1",
"@getpaseo/relay": "0.17.1",
"@getpaseo/client": "0.17.2",
"@getpaseo/highlight": "0.17.2",
"@getpaseo/plugin": "0.17.2",
"@getpaseo/protocol": "0.17.2",
"@getpaseo/relay": "0.17.2",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -41484,7 +41484,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.17.1",
"version": "0.17.2",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43095,7 +43095,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.17.1",
"version": "0.17.2",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.1",
"version": "0.17.2",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -430,7 +430,8 @@ async function expectFooterWithinWidth(page: Page, width: number): Promise<void>
const label = page.getByRole("button", { name: /^Worked for/ }).last();
await expect(label).toBeVisible();
await expectTimingInsideFooter(page);
const controls = footer.getByRole("button", { name: /Copy turn|Fork chat/ });
await expect(footer.getByRole("button", { name: "Turn stats" })).toBeVisible();
const controls = footer.getByRole("button", { name: /Copy turn|Fork chat|Turn stats/ });
const before = await controls.evaluateAll((elements) =>
elements.map((element) => {
const rect = element.getBoundingClientRect();
@@ -118,7 +118,8 @@ async function exerciseProviderSettingsStack(page: Page) {
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await expectProviderSettingsVisible(page);
await expect(page.getByText("Checked just now", { exact: true })).toBeVisible({
// The Models header puts the model count before it: "12 · Checked just now".
await expect(page.getByText(/Checked just now$/)).toBeVisible({
timeout: 30_000,
});
}
+112 -8
View File
@@ -34,6 +34,7 @@ import {
openUsageFromItem,
pinRow,
openUsageOptions,
openUsageSources,
closeUsageOptions,
pickUsageHost,
usageModalHost,
@@ -250,16 +251,15 @@ test.describe("usage modal", () => {
await expect(alphaHandle).toHaveCSS("opacity", "1");
await alphaHandle.blur();
// The off card collapses to its header, which still names the account.
await setUsageCardOn(page, "beta plan (work)", false);
const work = page.getByTestId("usage-report-beta:work");
await expect(work.getByText("12% used")).toHaveCount(0);
await expect(work.getByText("work", { exact: true })).toBeVisible();
// Turning a source off in the dedicated Sources list removes its card and sidebar summary.
await setUsageCardOn(page, "beta:work", false);
await expectUsageCardOrder(page, ["alpha:a", "beta:home"]);
await expect(page.getByTestId("usage-report-beta:work")).toHaveCount(0);
await expectPinnedUsage(page, ["31% Weekly", "20% Weekly"]);
const stopRecording = await recordUsageCardPositionsAfterRelease(page);
await dragUsageCardAbove(page, "beta:home", "alpha:a");
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
await expectUsageCardOrder(page, ["beta:home", "alpha:a"]);
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
// The cards are in their new slots from the first frame after the drop.
const framesAfterDrop = await stopRecording();
@@ -270,10 +270,114 @@ test.describe("usage modal", () => {
await page.reload();
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
await expect(page.getByTestId("usage-report-beta:work").getByText("12% used")).toHaveCount(0);
await expectUsageCardOrder(page, ["beta:home", "alpha:a"]);
await expect(page.getByTestId("usage-report-beta:work")).toHaveCount(0);
});
for (const [size, viewport] of Object.entries({
desktop: { width: 1440, height: 900 },
compact: { width: 390, height: 844 },
})) {
test(`dedicated Sources list manages default-off sources without clutter (${size})`, async ({
page,
}) => {
test.setTimeout(120_000);
const [claude, codex] = claudeAndCodexReports();
const fetchedAt = twoHoursAgo();
await installUsageReportsFixture(page, {
lists: [
() => [
claude!,
codex!,
{
id: "copilot:default",
account: {},
fetchedAt,
sourceId: "copilot",
sourceLabel: "GitHub Copilot",
defaultEnabled: false,
report: {
status: "unavailable",
problem: { kind: "rejected", status: 403 },
},
},
{
id: "cursor:default",
account: { label: "dev@example.com" },
fetchedAt,
sourceId: "cursor",
sourceLabel: "Cursor",
defaultEnabled: false,
report: {
status: "available",
windows: [
{ id: "monthly", label: "Monthly", shortLabel: "mo", summary: true, usedPct: 18 },
],
},
},
],
],
});
await page.setViewportSize(viewport);
await gotoAppShell(page);
if (size === "compact") await openCompactSidebar(page);
// Only active sources appear in the sidebar summary and modal cards.
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["claude:default", "codex:default"]);
await expect(page.getByTestId("usage-report-copilot:default")).toHaveCount(0);
await expect(page.getByTestId("usage-report-cursor:default")).toHaveCount(0);
await qaScreenshot(page, `usage-sources-${size}-cards`);
await openUsageOptions(page);
await expect(page.getByTestId("usage-options-sources")).toContainText("2 of 4");
await qaScreenshot(page, `usage-sources-${size}-settings`);
if (size === "compact") {
// Compact sheets expose menu rows in the browser Tab order so keyboard users can open
// Sources and toggle checkboxes without a pointer.
await page.getByTestId("usage-options-sources").focus();
await expect(page.getByTestId("usage-options-sources")).toBeFocused();
await expect(page.getByTestId("usage-options-sources")).toHaveAttribute("tabindex", "0");
await page.keyboard.press("Enter");
} else {
await openUsageSources(page);
}
const claudeToggle = page.getByRole("checkbox", { name: /^Claude/ });
const copilotToggle = page.getByRole("checkbox", { name: /^GitHub Copilot/ });
const cursorToggle = page.getByRole("checkbox", { name: /^Cursor/ });
await expect(claudeToggle).toBeChecked();
await expect(copilotToggle).not.toBeChecked();
await expect(copilotToggle).toContainText("Provider inactive");
await qaScreenshot(page, `usage-sources-${size}-list`);
// Opting into a default-off source brings its card and summary window in immediately.
if (size === "compact") {
await cursorToggle.focus();
await expect(cursorToggle).toBeFocused();
await expect(cursorToggle).toHaveAttribute("tabindex", "0");
await page.keyboard.press("Space");
} else {
await cursorToggle.click();
}
await expect(cursorToggle).toBeChecked();
await closeUsageOptions(page);
await expectUsageCardOrder(page, ["claude:default", "codex:default", "cursor:default"]);
// Hiding every source shows a quiet empty state with a shortcut back to Settings.
await openUsageSources(page);
await page.getByTestId("usage-source-toggle-claude:default").click();
await page.getByTestId("usage-source-toggle-codex:default").click();
await page.getByTestId("usage-source-toggle-cursor:default").click();
await closeUsageOptions(page);
await expect(page.getByTestId("usage-all-hidden")).toBeVisible();
await expect(page.getByTestId("usage-choose-sources")).toBeVisible();
await qaScreenshot(page, `usage-sources-${size}-empty`);
await page.getByTestId("usage-choose-sources").click();
await expect(page.getByTestId("usage-options-sources")).toContainText("0 of 4");
});
}
test("refreshes one report from its card", async ({ page }) => {
test.setTimeout(120_000);
const serverId = getServerId();
@@ -291,12 +291,12 @@ test.describe("Usage item", () => {
await gotoAppShell(page);
const screen = page.getByTestId(`usage-host-${serverId}`);
await test.step("a fresh device shows default windows once the Usage item is on", async () => {
// The Usage item starts off on every layout; turning it on stores the choice.
await expectNoUsageItem(page);
await test.step("a fresh device shows default windows in the sidebar automatically", async () => {
// The Usage item starts on by default on every layout.
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await qaScreenshot(page, "desktop-footer-defaults", { kind: "footer" });
await openSidebarNavSettings(page);
await expectFooterItemSetting(page, "usage", false);
await setFooterItemVisible(page, "usage", true);
await expectFooterItemSetting(page, "usage", true);
await qaScreenshot(page, "desktop-settings-sidebar-footer");
await page.setViewportSize(COMPACT);
await expectFooterItemSetting(page, "usage", true);
@@ -308,7 +308,6 @@ test.describe("Usage item", () => {
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await qaScreenshot(page, "desktop-footer-defaults", { kind: "footer" });
await openUsageFromItem(page);
await qaScreenshot(page, "default-pins-card");
await expect(pinRow(screen, "Claude", "Session")).toBeChecked();
@@ -478,7 +477,7 @@ test("without summary data the footer drops the Usage item and keeps the Usage i
await openUsageFromIcon(page);
});
test("the Usage Settings switch turns on the sidebar summary and the pins with it", async ({
test("the Usage Settings switch turns the sidebar summary and pins off and back on", async ({
page,
}) => {
const serverId = getServerId();
@@ -488,8 +487,17 @@ test("the Usage Settings switch turns on the sidebar summary and the pins with i
const screen = page.getByTestId(`usage-host-${serverId}`);
const claude = screen.getByTestId("usage-report-claude:default");
await test.step("off by default: no Usage item, and rows that do not pin", async () => {
await openUsageFromIcon(page);
await test.step("on by default: the Usage item and pins appear", async () => {
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await openUsageFromItem(page);
await expect(pinRow(screen, "Claude", "Weekly")).toBeChecked();
await togglePin(screen, "Claude", "Weekly");
await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]);
await qaScreenshot(page, "usage-summary-on");
});
await test.step("off: no Usage item, and rows that do not pin", async () => {
await setSummaryInSidebar(page, false);
await expectNoUsageItem(page);
await expect(claude.getByText("Session", { exact: true })).toBeVisible({ timeout: 10_000 });
await expectUnpinnableRows(claude);
@@ -498,19 +506,7 @@ test("the Usage Settings switch turns on the sidebar summary and the pins with i
await qaScreenshot(page, "usage-summary-off");
});
await test.step("on: the Usage item and the pins appear", async () => {
await setSummaryInSidebar(page, true);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await expect(pinRow(screen, "Claude", "Weekly")).toBeChecked();
await togglePin(screen, "Claude", "Weekly");
await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]);
await qaScreenshot(page, "usage-summary-on");
});
await test.step("off then on again, after a reload, brings back the saved pins", async () => {
await setSummaryInSidebar(page, false);
await expectNoUsageItem(page);
await expectUnpinnableRows(claude);
await test.step("after a reload, turning it back on brings back the saved pins", async () => {
await page.reload();
await openUsageFromIcon(page);
await expectSummaryInSidebar(page, false);
@@ -554,6 +550,7 @@ test("released hosts supply source logos through the client conversion", async (
test("hidden usage sends no requests until opened", async ({ page }) => {
test.setTimeout(180_000);
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: false }]);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectNoUsageItem(page);
@@ -569,10 +566,9 @@ test("hidden usage sends no requests until opened", async ({ page }) => {
expect(usage.listRequests()).toHaveLength(1);
});
test("visible usage summary requests reports on load", async ({ page }) => {
test("visible usage summary requests reports on load by default", async ({ page }) => {
test.setTimeout(180_000);
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
@@ -6,6 +6,7 @@ import {
type ChildProcess,
type SpawnOptions,
} from "node:child_process";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import net from "node:net";
import { tmpdir } from "node:os";
@@ -229,7 +230,11 @@ export async function startIsolatedHostDaemon(
stdio: ["ignore", "ignore", "pipe"],
detached: false,
};
const spawned = publishedPackageRoot
const builtSupervisor = path.join(serverDir, "dist/scripts/supervisor-entrypoint.js");
const useBuiltSupervisor = Boolean(
publishedPackageRoot || (process.env.CI && existsSync(builtSupervisor)),
);
const spawned = useBuiltSupervisor
? spawn(process.execPath, ["dist/scripts/supervisor-entrypoint.js"], spawnOptions)
: spawnTsx("scripts/supervisor-entrypoint.ts", ["--dev"], spawnOptions);
+3 -1
View File
@@ -567,7 +567,9 @@ export async function expectProviderPageLoaded(page: Page, providerName: string)
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName, {
timeout: 30_000,
});
await expect(page.getByText("Provider status")).toBeVisible({ timeout: 30_000 });
await expect(page.getByRole("button", { name: "Diagnostic report" })).toBeVisible({
timeout: 30_000,
});
}
export async function expectProviderNotOnHost(page: Page): Promise<void> {
@@ -160,11 +160,23 @@ export async function expectUsageCardOrder(page: Page, reportIds: string[]): Pro
.toEqual(reportIds);
}
/** Turns a card on or off from its header switch, named by its source and account. */
export async function setUsageCardOn(page: Page, name: string, on: boolean): Promise<void> {
const cardSwitch = usageModal(page).getByRole("switch", { name: `Show ${name}`, exact: true });
await cardSwitch.click();
await expect(cardSwitch).toBeChecked({ checked: on });
/** Turns a source on or off from the Sources page in Usage Settings, by report id. */
export async function setUsageCardOn(page: Page, reportId: string, on: boolean): Promise<void> {
await openUsageSources(page);
const item = visible(page, `usage-source-toggle-${reportId}`);
const checked = (await item.getAttribute("aria-checked")) === "true";
if (checked !== on) {
await item.click();
await expect(item).toHaveAttribute("aria-checked", String(on));
}
await closeUsageOptions(page);
}
/** Opens the Sources submenu inside Usage Settings (flyout on wide, in-place page on compact). */
export async function openUsageSources(page: Page): Promise<void> {
await openUsageOptions(page);
await visible(page, "usage-options-sources").click();
await expect(page.locator('[data-testid^="usage-source-toggle-"]:visible').first()).toBeVisible();
}
/** Drags a card by its handle until it sits above another card, with the mouse. */
@@ -245,18 +257,14 @@ export function pinRow(scope: Locator, source: string, window: string): Locator
/**
* A report card whose window rows do not pin: no pin toggle, no pin glyph, and nothing focusable
* but the header's buttons and on/off switch, so no row presses or highlights on hover.
* but the header's buttons, so no row presses or highlights on hover.
*/
export async function expectUnpinnableRows(card: Locator): Promise<void> {
await expect(card.getByRole("checkbox")).toHaveCount(0);
await expect(card.locator('[data-testid^="usage-pin-"]')).toHaveCount(0);
const focusable = await card
.locator("[tabindex]")
.evaluateAll(
(nodes) =>
nodes.filter((node) => !["button", "switch"].includes(node.getAttribute("role") ?? ""))
.length,
);
.evaluateAll((nodes) => nodes.filter((node) => node.getAttribute("role") !== "button").length);
expect(focusable).toBe(0);
}
@@ -388,6 +396,7 @@ export async function closeUsageOptions(page: Page): Promise<void> {
await waitForSettledPosition(usageOptionsSurface(page));
await page.mouse.click(0, 0);
await expect(page.getByTestId("usage-display-used")).toHaveCount(0);
await expect(page.locator('[data-testid^="usage-source-toggle-"]:visible')).toHaveCount(0);
}
export async function showUsageAs(page: Page, displayAs: "used" | "remaining") {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.1",
"version": "0.17.2",
"private": true,
"main": "index.ts",
"scripts": {
+19
View File
@@ -29,6 +29,25 @@ export function agentCommandsQueryRoot(serverId: string) {
return [AGENT_COMMANDS_QUERY_ROOT, serverId] as const;
}
function queryCommandsCwd(query: { queryKey: readonly unknown[]; meta?: Record<string, unknown> }) {
const isDraft = query.queryKey[2] === "draft";
const cwd = query.meta?.agentCommandCwd ?? (isDraft ? query.queryKey[4] : undefined);
return typeof cwd === "string" ? normalizeAgentCommandsCwd(cwd) : undefined;
}
/** Marks every catalog for a directory stale. Only observed catalogs refetch; the rest refetch
* when next mounted. Used when a provider change is announced without its new snapshot. */
export function invalidateCommandsForDirectory(input: {
queryClient: QueryClient;
serverId: string;
cwd: string | null;
}): Promise<void> {
return input.queryClient.invalidateQueries({
queryKey: agentCommandsQueryRoot(input.serverId),
predicate: (query) => !input.cwd || queryCommandsCwd(query) === input.cwd,
});
}
/** Snapshot announcements contain provider metadata, not command catalogs. Ignore initial
* discovery and unrelated providers; explicit refresh still invalidates every catalog. */
export function invalidateCommandsForProviderChange(input: {
@@ -393,6 +393,39 @@ describe("layoutStream", () => {
expect(findLayoutItem(layout, thinking.id).toolSequence).toBe("last");
});
it.each(["web", "android"] as const)(
"carries turn metrics from the footer's source row on %s",
(platform) => {
const metrics = [{ label: "Model", value: "opus" }];
const earlier = { ...assistantMessage("a1", 2), turnMetrics: metrics };
const latest = { ...toolCall("tool-2", 5), turnMetrics: [{ label: "Steps", value: "2" }] };
const layout = layoutFor({
platform,
tail: [userMessage("u1", 1), earlier, toolCall("tool-1", 3), userMessage("u2", 4), latest],
});
expect(findLayoutItem(layout, "tool-1").completedFooter?.turnMetrics).toBe(metrics);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(latest.turnMetrics);
},
);
it("lays out the footer again when its source row gains turn metrics", () => {
const assistant = assistantMessage("a1", 2);
const trailing = toolCall("tool-2", 4);
const tail = [userMessage("u1", 1), assistant, toolCall("tool-1", 3), trailing];
const next = userMessage("u2", 5);
const before = layoutFor({ platform: "android", tail: [...tail, next] });
const metrics = [{ label: "Model", value: "opus" }];
const stamped = [...tail];
stamped[1] = { ...assistant, turnMetrics: metrics };
const after = layoutFor({ platform: "android", tail: [...stamped, next] });
expect(findLayoutItem(before, trailing.id).completedFooter?.turnMetrics).toBeUndefined();
expect(findLayoutItem(after, trailing.id).completedFooter?.turnMetrics).toBe(metrics);
expect(findLayoutItem(after, next.id)).toBe(findLayoutItem(before, next.id));
});
it("keeps bottom and inline footer ownership mutually exclusive", () => {
const assistant = assistantMessage("a1", 2);
const layout = layoutFor({
+8
View File
@@ -1,3 +1,4 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing";
@@ -10,6 +11,7 @@ export interface TurnFooterHost {
itemId: string;
items: StreamItem[];
timing?: TurnTiming;
turnMetrics?: AgentMetric[];
startIndex: number;
}
@@ -69,10 +71,15 @@ function createTurnFooterHost(input: {
index: number;
timingByItemId: Map<string, TurnTiming>;
}): TurnFooterHost {
const turnMetrics =
input.item.kind === "assistant_message" || input.item.kind === "tool_call"
? input.item.turnMetrics
: undefined;
return {
itemId: input.item.id,
items: input.items,
timing: input.timingByItemId.get(input.item.id),
...(turnMetrics ? { turnMetrics } : {}),
startIndex: input.index,
};
}
@@ -247,6 +254,7 @@ function areTurnFooterHostsEqual(
return (
left.itemId === right.itemId &&
left.timing === right.timing &&
left.turnMetrics === right.turnMetrics &&
left.startIndex === right.startIndex &&
left.items === right.items
);
@@ -1,6 +1,10 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { PortalProvider } from "@gorhom/portal";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { FloatingPanelPortalHost } from "@/components/ui/floating-panel-portal";
import { i18n } from "@/i18n/i18next";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
@@ -92,3 +96,57 @@ it.each([
"Friday 11:11 PM": 1,
});
});
const COMPLETED_TIMING: TurnTiming = { completedAt: FRIDAY_NIGHT, durationMs: 26_000 };
describe("turn stats", () => {
const metrics: AgentMetric[] = [
{ label: "Model", value: "opus" },
{ label: "Cost", value: "$0.42", tone: "warning" },
];
function renderFooterWithMetrics(turnMetrics?: AgentMetric[]): void {
act(() =>
root.render(
<PortalProvider>
<CompletedTurnFooterRow
strategy={createNativeStreamStrategy()}
items={[reply]}
timing={COMPLETED_TIMING}
startIndex={0}
supportsTimelineCursor={false}
turnMetrics={turnMetrics}
/>
<FloatingPanelPortalHost />
</PortalProvider>,
),
);
}
it("has no trigger when the provider reported nothing for the turn", () => {
renderFooterWithMetrics(undefined);
expect(page.getByRole("button", { name: "Turn stats" }).elements()).toHaveLength(0);
});
it("shows the turn's metrics while the pointer is on the trigger", async () => {
renderFooterWithMetrics(metrics);
await page.getByRole("button", { name: "Turn stats" }).hover();
const card = page.getByRole("dialog", { name: "Turn stats" });
await expect.element(card).toBeVisible();
await expect.element(card.getByText("Model")).toBeVisible();
await expect.element(card.getByText("opus")).toBeVisible();
await expect.element(card.getByText("$0.42")).toBeVisible();
});
it("keeps the footer's height when the trigger appears", () => {
renderFooterWithMetrics(undefined);
const without = host.getBoundingClientRect().height;
renderFooterWithMetrics(metrics);
expect(host.getBoundingClientRect().height).toBe(without);
});
});
@@ -1,3 +1,4 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import React, { memo, useCallback, useMemo, type ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -81,6 +82,7 @@ export const TurnFooter = memo(function TurnFooter({
items={host.items}
timing={host.timing}
startIndex={host.startIndex}
turnMetrics={host.turnMetrics}
supportsTimelineCursor={supportsTimelineCursor}
onForkAssistantTurn={onForkAssistantTurn}
/>
@@ -92,6 +94,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({
items,
timing,
startIndex,
turnMetrics,
supportsTimelineCursor,
onForkAssistantTurn,
}: {
@@ -99,6 +102,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({
items: StreamItem[];
timing?: TurnTiming;
startIndex: number;
turnMetrics?: AgentMetric[];
supportsTimelineCursor: boolean;
onForkAssistantTurn?: AssistantTurnForkHandler;
}) {
@@ -109,6 +113,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({
items={items}
timing={timing}
startIndex={startIndex}
turnMetrics={turnMetrics}
supportsTimelineCursor={supportsTimelineCursor}
onForkAssistantTurn={onForkAssistantTurn}
/>
@@ -165,6 +170,7 @@ function CompletedTurnFooter({
items,
timing,
startIndex,
turnMetrics,
supportsTimelineCursor,
onForkAssistantTurn,
}: {
@@ -172,6 +178,7 @@ function CompletedTurnFooter({
items: StreamItem[];
timing?: TurnTiming;
startIndex: number;
turnMetrics?: AgentMetric[];
supportsTimelineCursor: boolean;
onForkAssistantTurn?: AssistantTurnForkHandler;
}) {
@@ -205,6 +212,7 @@ function CompletedTurnFooter({
completedAt={timing?.completedAt}
durationMs={timing?.durationMs}
onFork={boundary && onForkAssistantTurn ? handleFork : undefined}
metrics={turnMetrics}
/>
</View>
);
+1
View File
@@ -188,6 +188,7 @@ function renderStreamItemWithTurnFooter(input: {
items={footerHost.items}
timing={footerHost.timing}
startIndex={footerHost.startIndex}
turnMetrics={footerHost.turnMetrics}
supportsTimelineCursor={input.supportsTimelineCursor}
onForkAssistantTurn={input.onForkAssistantTurn}
/>
@@ -0,0 +1,65 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { i18n } from "@/i18n/i18next";
import { ContextWindowDetails } from "./context-window-details";
const CONTEXT = { percentage: 40, usedTokens: 80_000, maxTokens: 200_000 };
let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
function renderDetails(sessionMetrics: AgentMetric[]): void {
act(() =>
root.render(
<QueryClientProvider client={new QueryClient()}>
<ContextWindowDetails
serverId="server"
agentId="agent"
context={CONTEXT}
sessionCost="$1.20"
sessionMetrics={sessionMetrics}
showTitle
refreshable={false}
/>
</QueryClientProvider>,
),
);
}
it("shows what the provider reports about the session", async () => {
renderDetails([
{ label: "Model", value: "opus" },
{ label: "Requests", value: "12" },
]);
await expect.element(page.getByText("Model")).toBeVisible();
await expect.element(page.getByText("opus")).toBeVisible();
await expect.element(page.getByText("Requests")).toBeVisible();
await expect.element(page.getByText("Session cost $1.20")).toBeVisible();
});
it("leaves the cost to the provider when it reports one", async () => {
renderDetails([{ label: "Cost", value: "$1.25" }]);
await expect.element(page.getByText("$1.25")).toBeVisible();
expect(page.getByText("Session cost $1.20").elements()).toHaveLength(0);
});
@@ -1,8 +1,10 @@
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { AgentUsage } from "@/usage";
import { formatTokenCount } from "./context-window-meter.utils";
import { MetricsList } from "./metrics-list";
interface ContextWindowDetailsProps {
serverId: string;
@@ -13,6 +15,8 @@ interface ContextWindowDetailsProps {
maxTokens: number;
} | null;
sessionCost: string | null;
/** What the provider reports about the session. A reported cost replaces `sessionCost`. */
sessionMetrics: AgentMetric[];
/** The hover card and tooltip title themselves; the sheet's header carries the title instead. */
showTitle: boolean;
/** Whether the usage cards have a Refresh button; without one they show their freshness. */
@@ -20,18 +24,22 @@ interface ContextWindowDetailsProps {
}
/**
* What the context window meter opens: how full the window is, then the usage of the agent's
* account. The desktop hover card, the native wide tooltip, and the compact sheet all render it.
* What the context window meter opens: how full the window is, what the provider reports about the
* session, then the usage of the agent's account. The desktop hover card, the native wide tooltip, and the compact sheet all render it.
*/
export function ContextWindowDetails({
serverId,
agentId,
context,
sessionCost,
sessionMetrics,
showTitle,
refreshable,
}: ContextWindowDetailsProps) {
const { t } = useTranslation();
const providerReportsCost = sessionMetrics.some(
(metric) => metric.label.toLowerCase() === "cost",
);
return (
<>
<View style={styles.summary}>
@@ -51,10 +59,11 @@ export function ContextWindowDetails({
) : (
<Text style={styles.detail}>{t("contextWindow.noData")}</Text>
)}
{sessionCost ? (
{sessionCost && !providerReportsCost ? (
<Text style={styles.detail}>{t("contextWindow.sessionCost", { cost: sessionCost })}</Text>
) : null}
</View>
{sessionMetrics.length > 0 ? <MetricsList metrics={sessionMetrics} /> : null}
<AgentUsage serverId={serverId} agentId={agentId} refreshable={refreshable} />
</>
);
@@ -13,11 +13,12 @@ import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/h
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { useHostReportsUsage } from "@/usage";
import type { Theme } from "@/styles/theme";
import { TOOLBAR_DISC_SIZE, type ToolbarRing } from "@/components/ui/control-geometry";
import { ContextWindowDetails } from "./context-window-details";
import { ContextWindowSheet } from "./context-window-sheet";
import { DetailsSheet } from "./details-sheet";
import { formatContextPercentage } from "./context-window-meter.utils";
interface ContextWindowMeterProps {
@@ -26,11 +27,14 @@ interface ContextWindowMeterProps {
maxTokens: number | null;
usedTokens: number | null;
totalCostUsd?: number | null;
/** What the provider reports about the session, shown in the details. */
sessionMetrics?: AgentMetric[];
showPercentage?: boolean;
/** The ring's box and stroke when it sits in an icon toolbar. */
toolbarRing?: ToolbarRing;
}
const EMPTY_METRICS: AgentMetric[] = [];
const SVG_SIZE = 14;
const USAGE_POPOVER_WIDTH = 300;
const COMPACT_SVG_SIZE = 12;
@@ -156,13 +160,16 @@ export function ContextWindowMeter({
maxTokens,
usedTokens,
totalCostUsd,
sessionMetrics = EMPTY_METRICS,
showPercentage = false,
toolbarRing,
}: ContextWindowMeterProps) {
const { t, i18n } = useTranslation();
const { width } = useWindowDimensions();
// Usage cards need a wider popover; without them it keeps the plain tooltip shape.
// Usage cards and session metrics need a wider popover; without them it keeps the plain tooltip
// shape.
const showsUsage = useHostReportsUsage(serverId);
const isWide = showsUsage || sessionMetrics.length > 0;
const popoverWidth = Math.min(USAGE_POPOVER_WIDTH, width - 24);
// Compact screens open the details in a sheet, which can hold a pressable Refresh.
const isCompact = useIsCompactFormFactor();
@@ -226,21 +233,22 @@ export function ContextWindowMeter({
{ring}
{percentageLabel}
</Pressable>
<ContextWindowSheet open={isSheetOpen} onClose={closeSheet}>
<DetailsSheet open={isSheetOpen} onClose={closeSheet} title={t("contextWindow.title")}>
<ContextWindowDetails
serverId={serverId}
agentId={agentId}
context={context}
sessionCost={formattedSessionCost}
sessionMetrics={sessionMetrics}
showTitle={false}
refreshable
/>
</ContextWindowSheet>
</DetailsSheet>
</>
);
}
const popoverStyle = showsUsage
const popoverStyle = isWide
? [styles.usagePopover, { width: popoverWidth }]
: styles.plainPopover;
@@ -264,7 +272,7 @@ export function ContextWindowMeter({
side="top"
align="center"
offset={8}
maxWidth={showsUsage ? popoverWidth : undefined}
maxWidth={isWide ? popoverWidth : undefined}
style={popoverStyle}
testID="context-window-meter-tooltip"
>
@@ -273,6 +281,7 @@ export function ContextWindowMeter({
agentId={agentId}
context={context}
sessionCost={formattedSessionCost}
sessionMetrics={sessionMetrics}
showTitle
refreshable={false}
/>
@@ -307,6 +316,7 @@ export function ContextWindowMeter({
agentId={agentId}
context={context}
sessionCost={formattedSessionCost}
sessionMetrics={sessionMetrics}
showTitle
refreshable
/>
@@ -1,7 +1,6 @@
import { useMemo, type ReactNode } from "react";
import { View, useWindowDimensions } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { BottomSheetScrollView } from "@gorhom/bottom-sheet";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SheetHeaderView, SHEET_HORIZONTAL_PADDING_SCALE } from "@/components/adaptive-modal-sheet";
@@ -23,23 +22,24 @@ const ThemedBottomSheetModal = withUnistyles(IsolatedBottomSheetModal, (theme) =
}));
/**
* The context window meter's details on compact screens, in a sheet as tall as its content.
* Gorhom mounts the content only while the sheet is presented, so whatever it fetches stops once
* the sheet closes.
* What a hover card or tooltip shows on wide screens, shown on compact screens in a sheet as tall
* as its content. Gorhom mounts the content only while the sheet is presented, so whatever it
* fetches stops once the sheet closes.
*/
export function ContextWindowSheet({
export function DetailsSheet({
open,
onClose,
title,
children,
}: {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
}) {
const { t } = useTranslation();
const { height } = useWindowDimensions();
const insets = useSafeAreaInsets();
const header = useMemo(() => ({ title: t("contextWindow.title") }), [t]);
const header = useMemo(() => ({ title }), [title]);
const scrollContentStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]);
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
visible: open,
@@ -50,7 +50,8 @@ export function ContextWindowSheet({
<ThemedBottomSheetModal
ref={sheetRef}
contextBridge={null}
// Content-sized rather than fixed snap points: the usage cards stream in one at a time.
// Content-sized rather than fixed snap points: a few rows of details, or usage cards that
// stream in one at a time.
enableDynamicSizing
maxDynamicContentSize={height * 0.8}
onChange={handleSheetChange}
+14 -2
View File
@@ -3,6 +3,7 @@ import { MessagePreview, MessageSender } from "@/components/user-message";
import { useStableEvent } from "@/hooks/use-stable-event";
import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content";
import { AssistantForkMenu, type AssistantForkTarget } from "@/components/assistant-fork-menu";
import { TurnMetricsButton } from "@/components/turn-metrics";
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
import {
AttachmentFrame,
@@ -36,7 +37,11 @@ import { useToolCallExpanded } from "@/tool-calls/expansion-context";
import { useTargetAgentTitle } from "@/tool-calls/use-target-agent-title";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { AgentCapabilityFlags, ToolCallDetail } from "@getpaseo/protocol/agent-types";
import type {
AgentCapabilityFlags,
AgentMetric,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import {
@@ -560,6 +565,8 @@ interface AssistantTurnFooterProps {
completedAt?: Date;
durationMs?: number | null;
onFork?: (target: AssistantForkTarget) => Promise<void> | void;
/** What the provider reported about the turn. Without any, the footer has no stats button. */
metrics?: AgentMetric[];
}
const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({
@@ -596,6 +603,8 @@ const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({
flexShrink: 0,
color: theme.colors.foregroundMuted,
fontSize: STREAM_METADATA_FONT_SIZE,
// React Native Web preserves trailing spaces at line wraps by default.
...(isWeb ? { whiteSpace: "normal" } : {}),
},
overlappingLabel: {
marginLeft: "-100%",
@@ -617,6 +626,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
completedAt,
durationMs,
onFork,
metrics,
}: AssistantTurnFooterProps) {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
@@ -666,10 +676,11 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
[onFork],
);
const canFork = Boolean(onFork);
const hasMetrics = metrics !== undefined && metrics.length > 0;
return (
<View style={assistantTurnFooterStylesheet.container}>
{getContent || canFork ? (
{getContent || canFork || hasMetrics ? (
<View style={assistantTurnFooterStylesheet.actions}>
{getContent ? (
<TurnCopyButton
@@ -678,6 +689,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
/>
) : null}
{canFork ? <AssistantForkMenu onFork={handleFork} /> : null}
{hasMetrics ? <TurnMetricsButton metrics={metrics} /> : null}
</View>
) : null}
{primaryLabel ? (
@@ -0,0 +1,72 @@
import { memo } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
/**
* Label and value rows a provider reports for a session or a turn. The provider owns the words and
* the tone; the list only lines them up.
*/
export const MetricsList = memo(function MetricsList({
metrics,
testID,
}: {
metrics: AgentMetric[];
testID?: string;
}) {
return (
<View style={styles.list} testID={testID}>
{metrics.map((metric) => (
<View key={metric.label} style={styles.row}>
<Text style={styles.label} numberOfLines={1}>
{metric.label}
</Text>
<Text style={[styles.value, toneStyle(metric.tone)]} numberOfLines={1}>
{metric.value}
</Text>
</View>
))}
</View>
);
});
function toneStyle(tone: AgentMetric["tone"]) {
switch (tone) {
case "ok":
return styles.ok;
case "warning":
return styles.warning;
case "danger":
return styles.danger;
default:
return null;
}
}
const styles = StyleSheet.create((theme) => ({
list: {
gap: theme.spacing[1.5],
},
row: {
flexDirection: "row",
alignItems: "baseline",
gap: theme.spacing[6],
},
label: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: theme.fontSize.sm * 1.4,
},
value: {
flex: 1,
textAlign: "right",
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
lineHeight: theme.fontSize.sm * 1.4,
fontVariant: ["tabular-nums"],
},
ok: { color: theme.colors.statusSuccess },
warning: { color: theme.colors.statusWarning },
danger: { color: theme.colors.statusDanger },
}));
@@ -1,13 +1,15 @@
import { AppearanceText as Text } from "@/appearance/text";
import { ChevronRight } from "lucide-react-native";
import { useMemo, type ReactNode } from "react";
import { Platform, ScrollView, View } from "react-native";
import { Platform, ScrollView, View, type PressableStateCallbackType } from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BackHeader } from "@/components/headers/back-header";
import { MenuHeader } from "@/components/headers/menu-header";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useIsCompactFormFactor } from "@/constants/layout";
import { SPACING } from "@/styles/theme";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
@@ -58,14 +60,7 @@ export function PageLayout({
testID={testID}
>
<View style={width === "wide" ? styles.contentWide : styles.content}>
{showTitle ? (
<View style={styles.titleRow} testID={titleTestID}>
<Text style={styles.title} testID="page-title">
{title}
</Text>
{actions}
</View>
) : null}
{showTitle ? <PageTitle title={title} actions={actions} testID={titleTestID} /> : null}
{children}
</View>
</PageScrollView>
@@ -73,6 +68,77 @@ export function PageLayout({
);
}
/** The page that holds this one. Its name is the first part of the title and goes back to it. */
export interface PageTitleParent {
label: string;
/** What the press does, such as "Back to providers". */
accessibilityLabel: string;
onPress: () => void;
testID?: string;
}
interface PageTitleProps {
parent?: PageTitleParent;
/** Drawn before the title, such as the icon of the thing the page is about. */
icon?: ReactNode;
title?: string;
/** A control that belongs to the title, drawn right after it. */
adornment?: ReactNode;
/** Controls for the whole page, drawn at the trailing edge. */
actions?: ReactNode;
testID?: string;
titleTestID?: string;
}
/**
* The heading of a desktop page. A page that opens from another page, such as one provider from
* Providers, names that page first: "Providers > Antigravity".
*/
export function PageTitle({
parent,
icon,
title,
adornment,
actions,
testID,
titleTestID = "page-title",
}: PageTitleProps) {
return (
<View style={styles.titleRow} testID={testID}>
<View style={styles.titleParts}>
{parent ? (
<PressHighlight
accessibilityRole="button"
accessibilityLabel={parent.accessibilityLabel}
onPress={parent.onPress}
testID={parent.testID}
>
{({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => (
<Text style={[styles.title, styles.parent, hovered && styles.parentHovered]}>
{parent.label}
</Text>
)}
</PressHighlight>
) : null}
{parent && title !== undefined ? (
<ThemedChevronRight size={ICON_SIZE.lg} uniProps={separatorColor} />
) : null}
{icon}
{title !== undefined ? (
<Text style={[styles.title, styles.titleLeaf]} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
) : null}
{adornment}
</View>
{actions}
</View>
);
}
const ThemedChevronRight = withUnistyles(ChevronRight);
const separatorColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
@@ -102,11 +168,27 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[4],
marginBottom: theme.spacing[6],
},
title: {
titleParts: {
// Line up with the section titles, which sit inset from their cards.
marginLeft: theme.spacing[1],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
flexShrink: 1,
minWidth: 0,
},
title: {
fontSize: theme.fontSize["4xl"],
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
},
titleLeaf: {
flexShrink: 1,
},
parent: {
color: theme.colors.foregroundMuted,
},
parentHovered: {
color: theme.colors.foreground,
},
}));
@@ -2,7 +2,9 @@ import { ArrowLeft } from "lucide-react-native";
import type { ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { PageTitle, type PageTitleParent } from "@/components/page-layout";
import { Button } from "@/components/ui/button";
import { useIsCompactFormFactor } from "@/constants/layout";
/**
* "Back to …" above a settings detail page on wide layouts, where the page has no header of its
@@ -32,32 +34,43 @@ export function SettingsBackLink({
}
/**
* The top of a settings detail page: "Back to …" when the page has no header of its own, then the
* icon and name the page is about, with an optional action after the name.
* The top of a settings detail page: the icon and name of the thing the page is about, with an
* optional action after the name. On wide layouts it is the page's title and names the parent page
* first, which goes back to it. On compact layouts the back header already names the parent.
*/
export function SettingsDetailHeader({
back,
parent,
icon,
title,
trailing,
titleTestID,
}: {
back?: { label: string; onPress: () => void; testID?: string };
icon: ReactNode;
title: string;
parent: PageTitleParent;
icon?: ReactNode;
/** Absent while the page has nothing to name, such as a project that no longer exists. */
title?: string;
trailing?: ReactNode;
titleTestID?: string;
}) {
const isCompact = useIsCompactFormFactor();
if (!isCompact)
return (
<PageTitle
parent={parent}
icon={icon}
title={title}
adornment={trailing}
titleTestID={titleTestID}
/>
);
if (title === undefined) return null;
return (
<View style={styles.header}>
{back ? <SettingsBackLink {...back} /> : null}
<View style={styles.titleRow}>
{icon}
<Text style={styles.title} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
{trailing}
</View>
<View style={styles.titleRow}>
{icon}
<Text style={styles.title} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
{trailing}
</View>
);
}
@@ -67,15 +80,13 @@ const styles = StyleSheet.create((theme) => ({
alignSelf: "flex-start",
paddingHorizontal: 0,
},
header: {
gap: theme.spacing[2],
marginBottom: theme.spacing[4],
},
titleRow: {
marginTop: theme.spacing[2],
// Line up with the section titles, which sit inset from their cards.
marginLeft: theme.spacing[1],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
marginBottom: theme.spacing[4],
},
title: {
color: theme.colors.foreground,
@@ -0,0 +1,22 @@
import type { ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
/**
* The action at a heading's end. It adds no height, so a heading with a button is as tall as one
* without and both sit the same distance from their cards. The button stays centered on the title
* and its hit area grows past the heading.
*/
export function HeadingTrailing({ children }: { children: ReactNode }) {
if (children === null || children === undefined || children === false) return null;
return <View style={styles.trailing}>{children}</View>;
}
const styles = StyleSheet.create({
trailing: {
height: 0,
justifyContent: "center",
// A long trailing gives way to the title.
flexShrink: 1,
},
});
@@ -1,6 +1,7 @@
import { useMemo, type ReactNode } from "react";
import { Text, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { HeadingTrailing } from "./heading-trailing";
import { SettingsInfoTip } from "./settings-info-tip";
interface SettingsGroupProps {
@@ -40,7 +41,7 @@ export function SettingsGroup({
/>
) : null}
</View>
{trailing}
<HeadingTrailing>{trailing}</HeadingTrailing>
</View>
{children}
</View>
@@ -3,6 +3,7 @@ import { useMemo, type ReactNode } from "react";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
import { HeadingTrailing } from "./heading-trailing";
import { SettingsInfoTip } from "./settings-info-tip";
import { settingsStyles } from "@/styles/settings";
@@ -67,7 +68,7 @@ export function SettingsSection({
<ExternalLink {...link} />
</View>
) : null}
{trailing}
<HeadingTrailing>{trailing}</HeadingTrailing>
</View>
<View style={styles.content}>{children}</View>
</View>
@@ -7,6 +7,7 @@ import {
SettingsCollapsibleRow,
SettingsDetailRow,
SettingsRow,
SettingsSwitch,
} from "@/components/settings";
let root: Root | null = null;
@@ -20,6 +21,7 @@ afterEach(() => {
});
function openNothing() {}
function toggleNothing() {}
function mountRows() {
container = document.createElement("div");
@@ -33,6 +35,13 @@ function mountRows() {
Download
</Button>
</SettingsRow>
<SettingsRow label="Text only" testID="text-row" />
<SettingsSwitch
label="Toggles"
value={false}
onValueChange={toggleNothing}
testID="switch-row"
/>
<SettingsDetailRow label="Opens a page" onPress={openNothing} testID="detail-row" />
<SettingsCollapsibleRow label="Group" defaultExpanded testID="group">
<SettingsRow label="Nested with a button" testID="nested-with-button">
@@ -74,11 +83,13 @@ describe("settings row density", () => {
expect(heightOf("group-toggle")).toBeGreaterThan(heightOf("nested-without-button"));
});
it("keeps a row that opens something as tall as a row holding a control", () => {
it("lines up text, switch, and opening rows below a row holding a button", () => {
mountRows();
expect(heightOf("detail-row")).toBe(heightOf("card-row"));
expect(heightOf("group-toggle")).toBe(heightOf("card-row"));
expect(heightOf("switch-row")).toBe(heightOf("text-row"));
expect(heightOf("detail-row")).toBe(heightOf("text-row"));
expect(heightOf("group-toggle")).toBe(heightOf("text-row"));
expect(heightOf("card-row")).toBeGreaterThan(heightOf("text-row"));
});
it("sizes nested text and controls one step below card rows", () => {
@@ -27,11 +27,6 @@ export function MenuSettingsRows({ children }: { children: ReactNode }) {
export interface SettingsRowLayout {
row: StyleProp<ViewStyle>;
/**
* A row as tall as one holding a control of `controlSize`, whether or not it holds one. In a menu
* it keeps the menu's row height.
*/
controlRow: StyleProp<ViewStyle>;
title: StyleProp<TextStyle>;
hint: StyleProp<TextStyle>;
/** The size of the controls in the row's trailing slot. */
@@ -43,7 +38,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "nested":
return {
row: [settingsStyles.row, styles.nestedRow],
controlRow: [settingsStyles.row, styles.nestedRow],
title: [settingsStyles.rowTitle, styles.nestedText],
hint: [settingsStyles.rowHint, styles.nestedText],
controlSize: "sm",
@@ -51,7 +45,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "menu":
return {
row: [settingsStyles.row, styles.menuRow],
controlRow: [settingsStyles.row, styles.menuRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -59,7 +52,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "card":
return {
row: settingsStyles.row,
controlRow: [settingsStyles.row, styles.cardControlRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -74,9 +66,6 @@ export function useSettingsRowLayout(): SettingsRowLayout {
}
const styles = StyleSheet.create((theme) => ({
cardControlRow: {
minHeight: mapLayout(CONTROL_HEIGHTS.md, (height) => height + theme.spacing[4] * 2),
},
// Every nested row is as tall as one holding an `sm` control, so rows with and without a
// trailing button line up.
nestedRow: {
@@ -86,7 +86,7 @@ export function SettingsRowHeader({
const handlePointerEnter = useCallback(() => setPointerOver(true), []);
const handlePointerLeave = useCallback(() => setPointerOver(false), []);
const hovered = pointerOver && !disabled;
const rowStyle = useMemo(() => [layout.controlRow, hovered && styles.hovered], [hovered, layout]);
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded],
[expanded],
@@ -0,0 +1,148 @@
import { memo, useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { ChartNoAxesColumn } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
useHoverCardOpen,
} from "@/components/ui/hover-card";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { DetailsSheet } from "./details-sheet";
import { MetricsList } from "./metrics-list";
const ThemedChart = withUnistyles(ChartNoAxesColumn);
const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
/**
* The turn footer's stats button: what the provider reported about this turn, in a hover card on
* web, a tooltip opened by press on native wide screens, and a sheet on compact screens.
*/
export const TurnMetricsButton = memo(function TurnMetricsButton({
metrics,
}: {
metrics: AgentMetric[];
}) {
const isCompact = useIsCompactFormFactor();
if (isCompact) return <TurnMetricsSheetButton metrics={metrics} />;
if (isNative) return <TurnMetricsTooltipButton metrics={metrics} />;
return <TurnMetricsHoverCardButton metrics={metrics} />;
});
function TurnMetricsSheetButton({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const openSheet = useCallback(() => setOpen(true), []);
const closeSheet = useCallback(() => setOpen(false), []);
return (
<>
<PressHighlight
style={styles.trigger}
accessibilityRole="button"
accessibilityLabel={t("message.actions.turnStats")}
onPress={openSheet}
testID="turn-metrics-trigger"
>
{({ hovered }) => <TurnMetricsIcon active={open || Boolean(hovered)} />}
</PressHighlight>
<DetailsSheet open={open} onClose={closeSheet} title={t("message.actions.turnStats")}>
<MetricsList metrics={metrics} />
</DetailsSheet>
</>
);
}
function TurnMetricsTooltipButton({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return (
<Tooltip open={open} onOpenChange={setOpen} delayDuration={0} enabledOnDesktop enabledOnMobile>
<TooltipTrigger asChild triggerRefProp="ref">
<PressHighlight
style={styles.trigger}
accessibilityRole="button"
accessibilityLabel={t("message.actions.turnStats")}
testID="turn-metrics-trigger"
>
{({ hovered }) => <TurnMetricsIcon active={open || Boolean(hovered)} />}
</PressHighlight>
</TooltipTrigger>
<TooltipContent side="top" align="start" offset={8} style={styles.popover}>
<TurnMetricsDetails metrics={metrics} />
</TooltipContent>
</Tooltip>
);
}
function TurnMetricsHoverCardButton({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
return (
<HoverCard>
<HoverCardTrigger focusable accessibilityLabel={t("message.actions.turnStats")}>
<View style={styles.trigger} testID="turn-metrics-trigger">
<HoverCardTurnMetricsIcon />
</View>
</HoverCardTrigger>
<HoverCardContent
placement="top"
alignment="start"
offset={8}
role="dialog"
accessibilityLabel={t("message.actions.turnStats")}
testID="turn-metrics-details"
style={styles.popover}
>
<TurnMetricsDetails metrics={metrics} />
</HoverCardContent>
</HoverCard>
);
}
function HoverCardTurnMetricsIcon() {
return <TurnMetricsIcon active={useHoverCardOpen()} />;
}
function TurnMetricsIcon({ active }: { active: boolean }) {
return (
<ThemedChart
size={ICON_SIZE.sm}
uniProps={active ? foregroundColorMapping : foregroundMutedColorMapping}
/>
);
}
function TurnMetricsDetails({ metrics }: { metrics: AgentMetric[] }) {
const { t } = useTranslation();
return (
<>
<Text style={styles.title}>{t("message.actions.turnStats")}</Text>
<MetricsList metrics={metrics} />
</>
);
}
const styles = StyleSheet.create((theme) => ({
// Matches the Copy and Fork buttons beside it, so the glyphs share one row and one spacing.
trigger: {
alignSelf: "center",
padding: theme.spacing[1],
borderRadius: theme.borderRadius.md,
},
popover: {
minWidth: 220,
padding: theme.spacing[3],
gap: theme.spacing[2],
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
}));
@@ -302,23 +302,23 @@ describe("control geometry", () => {
trackHeight: 20,
thumbSize: 16,
thumbTravel: 14,
reservedHeight: 32,
hitHeight: 32,
});
expect(switchGeometryForLayout("md", true)).toEqual({
trackWidth: 44,
trackHeight: 26,
thumbSize: 22,
thumbTravel: 18,
reservedHeight: 44,
hitHeight: 44,
});
// Tight chrome keeps the pointer-sized track on every layout and reserves its row's height.
// Tight chrome keeps the pointer-sized track on every layout and takes presses over its row's control height.
expect(switchGeometryForLayout("sm", true)).toMatchObject({
trackWidth: 34,
reservedHeight: 32,
hitHeight: 32,
});
expect(switchGeometryForLayout("sm", false)).toMatchObject({
trackWidth: 34,
reservedHeight: 28,
hitHeight: 28,
});
});
@@ -223,8 +223,11 @@ export interface SwitchGeometry {
thumbSize: number;
/** How far the thumb slides between off and on. */
thumbTravel: number;
/** The control height the switch reserves, so its row lines up with one holding a button. */
reservedHeight: number;
/**
* The height of the area that takes the press: the control height of the switch's size. The
* switch itself is only as tall as its track, so it never makes a row taller.
*/
hitHeight: number;
}
function switchSize(trackWidth: number, trackHeight: number, thumbSize: number) {
@@ -235,6 +238,15 @@ function switchSize(trackWidth: number, trackHeight: number, thumbSize: number)
const SWITCH_POINTER = switchSize(34, 20, 16);
const SWITCH_TOUCH = switchSize(44, 26, 22);
/**
* The height of a default switch. Exported so a row can be as tall as one holding a switch whether
* or not it holds one. A breakpoint value, so it only works inside a Unistyles stylesheet.
*/
export const SWITCH_HEIGHT = bySizing({
touch: SWITCH_TOUCH.trackHeight,
pointer: SWITCH_POINTER.trackHeight,
});
/**
* A switch follows the same two sizes as every other control. Its thumb travel feeds an
* animation, so the size is resolved to plain numbers here instead of a stylesheet breakpoint.
@@ -242,7 +254,7 @@ const SWITCH_TOUCH = switchSize(44, 26, 22);
export function switchGeometryForLayout(size: ControlSize, isCompact: boolean): SwitchGeometry {
const touchSized = controlSizingForLayout(isCompact) === "touch";
const track = size === "md" && touchSized ? SWITCH_TOUCH : SWITCH_POINTER;
return { ...track, reservedHeight: controlHeightForLayout(size, isCompact) };
return { ...track, hitHeight: controlHeightForLayout(size, isCompact) };
}
function fieldLineHeight(fontSize: number): number {
@@ -1,5 +1,6 @@
import { useCallback, type ReactElement } from "react";
import {
MenuCheckboxItem,
MenuHint,
MenuItem,
MenuLabel,
@@ -23,11 +24,16 @@ import {
export { MenuRoot as DropdownMenu };
export { MenuTrigger as DropdownMenuTrigger };
export { MenuItem as DropdownMenuItem };
export { MenuCheckboxItem as DropdownMenuCheckboxItem };
export { MenuLabel as DropdownMenuLabel };
export { MenuSeparator as DropdownMenuSeparator };
export { MenuHint as DropdownMenuHint };
export type { MenuTriggerProps as DropdownMenuTriggerProps };
export type { ActionStatus, MenuItemProps as DropdownMenuItemProps } from "@/components/ui/menu";
export type {
ActionStatus,
MenuCheckboxItemProps as DropdownMenuCheckboxItemProps,
MenuItemProps as DropdownMenuItemProps,
} from "@/components/ui/menu";
export type { MenuPageDefinition } from "@/components/ui/menu";
export { MenuSubTrigger as DropdownMenuSubTrigger } from "@/components/ui/menu";
@@ -267,6 +267,11 @@ function WebHoverCard({
);
}
/** Whether the enclosing card is open, so its trigger can look active while it is. */
export function useHoverCardOpen(): boolean {
return useContext(HoverCardContext)?.open ?? false;
}
export function HoverCardTrigger({
children,
focusable = false,
@@ -19,6 +19,7 @@ export {
} from "./menu-surface";
export { MenuSubTrigger } from "./menu-sub";
export {
MenuCheckboxItem,
MenuHint,
MenuItem,
MenuLabel,
@@ -26,6 +27,7 @@ export {
MenuTextField,
menuRowContentInset,
type ActionStatus,
type MenuCheckboxItemProps,
type MenuItemProps,
} from "./menu-item";
export { MENU_ITEM_HEIGHT } from "./menu-geometry";
@@ -18,6 +18,7 @@ import { Check, CheckCircle } from "lucide-react-native";
import { AdaptiveTextInput } from "@/components/adaptive-modal-sheet";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { isWeb } from "@/constants/platform";
import type { Theme } from "@/styles/theme";
import { MenuDepthProvider, useMenuContext } from "./menu-context";
import { MENU_ITEM_HEIGHT } from "./menu-geometry";
@@ -221,6 +222,36 @@ function resolveItemLabel(input: {
return children;
}
function resolveTrailingContent(input: {
trailing: ReactElement | null | undefined;
showSelectedCheck: boolean;
selected: boolean | undefined;
}): ReactElement | null {
if (input.trailing !== undefined) return input.trailing;
if (!input.showSelectedCheck && input.selected) {
return <ThemedCheck size={16} uniProps={mutedMapping} />;
}
return null;
}
function useSheetSpaceKeyProps(
enabled: boolean,
onPress: () => void,
): { onKeyDown?: (event: { key?: string; preventDefault?: () => void }) => void } {
return useMemo(() => {
if (!isWeb || !enabled) return {};
return {
// React Native Web's Pressable activates Space only for role="button", not menuitem/checkbox.
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
onPress();
}
},
};
}, [enabled, onPress]);
}
export interface MenuItemProps {
description?: string;
onSelect?: () => void;
@@ -253,7 +284,37 @@ export interface MenuItemProps {
tooltip?: string;
}
export function MenuItem({
export function MenuItem(props: PropsWithChildren<MenuItemProps>): ReactElement {
return <MenuRow {...props} accessibilityRole="menuitem" />;
}
export interface MenuCheckboxItemProps extends Omit<MenuItemProps, "selected" | "onSelect"> {
checked: boolean;
onToggle: () => void;
}
/**
* A toggleable menu row that stays open on press by default and exposes `checkbox` semantics so
* screen readers announce its checked state.
*/
export function MenuCheckboxItem({
checked,
onToggle,
closeOnSelect = false,
...rest
}: PropsWithChildren<MenuCheckboxItemProps>): ReactElement {
return (
<MenuRow
{...rest}
selected={checked}
onSelect={onToggle}
closeOnSelect={closeOnSelect}
accessibilityRole="checkbox"
/>
);
}
function MenuRow({
children,
description,
onSelect,
@@ -272,8 +333,11 @@ export function MenuItem({
closeOnSelect = true,
testID,
tooltip,
}: PropsWithChildren<MenuItemProps>): ReactElement {
const { selectItem } = useMenuContext("MenuItem");
accessibilityRole,
}: PropsWithChildren<
MenuItemProps & { accessibilityRole: "menuitem" | "checkbox" }
>): ReactElement {
const { selectItem, presentation } = useMenuContext("MenuItem");
const isPending = status === "pending" || loading;
const isSuccess = status === "success";
const isDisabled = disabled || isPending || isSuccess;
@@ -286,14 +350,14 @@ export function MenuItem({
const label = resolveItemLabel({ children, isPending, isSuccess, pendingLabel, successLabel });
const trailingContent =
trailing ??
(!showSelectedCheck && selected ? <ThemedCheck size={16} uniProps={mutedMapping} /> : null);
const trailingContent = resolveTrailingContent({ trailing, showSelectedCheck, selected });
const handleItemPress = useCallback(() => {
if (isDisabled) return;
selectItem(onSelect, closeOnSelect);
}, [isDisabled, selectItem, onSelect, closeOnSelect]);
const isSheet = presentation === "sheet";
const sheetKeyProps = useSheetSpaceKeyProps(isSheet, handleItemPress);
// A row that draws a check has to say so as well: a multi-select page is a list of things that
// are on or off, and the check is the only thing telling a sighted user which. Rows that answer
@@ -336,11 +400,13 @@ export function MenuItem({
const content = (
<Pressable
{...sheetKeyProps}
testID={testID}
accessibilityRole="menuitem"
accessibilityRole={accessibilityRole}
accessibilityState={accessibilityState}
aria-checked={selected}
tabIndex={-1}
// Popovers manage focus via arrow keys; compact sheets rely on the browser's Tab order.
tabIndex={isSheet ? 0 : -1}
dataSet={itemDataSet}
disabled={isDisabled}
onPress={handleItemPress}
@@ -25,6 +25,8 @@ export interface SearchFieldProps {
/** Falls back to `placeholder`, which already names the field. */
accessibilityLabel?: string;
clearAccessibilityLabel: string;
/** Fill the container, for a search that heads one list. Defaults to the filter rail's width. */
fullWidth?: boolean;
testID?: string;
clearTestID?: string;
}
@@ -42,6 +44,7 @@ export function SearchField({
placeholder,
accessibilityLabel,
clearAccessibilityLabel,
fullWidth = false,
testID,
clearTestID,
}: SearchFieldProps): ReactElement {
@@ -55,7 +58,9 @@ export function SearchField({
}, [onChangeText]);
return (
<View style={[styles.field, isFocused && styles.fieldFocused]}>
<View
style={[styles.field, fullWidth && styles.fieldFullWidth, isFocused && styles.fieldFocused]}
>
<ThemedSearch size={14} uniProps={mutedColorMapping} />
<ThemedTextInput
testID={testID}
@@ -103,6 +108,9 @@ const styles = StyleSheet.create((theme) => ({
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
},
fieldFullWidth: {
maxWidth: "100%",
},
fieldFocused: {
borderColor: theme.colors.borderAccent,
backgroundColor: theme.colors.surface2,
+7 -2
View File
@@ -123,11 +123,16 @@ export function Switch({
const pressableStyle = useMemo(
() => [
styles.switchControl,
{ minHeight: geometry.reservedHeight },
// The press area is a full control tall and grows out of the track; the layout only sees
// the track.
{
minHeight: geometry.hitHeight,
marginVertical: (geometry.trackHeight - geometry.hitHeight) / 2,
},
disabled ? styles.disabled : null,
style,
],
[disabled, geometry.reservedHeight, style],
[disabled, geometry.hitHeight, geometry.trackHeight, style],
);
return (
+6
View File
@@ -147,6 +147,7 @@ import { RenderProfile } from "@/utils/render-profiler";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { isWeb, isNative } from "@/constants/platform";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import type {
AttachmentMetadata,
ComposerAttachment,
@@ -295,6 +296,8 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
);
}
const EMPTY_METRICS: AgentMetric[] = [];
function buildAgentStateSelector(serverId: string, agentId: string) {
return (state: ReturnType<typeof useSessionStore.getState>) => {
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
@@ -303,6 +306,7 @@ function buildAgentStateSelector(serverId: string, agentId: string) {
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
model: agent?.model ?? null,
};
};
@@ -2225,6 +2229,7 @@ function ComposerContentImpl({
maxTokens={agentState.contextWindowMaxTokens}
usedTokens={agentState.contextWindowUsedTokens}
totalCostUsd={agentState.totalCostUsd}
sessionMetrics={agentState.sessionMetrics}
toolbarRing={TOOLBAR_RINGS[controlSizing]}
/>
</View>
@@ -2236,6 +2241,7 @@ function ComposerContentImpl({
agentState.contextWindowMaxTokens,
agentState.contextWindowUsedTokens,
agentState.totalCostUsd,
agentState.sessionMetrics,
controlSizing,
],
);
@@ -637,7 +637,7 @@ it("stores and expands identical content once across directory associations", as
});
it("coalesces missing bodies and keeps a newer pushed association when an older pull completes", async () => {
const { QueryClient } = await import("@tanstack/react-query");
const { QueryClient, QueryObserver } = await import("@tanstack/react-query");
const { applyProvidersSnapshotUpdate } = await import("./push-router");
const { fetchProvidersSnapshot, providersSnapshotQueryKey } =
await import("./providers-snapshot");
@@ -653,6 +653,16 @@ it("coalesces missing bodies and keeps a newer pushed association when an older
fetchedAt: { pi: fetchedAt },
requestId: hash,
});
// Announcements only download for directories a screen is showing.
const unsubscribers = ["/a", "/b", "/c"].map((cwd) => {
const queryKey = providersSnapshotQueryKey(serverId, cwd);
queryClient.setQueryData(queryKey, snapshot("seed"));
return new QueryObserver(queryClient, {
queryKey,
queryFn: async () => snapshot("seed"),
staleTime: Infinity,
}).subscribe(() => {});
});
let transfers = 0;
const client = {
async getProvidersSnapshot() {
@@ -776,6 +786,7 @@ it("coalesces missing bodies and keeps a newer pushed association when an older
entries: [{ models: [{ id: "shared" }] }],
});
} finally {
for (const unsubscribe of unsubscribers) unsubscribe();
queryClient.clear();
}
});
@@ -1,5 +1,5 @@
import { createRequire } from "node:module";
import { QueryClient, CancelledError } from "@tanstack/react-query";
import { QueryClient, CancelledError, QueryObserver } from "@tanstack/react-query";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { GetProvidersSnapshotResponseMessage } from "@getpaseo/protocol/messages";
import { compactProviderSnapshot } from "@getpaseo/protocol/provider-snapshot-codec";
@@ -307,6 +307,14 @@ describe("provider snapshot publication identity", () => {
snapshotHash: "next-hash",
compactSnapshot: compactProviderSnapshot([{ ...entries[0]!, label: "Updated provider" }]),
};
// Announcements only publish into a directory a screen is showing.
const shownKey = providersSnapshotQueryKey(serverId, snapshot.cwd);
queryClient.setQueryData(shownKey, snapshot);
const unsubscribe = new QueryObserver(queryClient, {
queryKey: shownKey,
queryFn: async () => snapshot,
staleTime: Infinity,
}).subscribe(() => {});
try {
for (const body of [snapshot, changed, changed]) {
await applyProvidersSnapshotUpdate({
@@ -325,6 +333,7 @@ describe("provider snapshot publication identity", () => {
expect(published.entries[0]!.models).toBe(canonical.entries[0]!.models);
}
} finally {
unsubscribe();
queryClient.clear();
}
});
+168 -1
View File
@@ -8,8 +8,12 @@ import { checkoutDiffQueryKey } from "@/git/query-keys";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { daemonConfigQueryKey } from "@/data/daemon-config";
import { daemonPairingOfferQueryKey } from "@/data/daemon-pairing";
import { providersSnapshotQueryKey } from "@/data/providers-snapshot";
import { providersSnapshotQuery, providersSnapshotQueryKey } from "@/data/providers-snapshot";
import { replicaQueryOptions } from "@/data/query";
import { createProviderSnapshotCache } from "@/data/provider-snapshot-cache";
import { draftAgentCommandsQueryKey } from "@/agent-commands/cache";
import {
applyProvidersSnapshotUpdate,
checkoutDiffPushRoute,
invalidateServerDataQueriesAfterReconnect,
mountServerDataPushRouter,
@@ -594,6 +598,13 @@ describe("server data push router", () => {
const serverId = "server-1";
const pairingOfferKey = daemonPairingOfferQueryKey(serverId);
queryClient.setQueryData(pairingOfferKey, { relayEnabled: true, url: "https://pairing" });
const snapshotKey = providersSnapshotQueryKey(serverId);
queryClient.setQueryData(snapshotKey, { entries: [], generatedAt: "seed", requestId: "seed" });
const unsubscribeSnapshot = new QueryObserver(queryClient, {
queryKey: snapshotKey,
queryFn: async () => ({ entries: [], generatedAt: "seed", requestId: "seed" }),
staleTime: Infinity,
}).subscribe(() => undefined);
const unmount = mountServerDataPushRouter({ client: fake.client, queryClient, serverId });
fake.emit(providerUpdate("2026-01-01T00:00:00.000Z"));
@@ -622,6 +633,7 @@ describe("server data push router", () => {
generatedAt: "2026-01-01T00:00:00.000Z",
requestId: "providers_snapshot_update",
});
unsubscribeSnapshot();
});
it.each(["base", "all"] as const)("routes %s diff snapshots and updates", (mode) => {
@@ -982,3 +994,158 @@ describe("server data push router", () => {
expect(queryClient.getQueryState(otherProviderKey)?.isInvalidated).toBe(false);
});
});
describe("applyProvidersSnapshotUpdate by observation", () => {
const serverId = "observed-host";
const cwd = "/repo";
function createStorage() {
const values = new Map<string, string>();
return {
values,
async getItem(key: string) {
return values.get(key) ?? null;
},
async setItem(key: string, value: string) {
values.set(key, value);
},
async removeItem(key: string) {
values.delete(key);
},
async getAllKeys() {
return [...values.keys()];
},
async multiGet(keys: readonly string[]) {
return keys.map((key) => [key, values.get(key) ?? null] as const);
},
async multiRemove(keys: readonly string[]) {
for (const key of keys) values.delete(key);
},
};
}
function snapshotFor(label: string) {
return {
requestId: label,
cwd,
entries: [
{
provider: "codex",
status: "ready",
enabled: true,
label,
models: [{ provider: "codex", id: label, label, thinkingOptions: [] }],
},
],
generatedAt: "2026-01-01T00:00:00.000Z",
} as never;
}
function setup() {
const storage = createStorage();
const cache = createProviderSnapshotCache(storage);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const calls: unknown[] = [];
let current = "v1";
const client = {
async getProvidersSnapshot(options?: unknown) {
calls.push(options);
return snapshotFor(current);
},
};
const observe = () =>
new QueryObserver(
queryClient,
replicaQueryOptions(
providersSnapshotQuery({ serverId, cwd, client: () => client, queryClient, cache }),
),
);
const announce = () =>
applyProvidersSnapshotUpdate({
serverId,
queryClient,
cache,
client,
message: {
type: "providers_snapshot_update",
payload: {
cwd,
entries: [],
snapshotHash: "hash-v2",
generatedAt: "2026-01-01T00:00:01Z",
},
} as never,
});
return {
queryClient,
calls,
storage,
observe,
announce,
setCurrent: (value: string) => {
current = value;
},
};
}
it("does nothing for a directory this client never opened", async () => {
const { queryClient, calls, storage, announce } = setup();
await announce();
expect(calls).toEqual([]);
expect(
queryClient.getQueryCache().find({ queryKey: providersSnapshotQueryKey(serverId, cwd) }),
).toBeUndefined();
expect(storage.values.size).toBe(0);
queryClient.clear();
});
it("marks an unobserved cached directory stale without downloading and refetches it on mount", async () => {
const { queryClient, calls, observe, announce, setCurrent } = setup();
const queryKey = providersSnapshotQueryKey(serverId, cwd);
const commandsKey = draftAgentCommandsQueryKey({
serverId,
draftConfig: { provider: "codex", cwd },
});
queryClient.setQueryData(queryKey, snapshotFor("v1"));
queryClient.setQueryData(commandsKey, [{ name: "review" }]);
setCurrent("v2");
await announce();
expect(calls).toEqual([]);
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true);
expect(queryClient.getQueryState(commandsKey)?.isInvalidated).toBe(true);
const observer = observe();
const unsubscribe = observer.subscribe(() => {});
await queryClient.getQueryCache().find({ queryKey })?.promise;
expect(calls).toHaveLength(1);
expect(
(queryClient.getQueryData(queryKey) as { entries: Array<{ label: string }> }).entries[0]!
.label,
).toBe("v2");
unsubscribe();
queryClient.clear();
});
it("keeps the reference-aware fetch for an observed directory", async () => {
const { queryClient, calls, observe, announce } = setup();
const queryKey = providersSnapshotQueryKey(serverId, cwd);
const observer = observe();
const unsubscribe = observer.subscribe(() => {});
await queryClient.getQueryCache().find({ queryKey })?.promise;
expect(calls).toHaveLength(1);
await announce();
// The announced hash is not resident, so exactly one content transfer is fetched and
// published to the observed query.
expect(calls).toHaveLength(2);
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false);
unsubscribe();
queryClient.clear();
});
});
+18 -1
View File
@@ -8,7 +8,10 @@ import type {
MutableDaemonConfig,
SessionOutboundMessage,
} from "@getpaseo/protocol/messages";
import { invalidateCommandsForProviderChange } from "@/agent-commands/cache";
import {
invalidateCommandsForDirectory,
invalidateCommandsForProviderChange,
} from "@/agent-commands/cache";
import { shareCheckoutDiff } from "@/git/diff-sharing";
import { orderCheckoutDiffFiles } from "@/git/diff-order";
import { daemonConfigQueryKey } from "@/data/daemon-config";
@@ -184,6 +187,20 @@ export async function applyProvidersSnapshotUpdate(input: {
const snapshot = { ...input.message.payload, requestId: "providers_snapshot_update" };
const cwd = normalizeProvidersSnapshotCwd(snapshot.cwd);
const queryKey = providersSnapshotQueryKey(input.serverId, cwd);
const cached = input.queryClient.getQueryCache().find({ queryKey, exact: true });
// Only a screen showing this directory is worth a download. A cached but unobserved
// directory refetches on its next mount; one this client never opened needs nothing.
if (!cached) return;
if (!cached.isActive()) {
await input.queryClient.cancelQueries({ queryKey, exact: true });
await input.queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "none" });
await invalidateCommandsForDirectory({
queryClient: input.queryClient,
serverId: input.serverId,
cwd,
});
return;
}
const previous = input.queryClient.getQueryData<{ entries: ProviderSnapshotEntry[] }>(queryKey);
let announcement: typeof snapshot | undefined = snapshot;
void input.queryClient.cancelQueries({ queryKey, exact: true });
+50
View File
@@ -0,0 +1,50 @@
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { replicaQueryOptions } from "./query";
function setup() {
const queryClient = new QueryClient();
const queryKey = ["replica", "value"] as const;
let fetches = 0;
const options = replicaQueryOptions({
queryKey,
pushEvent: "value_update",
queryFn: async () => {
fetches++;
return `fetch-${fetches}`;
},
});
return { queryClient, queryKey, options, fetchCount: () => fetches };
}
describe("replicaQueryOptions mount behavior", () => {
it("does not refetch on mount while the cached value is not invalidated", async () => {
const { queryClient, queryKey, options, fetchCount } = setup();
queryClient.setQueryData(queryKey, "cached");
const observer = new QueryObserver(queryClient, options);
const unsubscribe = observer.subscribe(() => {});
await Promise.resolve();
expect(fetchCount()).toBe(0);
expect(observer.getCurrentResult().data).toBe("cached");
unsubscribe();
queryClient.clear();
});
it("refetches on mount when the cached value was invalidated while unobserved", async () => {
const { queryClient, queryKey, options, fetchCount } = setup();
queryClient.setQueryData(queryKey, "cached");
await queryClient.invalidateQueries({ queryKey, refetchType: "none" });
expect(fetchCount()).toBe(0);
const observer = new QueryObserver(queryClient, options);
const unsubscribe = observer.subscribe(() => {});
await queryClient.getQueryCache().find({ queryKey })?.promise;
expect(fetchCount()).toBe(1);
expect(observer.getCurrentResult().data).toBe("fetch-1");
unsubscribe();
queryClient.clear();
});
});
+3 -1
View File
@@ -86,7 +86,9 @@ export function replicaQueryOptions<
},
},
queryFn: options.queryFn ?? skipToken,
refetchOnMount: false,
// Pushes keep a replica fresh; a mount only refetches what an invalidation marked stale
// while nothing observed it.
refetchOnMount: (query) => query.state.isInvalidated,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
@@ -0,0 +1,91 @@
import { useCallback } from "react";
import {
useActiveWorkspaceSelection,
type ActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { getFocusedWorkspaceSelection } from "@/navigation/workspace-route-navigation";
import { useSessionStore } from "@/stores/session-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
// The redirect compares descriptor ids; the route's id is not guaranteed to equal one (see
// use-global-workspace-pin-action.ts), so resolve it through the session store.
function readActiveDescriptorSelection(): ActiveWorkspaceSelection | null {
const selection = getFocusedWorkspaceSelection();
if (!selection) {
return null;
}
const workspaces = useSessionStore.getState().sessions[selection.serverId]?.workspaces;
const key = resolveWorkspaceMapKeyByIdentity({
workspaces,
workspaceId: selection.workspaceId,
});
const descriptor = key ? workspaces?.get(key) : undefined;
return descriptor ? { serverId: selection.serverId, workspaceId: descriptor.id } : null;
}
export interface ActiveWorkspaceArchive {
/** False when no workspace is routed, or the routed one is already archiving. */
canArchive: boolean;
/** Starts the archive for the routed workspace. Returns false when nothing was started. */
archive: () => boolean;
}
/**
* Archives the workspace the route points at. Keyed on the route selection rather than a rendered
* row, so it works from the keyboard shortcut and from the compact header menu alike.
*/
export function useActiveWorkspaceArchive(): ActiveWorkspaceArchive {
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
const routeWorkspaceId = selection?.workspaceId ?? null;
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
id: workspace.id,
workspaceKind: workspace.workspaceKind,
workspaceDirectory: workspace.workspaceDirectory,
name: workspace.name,
archivingAt: workspace.archivingAt,
diffStat: workspace.diffStat,
}));
// The archive starts after the host answers and you confirm, by which time the header that began
// it may be gone (a resize swaps it, and on native switching workspaces unmounts it), and you may
// have left workspace routes. So the redirect reads the focused route now, not this render's.
const redirectAfterArchive = useCallback((workspace: WorkspaceArchiveTarget) => {
redirectIfArchivingActiveWorkspace({
...workspace,
activeWorkspaceSelection: readActiveDescriptorSelection(),
});
}, []);
const archiveController = useWorkspaceArchive({
serverId: serverId ?? "",
workspaceId: fields?.id ?? "",
workspaceKind: fields?.workspaceKind ?? "directory",
workspaceDirectory: fields?.workspaceDirectory ?? "",
name: fields?.name ?? "",
diffStat: fields?.diffStat,
onArchiveStarted: redirectAfterArchive,
});
const canArchive = fields !== null && fields.archivingAt === null;
const archive = useCallback(() => {
if (!canArchive || !serverId) {
return false;
}
// Archiving hides its target immediately. Read the store in case this runs again before
// React renders that update.
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
return false;
}
archiveController.archive();
return true;
}, [archiveController, canArchive, fields, serverId]);
return { canArchive, archive };
}
@@ -1,11 +1,6 @@
import { useCallback } from "react";
import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
@@ -14,64 +9,13 @@ const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archi
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
// active route selection.
export function useGlobalWorkspaceArchiveAction() {
const selection = useActiveWorkspaceSelection();
const serverId = selection?.serverId ?? null;
const routeWorkspaceId = selection?.workspaceId ?? null;
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
id: workspace.id,
workspaceKind: workspace.workspaceKind,
workspaceDirectory: workspace.workspaceDirectory,
name: workspace.name,
archivingAt: workspace.archivingAt,
diffStat: workspace.diffStat,
}));
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
// the redirect compares against.
const activeWorkspaceId = fields?.id ?? null;
const redirectAfterArchive = useCallback(
(workspace: WorkspaceArchiveTarget) => {
redirectIfArchivingActiveWorkspace({
...workspace,
activeWorkspaceSelection:
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
});
},
[activeWorkspaceId, serverId],
);
const archiveController = useWorkspaceArchive({
serverId: serverId ?? "",
workspaceId: fields?.id ?? "",
workspaceKind: fields?.workspaceKind ?? "directory",
workspaceDirectory: fields?.workspaceDirectory ?? "",
name: fields?.name ?? "",
diffStat: fields?.diffStat,
onArchiveStarted: redirectAfterArchive,
});
const canArchive = fields !== null && fields.archivingAt === null;
const handle = useCallback(() => {
if (!canArchive || !serverId) {
return false;
}
// Archiving hides its target immediately. Read the store in case the shortcut
// runs again before React renders that update.
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
return false;
}
archiveController.archive();
return true;
}, [archiveController, canArchive, fields, serverId]);
const { canArchive, archive } = useActiveWorkspaceArchive();
useKeyboardActionHandler({
handlerId: "workspace-archive-global",
actions: WORKSPACE_ARCHIVE_ACTIONS,
enabled: canArchive,
priority: 0,
handle,
handle: archive,
});
}
@@ -352,6 +352,19 @@ describe("applyProvidersSnapshotUpdate", () => {
queryClient = new QueryClient();
});
// Announcements only download for directories a screen is showing, so these tests mount one.
function showSnapshot(cwd?: string) {
const queryKey = providersSnapshotQueryKey(serverId, cwd);
if (queryClient.getQueryData(queryKey) === undefined) {
queryClient.setQueryData(queryKey, providersSnapshot([]));
}
return new QueryObserver(queryClient, {
queryKey,
queryFn: async () => providersSnapshot([]),
staleTime: Infinity,
}).subscribe(() => {});
}
function updateMessage(entries: ProviderSnapshotEntry[], cwd?: string): ProvidersSnapshotUpdate {
return {
type: "providers_snapshot_update",
@@ -364,6 +377,7 @@ describe("applyProvidersSnapshotUpdate", () => {
}
it("refreshes active commands only when their provider changes after discovery", async () => {
showSnapshot("/repo-a");
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
let requests = 0;
const observer = new QueryObserver(queryClient, {
@@ -447,6 +461,7 @@ describe("applyProvidersSnapshotUpdate", () => {
});
it("retries a failed command discovery when its provider first becomes ready", async () => {
showSnapshot("/repo-a");
const key = sessionAgentCommandsQueryKey({ serverId, agentId: "agent-1" });
let ready = false;
let requests = 0;
@@ -493,6 +508,7 @@ describe("applyProvidersSnapshotUpdate", () => {
providersSnapshotQueryKey(serverId, "/repo-a"),
providersSnapshot([codexEntry("ready", [readyCodexModel])]),
);
showSnapshot("/repo-a");
const send = (label: string) =>
applyProvidersSnapshotUpdate({
client: createClient(),
@@ -511,6 +527,7 @@ describe("applyProvidersSnapshotUpdate", () => {
});
it("routes updates to the home query cache when the message carries no cwd", async () => {
showSnapshot();
await applyProvidersSnapshotUpdate({
client: createClient(),
serverId,
@@ -527,6 +544,7 @@ describe("applyProvidersSnapshotUpdate", () => {
it("routes workspace updates to the matching scope without touching siblings", async () => {
queryClient.setQueryData(providersSnapshotQueryKey(serverId, "/repo-b"), providersSnapshot([]));
showSnapshot("/repo-a");
await applyProvidersSnapshotUpdate({
client: createClient(),
@@ -546,6 +564,7 @@ describe("applyProvidersSnapshotUpdate", () => {
});
it("persists compact push updates", async () => {
showSnapshot("/repo-a");
const entries = [codexEntry("ready", [readyCodexModel])];
const compactSnapshot = compactProviderSnapshot(entries);
const cache = createCache();
@@ -579,6 +598,7 @@ describe("applyProvidersSnapshotUpdate", () => {
providersSnapshotQueryKey(serverId, workspaceCwd),
providersSnapshot([codexEntry("loading")]),
);
showSnapshot(workspaceCwd);
await applyProvidersSnapshotUpdate({
client: createClient(),
@@ -606,6 +626,7 @@ describe("applyProvidersSnapshotUpdate", () => {
providersSnapshotQueryKey(serverId, "/repo-a"),
providersSnapshot([codexEntry("ready")]),
);
showSnapshot("/repo-a");
await applyProvidersSnapshotUpdate({
client: createClient(),
@@ -331,7 +331,7 @@ describe("loadAppSettingsFromStorage", () => {
pins: null,
serverId: null,
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
const deps = makeDeps({
@@ -357,7 +357,7 @@ describe("loadAppSettingsFromStorage", () => {
],
serverId: "server",
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
});
@@ -374,7 +374,7 @@ describe("loadAppSettingsFromStorage", () => {
pins: [],
serverId: "server",
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
});
@@ -396,7 +396,7 @@ describe("loadAppSettingsFromStorage", () => {
pins: [{ sourceId: "claude", windowId: "weekly" }],
serverId: null,
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
});
+8 -2
View File
@@ -349,6 +349,7 @@ export const ar: TranslationResources = {
copyTurn: "نسخ بدوره",
copyMessage: "انسخ الرسالة",
forkMenu: "تفريع الرسالة",
turnStats: "إحصاءات الدور",
forkInNewTab: "تفريع في تبويب جديد",
forkInNewWorkspace: "تفريع في مساحة عمل جديدة",
forkUnavailable: "حدّث المضيف لاستخدام هذا.",
@@ -2264,7 +2265,11 @@ export const ar: TranslationResources = {
title: "استخدام الخطة",
refresh: "تحديث",
reorderCard: "إعادة ترتيب {{source}}",
showCard: "إظهار {{source}}",
sources: "المصادر",
sourcesCount: "{{shown}} من {{total}}",
providerInactive: "المزود غير نشط",
allSourcesHidden: "لا توجد مصادر استخدام معروضة",
chooseSources: "اختيار المصادر",
refreshAll: "تحديث الكل",
refreshing: "جارٍ التحديث...",
loading: "جارٍ تحميل بيانات الاستخدام...",
@@ -3113,6 +3118,7 @@ export const ar: TranslationResources = {
status: "حالة المزود",
checked: "تم الفحص {{time}}",
diagnosticReport: "تقرير التشخيص",
docs: "الوثائق",
dangerZone: "منطقة الخطر",
removeHint: "يحذف هذا المزود من config.json",
},
@@ -3158,7 +3164,7 @@ export const ar: TranslationResources = {
noSearchMatches: "لا توجد نماذج تطابق بحثك",
noneDetected: "لم يتم اكتشاف أي نماذج",
noCustom: "لا توجد نماذج مخصصة",
discovered: "اكتشف",
title: "النماذج",
custom: "نماذج مخصصة",
updated: "تم تحديث{{time}}",
},
+8 -2
View File
@@ -348,6 +348,7 @@ export const en = {
copyTurn: "Copy turn",
copyMessage: "Copy message",
forkMenu: "Fork chat from here",
turnStats: "Turn stats",
forkInNewTab: "Fork in a new tab",
forkInNewWorkspace: "Fork in a new workspace",
forkUnavailable: "Update the host to use this.",
@@ -2292,7 +2293,11 @@ export const en = {
title: "Plan usage",
refresh: "Refresh",
reorderCard: "Reorder {{source}}",
showCard: "Show {{source}}",
sources: "Sources",
sourcesCount: "{{shown}} of {{total}}",
providerInactive: "Provider inactive",
allSourcesHidden: "No usage sources shown",
chooseSources: "Choose sources",
refreshAll: "Refresh all",
refreshing: "Refreshing...",
loading: "Loading usage...",
@@ -3211,6 +3216,7 @@ export const en = {
status: "Provider status",
checked: "Checked {{time}}",
diagnosticReport: "Diagnostic report",
docs: "Docs",
dangerZone: "Danger zone",
removeHint: "Deletes this provider from config.json",
},
@@ -3256,7 +3262,7 @@ export const en = {
noSearchMatches: "No models match your search",
noneDetected: "No models detected",
noCustom: "No custom models",
discovered: "Discovered",
title: "Models",
custom: "Custom models",
updated: "Updated {{time}}",
},
+8 -2
View File
@@ -354,6 +354,7 @@ export const es: TranslationResources = {
copyTurn: "Copiar turno",
copyMessage: "Copiar mensaje",
forkMenu: "Bifurcar mensaje",
turnStats: "Estadísticas del turno",
forkInNewTab: "Bifurcar en una pestaña nueva",
forkInNewWorkspace: "Bifurcar en un espacio de trabajo nuevo",
forkUnavailable: "Actualiza el host para usar esto.",
@@ -2313,7 +2314,11 @@ export const es: TranslationResources = {
title: "Uso del plan",
refresh: "Actualizar",
reorderCard: "Reordenar {{source}}",
showCard: "Mostrar {{source}}",
sources: "Fuentes",
sourcesCount: "{{shown}} de {{total}}",
providerInactive: "Proveedor inactivo",
allSourcesHidden: "No hay fuentes de uso visibles",
chooseSources: "Elegir fuentes",
refreshAll: "Actualizar todo",
refreshing: "Actualizando...",
loading: "Cargando uso...",
@@ -3141,6 +3146,7 @@ export const es: TranslationResources = {
status: "Estado del proveedor",
checked: "Comprobado {{time}}",
diagnosticReport: "Informe de diagnóstico",
docs: "Documentación",
dangerZone: "Zona de peligro",
removeHint: "Elimina este proveedor de config.json",
},
@@ -3186,7 +3192,7 @@ export const es: TranslationResources = {
noSearchMatches: "Ningún modelo coincide con tu búsqueda",
noneDetected: "No se detectaron modelos",
noCustom: "No hay modelos personalizados",
discovered: "descubierto",
title: "Modelos",
custom: "Modelos personalizados",
updated: "{{time}}actualizado",
},
+8 -2
View File
@@ -354,6 +354,7 @@ export const fr: TranslationResources = {
copyTurn: "Copier l’échange",
copyMessage: "Copier le message",
forkMenu: "Forker la conversation à partir d’ici",
turnStats: "Statistiques de l’échange",
forkInNewTab: "Forker dans un nouvel onglet",
forkInNewWorkspace: "Forker dans un nouvel espace de travail",
forkUnavailable: "Mettez à jour l’hôte pour utiliser cette fonction.",
@@ -2314,7 +2315,11 @@ export const fr: TranslationResources = {
title: "Utilisation du forfait",
refresh: "Actualiser",
reorderCard: "Réorganiser {{source}}",
showCard: "Afficher {{source}}",
sources: "Sources",
sourcesCount: "{{shown}} sur {{total}}",
providerInactive: "Fournisseur inactif",
allSourcesHidden: "Aucune source d'utilisation affichée",
chooseSources: "Choisir les sources",
refreshAll: "Tout actualiser",
refreshing: "Actualisation...",
loading: "Chargement de l’utilisation...",
@@ -3147,6 +3152,7 @@ export const fr: TranslationResources = {
status: "État du fournisseur",
checked: "Vérifié {{time}}",
diagnosticReport: "Rapport de diagnostic",
docs: "Documentation",
dangerZone: "Zone de danger",
removeHint: "Supprime ce fournisseur de config.json",
},
@@ -3193,7 +3199,7 @@ export const fr: TranslationResources = {
noSearchMatches: "Aucun modèle ne correspond à votre recherche",
noneDetected: "Aucun modèle détecté",
noCustom: "Aucun modèle personnalisé",
discovered: "Détectés",
title: "Modèles",
custom: "Modèles personnalisés",
updated: "Mis à jour {{time}}",
},
+8 -2
View File
@@ -354,6 +354,7 @@ export const ja: TranslationResources = {
copyTurn: "ターンをコピー",
copyMessage: "メッセージをコピー",
forkMenu: "メッセージをフォーク",
turnStats: "ターンの統計",
forkInNewTab: "新しいタブにフォーク",
forkInNewWorkspace: "新しいワークスペースにフォーク",
forkUnavailable: "これを使用するにはホストを更新してください。",
@@ -2287,7 +2288,11 @@ export const ja: TranslationResources = {
title: "プラン使用量",
refresh: "更新",
reorderCard: "{{source}} を並べ替え",
showCard: "{{source}} を表示",
sources: "ソース",
sourcesCount: "{{shown}} / {{total}}",
providerInactive: "プロバイダー無効",
allSourcesHidden: "表示中の使用量ソースはありません",
chooseSources: "ソースを選択",
refreshAll: "すべて更新",
refreshing: "更新中...",
loading: "使用状況を読み込み中...",
@@ -3109,6 +3114,7 @@ export const ja: TranslationResources = {
status: "プロバイダーの状態",
checked: "{{time}}に確認",
diagnosticReport: "診断レポート",
docs: "ドキュメント",
dangerZone: "危険な操作",
removeHint: "このプロバイダーを config.json から削除します",
},
@@ -3154,7 +3160,7 @@ export const ja: TranslationResources = {
noSearchMatches: "検索に一致するモデルがありません",
noneDetected: "モデルが検出されませんでした",
noCustom: "カスタムモデルはありません",
discovered: "検出済み",
title: "モデル",
custom: "カスタムモデル",
updated: "{{time}}に更新",
},
+8 -2
View File
@@ -350,6 +350,7 @@ export const ko: TranslationResources = {
copyTurn: "턴 복사",
copyMessage: "메시지 복사",
forkMenu: "여기에서 채팅 분기",
turnStats: "턴 통계",
forkInNewTab: "새 탭으로 분기",
forkInNewWorkspace: "새 워크스페이스로 분기",
forkUnavailable: "이를 사용하려면 호스트를 업데이트하세요.",
@@ -2275,7 +2276,11 @@ export const ko: TranslationResources = {
title: "플랜 사용량",
refresh: "새로 고침",
reorderCard: "{{source}} 순서 변경",
showCard: "{{source}} 표시",
sources: "소스",
sourcesCount: "{{shown}} / {{total}}",
providerInactive: "제공업체 비활성",
allSourcesHidden: "표시된 사용량 소스가 없습니다",
chooseSources: "소스 선택",
refreshAll: "모두 새로 고침",
refreshing: "새로 고치는 중...",
loading: "사용량 불러오는 중...",
@@ -3094,6 +3099,7 @@ export const ko: TranslationResources = {
status: "프로바이더 상태",
checked: "{{time}} 확인됨",
diagnosticReport: "진단 보고서",
docs: "문서",
dangerZone: "위험 구역",
removeHint: "config.json에서 이 프로바이더를 삭제합니다",
},
@@ -3140,7 +3146,7 @@ export const ko: TranslationResources = {
noSearchMatches: "검색과 일치하는 모델이 없습니다",
noneDetected: "감지된 모델이 없습니다",
noCustom: "사용자 지정 모델 없음",
discovered: "발견됨",
title: "모델",
custom: "사용자 지정 모델",
updated: "{{time}} 업데이트됨",
},
+8 -2
View File
@@ -353,6 +353,7 @@ export const ptBR: TranslationResources = {
copyTurn: "Copiar turno",
copyMessage: "Copiar mensagem",
forkMenu: "Bifurcar mensagem",
turnStats: "Estatísticas do turno",
forkInNewTab: "Bifurcar em uma nova aba",
forkInNewWorkspace: "Bifurcar em um novo workspace",
forkUnavailable: "Atualize o host para usar isto.",
@@ -2298,7 +2299,11 @@ export const ptBR: TranslationResources = {
title: "Uso do plano",
refresh: "Atualizar",
reorderCard: "Reordenar {{source}}",
showCard: "Mostrar {{source}}",
sources: "Fontes",
sourcesCount: "{{shown}} de {{total}}",
providerInactive: "Provedor inativo",
allSourcesHidden: "Nenhuma fonte de uso exibida",
chooseSources: "Escolher fontes",
refreshAll: "Atualizar tudo",
refreshing: "Atualizando...",
loading: "Carregando uso...",
@@ -3122,6 +3127,7 @@ export const ptBR: TranslationResources = {
status: "Status do provedor",
checked: "Verificado {{time}}",
diagnosticReport: "Relatório de diagnóstico",
docs: "Documentação",
dangerZone: "Zona de perigo",
removeHint: "Exclui este provedor do config.json",
},
@@ -3167,7 +3173,7 @@ export const ptBR: TranslationResources = {
noSearchMatches: "Nenhum modelo corresponde à sua busca",
noneDetected: "Nenhum modelo detectado",
noCustom: "Nenhum modelo personalizado",
discovered: "Descobertos",
title: "Modelos",
custom: "Modelos personalizados",
updated: "Atualizado {{time}}",
},
+8 -2
View File
@@ -353,6 +353,7 @@ export const ru: TranslationResources = {
copyTurn: "Скопировать ответ",
copyMessage: "Копировать сообщение",
forkMenu: "Форкнуть чат отсюда",
turnStats: "Статистика ответа",
forkInNewTab: "Создать форк в новой вкладке",
forkInNewWorkspace: "Создать форк в новом рабочем пространстве",
forkUnavailable: "Обновите хост, чтобы использовать эту функцию.",
@@ -2300,7 +2301,11 @@ export const ru: TranslationResources = {
title: "Использование плана",
refresh: "Обновить",
reorderCard: "Переместить {{source}}",
showCard: "Показывать {{source}}",
sources: "Источники",
sourcesCount: "{{shown}} из {{total}}",
providerInactive: "Провайдер неактивен",
allSourcesHidden: "Источники использования скрыты",
chooseSources: "Выбрать источники",
refreshAll: "Обновить всё",
refreshing: "Обновление...",
loading: "Загрузка данных об использовании...",
@@ -3133,6 +3138,7 @@ export const ru: TranslationResources = {
status: "Состояние провайдера",
checked: "Проверено {{time}}",
diagnosticReport: "Диагностический отчёт",
docs: "Документация",
dangerZone: "Опасная зона",
removeHint: "Удаляет этого провайдера из config.json",
},
@@ -3179,7 +3185,7 @@ export const ru: TranslationResources = {
noSearchMatches: "Ни одна модель не соответствует вашему запросу",
noneDetected: "Модели не обнаружены",
noCustom: "Нет пользовательских моделей",
discovered: "Обнаруженные модели",
title: "Модели",
custom: "Пользовательские модели",
updated: "Обновлено {{time}}",
},
+8 -2
View File
@@ -349,6 +349,7 @@ export const zhCN: TranslationResources = {
copyTurn: "复制回合",
copyMessage: "复制消息",
forkMenu: "分叉消息",
turnStats: "回合统计",
forkInNewTab: "分叉到新标签页",
forkInNewWorkspace: "分叉到新工作区",
forkUnavailable: "请更新主机以使用此功能。",
@@ -2241,7 +2242,11 @@ export const zhCN: TranslationResources = {
title: "套餐用量",
refresh: "刷新",
reorderCard: "重新排序 {{source}}",
showCard: "显示 {{source}}",
sources: "来源",
sourcesCount: "{{shown}} / {{total}}",
providerInactive: "提供商未启用",
allSourcesHidden: "未显示任何用量来源",
chooseSources: "选择来源",
refreshAll: "全部刷新",
refreshing: "刷新中...",
loading: "正在加载用量...",
@@ -3042,6 +3047,7 @@ export const zhCN: TranslationResources = {
status: "Provider 状态",
checked: "{{time}}检查",
diagnosticReport: "诊断报告",
docs: "文档",
dangerZone: "危险操作",
removeHint: "从 config.json 中删除此 Provider",
},
@@ -3087,7 +3093,7 @@ export const zhCN: TranslationResources = {
noSearchMatches: "没有匹配搜索的 Model",
noneDetected: "未检测到 Model",
noCustom: "没有自定义模型",
discovered: "已发现",
title: "Models",
custom: "自定义 Models",
updated: "已更新 {{time}}",
},
@@ -1,17 +1,22 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { NavigationContainerRefWithCurrent } from "expo-router/react-navigation";
import {
getFocusedWorkspaceSelection,
navigateToHostWorkspaceRoute,
registerWorkspaceRouteNavigationRef,
} from "./workspace-route-navigation";
function createNavigationRef(rootState: unknown, options: { ready?: boolean } = {}) {
function createNavigationRef(
rootState: unknown,
options: { ready?: boolean; currentRoute?: { name: string; params?: object } } = {},
) {
const dispatch = vi.fn();
let ready = options.ready ?? true;
const readyListeners = new Set<() => void>();
const navigation = {
isReady: () => ready,
getRootState: () => rootState,
getCurrentRoute: () => options.currentRoute,
dispatch,
addListener: (event: string, listener: () => void) => {
if (event === "ready") readyListeners.add(listener);
@@ -215,3 +220,27 @@ describe("navigateToHostWorkspaceRoute", () => {
expect(dismissTo).toHaveBeenCalledWith("/h/server-1/workspace/workspace-a");
});
});
describe("getFocusedWorkspaceSelection", () => {
function focus(currentRoute?: { name: string; params?: object }) {
registerWorkspaceRouteNavigationRef(createNavigationRef({}, { currentRoute }).navigationRef);
}
it("returns the workspace on screen", () => {
focus({
name: "workspace/[workspaceId]/index",
params: { serverId: "server-1", workspaceId: "workspace-a" },
});
expect(getFocusedWorkspaceSelection()).toEqual({
serverId: "server-1",
workspaceId: "workspace-a",
});
});
it("returns null when a non-workspace screen is focused", () => {
focus({ name: "settings/[section]", params: { section: "general" } });
expect(getFocusedWorkspaceSelection()).toBeNull();
});
});
@@ -5,6 +5,7 @@ import type {
} from "expo-router/react-navigation";
import { router, type Href } from "expo-router";
import {
decodeWorkspaceIdFromPathSegment,
encodeWorkspaceIdForPathSegment,
getHostWorkspaceOpenParamFromPathname,
parseHostWorkspaceRouteFromPathname,
@@ -39,6 +40,27 @@ export function registerWorkspaceRouteNavigationRef(
};
}
/**
* The workspace on screen right now, read from the focused route, or null on any other screen
* (Settings, New workspace, ...). Unlike a component's last render, it stays correct for work that
* finishes after the screen that started it is gone.
*/
export function getFocusedWorkspaceSelection(): { serverId: string; workspaceId: string } | null {
// Typed routes narrow the container's route to `never`; this only reads name and params.
const route = rootNavigationRef?.current?.getCurrentRoute() as
| { name: string; params?: { serverId?: unknown; workspaceId?: unknown } }
| undefined;
if (route?.name !== HOST_WORKSPACE_ROUTE_NAME) {
return null;
}
const params = route.params;
if (typeof params?.serverId !== "string" || typeof params.workspaceId !== "string") {
return null;
}
const workspaceId = decodeWorkspaceIdFromPathSegment(params.workspaceId);
return workspaceId ? { serverId: params.serverId, workspaceId } : null;
}
interface MountedRouteStack {
key: string;
focusedRouteName: string | null;
@@ -1,44 +1,53 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { SettingsDetailHeader } from "@/components/settings";
import { useIsCompactFormFactor } from "@/constants/layout";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { ProviderDetail, useProviderDetail } from "./provider-detail";
import { ProviderGlyph } from "./provider-glyph";
/**
* A provider's detail as a Settings page, shaped like a project's: the screen titles it
* "Providers", the page names the provider. On wide layouts the page has no back button of its
* own, so it draws "Back to providers".
* A provider's detail as a Settings page, shaped like a project's. On wide layouts the page is
* titled "Providers > name" and "Providers" goes back. On compact layouts the screen titles it
* "Providers" and the page names the provider.
*/
export function ProviderDetailPage({
serverId,
provider,
onBack,
showBack,
}: {
serverId: string;
provider: string;
onBack: () => void;
showBack: boolean;
}) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const detail = useProviderDetail({ serverId, provider, onRemoved: onBack });
const back = useMemo(
const parent = useMemo(
() => ({
label: t("settings.providers.detail.backToProviders"),
label: t("settings.hostSections.providers"),
accessibilityLabel: t("settings.providers.detail.backToProviders"),
onPress: onBack,
testID: "provider-detail-back",
}),
[onBack, t],
);
const icon = useMemo(
() => <ProviderGlyph serverId={serverId} provider={provider} />,
[provider, serverId],
() => (
<ThemedProviderGlyph
serverId={serverId}
provider={provider}
uniProps={isCompact ? rowTitleSize : pageTitleSize}
/>
),
[isCompact, provider, serverId],
);
return (
<View testID="provider-detail-page">
<SettingsDetailHeader
back={showBack ? back : undefined}
parent={parent}
icon={icon}
title={detail.label}
titleTestID="provider-detail-title"
@@ -47,3 +56,8 @@ export function ProviderDetailPage({
</View>
);
}
// The glyph is as large as the name beside it. The page title scales with the interface size.
const ThemedProviderGlyph = withUnistyles(ProviderGlyph);
const pageTitleSize = (theme: Theme) => ({ size: theme.fontSize["4xl"] });
const rowTitleSize = () => ({ size: ICON_SIZE.md });
@@ -14,9 +14,9 @@ import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { readAcpProviderInstallGuide } from "@/hooks/use-acp-provider-catalog";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useTimeAgo } from "@/hooks/use-time-ago";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import { openExternalUrl } from "@/utils/open-external-url";
import {
readDetailPresence,
readDetailSections,
@@ -27,6 +27,7 @@ import { DiagnosticSheet } from "./diagnostic-sheet";
import { useProviderConfigActions, type ProviderEntry } from "./provider-config";
import { ProviderModels } from "./provider-models";
import { ProviderNotice } from "./provider-notice";
import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh";
export interface ProviderDetailState {
provider: string;
@@ -81,6 +82,9 @@ export function useProviderDetail({
/**
* Everything about one provider, top to bottom: what is wrong, whether it runs, its installation,
* its models, then the rare actions. The page and the sheet frame the same body.
*
* Refresh sits with the model list, which is what it is most often pressed for. A provider that
* lists no models of its own keeps it under Troubleshooting.
*/
export function ProviderDetail({
serverId,
@@ -106,6 +110,13 @@ export function ProviderDetail({
installGuide: readAcpProviderInstallGuide(provider),
});
const sections = readDetailSections(entry, shownInstallation);
const listsModels = sections.models === "all";
const providerRefresh: ProviderRefresh = {
checkedAt: entry.fetchedAt,
// The probe running again is a refresh too, whoever asked for it.
busy: isRefreshing || installation.refreshing || entry.status === "loading",
run: handleRefresh,
};
return (
<View testID="provider-detail">
@@ -117,13 +128,16 @@ export function ProviderDetail({
action={installation.action}
/>
{sections.models ? (
<ProviderModels serverId={serverId} entry={entry} discovered={sections.models === "all"} />
<ProviderModels
serverId={serverId}
entry={entry}
refresh={listsModels ? providerRefresh : null}
/>
) : null}
<Troubleshooting
serverId={serverId}
entry={entry}
refreshing={isRefreshing || installation.refreshing}
onRefresh={handleRefresh}
refresh={listsModels ? null : providerRefresh}
/>
{/* Config no longer owns a provider whose removal has succeeded. */}
{detail.removing || detail.canRemove(entry) ? (
@@ -182,42 +196,39 @@ function EnabledCard({ serverId, entry }: { serverId: string; entry: ProviderEnt
function Troubleshooting({
serverId,
entry,
refreshing,
onRefresh,
refresh,
}: {
serverId: string;
entry: ProviderEntry;
refreshing: boolean;
onRefresh: () => void;
/** Null when the model list carries Refresh. */
refresh: ProviderRefresh | null;
}) {
const { t } = useTranslation();
const [diagnosticOpen, setDiagnosticOpen] = useState(false);
const openDiagnostic = useCallback(() => setDiagnosticOpen(true), []);
const closeDiagnostic = useCallback(() => setDiagnosticOpen(false), []);
const checked = useTimeAgo(entry.fetchedAt ? new Date(entry.fetchedAt) : null);
// The probe running again is a refresh too, whoever asked for it.
const busy = refreshing || entry.status === "loading";
const docsUrl = entry.docsUrl;
const openDocs = useCallback(() => {
if (docsUrl) void openExternalUrl(docsUrl);
}, [docsUrl]);
return (
<SettingsSection title={t("settings.providers.detail.troubleshooting")}>
<SettingsCard>
<SettingsRow
label={t("settings.providers.detail.status")}
hint={
entry.fetchedAt ? t("settings.providers.detail.checked", { time: checked }) : undefined
}
>
<Button variant="outline" onPress={onRefresh} loading={busy} testID="provider-refresh">
{busy
? t("settings.providers.diagnostic.refreshing")
: t("settings.providers.diagnostic.refresh")}
</Button>
</SettingsRow>
{refresh ? <ProviderStatusRow refresh={refresh} /> : null}
<SettingsDetailRow
label={t("settings.providers.detail.diagnosticReport")}
onPress={openDiagnostic}
testID="provider-diagnostic-report"
/>
{docsUrl ? (
<SettingsDetailRow
label={t("settings.providers.detail.docs")}
onPress={openDocs}
external
testID="provider-docs"
/>
) : null}
</SettingsCard>
<DiagnosticSheet
serverId={serverId}
@@ -229,6 +240,16 @@ function Troubleshooting({
);
}
function ProviderStatusRow({ refresh }: { refresh: ProviderRefresh }) {
const { t } = useTranslation();
const checked = useCheckedLabel(refresh);
return (
<SettingsRow label={t("settings.providers.detail.status")} hint={checked}>
<ProviderRefreshButton refresh={refresh} form="labelled" />
</SettingsRow>
);
}
function DangerZone({ removing, onRemove }: { removing: boolean; onRemove: () => void }) {
const { t } = useTranslation();
return (
@@ -2,10 +2,18 @@ import { StyleSheet } from "react-native-unistyles";
import { useProviderIcon } from "@/components/provider-icons";
import { ICON_SIZE } from "@/styles/theme";
/** A provider's icon at row size, drawn in the foreground colour. */
export function ProviderGlyph({ serverId, provider }: { serverId: string; provider: string }) {
/** A provider's icon in the foreground colour, at row size unless the caller names another. */
export function ProviderGlyph({
serverId,
provider,
size = ICON_SIZE.md,
}: {
serverId: string;
provider: string;
size?: number;
}) {
const Icon = useProviderIcon(provider, serverId);
return <Icon size={ICON_SIZE.md} color={styles.glyph.color} />;
return <Icon size={size} color={styles.glyph.color} />;
}
const styles = StyleSheet.create((theme) => ({
@@ -1,7 +1,7 @@
import { Plus, Trash2 } from "lucide-react-native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { ScrollView, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types";
import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config";
@@ -26,6 +26,7 @@ import {
type ProviderDiscoveredModelsCache,
} from "./discovered-models";
import type { ProviderEntry } from "./provider-config";
import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh";
const ThemedTrash = withUnistyles(Trash2);
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
@@ -51,15 +52,19 @@ function rankModels<T>(items: T[], query: string, fields: (item: T) => string[])
export function ProviderModels({
serverId,
entry,
discovered,
refresh,
}: {
serverId: string;
entry: ProviderEntry;
/** List the models the provider reports, with search. Only a running provider reports them. */
discovered: boolean;
/**
* Lists the models the provider reports, with search and the way to ask for them again. Null for
* a provider that is not running, which reports none.
*/
refresh: ProviderRefresh | null;
}) {
const { t } = useTranslation();
const provider = entry.provider;
const discovered = refresh !== null;
const { config, patchConfig } = useDaemonConfig(serverId);
const [query, setQuery] = useState("");
const [addSheetOpen, setAddSheetOpen] = useState(false);
@@ -130,10 +135,8 @@ export function ProviderModels({
const discoveredTrailing = useMemo(
() =>
discoveredModels.length > 0 ? (
<Text style={settingsStyles.sectionHeaderTitle}>{discoveredModels.length}</Text>
) : null,
[discoveredModels.length],
refresh ? <DiscoveredTrailing count={discoveredModels.length} refresh={refresh} /> : null,
[discoveredModels.length, refresh],
);
let discoveredBody: React.ReactNode;
@@ -173,23 +176,29 @@ export function ProviderModels({
return (
<View testID="provider-models">
{discovered ? (
<>
<View style={styles.searchRail}>
<SettingsSection title={t("settings.providers.models.title")} trailing={discoveredTrailing}>
<View style={styles.searchRow}>
<SearchField
value={query}
onChangeText={setQuery}
placeholder={t("settings.providers.models.searchPlaceholder")}
clearAccessibilityLabel={t("sessions.actions.clearSearch")}
fullWidth
testID="provider-settings-search"
/>
</View>
<SettingsSection
title={t("settings.providers.models.discovered")}
trailing={discoveredTrailing}
>
<View style={settingsStyles.card}>{discoveredBody}</View>
</SettingsSection>
</>
<View style={settingsStyles.card}>
{/* A provider can report hundreds of models; the rest of the page stays in reach. */}
<ScrollView
style={styles.discoveredList}
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
nestedScrollEnabled
testID="provider-discovered-models"
>
{discoveredBody}
</ScrollView>
</View>
</SettingsSection>
) : null}
<SettingsSection title={t("settings.providers.models.custom")} trailing={customTrailing}>
<View style={settingsStyles.card}>{customBody}</View>
@@ -205,6 +214,22 @@ export function ProviderModels({
);
}
/** How many models the provider reports, when it last reported them, and the way to ask again. */
function DiscoveredTrailing({ count, refresh }: { count: number; refresh: ProviderRefresh }) {
const checked = useCheckedLabel(refresh);
const facts = [count > 0 ? String(count) : null, checked].filter(Boolean).join(" · ");
return (
<View style={styles.headerTrailing}>
{facts ? (
<Text style={[settingsStyles.sectionHeaderTitle, styles.headerFacts]} numberOfLines={1}>
{facts}
</Text>
) : null}
<ProviderRefreshButton refresh={refresh} form="icon" />
</View>
);
}
function MutedRow({ children }: { children: string }) {
return (
<View style={styles.modelRow}>
@@ -367,15 +392,23 @@ function AddCustomModelSheet({
const ADD_SNAP_POINTS = ["40%"];
const styles = StyleSheet.create((theme) => ({
searchRail: {
// The search field sizes itself along a row.
searchRow: {
flexDirection: "row",
marginBottom: theme.spacing[3],
},
// Nine rows and part of a tenth, so a longer list visibly continues.
discoveredList: {
maxHeight: 320,
},
headerTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
// The facts give way before the button does.
headerFacts: {
flexShrink: 1,
},
modelRow: {
flexDirection: "row",
alignItems: "center",
@@ -0,0 +1,55 @@
import { RotateCw } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { useTimeAgo } from "@/hooks/use-time-ago";
/** Asking the provider again for its status, version and models. */
export interface ProviderRefresh {
/** When the provider last answered. Absent before its first answer. */
checkedAt: string | undefined;
/** A check is running, whoever asked for it. */
busy: boolean;
run: () => void;
}
/** "Checked 5m ago", kept current, or nothing before the provider's first answer. */
export function useCheckedLabel(refresh: ProviderRefresh): string | undefined {
const { t } = useTranslation();
const time = useTimeAgo(refresh.checkedAt ? new Date(refresh.checkedAt) : null);
return refresh.checkedAt ? t("settings.providers.detail.checked", { time }) : undefined;
}
export function ProviderRefreshButton({
refresh,
form,
}: {
refresh: ProviderRefresh;
/** `icon` in a section header, `labelled` in a row. */
form: "icon" | "labelled";
}) {
const { t } = useTranslation();
const label = refresh.busy
? t("settings.providers.diagnostic.refreshing")
: t("settings.providers.diagnostic.refresh");
if (form === "icon")
return (
<Button
variant="ghost"
leftIcon={RotateCw}
onPress={refresh.run}
loading={refresh.busy}
accessibilityLabel={label}
testID="provider-refresh"
/>
);
return (
<Button
variant="outline"
onPress={refresh.run}
loading={refresh.busy}
testID="provider-refresh"
>
{label}
</Button>
);
}
@@ -806,6 +806,28 @@ describe("ReplicaCache", () => {
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([timelineItem("New")]);
});
it("keeps a turn's stats on its footer row across cache reopen", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const answer: StreamItem = {
...(timelineItem("Done") as Extract<StreamItem, { kind: "assistant_message" }>),
turnMetrics: [
{ label: "Model", value: "gemini-3.6-flash" },
{ label: "Cache", value: "64%", tone: "ok" },
],
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
items: [answer],
range: { epoch: "epoch-1", startSeq: 12, endSeq: 12 },
hasOlder: false,
});
await writer.flush();
const reader = createCache(storage);
expect((await reader.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([answer]);
});
it("round-trips plugin timeline items", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -2,6 +2,7 @@ import { findMountedWindowStart } from "@/agent-stream/history-window";
import { z } from "zod";
import {
AgentBackgroundWorkSummarySchema,
AgentMetricSchema,
AgentStatusSchema,
AgentTimelineItemPayloadSchema,
ForgeWebSchema,
@@ -129,6 +130,7 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
...TimelineItemBaseShape,
kind: z.literal("assistant_message"),
messageId: z.string().optional(),
turnMetrics: z.array(AgentMetricSchema).optional(),
text: z.string(),
// Reject old caches containing display fragments; refetch the complete source text.
}),
@@ -163,6 +165,7 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
...TimelineItemBaseShape,
kind: z.literal("tool_call"),
provider: AgentProviderSchema,
turnMetrics: z.array(AgentMetricSchema).optional(),
item: AgentTimelineItemPayloadSchema.refine((item) => item.type === "tool_call"),
}),
z.strictObject({
@@ -482,6 +485,7 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...base,
kind: item.kind,
...(item.messageId ? { messageId: item.messageId } : {}),
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
text: item.text,
};
case "thought":
@@ -516,6 +520,7 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...base,
kind: item.kind,
provider: item.payload.data.provider,
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
item: serializeAgentToolCall(item.payload.data),
};
case "plugin":
@@ -575,6 +580,7 @@ function deserializeBuiltinTimelineItem(
...base,
kind: item.kind,
...(item.messageId ? { messageId: item.messageId } : {}),
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
text: item.text,
};
case "thought":
@@ -611,6 +617,7 @@ function deserializeBuiltinTimelineItem(
return {
...base,
kind: item.kind,
...(item.turnMetrics ? { turnMetrics: item.turnMetrics } : {}),
payload: {
source: "agent",
data: {
@@ -29,7 +29,9 @@ import { EditingTextInput as TextInput } from "@/components/ui/text-input";
import { SettingsTextAreaCard } from "@/components/settings-textarea";
import { SettingsGroup } from "@/components/settings/headings/settings-group";
import { SettingsSection } from "@/components/settings/headings/settings-section";
import { SettingsBackLink, SettingsDetailHeader } from "@/components/settings";
import type { PageTitleParent } from "@/components/page-layout";
import { useIsCompactFormFactor } from "@/constants/layout";
import { SettingsDetailHeader } from "@/components/settings";
import { settingsStyles } from "@/styles/settings";
import { useProjects } from "@/hooks/use-projects";
import type { ProjectEditFormSnapshot } from "@/projects/edit-form";
@@ -95,14 +97,12 @@ export interface ProjectSettingsScreenProps {
serverId: string;
projectId: string;
onBackToProjects: () => void;
showBackToProjects: boolean;
}
export default function ProjectSettingsScreen({
serverId,
projectId,
onBackToProjects,
showBackToProjects,
}: ProjectSettingsScreenProps) {
const { projects } = useProjects();
const project = useMemo(
@@ -123,12 +123,7 @@ export default function ProjectSettingsScreen({
selectedHost.repoRoot.trim().length > 0;
if (!project || !selectedHost || !client || !canEdit) {
return (
<NoEditableTarget
onBackToProjects={onBackToProjects}
showBackToProjects={showBackToProjects}
/>
);
return <NoProject onBackToProjects={onBackToProjects} />;
}
return (
@@ -138,24 +133,29 @@ export default function ProjectSettingsScreen({
client={client}
isHostGone={isHostGone}
onBackToProjects={onBackToProjects}
showBackToProjects={showBackToProjects}
/>
);
}
function NoEditableTarget({
onBackToProjects,
showBackToProjects,
}: {
onBackToProjects: () => void;
showBackToProjects: boolean;
}) {
/** A project page with no project to name: the title is the way back to Projects. */
function NoProject({ onBackToProjects }: { onBackToProjects: () => void }) {
const parent = useProjectsParent(onBackToProjects);
return (
<>
<SettingsDetailHeader parent={parent} />
<NoEditableTarget onBackToProjects={onBackToProjects} />
</>
);
}
function NoEditableTarget({ onBackToProjects }: { onBackToProjects: () => void }) {
const { t } = useTranslation();
// The compact back header already goes back to Projects.
const isCompact = useIsCompactFormFactor();
return (
<View style={styles.noTargetContainer}>
{showBackToProjects ? <BackToProjectsButton onPress={onBackToProjects} /> : null}
<Text style={styles.noTargetText}>{t("settings.project.noEditableTarget")}</Text>
{showBackToProjects ? (
{isCompact ? null : (
<Button
testID="project-settings-back-button"
onPress={onBackToProjects}
@@ -163,19 +163,22 @@ function NoEditableTarget({
>
{t("settings.project.backToProjects")}
</Button>
) : null}
)}
</View>
);
}
function BackToProjectsButton({ onPress }: { onPress: () => void }) {
/** Projects as the first part of a project page's title, which goes back to the list. */
function useProjectsParent(onPress: () => void): PageTitleParent {
const { t } = useTranslation();
return (
<SettingsBackLink
label={t("settings.project.backToProjects")}
onPress={onPress}
testID="project-settings-back-link"
/>
return useMemo(
() => ({
label: t("settings.projects"),
accessibilityLabel: t("settings.project.backToProjects"),
onPress,
testID: "project-settings-back-link",
}),
[onPress, t],
);
}
@@ -185,7 +188,6 @@ interface ProjectSettingsBodyProps {
client: DaemonClient;
isHostGone: boolean;
onBackToProjects: () => void;
showBackToProjects: boolean;
}
function ProjectSettingsBody({
@@ -194,7 +196,6 @@ function ProjectSettingsBody({
client,
isHostGone,
onBackToProjects,
showBackToProjects,
}: ProjectSettingsBodyProps) {
const { t } = useTranslation();
const [isEditSheetOpen, setIsEditSheetOpen] = useState(false);
@@ -256,17 +257,7 @@ function ProjectSettingsBody({
const handleReload = useCallback(() => {
void readQuery.refetch();
}, [readQuery]);
const backLink = useMemo(
() =>
showBackToProjects
? {
label: t("settings.project.backToProjects"),
onPress: onBackToProjects,
testID: "project-settings-back-link",
}
: undefined,
[onBackToProjects, showBackToProjects, t],
);
const parent = useProjectsParent(onBackToProjects);
const titleIcon = useMemo(
() => (
<ProjectTitleIcon
@@ -294,9 +285,9 @@ function ProjectSettingsBody({
);
return (
<View role="main" style={styles.body}>
<View role="main">
<SettingsDetailHeader
back={backLink}
parent={parent}
icon={titleIcon}
title={selectedHost.projectName}
trailing={editButton}
@@ -327,7 +318,6 @@ function ProjectSettingsBody({
onReload: handleReload,
isHostGone,
onBackToProjects,
showBackToProjects,
})}
</View>
);
@@ -345,7 +335,6 @@ interface RenderContentInput {
onReload: () => void;
isHostGone: boolean;
onBackToProjects: () => void;
showBackToProjects: boolean;
}
function renderContent({
@@ -360,7 +349,6 @@ function renderContent({
onReload,
isHostGone,
onBackToProjects,
showBackToProjects,
}: RenderContentInput) {
if (readQuery.isLoading) {
return (
@@ -379,12 +367,7 @@ function renderContent({
}
if (isHostGone) {
return (
<NoEditableTarget
onBackToProjects={onBackToProjects}
showBackToProjects={showBackToProjects}
/>
);
return <NoEditableTarget onBackToProjects={onBackToProjects} />;
}
if (!loadedConfig) {
@@ -1118,10 +1101,6 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
body: {
padding: theme.spacing[4],
gap: theme.spacing[2],
},
editButton: {
padding: theme.spacing[1],
},
+2 -3
View File
@@ -1335,7 +1335,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
serverId={view.serverId}
projectId={view.projectId}
onBackToProjects={handleBackFromDetail}
showBackToProjects={!isCompactLayout}
/>
);
}
@@ -1345,7 +1344,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
serverId={view.serverId}
provider={view.providerId}
onBack={handleBackFromDetail}
showBack={!isCompactLayout}
/>
);
}
@@ -1450,7 +1448,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
<WindowChromeRegion corners="top-right">
<View style={desktopStyles.contentPane} testID="settings-detail-pane">
<PageLayout
title={detailTitle}
// A project or provider page draws its own title, which names the list it came from.
title={view.kind === "project" || view.kind === "provider" ? undefined : detailTitle}
actions={detailActions}
width={detailWidth}
titleTestID="settings-detail-header-title"
@@ -3,7 +3,14 @@ import React, { useCallback, useMemo } from "react";
import { View } from "react-native";
import { useRouter, type Href } from "expo-router";
import { useTranslation } from "react-i18next";
import { Copy, Ellipsis, Globe, Import as ImportIcon, Settings } from "lucide-react-native";
import {
Archive,
Copy,
Ellipsis,
Globe,
Import as ImportIcon,
Settings,
} from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { TerminalProfile } from "@getpaseo/protocol/messages";
import {
@@ -21,6 +28,7 @@ import {
useIconButtonChromeStyle,
} from "@/components/ui/icon-button-chrome";
import { TerminalProfileIcon } from "@/components/terminal-profile-icon";
import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import {
getTerminalProfileIcon,
@@ -35,6 +43,7 @@ import {
import { usePluginWorkspaceMenu } from "@/plugins";
const ThemedEllipsis = withUnistyles(Ellipsis);
const ThemedArchive = withUnistyles(Archive);
const ThemedCopy = withUnistyles(Copy);
const ThemedGlobe = withUnistyles(Globe);
const ThemedImport = withUnistyles(ImportIcon);
@@ -45,6 +54,7 @@ const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMut
const MENU_NEW_BROWSER_ICON = <ThemedGlobe size={16} uniProps={mutedColorMapping} />;
const MENU_IMPORT_ICON = <ThemedImport size={16} uniProps={mutedColorMapping} />;
const MENU_COPY_ICON = <ThemedCopy size={16} uniProps={mutedColorMapping} />;
const MENU_ARCHIVE_ICON = <ThemedArchive size={16} uniProps={mutedColorMapping} />;
const MENU_SETTINGS_ICON = <ThemedSettings size={16} uniProps={mutedColorMapping} />;
function WorkspaceHeaderMenuTriggerIcon() {
return (
@@ -259,6 +269,10 @@ export function WorkspaceHeaderMenuMobile({
const handleEditProfiles = useCallback(() => {
router.push(buildSettingsHostSectionRoute(normalizedServerId, "terminals") as Href);
}, [normalizedServerId, router]);
const { canArchive, archive } = useActiveWorkspaceArchive();
const handleArchiveWorkspace = useCallback(() => {
archive();
}, [archive]);
const scriptsMenu = useWorkspaceScriptsMenuPages(scripts);
const pluginMenu = usePluginWorkspaceMenu(normalizedServerId, normalizedWorkspaceId);
const pages = useMemo(
@@ -330,6 +344,15 @@ export function WorkspaceHeaderMenuMobile({
) : null}
<WorkspaceHeaderWorkspaceActionItems {...workspaceActions} />
<DropdownMenuSeparator />
<DropdownMenuItem
testID="workspace-header-archive-workspace"
leading={MENU_ARCHIVE_ICON}
disabled={!canArchive}
onSelect={handleArchiveWorkspace}
>
{t("sidebar.workspace.actions.archiveWorkspace")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>{t("workspace.tabs.actions.terminalProfilesMenu")}</DropdownMenuLabel>
{profiles.map((profile) => (
<HeaderMenuProfileItem
+5 -5
View File
@@ -115,12 +115,12 @@ describe("resolveSidebarNavItems", () => {
});
describe("resolveSidebarNavItems for the Usage item", () => {
it("hides the Usage item until it is turned on", () => {
it("shows the Usage item by default and honors an explicit off choice", () => {
const resolve = (preferences: SidebarNavPreference[]) =>
summarize(resolveSidebarNavItems({ section: "footer", pluginGroups: [], preferences }));
expect(resolve([])).toEqual([{ key: "usage", visible: false }]);
expect(resolve([{ key: "usage", visible: true }])).toEqual([{ key: "usage", visible: true }]);
expect(resolve([])).toEqual([{ key: "usage", visible: true }]);
expect(resolve([{ key: "usage", visible: false }])).toEqual([{ key: "usage", visible: false }]);
});
});
@@ -297,7 +297,7 @@ describe("footer section", () => {
});
expect(summarize(items)).toEqual([
{ key: "usage", visible: false },
{ key: "usage", visible: true },
{ key: syncKey, visible: true },
]);
});
@@ -309,7 +309,7 @@ describe("footer section", () => {
preferences: [{ key: "history", visible: false }],
});
expect(summarize(items)).toEqual([{ key: "usage", visible: false }]);
expect(summarize(items)).toEqual([{ key: "usage", visible: true }]);
});
it("ignores the footer icon buttons, which are fixed and not items", () => {
+2 -5
View File
@@ -69,11 +69,8 @@ export function builtinSidebarNavShortcutAction(id: BuiltinSidebarItemId): strin
return BUILTIN_SHORTCUT_ACTIONS[id];
}
/** Builtins that start hidden until the user turns them on: the Usage summary is opt-in. */
const HIDDEN_BY_DEFAULT: ReadonlySet<BuiltinSidebarItemId> = new Set(["usage"]);
function builtinVisibleByDefault(id: BuiltinSidebarItemId): boolean {
return !HIDDEN_BY_DEFAULT.has(id);
function builtinVisibleByDefault(_id: BuiltinSidebarItemId): boolean {
return true;
}
export function pluginSidebarNavKey(
+3
View File
@@ -33,6 +33,7 @@ import type {
AgentMode,
AgentCapabilityFlags,
AgentUsage,
AgentMetric,
AgentPersistenceHandle,
} from "@getpaseo/protocol/agent-types";
import type {
@@ -93,6 +94,8 @@ export interface Agent {
runtimeInfo?: AgentRuntimeInfo;
usageScopeKey?: string;
lastUsage?: AgentUsage;
/** What the provider reports about the session, as label and value rows. */
sessionMetrics?: AgentMetric[];
lastError?: string | null;
title: string | null;
cwd: string;
+3
View File
@@ -1,4 +1,5 @@
import { StyleSheet } from "react-native-unistyles";
import { mapLayout, SWITCH_HEIGHT } from "@/components/ui/control-geometry";
export const settingsStyles = StyleSheet.create((theme) => ({
section: {
@@ -34,6 +35,8 @@ export const settingsStyles = StyleSheet.create((theme) => ({
justifyContent: "space-between",
paddingVertical: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
// As tall as a row holding a switch, so rows with and without one line up.
minHeight: mapLayout(SWITCH_HEIGHT, (height) => height + theme.spacing[4] * 2),
},
rowBorder: {
borderTopWidth: 1,
@@ -4558,3 +4558,262 @@ describe("createAgentStreamReducerQueue", () => {
expect(scheduler.size).toBe(0);
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "opus" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
function liveTurn(events: AgentStreamEventPayload[]) {
let seq = 0;
return processAgentStreamEvents({
events: events.map((event) =>
event.type === "timeline"
? makeStreamReducerEvent(event, ++seq)
: { event, seq: undefined, epoch: undefined, timestamp: new Date(1000 + seq) },
),
currentTail: [],
currentHead: [],
currentCursor: undefined,
});
}
function inTurn(event: AgentStreamEventPayload, turnId: string): AgentStreamEventPayload {
return { ...event, turnId } as AgentStreamEventPayload;
}
function turnCompleted(turnId?: string, turnMetrics = metrics): AgentStreamEventPayload {
return {
type: "turn_completed",
provider: "claude",
...(turnId ? { turnId } : {}),
metrics: turnMetrics,
};
}
function metricsByKind(items: StreamItem[]) {
return items.map((item) => ({
kind: item.kind,
turnMetrics: "turnMetrics" in item ? item.turnMetrics : undefined,
}));
}
it("puts a live turn's metrics on its last assistant message", () => {
const result = liveTurn([
inTurn(makeTimelineEvent("question", "user_message"), "turn-1"),
inTurn(makeAssistantTimelineEvent("Looking."), "turn-1"),
inTurn(makeToolCallTimelineEvent("read-1"), "turn-1"),
inTurn(makeAssistantTimelineEvent("Done."), "turn-1"),
turnCompleted("turn-1"),
]);
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
it("puts a live tool-only turn's metrics on its last tool call", () => {
const result = liveTurn([
inTurn(makeTimelineEvent("question", "user_message"), "turn-1"),
inTurn(makeToolCallTimelineEvent("read-1"), "turn-1"),
inTurn(makeToolCallTimelineEvent("read-2"), "turn-1"),
turnCompleted("turn-1"),
]);
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: metrics },
]);
});
it("does not put a turn's metrics on an earlier turn's reply", () => {
const result = liveTurn([
inTurn(makeTimelineEvent("first", "user_message"), "turn-1"),
inTurn(makeAssistantTimelineEvent("First reply."), "turn-1"),
turnCompleted("turn-1", [{ label: "Model", value: "first" }]),
inTurn(makeTimelineEvent("second", "user_message"), "turn-2"),
inTurn(makeToolCallTimelineEvent("read-1"), "turn-2"),
inTurn(makeTimelineEvent("thinking", "reasoning"), "turn-2"),
turnCompleted("turn-2"),
]);
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: [{ label: "Model", value: "first" }] },
{ kind: "user_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: undefined },
{ kind: "thought", turnMetrics: undefined },
]);
});
it("leaves the timeline untouched when a turn completes without metrics", () => {
const before = liveTurn([
inTurn(makeTimelineEvent("question", "user_message"), "turn-1"),
inTurn(makeAssistantTimelineEvent("Done."), "turn-1"),
turnCompleted("turn-1", []),
]);
const after = processAgentStreamEvent({
...baseStreamInput,
event: { type: "turn_completed", provider: "claude", turnId: "turn-1" },
currentTail: before.tail,
currentHead: before.head,
});
expect(after.tail).toBe(before.tail);
expect(metricsByKind(after.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: undefined },
]);
});
it("hydrates turn metrics from a replaced history page", () => {
const result = processTimelineResponse({
...baseTimelineInput,
payload: {
...baseTimelineInput.payload,
reset: true,
startCursor: { seq: 1 },
endCursor: { seq: 4 },
entries: [
makeTimelineEntry(1, "question", "user_message"),
{ ...makeTimelineEntry(2, "Reply."), turnMetrics: metrics },
makeTimelineEntry(3, "next question", "user_message"),
{
...makeToolCallTimelineEntry(4, "read-1", "completed", {
type: "read",
filePath: "/tmp/a.ts",
}),
turnMetrics: [{ label: "Model", value: "sonnet" }],
},
],
},
});
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
{ kind: "user_message", turnMetrics: undefined },
{ kind: "tool_call", turnMetrics: [{ label: "Model", value: "sonnet" }] },
]);
});
it("hydrates turn metrics from an older history page", () => {
const currentTail: StreamItem[] = [
{ kind: "user_message", id: "current-3", text: "current-3", timestamp: new Date(3000) },
];
const result = processTimelineResponse({
...baseTimelineInput,
currentTail,
currentCursor: { epoch: "epoch-1", startSeq: 3, endSeq: 3 },
payload: {
...baseTimelineInput.payload,
direction: "before",
startCursor: { seq: 1 },
endCursor: { seq: 2 },
entries: [
makeTimelineEntry(1, "older question", "user_message"),
{ ...makeTimelineEntry(2, "Older reply."), turnMetrics: metrics },
],
},
});
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
{ kind: "user_message", turnMetrics: undefined },
]);
});
it("hydrates turn metrics on a projected reply that replaces the live one", () => {
const live = processAgentStreamEvents({
events: [makeStreamReducerEvent(makeAssistantTimelineEvent("Partial"), 2)],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 1 },
});
const result = processTimelineResponse({
...baseTimelineInput,
currentTail: live.tail,
currentHead: live.head,
currentCursor: live.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
startCursor: { seq: 3 },
endCursor: { seq: 3 },
entries: [
{
...makeTimelineEntry(2, "Partial reply.", "assistant_message", 3),
sourceSeqRanges: [{ startSeq: 2, endSeq: 3 }],
turnMetrics: metrics,
},
],
},
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
it("keeps live turn metrics when canonical history replaces the timeline", () => {
const live = liveTurn([
makeTimelineEvent("question", "user_message"),
makeAssistantTimelineEvent("Done."),
turnCompleted(),
]);
const result = processTimelineResponse({
...baseTimelineInput,
currentTail: live.tail,
currentHead: live.head,
currentCursor: live.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
reset: true,
startCursor: { seq: 1 },
endCursor: { seq: 2 },
entries: [
makeTimelineEntry(1, "question", "user_message"),
{ ...makeTimelineEntry(2, "Done."), turnMetrics: metrics },
],
},
});
expect(metricsByKind(result.tail)).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
it("keeps row identity when a page repeats metrics the row already has", () => {
const first = processTimelineResponse({
...baseTimelineInput,
payload: {
...baseTimelineInput.payload,
reset: true,
startCursor: { seq: 1 },
endCursor: { seq: 1 },
entries: [{ ...makeTimelineEntry(1, "Reply."), turnMetrics: metrics }],
},
});
const repeated = processTimelineResponse({
...baseTimelineInput,
currentTail: first.tail,
currentCursor: first.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
startCursor: { seq: 1 },
endCursor: { seq: 1 },
entries: [{ ...makeTimelineEntry(1, "Reply."), turnMetrics: [...metrics] }],
},
});
expect(repeated.tail).toBe(first.tail);
});
});
@@ -1,8 +1,9 @@
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
applyStreamEvent,
flushHeadToTail,
@@ -133,6 +134,7 @@ interface TimelineResponseEntry {
turnId?: string;
item: AgentTimelineItem;
timestamp: string;
turnMetrics?: AgentMetric[];
}
export interface ProcessTimelineResponseInput {
@@ -1268,7 +1270,8 @@ export function processTimelineResponse(
// ------------------------------------------------------------------
// Convert entries to timeline units
// ------------------------------------------------------------------
const timelineUnits = selectEntriesOwnedByTimelinePage(payload).map((entry) => ({
const pageEntries = selectEntriesOwnedByTimelinePage(payload);
const timelineUnits = pageEntries.map((entry) => ({
seq: entry.seqStart,
seqEnd: entry.seqEnd,
sourceSeqRanges:
@@ -1379,8 +1382,8 @@ export function processTimelineResponse(
});
}
const nextTail = timelineResult.tail;
const nextHead = timelineResult.head;
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
const nextCursor = timelineResult.cursor;
const cursorChanged = timelineResult.cursorChanged;
sideEffects.push(...timelineResult.sideEffects);
+101
View File
@@ -0,0 +1,101 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import { continuesResponse } from "@/agent-stream/turn-membership";
import type { StreamItem, TimelinePosition } from "@/types/stream";
type TurnFooterAnchor = Extract<StreamItem, { kind: "assistant_message" | "tool_call" }>;
/**
* Puts a completed turn's metrics on the row its footer hangs on: the turn's last assistant
* message, else its last row when that row is a tool call. The daemon stamps the same row, so a
* later timeline fetch agrees with what the live event showed.
*/
export function stampCompletedTurnMetrics(
items: StreamItem[],
metrics: AgentMetric[] | undefined,
turnId: string | undefined,
): StreamItem[] {
if (!metrics || metrics.length === 0) return items;
const index = findTurnFooterAnchorIndex(items, turnId);
if (index === null) return items;
return replaceAt(items, index, metrics);
}
/**
* Puts the metrics a timeline page carries on the rows it wrote. Every reducer path leaves a row
* with the cursor of the last entry that wrote it, which is the entry the daemon stamped.
*/
export function stampTimelineTurnMetrics(
items: StreamItem[],
epoch: string,
entries: ReadonlyArray<{ seqEnd: number; turnMetrics?: AgentMetric[] }>,
): StreamItem[] {
const metricsBySeq = new Map<number, AgentMetric[]>();
for (const entry of entries) {
if (entry.turnMetrics && entry.turnMetrics.length > 0) {
metricsBySeq.set(entry.seqEnd, entry.turnMetrics);
}
}
if (metricsBySeq.size === 0) return items;
let next = items;
items.forEach((item, index) => {
const metrics = isTurnFooterAnchor(item)
? metricsBySeq.get(cursorSeqIn(item.timelineCursor, epoch) ?? -1)
: undefined;
if (metrics) next = replaceAt(next, index, metrics);
});
return next;
}
function findTurnFooterAnchorIndex(items: StreamItem[], turnId: string | undefined): number | null {
const last = lastIndexOfTurn(items, turnId);
if (last === null) return null;
for (let index = last; index >= 0; index--) {
if (index < last && !continuesResponse(items[index], items[index + 1])) break;
if (items[index].kind === "assistant_message") return index;
}
return items[last].kind === "tool_call" ? last : null;
}
function lastIndexOfTurn(items: StreamItem[], turnId: string | undefined): number | null {
const tail = items.length - 1;
if (tail < 0) return null;
if (turnId === undefined) return tail;
const index = items.findLastIndex((item) => item.turnId === turnId);
if (index >= 0) return index;
// Rows from daemons without turn ids belong to the trailing turn. A tail owned by another
// turn means this turn wrote no rows.
return items[tail].turnId === undefined ? tail : null;
}
function isTurnFooterAnchor(item: StreamItem): item is TurnFooterAnchor {
return item.kind === "assistant_message" || item.kind === "tool_call";
}
function cursorSeqIn(cursor: TimelinePosition | undefined, epoch: string): number | null {
return cursor?.epoch === epoch ? cursor.seq : null;
}
/** Returns `items` itself when the row already shows these metrics, so unchanged rows keep identity. */
function replaceAt(items: StreamItem[], index: number, metrics: AgentMetric[]): StreamItem[] {
const item = items[index];
if (!item || !isTurnFooterAnchor(item) || areMetricsEqual(item.turnMetrics, metrics)) {
return items;
}
const next = [...items];
next[index] = { ...item, turnMetrics: metrics };
return next;
}
function areMetricsEqual(left: AgentMetric[] | undefined, right: AgentMetric[]): boolean {
return (
left !== undefined &&
left.length === right.length &&
left.every(
(metric, index) =>
metric.label === right[index].label &&
metric.value === right[index].value &&
metric.tone === right[index].tone,
)
);
}
+8 -1
View File
@@ -1,5 +1,6 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type {
AgentMetric,
AgentProvider,
AgentTimelineItem,
JsonValue,
@@ -9,6 +10,7 @@ import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
import type { AgentAttachment, AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { AttachmentMetadata } from "@/attachments/types";
import type { OverviewSummary } from "@/tool-calls/detail-level/overview/model";
import { stampCompletedTurnMetrics } from "@/timeline/turn-metrics";
import { extractTaskEntriesFromToolCall } from "../utils/tool-call-parsers";
/**
@@ -715,6 +717,8 @@ export interface AssistantMessageItem {
timelineCursor?: TimelinePosition;
text: string;
timestamp: Date;
/** Set when this message carries its turn's footer. */
turnMetrics?: AgentMetric[];
/** Display-only fields, assigned after source-item plugin transforms. */
}
@@ -769,6 +773,8 @@ export interface ToolCallItem {
turnId?: string;
timestamp: Date;
payload: ToolCallPayload;
/** Set when this call carries its turn's footer. */
turnMetrics?: AgentMetric[];
}
export type AgentToolCallItem = ToolCallItem & {
@@ -1630,9 +1636,10 @@ export function reduceStreamUpdate(
);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
case "thread_started":
case "turn_started":
case "turn_completed":
case "turn_failed":
case "turn_canceled":
case "permission_requested":
+15 -51
View File
@@ -1,5 +1,5 @@
import { GripVertical, RotateCw } from "lucide-react-native";
import { useCallback, useMemo } from "react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Text, View, type StyleProp, type TextStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -9,14 +9,13 @@ import {
smallIconButtonChromeFrameSize,
} from "@/components/ui/icon-button-chrome";
import { DraggableListHandle } from "@/components/draggable-list";
import { ControlSizeProvider } from "@/components/ui/control-size";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
import { StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import type { TFunction } from "i18next";
import { useCallback } from "react";
import { UsageBalanceBar } from "./balance-bar";
import type { UsageDisplay } from "./display";
import { formatAgo, formatProviderUsageLabel, formatUsageAccountName } from "./format";
@@ -37,10 +36,8 @@ function statusText(report: UsageReport, t: TFunction): string | null {
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedGripVertical = withUnistyles(GripVertical);
/** A card in the user's arrangement: dragged by its handle, turned off from its switch. */
/** A card in the user's arrangement: dragged by its handle. */
export interface UsageCardArrangement {
on: boolean;
onSetOn: (on: boolean) => void;
/** The handle is always there; it shows while the card is hovered or where there is no hover. */
handleVisible: boolean;
}
@@ -64,7 +61,7 @@ export function UsageCard({
pinnable: boolean;
/** Whether the header has a Refresh button. Without one the freshness shows on the card. */
refreshable: boolean;
/** Present where the user arranges cards. An off card collapses to its header. */
/** Present where the user arranges cards. */
arrangement?: UsageCardArrangement;
compact?: boolean;
}) {
@@ -75,7 +72,6 @@ export function UsageCard({
const showsFreshnessInline = isNative || isCompact || !refreshable;
const usage = entry.report;
const status = statusText(usage, t);
const collapsed = arrangement?.on === false;
const report = resolveUsageReport(entry, t);
const { planLabel, successfulAt, retained } = report;
@@ -105,23 +101,15 @@ export function UsageCard({
<Text style={styles.name} numberOfLines={1}>
{entry.sourceLabel}
</Text>
{collapsed && entry.account.label ? (
// The body that names the account is gone, and two off cards of one source must differ.
<Text style={styles.collapsedAccount} numberOfLines={1}>
{entry.account.label}
</Text>
) : null}
{planLabel && !collapsed ? (
<StatusBadge label={planLabel} variant="muted" size="xs" />
) : null}
{planLabel ? <StatusBadge label={planLabel} variant="muted" size="xs" /> : null}
<View style={styles.headerSpacer} />
{status && !collapsed ? (
{status ? (
<View style={styles.statusRow}>
<View style={dotStyle} />
<Text style={styles.statusLabel}>{status}</Text>
</View>
) : null}
{refreshable && !collapsed ? (
{refreshable ? (
<UsageRefreshButton
sourceLabel={entry.sourceLabel}
successfulAt={successfulAt}
@@ -131,31 +119,16 @@ export function UsageCard({
compact={isCompact}
/>
) : null}
{arrangement ? (
<ControlSizeProvider size="sm">
<Switch
value={arrangement.on}
onValueChange={arrangement.onSetOn}
accessibilityLabel={t("providerUsage.showCard", {
source: formatUsageAccountName(entry),
})}
style={styles.cardSwitch}
testID={`usage-card-switch-${entry.id}`}
/>
</ControlSizeProvider>
) : null}
</View>
{collapsed ? null : (
<UsageCardBody
entry={entry}
display={display}
pinnable={pinnable}
report={report}
showsFreshnessInline={showsFreshnessInline}
refreshState={refreshState}
/>
)}
<UsageCardBody
entry={entry}
display={display}
pinnable={pinnable}
report={report}
showsFreshnessInline={showsFreshnessInline}
refreshState={refreshState}
/>
</View>
);
}
@@ -434,11 +407,6 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
collapsedAccount: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
headerSpacer: {
flex: 1,
},
@@ -510,10 +478,6 @@ const styles = StyleSheet.create((theme) => ({
},
dragHandle: dragHandleSlot(theme.spacing),
dragHandleHidden: { ...dragHandleSlot(theme.spacing), opacity: 0 },
// The switch's reserved control height overhangs the header like the Refresh button's hitbox.
cardSwitch: {
marginVertical: -theme.spacing[2],
},
refreshButton: iconHitboxOverhang(false),
refreshButtonCompact: iconHitboxOverhang(true),
}));
+47 -4
View File
@@ -3,6 +3,7 @@ import {
arrangeUsageCards,
arrangeUsageReports,
DEFAULT_USAGE_PREFERENCES,
isUsageCardOn,
setUsageCardOn,
UsagePreferencesSchema,
usageReportsOn,
@@ -11,13 +12,19 @@ import {
import { resolvePinnedUsage } from "./pinned";
import type { UsageReportEntry } from "./types";
function report(sourceId: string, sourceLabel: string, account?: string): UsageReportEntry {
function report(
sourceId: string,
sourceLabel: string,
account?: string,
defaultEnabled?: boolean,
): UsageReportEntry {
return {
id: `${sourceId}:${account ?? "default"}`,
sourceId,
sourceLabel,
account: account ? { label: account } : {},
fetchedAt: "2026-01-01T00:00:00.000Z",
...(defaultEnabled === undefined ? {} : { defaultEnabled }),
report: {
status: "available",
windows: [{ id: "weekly", label: "Weekly", summary: true, usedPct: 40 }],
@@ -114,8 +121,31 @@ describe("usage card order", () => {
describe("usage cards turned off", () => {
it("turns a card off and back on", () => {
const off = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, "codex:default", false);
expect(off.cardsOff).toEqual(["codex:default"]);
expect(setUsageCardOn(off, "codex:default", true).cardsOff).toEqual([]);
expect(off.cardVisibility).toEqual({ "codex:default": false });
expect(isUsageCardOn(off, codex)).toBe(false);
const on = setUsageCardOn(off, "codex:default", true);
expect(on.cardVisibility).toEqual({ "codex:default": true });
expect(isUsageCardOn(on, codex)).toBe(true);
});
it("hides sources hinted off by default until the user explicitly turns them on", () => {
const uninstalledCopilot = report("copilot", "GitHub Copilot", undefined, false);
expect(isUsageCardOn(DEFAULT_USAGE_PREFERENCES, uninstalledCopilot)).toBe(false);
expect(ids(usageReportsOn([codex, uninstalledCopilot], DEFAULT_USAGE_PREFERENCES))).toEqual([
"codex:default",
]);
expect(
resolvePinnedUsage([codex, uninstalledCopilot], DEFAULT_USAGE_PREFERENCES).map(
(source) => source.key,
),
).toEqual(["codex:default"]);
const optedIn = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, uninstalledCopilot.id, true);
expect(isUsageCardOn(optedIn, uninstalledCopilot)).toBe(true);
expect(ids(usageReportsOn([codex, uninstalledCopilot], optedIn))).toEqual([
"codex:default",
"copilot:default",
]);
});
it("leaves off cards out of the sidebar summary", () => {
@@ -143,11 +173,24 @@ describe("stored card preferences", () => {
);
});
it("migrates legacy cardsOff into cardVisibility", () => {
expect(
UsagePreferencesSchema.parse({
displayAs: "used",
serverId: null,
cardsOff: ["codex:default"],
}),
).toEqual({
...DEFAULT_USAGE_PREFERENCES,
cardVisibility: { "codex:default": false },
});
});
it("survives a save and reload, and ignores a malformed arrangement", () => {
const saved = setUsageCardOn(arranged(["codex:default"]), "claude:work", false);
expect(UsagePreferencesSchema.parse(JSON.parse(JSON.stringify(saved)))).toEqual(saved);
expect(
UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardsOff: [1] }),
UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardVisibility: [1] }),
).toEqual(DEFAULT_USAGE_PREFERENCES);
});
});
+26 -4
View File
@@ -1,8 +1,9 @@
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useMemo, type ReactElement } from "react";
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { UsageRefreshButton } from "./refresh-button";
import { UsageOptions } from "./options";
import { useUsageDisplay, type UsageDisplay } from "./display";
import { hasHostChoice, type UsageHostSelection } from "./hosts";
import { useHostUsage } from "./queries";
import type { UsageView } from "./types";
@@ -15,13 +16,19 @@ import type { UsageView } from "./types";
export function UsageControls({
view,
serverId,
display,
onRefresh,
hostSelection,
optionsOpen,
onOptionsOpenChange,
}: {
view: UsageView;
serverId: string;
display?: UsageDisplay;
onRefresh: () => void;
hostSelection?: UsageHostSelection;
optionsOpen?: boolean;
onOptionsOpenChange?: (open: boolean) => void;
}) {
const busy = view.kind === "loading" || (view.kind === "ready" && view.isRefreshing);
if (!hasUsageControls(view, hostSelection)) return null;
@@ -30,7 +37,14 @@ export function UsageControls({
{view.kind === "off" || view.kind === "unavailable" ? null : (
<UsageRefreshButton busy={busy} onRefresh={onRefresh} />
)}
<UsageOptions serverId={serverId} hostSelection={hostSelection} />
<UsageOptions
serverId={serverId}
hostSelection={hostSelection}
reports={view.kind === "ready" ? view.reports : []}
display={display}
open={optionsOpen}
onOpenChange={onOptionsOpenChange}
/>
</View>
);
}
@@ -54,10 +68,15 @@ const styles = StyleSheet.create((theme) => ({
*/
export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
view: UsageView;
display: UsageDisplay;
refresh: () => void;
controls: ReactElement | null;
openOptions: () => void;
} {
const { view, refresh } = useHostUsage(hostSelection.serverId);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
const [optionsOpen, setOptionsOpen] = useState(false);
const openOptions = useCallback(() => setOptionsOpen(true), []);
const controls = useMemo(
() =>
hasUsageControls(view, hostSelection) ? (
@@ -67,11 +86,14 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
key={hostSelection.serverId}
serverId={hostSelection.serverId}
view={view}
display={display}
onRefresh={refresh}
hostSelection={hostSelection}
optionsOpen={optionsOpen}
onOptionsOpenChange={setOptionsOpen}
/>
) : null,
[hostSelection, refresh, view],
[display, hostSelection, optionsOpen, refresh, view],
);
return { view, refresh, controls };
return { view, display, refresh, controls, openOptions };
}
+3 -3
View File
@@ -3,7 +3,7 @@ import { useAppSettings } from "@/hooks/use-settings";
import {
arrangeUsageCards,
arrangeUsageReports,
isUsageCardOff,
isUsageCardOn,
isUsagePinned,
setUsageCardOn,
setUsageDisplayAs,
@@ -25,7 +25,7 @@ export interface UsageDisplay {
arrange: (reports: readonly UsageReportEntry[]) => UsageReportEntry[];
/** Saves the order of the shown cards after the user drops one. */
arrangeCards: (drop: UsageCardDrop) => void;
isCardOn: (reportId: string) => boolean;
isCardOn: (entry: Pick<UsageReportEntry, "id" | "defaultEnabled">) => boolean;
setCardOn: (reportId: string, on: boolean) => void;
}
@@ -72,7 +72,7 @@ export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePref
togglePin,
arrange: (shown) => arrangeUsageReports(shown, preferences),
arrangeCards,
isCardOn: (reportId) => !isUsageCardOff(preferences, reportId),
isCardOn: (entry) => isUsageCardOn(preferences, entry),
setCardOn,
}),
[arrangeCards, preferences, reports, setCardOn, setDisplayAs, togglePin],
+5 -14
View File
@@ -16,8 +16,8 @@ function reportKey(entry: UsageReportEntry): string {
}
/**
* One card per report (source + account), in the user's order. Each card drags by its handle and
* turns off from its switch. Window rows pin while the sidebar summary is on.
* One card per shown report (source + account), in the user's order. Each card drags by its handle.
* Window rows pin while the sidebar summary is on.
*/
export function UsageList({
serverId,
@@ -29,8 +29,7 @@ export function UsageList({
display: UsageDisplay;
}) {
const { inSidebar } = useUsageInSidebar();
const { arrange, arrangeCards } = display;
const arranged = useMemo(() => arrange(reports), [arrange, reports]);
const { arrangeCards } = display;
const handleDragEnd = useCallback(
(next: UsageReportEntry[], moved: string) =>
arrangeCards({ moved, after: next.map(reportKey) }),
@@ -52,7 +51,7 @@ export function UsageList({
);
return (
<DraggableList
data={arranged}
data={reports}
keyExtractor={reportKey}
renderItem={renderItem}
onDragEnd={handleDragEnd}
@@ -90,19 +89,11 @@ function UsageListCard({
const [hasFocus, setHasFocus] = useState(false);
const handleFocus = useCallback(() => setHasFocus(true), []);
const handleBlur = useCallback(() => setHasFocus(false), []);
const { isCardOn, setCardOn } = display;
const on = isCardOn(entry.id);
const handleSetOn = useCallback(
(next: boolean) => setCardOn(entry.id, next),
[entry.id, setCardOn],
);
const arrangement = useMemo(
() => ({
on,
onSetOn: handleSetOn,
handleVisible: isHovered || hasFocus || dragging || isNative || isCompact,
}),
[dragging, handleSetOn, hasFocus, isCompact, isHovered, on],
[dragging, hasFocus, isCompact, isHovered],
);
return (
<View
+113 -20
View File
@@ -2,9 +2,10 @@ import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { Settings } from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { useMemo } from "react";
import { useCallback, useMemo } from "react";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuSubTrigger,
type MenuPageDefinition,
@@ -23,26 +24,36 @@ import { Alert } from "@/components/ui/alert";
import { useHosts } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import { useUsageSetting } from "./setting";
import { useUsageDisplay } from "./display";
import { useUsageDisplay, type UsageDisplay } from "./display";
import { useUsageInSidebar } from "./in-sidebar";
import { hasHostChoice, type UsageHostSelection } from "./hosts";
import type { UsageDisplayAs } from "./preferences";
import { UsageSourceIcon } from "./source-icon";
import type { UsageReportEntry } from "./types";
const ThemedSettings = withUnistyles(Settings);
const HOST_PAGE = "host";
const SOURCES_PAGE = "sources";
/**
* The shared usage preferences, opened from a cog as a popover or compact sheet. With more than
* one host, it leads with the host whose usage shows: the row reads as the current host, and the
* hosts are a page of the same surface, so a compact sheet never opens a second sheet over it.
* The shared usage preferences, opened from a cog as a popover or compact sheet. Host and Sources
* open as pages of the same surface, so a compact sheet never opens a second sheet over it.
*/
export function UsageOptions({
serverId,
hostSelection,
reports = [],
display: providedDisplay,
open,
onOpenChange,
}: {
serverId: string | null;
hostSelection?: UsageHostSelection;
reports?: readonly UsageReportEntry[];
display?: UsageDisplay;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const setting = useUsageSetting(serverId);
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
@@ -57,24 +68,37 @@ export function UsageOptions({
];
const compact = useIsCompactFormFactor();
const glyphSize = useIconButtonChromeGlyphSize("small", compact);
const { display } = useUsageDisplay([]);
const fallbackDisplay = useUsageDisplay(providedDisplay ? [] : reports).display;
const display = providedDisplay ?? fallbackDisplay;
const { inSidebar, setInSidebar } = useUsageInSidebar();
const hostChoice = hasHostChoice(hostSelection) ? hostSelection : null;
const pages = useMemo<MenuPageDefinition[] | undefined>(
() =>
hostChoice
? [
{
id: HOST_PAGE,
title: t("providerUsage.host"),
content: <UsageHostPage hostSelection={hostChoice} />,
},
]
: undefined,
[hostChoice, t],
const arrangedReports = useMemo(() => display.arrange(reports), [display, reports]);
const hasSources = arrangedReports.length > 0;
const shownCount = useMemo(
() => arrangedReports.filter((entry) => display.isCardOn(entry)).length,
[arrangedReports, display],
);
const pages = useMemo<MenuPageDefinition[] | undefined>(() => {
const definitions: MenuPageDefinition[] = [];
if (hostChoice) {
definitions.push({
id: HOST_PAGE,
title: t("providerUsage.host"),
content: <UsageHostPage hostSelection={hostChoice} />,
});
}
if (hasSources) {
definitions.push({
id: SOURCES_PAGE,
title: t("providerUsage.sources"),
content: <UsageSourcesPage reports={arrangedReports} display={display} />,
});
}
return definitions.length > 0 ? definitions : undefined;
}, [arrangedReports, display, hasSources, hostChoice, t]);
const hasSubTriggers = Boolean(hostChoice || hasSources);
return (
<DropdownMenu compactMode="sheet">
<DropdownMenu compactMode="sheet" open={open} onOpenChange={onOpenChange}>
<ToolbarButton
kind="menu"
label={t("providerUsage.options")}
@@ -99,8 +123,20 @@ export function UsageOptions({
{t("providerUsage.host")}
</DropdownMenuSubTrigger>
) : null}
{hasSources ? (
<DropdownMenuSubTrigger
id={SOURCES_PAGE}
value={t("providerUsage.sourcesCount", {
shown: shownCount,
total: arrangedReports.length,
})}
testID="usage-options-sources"
>
{t("providerUsage.sources")}
</DropdownMenuSubTrigger>
) : null}
<View
style={hostChoice ? settingsStyles.rowBorder : undefined}
style={hasSubTriggers ? settingsStyles.rowBorder : undefined}
testID="usage-options-fields"
>
<MenuSettingsRows>
@@ -156,3 +192,60 @@ function UsageHostPage({ hostSelection }: { hostSelection: UsageHostSelection })
</>
);
}
function UsageSourcesPage({
reports,
display,
}: {
reports: readonly UsageReportEntry[];
display: UsageDisplay;
}) {
const { t } = useTranslation();
const inactiveLabel = t("providerUsage.providerInactive");
return (
<>
{reports.map((entry) => (
<UsageSourceMenuItem
key={entry.id}
entry={entry}
on={display.isCardOn(entry)}
onToggle={display.setCardOn}
inactiveLabel={inactiveLabel}
/>
))}
</>
);
}
function UsageSourceMenuItem({
entry,
on,
onToggle,
inactiveLabel,
}: {
entry: UsageReportEntry;
on: boolean;
onToggle: (reportId: string, on: boolean) => void;
inactiveLabel: string;
}) {
const handleSelect = useCallback(() => onToggle(entry.id, !on), [entry.id, on, onToggle]);
const leading = useMemo(
() => <UsageSourceIcon svg={entry.icon ?? null} size={14} />,
[entry.icon],
);
const description =
[entry.account.label, !on && entry.defaultEnabled === false ? inactiveLabel : null]
.filter(Boolean)
.join(" · ") || undefined;
return (
<DropdownMenuCheckboxItem
leading={leading}
description={description}
checked={on}
onToggle={handleSelect}
testID={`usage-source-toggle-${entry.id}`}
>
{entry.sourceLabel}
</DropdownMenuCheckboxItem>
);
}
+42 -17
View File
@@ -20,8 +20,8 @@ export interface UsagePreferences {
serverId: string | null;
/** Report IDs the user arranged, in their order. Shared by every host. */
cardOrder: string[];
/** Report IDs the user turned off. Their cards collapse and leave the sidebar summary. */
cardsOff: string[];
/** Explicit per-report visibility overrides; absent IDs follow the host's `defaultEnabled` hint. */
cardVisibility: Record<string, boolean>;
}
export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = {
@@ -29,11 +29,12 @@ export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = {
pins: null,
serverId: null,
cardOrder: [],
cardsOff: [],
cardVisibility: {},
};
const pinsSchema = z.array(z.object({ sourceId: z.string(), windowId: z.string() }));
const reportIdsSchema = z.array(z.string()).optional().catch(undefined);
const cardVisibilitySchema = z.record(z.string(), z.boolean()).optional().catch(undefined);
export const UsagePreferencesSchema = z
.object({
@@ -44,18 +45,34 @@ export const UsagePreferencesSchema = z
pinned: pinsSchema.optional().catch([]),
serverId: z.string().nullable().catch(null),
cardOrder: reportIdsSchema,
cardVisibility: cardVisibilitySchema,
// COMPAT(usageCardsOff): replaced by cardVisibility in v0.18, remove after 2027-05-22.
cardsOff: reportIdsSchema,
})
.transform(({ displayAs, pins, pinned, serverId, cardOrder, cardsOff }): UsagePreferences => {
const legacyPins = pinned && pinned.length > 0 ? pinned : null;
return {
.transform(
({
displayAs,
pins: pins === undefined ? legacyPins : pins,
pins,
pinned,
serverId,
cardOrder: cardOrder ?? [],
cardsOff: cardsOff ?? [],
};
})
cardOrder,
cardVisibility,
cardsOff,
}): UsagePreferences => {
const legacyPins = pinned && pinned.length > 0 ? pinned : null;
const legacyVisibility =
cardsOff && cardsOff.length > 0
? Object.fromEntries(cardsOff.map((id) => [id, false] as const))
: {};
return {
displayAs,
pins: pins === undefined ? legacyPins : pins,
serverId,
cardOrder: cardOrder ?? [],
cardVisibility: cardVisibility ?? legacyVisibility,
};
},
)
.catch(DEFAULT_USAGE_PREFERENCES);
function samePin(a: UsagePin, b: UsagePin): boolean {
@@ -154,8 +171,8 @@ export function usageReportsOn(
reports: readonly UsageReportEntry[],
preferences: UsagePreferences,
): UsageReportEntry[] {
return arrangeUsageReports(reports, preferences).filter(
(entry) => !isUsageCardOff(preferences, entry.id),
return arrangeUsageReports(reports, preferences).filter((entry) =>
isUsageCardOn(preferences, entry),
);
}
@@ -188,8 +205,14 @@ export function arrangeUsageCards(
return { ...preferences, cardOrder: rest };
}
export function isUsageCardOff(preferences: UsagePreferences, reportId: string): boolean {
return preferences.cardsOff.includes(reportId);
/** Whether a report card is shown, honoring an explicit user override before the host's default hint. */
export function isUsageCardOn(
preferences: UsagePreferences,
entry: Pick<UsageReportEntry, "id" | "defaultEnabled">,
): boolean {
const explicit = preferences.cardVisibility[entry.id];
if (explicit !== undefined) return explicit;
return entry.defaultEnabled !== false;
}
export function setUsageCardOn(
@@ -197,6 +220,8 @@ export function setUsageCardOn(
reportId: string,
on: boolean,
): UsagePreferences {
const others = preferences.cardsOff.filter((id) => id !== reportId);
return { ...preferences, cardsOff: on ? others : [...others, reportId] };
return {
...preferences,
cardVisibility: { ...preferences.cardVisibility, [reportId]: on },
};
}
+8 -4
View File
@@ -4,7 +4,6 @@ import { View } from "react-native";
import { AdaptiveModalSheet, SheetHeaderSubtitle } from "@/components/adaptive-modal-sheet";
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
import { useHostUsageWithControls } from "./controls";
import { useUsageDisplay } from "./display";
import { getHostPickerLabel } from "@/components/hosts/host-picker";
import { hasHostChoice, useUsageHostSelection } from "./hosts";
import type { UsageHost } from "./model";
@@ -50,8 +49,7 @@ function HostUsageModal({
() => ({ hosts, serverId, onSelect: onSelectHost }),
[hosts, onSelectHost, serverId],
);
const { view, refresh, controls } = useHostUsageWithControls(hostSelection);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
const { view, display, refresh, controls, openOptions } = useHostUsageWithControls(hostSelection);
const hostLabel = hasHostChoice(hostSelection)
? getHostPickerLabel(hostSelection.hosts, hostSelection.serverId)
: undefined;
@@ -61,7 +59,13 @@ function HostUsageModal({
host's cards. The frame is not keyed: remounting it would dismiss a compact sheet, and Usage
with it. */}
<View key={serverId} testID={`usage-host-${serverId}`}>
<UsageBody serverId={serverId} view={view} display={display} onRefresh={refresh} />
<UsageBody
serverId={serverId}
view={view}
display={display}
onRefresh={refresh}
onOpenSources={openOptions}
/>
</View>
</UsageModalFrame>
);
+50 -9
View File
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Alert } from "@/components/ui/alert";
@@ -27,14 +27,31 @@ export function UsageSection({
onRefresh: () => void;
testID?: string;
}) {
const [optionsOpen, setOptionsOpen] = useState(false);
const openOptions = useCallback(() => setOptionsOpen(true), []);
const trailing = useMemo(
() => <UsageControls serverId={serverId} view={view} onRefresh={onRefresh} />,
[onRefresh, view, serverId],
() => (
<UsageControls
serverId={serverId}
view={view}
display={display}
onRefresh={onRefresh}
optionsOpen={optionsOpen}
onOptionsOpenChange={setOptionsOpen}
/>
),
[display, onRefresh, optionsOpen, serverId, view],
);
return (
<SettingsSection title={title} testID={testID} trailing={trailing}>
<UsageBody serverId={serverId} view={view} display={display} onRefresh={onRefresh} />
<UsageBody
serverId={serverId}
view={view}
display={display}
onRefresh={onRefresh}
onOpenSources={openOptions}
/>
</SettingsSection>
);
}
@@ -45,14 +62,23 @@ export function UsageBody({
view,
display,
onRefresh,
onOpenSources,
}: {
serverId: string;
view: UsageView;
display: UsageDisplay;
onRefresh: () => void;
onOpenSources?: () => void;
}) {
const { t } = useTranslation();
const setting = useUsageSetting(serverId);
const visibleReports = useMemo(
() =>
view.kind === "ready"
? display.arrange(view.reports).filter((entry) => display.isCardOn(entry))
: [],
[display, view],
);
if (view.kind === "off")
return (
<View>
@@ -84,16 +110,30 @@ export function UsageBody({
);
}
let content: React.ReactNode;
if (view.reports.length === 0) {
content = <UsageMessage text={t("providerUsage.empty")} />;
} else if (visibleReports.length === 0) {
content = (
<View style={[settingsStyles.card, styles.emptyCard]} testID="usage-all-hidden">
<Text style={styles.emptyText}>{t("providerUsage.allSourcesHidden")}</Text>
{onOpenSources ? (
<Button variant="outline" onPress={onOpenSources} testID="usage-choose-sources">
{t("providerUsage.chooseSources")}
</Button>
) : null}
</View>
);
} else {
content = <UsageList serverId={serverId} reports={visibleReports} display={display} />;
}
return (
<View style={styles.reports}>
{view.refreshFailed ? (
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
) : null}
{view.reports.length === 0 ? (
<UsageMessage text={t("providerUsage.empty")} />
) : (
<UsageList serverId={serverId} reports={view.reports} display={display} />
)}
{content}
</View>
);
}
@@ -110,6 +150,7 @@ const styles = StyleSheet.create((theme) => ({
reports: { gap: theme.spacing[3] },
emptyCard: {
padding: theme.spacing[4],
gap: theme.spacing[3],
alignItems: "center",
},
emptyText: {
@@ -199,6 +199,44 @@ describe("agent directory reconciliation", () => {
});
});
it("accepts session metrics from a stale buffered upsert without regressing metadata", () => {
const result = reconcileAgentDirectory({
snapshot: [
{
...entry("agent", "idle"),
agent: {
...snapshot("agent", "idle"),
title: "newer page",
updatedAt: "2026-07-12T12:00:00.000Z",
sessionMetrics: [{ label: "Cost", value: "$0.10" }],
},
},
],
deltas: [
{
kind: "upsert",
agent: {
...snapshot("agent", "running"),
title: "stale live",
updatedAt: "2026-07-12T11:00:00.000Z",
sessionMetrics: [{ label: "Cost", value: "$0.42" }],
},
project: entry("agent", "idle").project,
},
],
});
expect({
title: result[0]?.agent.title,
status: result[0]?.agent.status,
sessionMetrics: result[0]?.agent.sessionMetrics,
}).toEqual({
title: "newer page",
status: "idle",
sessionMetrics: [{ label: "Cost", value: "$0.42" }],
});
});
it("preserves usage when a stale buffered upsert omits it", () => {
const result = reconcileAgentDirectory({
snapshot: [

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