diff --git a/.oxlintrc.json b/.oxlintrc.json index ae335c0e48..fdbb917302 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -530,7 +530,7 @@ } }, // Press feedback is owned by the primitives in components/ui. Raw pressable burn-down: - // 94 files. They may only leave this list. + // 85 files. They may only leave this list. { "files": [ "packages/app/src/components/ui/**/*.{ts,tsx}", @@ -539,12 +539,9 @@ "packages/app/src/agent-skills/selection-sheet.tsx", "packages/app/src/agent-stream/chat-outline/rail.web.tsx", "packages/app/src/agent-stream/view.tsx", - "packages/app/src/changelog/internal/changelog-sheet.tsx", "packages/app/src/command-center/command-center.tsx", - "packages/app/src/components/adaptive-modal-sheet.tsx", "packages/app/src/components/add-project-flow.tsx", "packages/app/src/components/agent-list.tsx", - "packages/app/src/components/app-diagnostic-sheet.tsx", "packages/app/src/components/attachment-lightbox.tsx", "packages/app/src/components/attachment-pill.tsx", "packages/app/src/components/combined-model-selector.tsx", @@ -583,7 +580,6 @@ "packages/app/src/components/terminal-emulator-native-grid.native.tsx", "packages/app/src/components/terminal-pane.tsx", "packages/app/src/components/toast-host.tsx", - "packages/app/src/components/tool-call-sheet.tsx", "packages/app/src/components/welcome-screen.tsx", "packages/app/src/components/workspace-hover-card.tsx", "packages/app/src/components/zoomable-viewport/toolbar.tsx", @@ -619,7 +615,6 @@ "packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx", "packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx", "packages/app/src/screens/workspace/workspace-tab-presentation.tsx", - "packages/app/src/tool-calls/detail-level/overview/sheet.tsx", "packages/app/src/usage/sidebar-item.tsx", "packages/app/src/usage/window-bar.tsx", "packages/app/src/workspace-labels/manager-modal.tsx", diff --git a/CHANGELOG.md b/CHANGELOG.md index a66fde2adf..96bb9aeee0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,42 +1,117 @@ # Changelog -## 0.16.0-beta.1 - 2026-11-10 +## 0.16.1 - 2026-11-17 -- **Background tasks:** Paseo now shows the background tasks an agent is running, such as shells and monitors, above the composer, with a Stop button for each. Works with Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162) by [@fxlelouarn](https://github.com/fxlelouarn)) -- **Plugin sidebar views:** A plugin can replace the sidebar's content with its own layout of workspaces, agents, projects and terminals across every connected host. Pick the view per device under Settings → Sidebar; Paseo's sidebar header and footer stay in place. ([#8906](https://github.com/getpaseo/paseo/pull/8906)) -- **Plugin composer controls:** Plugins can add their own controls to the composer, and read and set its prompt, attachments, provider, model, mode and thinking. They can also put the cursor in any agent's composer, add items to New workspace, and store their own metadata on agents and workspaces. ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207)) -- **Faster diff loading:** Opening Changes shows the file tree right away while file contents load. Large diffs arrive in batches, so the rest of the app keeps responding while they load, and diffs take priority over the daemon's background worktree scans. ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243)) -- **Polish:** The chat stays still when a turn ends, and returning to a chat that has not changed shows it as it is with no refresh. Tool rows show their final title and icon from the first frame, the context window popover opens with usage already loaded, and sidebar hover cards open one at a time. ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175), [#9242](https://github.com/getpaseo/paseo/pull/9242), [#9248](https://github.com/getpaseo/paseo/pull/9248), [#9212](https://github.com/getpaseo/paseo/pull/9212), [#9071](https://github.com/getpaseo/paseo/pull/9071)) -- **Rebuilt mobile chat timeline:** The chat timeline on iOS and Android was rebuilt. Expanding or collapsing a turn summary, todo card or tool-call group keeps the line you tapped in place, and on Android so do Show more, Show less and plan cards. ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085)) -- **Keyboard shortcuts on mobile:** With a keyboard connected, iPad and Android now run the same shortcuts as desktop, including your custom bindings. Shortcut hints and Settings → Shortcuts appear when a keyboard is detected. Shortcuts also work in narrow desktop and browser windows. ([#8625](https://github.com/getpaseo/paseo/pull/8625) by [@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud)) -- **Touch-sized tablet controls:** On iPad and other touch-screen devices, the wide layout now has touch-sized buttons, rows and bars. The composer toolbar folds its controls into the model menu when space runs out, and swiping right on the workspace reveals a collapsed sidebar as an overlay. ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739) by [@zeyugao](https://github.com/zeyugao)) -- **Undo workspace archive:** Archiving a workspace in the app now shows a "Workspace archived" toast for six seconds. Undo, or Cmd/Ctrl+Z, restores the workspace with its tabs and agents. On desktop, sidebar workspace rows also get an archive button on hover. ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104)) -- **Fewer reconnects on return:** Returning to the app keeps a working connection, including one in the middle of a large response, and reconnects once when it has to. On a host with several saved connections, Paseo stays on the one that works. ([#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116)) +### Fixed + +- Fixed Claude Bypass approving actions without a permission card when a `permissions.ask` rule or a hook that returns `ask` required one ([#9927](https://github.com/getpaseo/paseo/pull/9927)) +- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input ([#9909](https://github.com/getpaseo/paseo/pull/9909) by [@michaelhthomas](https://github.com/michaelhthomas)) +- Fixed Claude sessions failing until `/login` when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token ([#9855](https://github.com/getpaseo/paseo/pull/9855) by [@daysun-k](https://github.com/daysun-k)) +- Fixed Add host text fields on web drawing without a box, which left the host password field invisible ([#9865](https://github.com/getpaseo/paseo/pull/9865) by [@angusb93](https://github.com/angusb93)) +- Fixed an OpenCode question that could not be answered or dismissed after a new message steered the turn ([#9891](https://github.com/getpaseo/paseo/pull/9891)) +- Fixed Pi and OMP model names that contain `/` being cut to the text after the last slash ([#9823](https://github.com/getpaseo/paseo/pull/9823), [#9836](https://github.com/getpaseo/paseo/pull/9836) by [@rms523](https://github.com/rms523)) +- Fixed Changes leaving out an edit when the file was saved with the same size in the same second it was staged ([#9854](https://github.com/getpaseo/paseo/pull/9854)) +- Fixed an error toast that never closed when marking a chat as read failed ([#9837](https://github.com/getpaseo/paseo/pull/9837)) +- Fixed wait results and finish notifications after a daemon restart joining an agent's self-started reply to the reply before it ([#9846](https://github.com/getpaseo/paseo/pull/9846)) +- Fixed Codex chats staying loaded in the daemon until restart when a client opened them only to read their history ([#9859](https://github.com/getpaseo/paseo/pull/9859) by [@Spshulem](https://github.com/Spshulem)) + +## 0.16.0 - 2026-11-16 + +- **Background tasks:** See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635) by [@fxlelouarn](https://github.com/fxlelouarn)) +- **Built-in plugin gallery:** Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. ([#9752](https://github.com/getpaseo/paseo/pull/9752)) +- **Command center tabs:** Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. ([#9689](https://github.com/getpaseo/paseo/pull/9689)) +- **Plugin sidebar views:** Plugins can replace the sidebar with their own workspace and agent layout across connected hosts. Choose a view per device in Settings → Sidebar. ([#8906](https://github.com/getpaseo/paseo/pull/8906)) +- **Plugin composer controls:** Plugins can add composer controls, edit drafts and attachments, and change agent settings. They can also add New workspace items and save metadata on agents and workspaces. ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207), [#9734](https://github.com/getpaseo/paseo/pull/9734) by [@michaelmwu](https://github.com/michaelmwu)) +- **Arrange Usage cards:** Drag provider cards into your preferred order and turn off cards you do not want in the sidebar summary. Choose the host from Usage settings. ([#9660](https://github.com/getpaseo/paseo/pull/9660), [#9740](https://github.com/getpaseo/paseo/pull/9740), [#9748](https://github.com/getpaseo/paseo/pull/9748), [#9780](https://github.com/getpaseo/paseo/pull/9780)) +- **Quieter app reopening:** Returning to an unchanged chat no longer flashes “Updating messages.” Paseo keeps healthy connections open and recovers dropped connections when you return. After reconnecting, an up-to-date chat no longer shows an extra update toast. ([#9242](https://github.com/getpaseo/paseo/pull/9242), [#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116), [#9558](https://github.com/getpaseo/paseo/pull/9558) by [@adamcstephens](https://github.com/adamcstephens)) +- **Rebuilt mobile chat:** Expanding turn summaries, todo cards and tool groups keeps your reading position on iOS and Android. Sending during a scroll moves to the new prompt. ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085), [#9806](https://github.com/getpaseo/paseo/pull/9806), [#9693](https://github.com/getpaseo/paseo/pull/9693)) +- **Faster diff loading:** Changes shows the file tree before file contents finish loading. Large diffs load in batches and take priority over background worktree scans. ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243), [#9584](https://github.com/getpaseo/paseo/pull/9584)) +- **Faster composer menus:** Command and file suggestions open sooner in large lists and stay against the composer as it changes size. ([#9657](https://github.com/getpaseo/paseo/pull/9657), [#9647](https://github.com/getpaseo/paseo/pull/9647), [#9642](https://github.com/getpaseo/paseo/pull/9642)) +- **Keyboard shortcuts on mobile:** A connected keyboard gives iPad and Android the same shortcuts as desktop, including custom bindings. Shift+Tab in the iPad composer switches mode without typing a tab. ([#8625](https://github.com/getpaseo/paseo/pull/8625), [#9561](https://github.com/getpaseo/paseo/pull/9561) by [@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud)) +- **Touch-sized tablet controls:** Wide layouts on touch devices have larger buttons and rows. The composer folds controls into the model menu when space runs out. ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739) by [@zeyugao](https://github.com/zeyugao)) +- **Undo workspace archive:** Restore an archived workspace with Undo or Cmd/Ctrl+Z during the six-second toast. Paseo checks for unsaved files and unpushed commits before removing a worktree. ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104), [#9625](https://github.com/getpaseo/paseo/pull/9625), [#9753](https://github.com/getpaseo/paseo/pull/9753) by [@ragokan](https://github.com/ragokan)) ### Added -- Added a Change base picker in Changes for worktree workspaces, so diffs, the commit list and Git actions can use another branch ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934) by [@Myasuka](https://github.com/Myasuka)) -- Added links for issue and pull request references such as `#123` and `owner/repo#123` in agent replies, plans, the pull request panel and file previews, for GitHub, GitLab, Gitea, Forgejo and Codeberg ([#8636](https://github.com/getpaseo/paseo/pull/8636)) -- Added iPhone Duo layout support: workspace actions sit in the system vertical bar, and the sidebar and workspace split on either side of the fold ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901) by [@zeyugao](https://github.com/zeyugao)) +- Added a Change base picker for worktree diffs, commits and Git actions ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934) by [@Myasuka](https://github.com/Myasuka)) +- Added issue and pull request links that resolve SSH aliases and fork parent repositories ([#8636](https://github.com/getpaseo/paseo/pull/8636), [#9576](https://github.com/getpaseo/paseo/pull/9576)) +- Added an iPhone Duo layout with the sidebar and workspace on opposite sides of the fold ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901) by [@zeyugao](https://github.com/zeyugao)) - Added fx as a provider you can add from the provider catalog in Settings → Hosts → Providers ([#9160](https://github.com/getpaseo/paseo/pull/9160)) -- Added background agents: an agent or plugin can create a helper with `background: true` that opens no tab, sends no notification and stays out of the sidebar and default agent lists ([#8683](https://github.com/getpaseo/paseo/pull/8683)) +- Added background agents that stay out of tabs, notifications and default agent lists ([#8683](https://github.com/getpaseo/paseo/pull/8683)) - Added syntax highlighting for Terraform and HCL files (`.tf`, `.tfvars`, `.hcl`) ([#9106](https://github.com/getpaseo/paseo/pull/9106)) - Added `PASEO_WORKSPACE_ID` to each agent's environment so an agent can identify, rename or archive its own workspace ([#8939](https://github.com/getpaseo/paseo/pull/8939) by [@DTTerastar](https://github.com/DTTerastar)) +- Added plugin badges to sidebar workspace rows ([#7645](https://github.com/getpaseo/paseo/pull/7645) by [@jtomaszewski](https://github.com/jtomaszewski)) +- Added a Download button for files without a preview ([#9640](https://github.com/getpaseo/paseo/pull/9640)) +- Added Copilot premium-request usage and remaining quota to Usage ([#8489](https://github.com/getpaseo/paseo/pull/8489) by [@thisisryanswift](https://github.com/thisisryanswift)) ### Changed - Changed opening a workspace to restore the tab you left instead of jumping to the agent that needs attention ([#8935](https://github.com/getpaseo/paseo/pull/8935)) -- Changed question cards so picking an option no longer advances automatically; continue with Next or Submit ([#8525](https://github.com/getpaseo/paseo/pull/8525)) -- Changed the slash command menu to show loading and error states with Retry, and to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905)) -- Changed the workspace header and tabs to switch to compact controls when Explorer or a split pane narrows the workspace ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao)) +- Changed question cards to wait for Next or Submit after you select an option ([#8525](https://github.com/getpaseo/paseo/pull/8525)) +- Changed the slash command menu to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905)) +- Changed workspace header controls to fit narrow split panes ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao)) - Changed sending a message to a Pi agent whose process has exited to fail immediately with an instruction to reload the agent ([#8718](https://github.com/getpaseo/paseo/pull/8718)) +- Changed Rename workspace in the sidebar on desktop and wide web layouts to edit the title in place instead of opening a dialog ([#9280](https://github.com/getpaseo/paseo/pull/9280)) +- Changed What's new to show highlights first, with the full list behind Show all changes ([#9281](https://github.com/getpaseo/paseo/pull/9281)) +- Changed Claude Bypass to approve execution requests from ask rules and hooks while keeping questions and plan review interactive ([#9760](https://github.com/getpaseo/paseo/pull/9760)) +- Changed Claude permission cards to show the reason supplied by the provider ([#3950](https://github.com/getpaseo/paseo/pull/3950) by [@codebutler](https://github.com/codebutler)) +- Changed the pull request pane so Activity can be resized or collapsed to give checks more space ([#9656](https://github.com/getpaseo/paseo/pull/9656)) +- Changed macOS desktop tab shortcuts to Cmd+Shift+[ and Cmd+Shift+] ([#7692](https://github.com/getpaseo/paseo/pull/7692) by [@jtomaszewski](https://github.com/jtomaszewski)) +- Changed Cmd/Ctrl+N on New workspace to open the project chooser without leaving the draft ([#9741](https://github.com/getpaseo/paseo/pull/9741)) +- Changed mobile Settings navigation to restore the sidebar where you left it ([#9641](https://github.com/getpaseo/paseo/pull/9641)) ### Fixed +- Fixed long tool details hiding their collapse header or preventing scrolling through their output ([#9770](https://github.com/getpaseo/paseo/pull/9770)) +- Fixed image previews briefly showing an error or a stretched image while loading ([#9698](https://github.com/getpaseo/paseo/pull/9698)) +- Fixed web and desktop chats jumping to the beginning when older history became virtualized ([#9664](https://github.com/getpaseo/paseo/pull/9664) by [@luoph](https://github.com/luoph)) +- Fixed older chat history requiring another mouse-wheel movement after reaching the top ([#9570](https://github.com/getpaseo/paseo/pull/9570)) +- Fixed losing code indentation and line breaks when copying a selection across part of a code block ([#9515](https://github.com/getpaseo/paseo/pull/9515) by [@michaelmwu](https://github.com/michaelmwu)) +- Fixed overlapping axis titles and clipped labels in Mermaid XY charts ([#9483](https://github.com/getpaseo/paseo/pull/9483) by [@FluidXin](https://github.com/FluidXin)) +- Fixed the iOS command menu staying open after tapping a command ([#9755](https://github.com/getpaseo/paseo/pull/9755)) +- Fixed retrying an edited agent draft after a failed start ([#9534](https://github.com/getpaseo/paseo/pull/9534) by [@michaelmwu](https://github.com/michaelmwu)) +- Fixed model profile buttons ignoring taps on Android tablets ([#9526](https://github.com/getpaseo/paseo/pull/9526) by [@moevis](https://github.com/moevis)) +- Fixed Settings losing scroll position and edits after appearance changes ([#9605](https://github.com/getpaseo/paseo/pull/9605)) +- Fixed unreadable selected rows in light plugin themes and barely visible highlights in Pure Black ([#9579](https://github.com/getpaseo/paseo/pull/9579) by [@nathansgreen](https://github.com/nathansgreen)) +- Fixed missing keyboard focus rings on header and toolbar icon buttons on web and desktop ([#9745](https://github.com/getpaseo/paseo/pull/9745) by [@junjzhang](https://github.com/junjzhang)) +- Fixed sidebar rows flashing in the wrong position after a drag on iOS and Android ([#9681](https://github.com/getpaseo/paseo/pull/9681)) +- Fixed desktop startup reporting failure while its daemon was still starting ([#9043](https://github.com/getpaseo/paseo/pull/9043) by [@magiclaw](https://github.com/magiclaw)) +- Fixed typed characters being lost while web and desktop terminals restored their screen ([#9533](https://github.com/getpaseo/paseo/pull/9533)) +- Fixed physical arrow keys failing in Android terminals and dropping the next typed character ([#9407](https://github.com/getpaseo/paseo/pull/9407) by [@moevis](https://github.com/moevis)) +- Fixed non-Git workspaces missing Archive workspace in the command center ([#9777](https://github.com/getpaseo/paseo/pull/9777) by [@andheiberg](https://github.com/andheiberg)) +- Fixed workspace scripts disappearing when a later configuration read timed out ([#9477](https://github.com/getpaseo/paseo/pull/9477) by [@dinhphieu](https://github.com/dinhphieu)) +- Fixed sidebar Usage hiding an account after its usage refresh failed ([#9594](https://github.com/getpaseo/paseo/pull/9594)) +- Fixed closed agents staying unread when their provider session no longer existed ([#9737](https://github.com/getpaseo/paseo/pull/9737) by [@luoph](https://github.com/luoph)) +- Fixed completion notifications showing an older reply after an autonomous agent turn ([#9793](https://github.com/getpaseo/paseo/pull/9793)) +- Fixed interrupting messages failing with "already has an active run" ([#9537](https://github.com/getpaseo/paseo/pull/9537) by [@michaelmwu](https://github.com/michaelmwu)) +- Fixed message retries being refused after a failure before delivery to the provider ([#9580](https://github.com/getpaseo/paseo/pull/9580) by [@tmad4000](https://github.com/tmad4000)) +- Fixed newly reopened agents losing their provider process on the next idle-cleanup sweep ([#8857](https://github.com/getpaseo/paseo/pull/8857) by [@fdkevin0](https://github.com/fdkevin0)) +- Fixed Claude session crons and /loop wakeups being lost to idle runtime cleanup ([#9744](https://github.com/getpaseo/paseo/pull/9744) by [@KronixDev](https://github.com/KronixDev)) +- Fixed forking from a reply when a tool started before it and finished afterward ([#9627](https://github.com/getpaseo/paseo/pull/9627) by [@ragokan](https://github.com/ragokan)) +- Fixed large Codex history pages stopping history loading when their individual items still fit ([#9432](https://github.com/getpaseo/paseo/pull/9432) by [@RockStone](https://github.com/RockStone)) +- Fixed OpenCode sessions failing to reconnect after a daemon restart when OpenCode used Bun ([#9653](https://github.com/getpaseo/paseo/pull/9653) by [@quickwind](https://github.com/quickwind)) +- Fixed provider refresh retaining OpenCode v1 after an upgrade to v2 ([#9593](https://github.com/getpaseo/paseo/pull/9593) by [@tkfka1](https://github.com/tkfka1)) +- Fixed OpenCode v2 failing to discover plugin tools available only to its session ([#9426](https://github.com/getpaseo/paseo/pull/9426) by [@dptsolutions](https://github.com/dptsolutions)) +- Fixed ACP models sharing the wrong thinking levels when the provider supplied levels per model ([#9717](https://github.com/getpaseo/paseo/pull/9717) by [@AlfredRR](https://github.com/AlfredRR), [@doskoi](https://github.com/doskoi)) +- Fixed failed ACP tools without output preventing conversation history from loading ([#9467](https://github.com/getpaseo/paseo/pull/9467) by [@Myasuka](https://github.com/Myasuka)) +- Fixed Pi and OMP tool calls with null optional arguments appearing as unknown tools ([#9506](https://github.com/getpaseo/paseo/pull/9506) by [@papag00se](https://github.com/papag00se)) +- Fixed imported OMP sessions saving a file path instead of their session ID ([#8854](https://github.com/getpaseo/paseo/pull/8854) by [@LiebeLee](https://github.com/LiebeLee)) +- Fixed cross-host child agents losing their caller's mode when both used the same provider ([#9512](https://github.com/getpaseo/paseo/pull/9512) by [@ortschun](https://github.com/ortschun)) +- Fixed plugin child agents changing from failed or canceled to completed when their session closed ([#8563](https://github.com/getpaseo/paseo/pull/8563) by [@hadan8977](https://github.com/hadan8977)) +- Fixed CLI commands acting on a different agent whose title matched a missing full agent ID ([#9680](https://github.com/getpaseo/paseo/pull/9680), [#9731](https://github.com/getpaseo/paseo/pull/9731) by [@ese111](https://github.com/ese111)) +- Fixed archive, detach and reload failing for agents omitted from the CLI listing ([#9726](https://github.com/getpaseo/paseo/pull/9726) by [@xunWhale](https://github.com/xunWhale)) +- Fixed `paseo agent wait` exiting successfully when no agent matched the ID ([#9782](https://github.com/getpaseo/paseo/pull/9782) by [@Eapp1e](https://github.com/Eapp1e)) +- Fixed voice mode failing to start when speech input and output both used OpenAI ([#9779](https://github.com/getpaseo/paseo/pull/9779) by [@Huyvux12](https://github.com/Huyvux12)) +- Fixed dictation hiding a stream error behind a 30-second delivery timeout ([#9784](https://github.com/getpaseo/paseo/pull/9784) by [@tieo](https://github.com/tieo)) +- Fixed plugin providers rejecting Review attachments in All mode ([#9590](https://github.com/getpaseo/paseo/pull/9590) by [@ese111](https://github.com/ese111)) +- Fixed plugin timeline writes accepting kinds that the app could not show ([#7677](https://github.com/getpaseo/paseo/pull/7677) by [@ragokan](https://github.com/ragokan)) +- Fixed the chat moving when a turn ended ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175)) +- Fixed Claude and OpenCode tool rows changing their title and icon as arguments arrived ([#9248](https://github.com/getpaseo/paseo/pull/9248)) +- Fixed the context window popover opening before usage was loaded ([#9212](https://github.com/getpaseo/paseo/pull/9212)) +- Fixed sidebar hover cards opening together ([#9071](https://github.com/getpaseo/paseo/pull/9071)) + - Fixed the working indicator disappearing when returning to a chat whose agent finished while you were away ([#9170](https://github.com/getpaseo/paseo/pull/9170)) -- Fixed chats with short collapsed turns opening with empty space until you scrolled ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083)) - Fixed Collapse turns hiding an earlier reply inside a later turn's summary line after an idle Claude, Codex or OpenCode agent was resumed ([#9098](https://github.com/getpaseo/paseo/pull/9098)) -- Fixed the missing space between a prompt and the reply or collapsed-turn summary line below it ([#9009](https://github.com/getpaseo/paseo/pull/9009)) - Fixed Markdown tables showing as literal pipes when written directly below a paragraph with no blank line ([#8485](https://github.com/getpaseo/paseo/pull/8485) by [@ragokan](https://github.com/ragokan), [@suk-6](https://github.com/suk-6), [@thsrite](https://github.com/thsrite)) - Fixed linked badge images that share a line with text rendering as full-width blocks on web and desktop ([#8530](https://github.com/getpaseo/paseo/pull/8530)) - Fixed View diagram opening fullscreen instead of returning to the inline Mermaid diagram after View source ([#8932](https://github.com/getpaseo/paseo/pull/8932) by [@luoph](https://github.com/luoph)) @@ -44,20 +119,16 @@ - Fixed unsent composer text and attachments being deleted when an agent tab was closed ([#9079](https://github.com/getpaseo/paseo/pull/9079)) - Fixed pasting text with hyperlinks into the composer dropping the link URLs; links now paste as Markdown ([#8972](https://github.com/getpaseo/paseo/pull/8972)) - Fixed the composer losing focus after clicking Send with a mouse ([#9015](https://github.com/getpaseo/paseo/pull/9015)) -- Fixed the composer resting 50pt above the bottom edge on iPhone ([#8823](https://github.com/getpaseo/paseo/pull/8823) by [@zeyugao](https://github.com/zeyugao)) - Fixed Add host sending you to Settings from the sidebar and New workspace ([#8512](https://github.com/getpaseo/paseo/pull/8512)) - Fixed a failed agent's red dot and Failed grouping staying in the sidebar after opening the agent or choosing Mark as read ([#8831](https://github.com/getpaseo/paseo/pull/8831)) -- Fixed a workspace's unread indicator staying on after it was cleared while the agent's runtime was closed ([#9087](https://github.com/getpaseo/paseo/pull/9087)) +- Fixed unarchiving a workspace not restoring the agents that were archived with it ([#9210](https://github.com/getpaseo/paseo/pull/9210)) - Fixed the context window popover closing by itself whenever the chat scrolled during a streaming reply ([#8742](https://github.com/getpaseo/paseo/pull/8742) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed the sidebar usage summary updating only when Usage was opened ([#7806](https://github.com/getpaseo/paseo/pull/7806) by [@ragokan](https://github.com/ragokan)) -- Fixed tooltips and menus above their trigger briefly covering it on Android when their content grew after opening ([#9247](https://github.com/getpaseo/paseo/pull/9247)) - Fixed History showing "Could not load history" after reloading the web app on the History screen ([#9029](https://github.com/getpaseo/paseo/pull/9029)) - Fixed section links in an HTML file preview replacing the preview with the Paseo app instead of scrolling within the file ([#8559](https://github.com/getpaseo/paseo/pull/8559) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed Files Refresh leaving a newly created file hidden when its folder was collapsed during the refresh ([#8582](https://github.com/getpaseo/paseo/pull/8582) by [@hadan8977](https://github.com/hadan8977)) - Fixed the branch switcher showing "No branches found" while branches are still loading or after the request fails ([#8938](https://github.com/getpaseo/paseo/pull/8938)) - Fixed commit history showing a doubled slash, no rename status and no diff for a file moved up a directory ([#8509](https://github.com/getpaseo/paseo/pull/8509) by [@hadan8977](https://github.com/hadan8977)) -- Fixed a merged pull request disappearing from its workspace when the checkout was behind the pull request's head -- Fixed workspace Git watchers staying in fallback polling after a watcher setup timeout - Fixed abandoned connections staying open for up to 45 seconds after the web or desktop app reconnected ([#9067](https://github.com/getpaseo/paseo/pull/9067)) - Fixed a connection routed through another host closing with "The receiving client cannot keep up with host output" while fetching a very large timeline ([#9109](https://github.com/getpaseo/paseo/pull/9109)) - Fixed a connected host staying in error after it was updated to a supported version ([#8423](https://github.com/getpaseo/paseo/pull/8423) by [@DAnaeto](https://github.com/DAnaeto)) @@ -73,11 +144,13 @@ - Fixed Codex "Apply file changes" approvals showing no file name or diff before you accept ([#8585](https://github.com/getpaseo/paseo/pull/8585) by [@ragokan](https://github.com/ragokan)) - Fixed the timeline showing only the first file's diff when Codex edits several files in one patch ([#8613](https://github.com/getpaseo/paseo/pull/8613) by [@ragokan](https://github.com/ragokan)) - Fixed Codex session discovery and startup intermittently failing with a SQLite initialization error when several Codex operations start at once ([#9008](https://github.com/getpaseo/paseo/pull/9008) by [@colonelpanic8](https://github.com/colonelpanic8), [@michaelmwu](https://github.com/michaelmwu)) +- Fixed Codex reconnect attempts and warnings not appearing in the timeline ([#9370](https://github.com/getpaseo/paseo/pull/9370) by [@whatamelon](https://github.com/whatamelon)) - Fixed OpenCode conversations that were mid-turn during a daemon restart showing idle and ignoring Stop ([#8698](https://github.com/getpaseo/paseo/pull/8698)) - Fixed OpenCode being told you declined a tool call when you sent a message while its approval was pending ([#8477](https://github.com/getpaseo/paseo/pull/8477)) - Fixed reopened Pi conversations missing the messages from before a context compaction ([#8523](https://github.com/getpaseo/paseo/pull/8523)) - Fixed archived Pi chats failing to open with `spawn pi ENOENT` after their working folder was removed ([#8442](https://github.com/getpaseo/paseo/pull/8442) by [@DAnaeto](https://github.com/DAnaeto)) - Fixed reading an archived Pi chat leaving a Pi process running when idle runtime cleanup is disabled ([#8554](https://github.com/getpaseo/paseo/pull/8554) by [@rylwin](https://github.com/rylwin)) +- Fixed resumed pi-subagents runs missing from the Subagents track ([#9261](https://github.com/getpaseo/paseo/pull/9261) by [@xxachangxx](https://github.com/xxachangxx)) - Fixed a prompt sent to an ACP agent whose process has exited staying in running forever instead of failing with an error ([#8406](https://github.com/getpaseo/paseo/pull/8406) by [@DAnaeto](https://github.com/DAnaeto)) - Fixed an ACP agent staying stuck on "waiting for permission" after it abandoned an approval request and ended its turn ([#8548](https://github.com/getpaseo/paseo/pull/8548) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed changing the mode of an ACP agent failing with `invalid_params` after the agent sends a config update ([#8912](https://github.com/getpaseo/paseo/pull/8912) by [@a-sh](https://github.com/a-sh)) @@ -109,21 +182,29 @@ ### Plugins - Added plugin subscriptions, which stream live events from the daemon to a plugin's panels, and binary (`Uint8Array`) payloads for plugin RPCs and events ([#8527](https://github.com/getpaseo/paseo/pull/8527)) +- Added an agent's background task count (`backgroundWork.count`) and `background` flag to plugin agent snapshots, and a `background` flag to agent hooks ([#9362](https://github.com/getpaseo/paseo/pull/9362)) - Changed Settings → Plugins to open a plugin's settings from a cog button, with a tab per settings screen ([#8675](https://github.com/getpaseo/paseo/pull/8675)) - Added an upward chevron to plugin composer pills that open a menu or popover ([#8673](https://github.com/getpaseo/paseo/pull/8673)) - Changed daemon startup to launch configured plugins concurrently instead of one after another ([#8427](https://github.com/getpaseo/paseo/pull/8427) by [@DAnaeto](https://github.com/DAnaeto)) - Fixed registry plugin installs failing with "npm artifact changed since review" when the host's npm uses a registry mirror ([#8756](https://github.com/getpaseo/paseo/pull/8756) by [@tlipoca9](https://github.com/tlipoca9)) +- Fixed a plugin the daemon terminated for an invalid message staying listed with no exit reported ([#9285](https://github.com/getpaseo/paseo/pull/9285) by [@Brandon168](https://github.com/Brandon168)) +- Fixed ACP provider plugins dropping the token usage an agent reports in its prompt response ([#9396](https://github.com/getpaseo/paseo/pull/9396) by [@Myasuka](https://github.com/Myasuka)) - Fixed the published `@getpaseo/*` npm packages declaring no license; they now declare Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816) by [@mdlawson](https://github.com/mdlawson), [@ragokan](https://github.com/ragokan)) -- Fixed forking from an earlier reply failing with "This checkpoint changed after it was created" after a plugin updated one of its timeline cards ([#8746](https://github.com/getpaseo/paseo/pull/8746) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) - Fixed Collapse turns leaving a turn open, or folding to an earlier reply, when a plugin renders the final reply ([#8811](https://github.com/getpaseo/paseo/pull/8811) by [@geoqiao](https://github.com/geoqiao)) - Fixed plugin screens showing "This plugin surface is unavailable" while the plugin catalog is still loading after an app reload ([#8123](https://github.com/getpaseo/paseo/pull/8123) by [@vs-tahir](https://github.com/vs-tahir)) - Fixed the Workspaces list being pushed out of the mobile sidebar on short screens when plugins add many navigation items ([#8727](https://github.com/getpaseo/paseo/pull/8727) by [@jaredwang](https://github.com/jaredwang)) - Fixed timeline plugins not receiving the sender, event and original text on agent-message tool calls ([#8492](https://github.com/getpaseo/paseo/pull/8492) by [@RRD-dev](https://github.com/RRD-dev), [@luoph](https://github.com/luoph)) - Fixed plugin RPCs failing when their input or output schema uses a transform ([#8550](https://github.com/getpaseo/paseo/pull/8550)) +### Breaking + +- Removed the deprecated `agent.turn.after.timeline` SDK field, which always returned an empty list ([#9573](https://github.com/getpaseo/paseo/pull/9573) by [@jtomaszewski](https://github.com/jtomaszewski)) + ### Notes -- Background tasks, the Change base picker, archive undo, background agents, plugin subscriptions and fx need both the host and the app on this version +- Update both the host and app to use the plugin gallery, background tasks, Change base, archive undo, background agents, plugin subscriptions and fx +- Plugin authors reading `agent.turn.after.timeline` must use `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })` and filter entries by `event.turnId` +- Archive undo restores the workspace, not uncommitted files removed with its worktree ## 0.15.4 - 2026-11-10 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index fd91d002ab..62dc8df5f8 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,42 +1,117 @@ # Changelog -## 0.16.0-beta.1 - 2026-11-10 +## 0.16.1 - 2026-11-17 -- **后台任务**:Paseo 现在会在 Composer 上方显示 Agent 正在运行的后台任务,例如 shell 和监视器,每项都带“停止”按钮。支持 Claude Code、Codex 和 OpenCode v2。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162),贡献者:[@fxlelouarn](https://github.com/fxlelouarn)) -- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏内容,展示所有已连接主机上的工作区、Agent、项目和终端。在“设置 → 侧边栏”中为每台设备选择视图;Paseo 的侧边栏页眉和页脚保持不变。 ([#8906](https://github.com/getpaseo/paseo/pull/8906)) -- **插件 Composer 控件**:插件可以向 Composer 添加自己的控件,并读取和设置其中的提示词、附件、Provider、模型、模式和思考强度。插件还可以把光标放到任意 Agent 的 Composer 中、向“新建工作区”添加条目,并在 Agent 和工作区上保存自己的元数据。 ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207)) -- **更快的 diff 加载**:打开“更改”时会立即显示文件树,文件内容随后加载。大型 diff 分批到达,加载期间应用的其他部分照常响应,并且 diff 优先于 daemon 的后台 worktree 扫描。 ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243)) -- **细节打磨**:一轮对话结束时聊天保持不动,返回没有变化的聊天时直接显示原样,无需刷新。工具行从第一帧起就显示最终标题和图标,上下文窗口浮层打开时用量已加载完成,侧边栏悬停卡片一次只打开一个。 ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175), [#9242](https://github.com/getpaseo/paseo/pull/9242), [#9248](https://github.com/getpaseo/paseo/pull/9248), [#9212](https://github.com/getpaseo/paseo/pull/9212), [#9071](https://github.com/getpaseo/paseo/pull/9071)) -- **重建移动端聊天时间线**:iOS 和 Android 上的聊天时间线已重建。展开或折叠轮次摘要、待办卡片或工具调用组时,你点按的那一行保持原位;在 Android 上,“显示更多”“收起”和计划卡片也是如此。 ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085)) -- **移动端键盘快捷键**:连接键盘后,iPad 和 Android 现在可使用与桌面端相同的快捷键,包括你自定义的绑定。检测到键盘时会显示快捷键提示和“设置 → 快捷键”。在较窄的桌面端和浏览器窗口中快捷键同样可用。 ([#8625](https://github.com/getpaseo/paseo/pull/8625),贡献者:[@jeroenfrenken](https://github.com/jeroenfrenken)、[@lstroud](https://github.com/lstroud)) -- **适合触控的平板控件**:在 iPad 和其他触屏设备上,宽屏布局现在使用适合触控尺寸的按钮、行和栏。Composer 工具栏在空间不足时会把控件收进模型菜单;在工作区上向右滑动,可将已折叠的侧边栏以浮层方式显示。 ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739),贡献者:[@zeyugao](https://github.com/zeyugao)) -- **撤销工作区归档**:在应用中归档工作区时,现在会显示“Workspace 已归档”提示,持续六秒。点击“撤销”或按 Cmd/Ctrl+Z 可恢复该工作区及其标签页和 Agent。在桌面端,侧边栏的工作区行在悬停时还会显示归档按钮。 ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104)) -- **返回时更少重连**:返回应用时会保留仍可用的连接,包括正在传输大型响应的连接,只在必要时重连一次。主机保存了多个连接时,Paseo 会留在可用的那个连接上。 ([#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116)) +### 修复 + +- 修复 `permissions.ask` 规则或返回 `ask` 的钩子要求确认时,Claude Bypass 不显示权限卡片就批准操作的问题 ([#9927](https://github.com/getpaseo/paseo/pull/9927)) +- 修复触屏笔记本以触控板或鼠标为主要输入时,控件仍使用触控尺寸的问题 ([#9909](https://github.com/getpaseo/paseo/pull/9909),贡献者:[@michaelhthomas](https://github.com/michaelhthomas)) +- 修复 Claude Code 正在续期已过期的访问令牌时,Paseo 刷新 Claude 模型列表导致 Claude 会话在执行 `/login` 前一直失败的问题 ([#9855](https://github.com/getpaseo/paseo/pull/9855),贡献者:[@daysun-k](https://github.com/daysun-k)) +- 修复 Web 端“添加主机”的文本字段没有输入框,导致主机密码字段不可见的问题 ([#9865](https://github.com/getpaseo/paseo/pull/9865),贡献者:[@angusb93](https://github.com/angusb93)) +- 修复新消息引导当前回合后,OpenCode 提问既无法回答也无法关闭的问题 ([#9891](https://github.com/getpaseo/paseo/pull/9891)) +- 修复名称包含 `/` 的 Pi 和 OMP 模型被截成最后一个斜杠之后文本的问题 ([#9823](https://github.com/getpaseo/paseo/pull/9823), [#9836](https://github.com/getpaseo/paseo/pull/9836),贡献者:[@rms523](https://github.com/rms523)) +- 修复文件暂存后在同一秒内以相同大小保存时,“更改”遗漏该修改的问题 ([#9854](https://github.com/getpaseo/paseo/pull/9854)) +- 修复将对话标记为已读失败后,错误提示一直不关闭的问题 ([#9837](https://github.com/getpaseo/paseo/pull/9837)) +- 修复 daemon 重启后,等待结果和完成通知把 Agent 自行开始的回复与上一条回复拼接在一起的问题 ([#9846](https://github.com/getpaseo/paseo/pull/9846)) +- 修复客户端仅为读取历史而打开的 Codex 对话一直加载在 daemon 中直到重启的问题 ([#9859](https://github.com/getpaseo/paseo/pull/9859),贡献者:[@Spshulem](https://github.com/Spshulem)) + +## 0.16.0 - 2026-11-16 + +- **后台任务**:在 Composer 上方查看并停止 Claude Code、Codex 和 OpenCode v2 的后台任务。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635),贡献者:[@fxlelouarn](https://github.com/fxlelouarn)) +- **内置插件库**:无需离开 Paseo,即可浏览、搜索和安装插件,并在同一页面管理插件设置和更新。 ([#9752](https://github.com/getpaseo/paseo/pull/9752)) +- **命令中心标签页**:在工作区、文件和操作之间切换,最近使用的工作区优先显示。搜索现在包含已归档工作区,还可匹配工作区内的 Agent 标题。 ([#9689](https://github.com/getpaseo/paseo/pull/9689)) +- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏,展示已连接主机上的工作区和 Agent。在“设置 → 侧边栏”中为每台设备选择视图。 ([#8906](https://github.com/getpaseo/paseo/pull/8906)) +- **插件 Composer 控件**:插件可以添加 Composer 控件、编辑草稿和附件,以及更改 Agent 设置。插件还可以添加“新建工作区”条目,并在 Agent 和工作区上保存元数据。 ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207), [#9734](https://github.com/getpaseo/paseo/pull/9734),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- **排列用量卡片**:拖动 Provider 卡片来调整顺序,并关闭不想在侧边栏摘要中显示的卡片。在用量设置中选择主机。 ([#9660](https://github.com/getpaseo/paseo/pull/9660), [#9740](https://github.com/getpaseo/paseo/pull/9740), [#9748](https://github.com/getpaseo/paseo/pull/9748), [#9780](https://github.com/getpaseo/paseo/pull/9780)) +- **返回应用时更少提示**:返回没有变化的聊天时,不再闪现“正在更新消息”。Paseo 会保留可用的连接,并在你返回时恢复断开的连接。重连后,已是最新状态的聊天也不再显示额外的更新提示。 ([#9242](https://github.com/getpaseo/paseo/pull/9242), [#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116), [#9558](https://github.com/getpaseo/paseo/pull/9558),贡献者:[@adamcstephens](https://github.com/adamcstephens)) +- **重建移动端聊天**:在 iOS 和 Android 上展开轮次摘要、待办卡片和工具组时,阅读位置保持不变。滚动期间发送消息会移到新提示词处。 ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085), [#9806](https://github.com/getpaseo/paseo/pull/9806), [#9693](https://github.com/getpaseo/paseo/pull/9693)) +- **更快的 diff 加载**:“更改”在文件内容加载完成前先显示文件树。大型 diff 分批加载,且优先于后台 worktree 扫描。 ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243), [#9584](https://github.com/getpaseo/paseo/pull/9584)) +- **更快的 Composer 菜单**:大型列表中的命令和文件建议更快打开,并随 Composer 尺寸变化保持贴合。 ([#9657](https://github.com/getpaseo/paseo/pull/9657), [#9647](https://github.com/getpaseo/paseo/pull/9647), [#9642](https://github.com/getpaseo/paseo/pull/9642)) +- **移动端键盘快捷键**:连接键盘后,iPad 和 Android 可使用与桌面端相同的快捷键,包括自定义绑定。在 iPad Composer 中按 Shift+Tab 会切换模式,不再输入制表符。 ([#8625](https://github.com/getpaseo/paseo/pull/8625), [#9561](https://github.com/getpaseo/paseo/pull/9561),贡献者:[@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud)) +- **适合触控的平板控件**:触屏设备上的宽屏布局使用更大的按钮和行。空间不足时,Composer 会将控件收进模型菜单。 ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739),贡献者:[@zeyugao](https://github.com/zeyugao)) +- **撤销工作区归档**:在六秒提示期间,点击“撤销”或按 Cmd/Ctrl+Z 可恢复已归档的工作区。Paseo 在移除 worktree 前会检查未保存的文件和未推送的提交。 ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104), [#9625](https://github.com/getpaseo/paseo/pull/9625), [#9753](https://github.com/getpaseo/paseo/pull/9753),贡献者:[@ragokan](https://github.com/ragokan)) ### 新增 -- 在“更改”中为 worktree 工作区新增基准分支选择器(Change base),diff、提交列表和 Git 操作可改用其他分支 ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934),贡献者:[@Myasuka](https://github.com/Myasuka)) -- 新增 Issue 和 PR 引用链接:Agent 回复、计划、PR 面板和文件预览中的 `#123`、`owner/repo#123` 等引用会链接到 GitHub、GitLab、Gitea、Forgejo 或 Codeberg ([#8636](https://github.com/getpaseo/paseo/pull/8636)) -- 新增 iPhone Duo 布局支持:工作区操作位于系统竖向栏中,侧边栏和工作区分列折痕两侧 ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901),贡献者:[@zeyugao](https://github.com/zeyugao)) +- 为 worktree 的 diff、提交和 Git 操作新增基准分支选择器(Change base) ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934),贡献者:[@Myasuka](https://github.com/Myasuka)) +- 新增可解析 SSH 别名和 fork 上游仓库的 Issue 和 PR 链接 ([#8636](https://github.com/getpaseo/paseo/pull/8636), [#9576](https://github.com/getpaseo/paseo/pull/9576)) +- 新增 iPhone Duo 布局,侧边栏和工作区分列折痕两侧 ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901),贡献者:[@zeyugao](https://github.com/zeyugao)) - 新增 fx Provider,可在“设置 → Hosts → 提供方”的 Provider 目录中添加 ([#9160](https://github.com/getpaseo/paseo/pull/9160)) -- 新增后台 Agent:Agent 或插件可通过 `background: true` 创建辅助 Agent,它不打开标签页、不发送通知,也不出现在侧边栏和默认 Agent 列表中 ([#8683](https://github.com/getpaseo/paseo/pull/8683)) +- 新增后台 Agent,不占用标签页、不发送通知,也不出现在默认 Agent 列表中 ([#8683](https://github.com/getpaseo/paseo/pull/8683)) - 新增 Terraform 和 HCL 文件(`.tf`、`.tfvars`、`.hcl`)的语法高亮 ([#9106](https://github.com/getpaseo/paseo/pull/9106)) - 在每个 Agent 的环境中新增 `PASEO_WORKSPACE_ID`,Agent 可据此识别、重命名或归档自己的工作区 ([#8939](https://github.com/getpaseo/paseo/pull/8939),贡献者:[@DTTerastar](https://github.com/DTTerastar)) +- 为侧边栏工作区行新增插件徽章 ([#7645](https://github.com/getpaseo/paseo/pull/7645),贡献者:[@jtomaszewski](https://github.com/jtomaszewski)) +- 为无法预览的文件新增“下载”按钮 ([#9640](https://github.com/getpaseo/paseo/pull/9640)) +- 在用量中新增 Copilot 高级请求用量和剩余额度 ([#8489](https://github.com/getpaseo/paseo/pull/8489),贡献者:[@thisisryanswift](https://github.com/thisisryanswift)) ### 变更 - 打开工作区时恢复你离开时的标签页,不再跳转到需要关注的 Agent ([#8935](https://github.com/getpaseo/paseo/pull/8935)) -- 问题卡片中选择选项后不再自动前进;请用“下一步”或“提交”继续 ([#8525](https://github.com/getpaseo/paseo/pull/8525)) -- 斜杠命令菜单现在显示加载和错误状态并提供“重试”,且不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905)) -- 文件浏览器(Explorer)或分屏使工作区变窄时,工作区页眉和标签页改用紧凑控件 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao)) +- 问题卡片在选择选项后等待点击“下一步”或“提交” ([#8525](https://github.com/getpaseo/paseo/pull/8525)) +- 斜杠命令菜单不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905)) +- 调整工作区页眉控件以适应较窄的分屏窗格 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao)) - 向进程已退出的 Pi Agent 发送消息时立即失败,并提示重新加载该 Agent ([#8718](https://github.com/getpaseo/paseo/pull/8718)) +- 在桌面端和宽屏网页布局中,侧边栏的“重命名 workspace”改为在原处编辑标题,不再打开对话框 ([#9280](https://github.com/getpaseo/paseo/pull/9280)) +- “更新内容”先显示亮点,完整列表收在“显示全部变更”之后 ([#9281](https://github.com/getpaseo/paseo/pull/9281)) +- Claude Bypass 现在批准来自 ask 规则和钩子的执行请求,提问和计划审核仍保留交互 ([#9760](https://github.com/getpaseo/paseo/pull/9760)) +- Claude 权限卡片现在显示 Provider 提供的原因 ([#3950](https://github.com/getpaseo/paseo/pull/3950),贡献者:[@codebutler](https://github.com/codebutler)) +- PR 窗格中的“活动”可调整大小或折叠,为检查结果留出更多空间 ([#9656](https://github.com/getpaseo/paseo/pull/9656)) +- macOS 桌面端的标签页切换快捷键改为 Cmd+Shift+[ 和 Cmd+Shift+] ([#7692](https://github.com/getpaseo/paseo/pull/7692),贡献者:[@jtomaszewski](https://github.com/jtomaszewski)) +- 在“新建工作区”按 Cmd/Ctrl+N 会打开项目选择器,同时保留草稿 ([#9741](https://github.com/getpaseo/paseo/pull/9741)) +- 移动端设置导航现在恢复侧边栏之前的位置 ([#9641](https://github.com/getpaseo/paseo/pull/9641)) ### 修复 +- 修复较长的工具详情隐藏折叠标题或无法滚动查看输出的问题 ([#9770](https://github.com/getpaseo/paseo/pull/9770)) +- 修复图片预览加载时短暂显示错误或拉伸图片的问题 ([#9698](https://github.com/getpaseo/paseo/pull/9698)) +- 修复网页端和桌面端聊天在较早历史记录进入虚拟化后跳到开头的问题 ([#9664](https://github.com/getpaseo/paseo/pull/9664),贡献者:[@luoph](https://github.com/luoph)) +- 修复滚动到顶部后仍需再次滚动鼠标滚轮才能加载更早聊天记录的问题 ([#9570](https://github.com/getpaseo/paseo/pull/9570)) +- 修复跨越部分代码块复制选区时丢失缩进和换行的问题 ([#9515](https://github.com/getpaseo/paseo/pull/9515),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- 修复 Mermaid XY 图表的轴标题重叠和标签被裁切的问题 ([#9483](https://github.com/getpaseo/paseo/pull/9483),贡献者:[@FluidXin](https://github.com/FluidXin)) +- 修复 iOS 上点击命令后命令菜单仍保持打开的问题 ([#9755](https://github.com/getpaseo/paseo/pull/9755)) +- 修复 Agent 启动失败后无法重试已编辑草稿的问题 ([#9534](https://github.com/getpaseo/paseo/pull/9534),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- 修复 Android 平板上模型配置按钮不响应点按的问题 ([#9526](https://github.com/getpaseo/paseo/pull/9526),贡献者:[@moevis](https://github.com/moevis)) +- 修复更改外观后设置页面丢失滚动位置和编辑内容的问题 ([#9605](https://github.com/getpaseo/paseo/pull/9605)) +- 修复浅色插件主题中选中行难以阅读、Pure Black 中高亮几乎不可见的问题 ([#9579](https://github.com/getpaseo/paseo/pull/9579),贡献者:[@nathansgreen](https://github.com/nathansgreen)) +- 修复网页端和桌面端页眉及工具栏图标按钮缺少键盘焦点框的问题 ([#9745](https://github.com/getpaseo/paseo/pull/9745),贡献者:[@junjzhang](https://github.com/junjzhang)) +- 修复 iOS 和 Android 上拖动后侧边栏行短暂出现在错误位置的问题 ([#9681](https://github.com/getpaseo/paseo/pull/9681)) +- 修复桌面端在 daemon 仍启动时报告启动失败的问题 ([#9043](https://github.com/getpaseo/paseo/pull/9043),贡献者:[@magiclaw](https://github.com/magiclaw)) +- 修复网页端和桌面端终端恢复画面时丢失输入字符的问题 ([#9533](https://github.com/getpaseo/paseo/pull/9533)) +- 修复 Android 终端中实体方向键失效并丢失下一个输入字符的问题 ([#9407](https://github.com/getpaseo/paseo/pull/9407),贡献者:[@moevis](https://github.com/moevis)) +- 修复非 Git 工作区在命令中心缺少“归档工作区”的问题 ([#9777](https://github.com/getpaseo/paseo/pull/9777),贡献者:[@andheiberg](https://github.com/andheiberg)) +- 修复后续配置读取超时后工作区脚本消失的问题 ([#9477](https://github.com/getpaseo/paseo/pull/9477),贡献者:[@dinhphieu](https://github.com/dinhphieu)) +- 修复账号用量刷新失败后侧边栏用量隐藏该账号的问题 ([#9594](https://github.com/getpaseo/paseo/pull/9594)) +- 修复 Provider 会话已不存在时,已关闭 Agent 仍保持未读的问题 ([#9737](https://github.com/getpaseo/paseo/pull/9737),贡献者:[@luoph](https://github.com/luoph)) +- 修复 Agent 自主运行一轮后完成通知显示旧回复的问题 ([#9793](https://github.com/getpaseo/paseo/pull/9793)) +- 修复中断消息因“already has an active run”而失败的问题 ([#9537](https://github.com/getpaseo/paseo/pull/9537),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- 修复消息在交给 Provider 前失败后无法重试的问题 ([#9580](https://github.com/getpaseo/paseo/pull/9580),贡献者:[@tmad4000](https://github.com/tmad4000)) +- 修复刚重新打开的 Agent 在下一次空闲清理时失去 Provider 进程的问题 ([#8857](https://github.com/getpaseo/paseo/pull/8857),贡献者:[@fdkevin0](https://github.com/fdkevin0)) +- 修复空闲运行时清理导致 Claude 会话 cron 和 /loop 唤醒丢失的问题 ([#9744](https://github.com/getpaseo/paseo/pull/9744),贡献者:[@KronixDev](https://github.com/KronixDev)) +- 修复工具在回复之前开始、之后结束时无法从该回复分叉的问题 ([#9627](https://github.com/getpaseo/paseo/pull/9627),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复大型 Codex 历史页面在单个条目仍符合大小限制时阻断历史加载的问题 ([#9432](https://github.com/getpaseo/paseo/pull/9432),贡献者:[@RockStone](https://github.com/RockStone)) +- 修复 OpenCode 使用 Bun 时,daemon 重启后会话无法重新连接的问题 ([#9653](https://github.com/getpaseo/paseo/pull/9653),贡献者:[@quickwind](https://github.com/quickwind)) +- 修复 OpenCode 升级到 v2 后刷新 Provider 仍保留 v1 的问题 ([#9593](https://github.com/getpaseo/paseo/pull/9593),贡献者:[@tkfka1](https://github.com/tkfka1)) +- 修复 OpenCode v2 无法发现仅对其会话可用的插件工具的问题 ([#9426](https://github.com/getpaseo/paseo/pull/9426),贡献者:[@dptsolutions](https://github.com/dptsolutions)) +- 修复 ACP Provider 按模型提供思考等级时,模型共用错误等级的问题 ([#9717](https://github.com/getpaseo/paseo/pull/9717),贡献者:[@AlfredRR](https://github.com/AlfredRR), [@doskoi](https://github.com/doskoi)) +- 修复没有输出的失败 ACP 工具阻止对话历史加载的问题 ([#9467](https://github.com/getpaseo/paseo/pull/9467),贡献者:[@Myasuka](https://github.com/Myasuka)) +- 修复带有 null 可选参数的 Pi 和 OMP 工具调用显示为未知工具的问题 ([#9506](https://github.com/getpaseo/paseo/pull/9506),贡献者:[@papag00se](https://github.com/papag00se)) +- 修复导入 OMP 会话时保存文件路径而非会话 ID 的问题 ([#8854](https://github.com/getpaseo/paseo/pull/8854),贡献者:[@LiebeLee](https://github.com/LiebeLee)) +- 修复跨主机子 Agent 与调用者使用相同 Provider 时丢失调用者模式的问题 ([#9512](https://github.com/getpaseo/paseo/pull/9512),贡献者:[@ortschun](https://github.com/ortschun)) +- 修复插件子 Agent 在会话关闭时从失败或已取消变为已完成的问题 ([#8563](https://github.com/getpaseo/paseo/pull/8563),贡献者:[@hadan8977](https://github.com/hadan8977)) +- 修复完整 Agent ID 不存在时,CLI 命令误操作标题与该 ID 相同的其他 Agent 的问题 ([#9680](https://github.com/getpaseo/paseo/pull/9680), [#9731](https://github.com/getpaseo/paseo/pull/9731),贡献者:[@ese111](https://github.com/ese111)) +- 修复无法归档、分离或重新加载未出现在 CLI 列表中的 Agent 的问题 ([#9726](https://github.com/getpaseo/paseo/pull/9726),贡献者:[@xunWhale](https://github.com/xunWhale)) +- 修复 `paseo agent wait` 在没有 Agent 匹配 ID 时仍成功退出的问题 ([#9782](https://github.com/getpaseo/paseo/pull/9782),贡献者:[@Eapp1e](https://github.com/Eapp1e)) +- 修复语音输入和输出都使用 OpenAI 时无法启动语音模式的问题 ([#9779](https://github.com/getpaseo/paseo/pull/9779),贡献者:[@Huyvux12](https://github.com/Huyvux12)) +- 修复听写流错误被 30 秒交付超时掩盖的问题 ([#9784](https://github.com/getpaseo/paseo/pull/9784),贡献者:[@tieo](https://github.com/tieo)) +- 修复插件 Provider 在 All 模式下拒绝 Review 附件的问题 ([#9590](https://github.com/getpaseo/paseo/pull/9590),贡献者:[@ese111](https://github.com/ese111)) +- 修复插件时间线写入接受应用无法显示的类型的问题 ([#7677](https://github.com/getpaseo/paseo/pull/7677),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复一轮结束时聊天位置移动的问题 ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175)) +- 修复 Claude 和 OpenCode 工具行随参数到达而更改标题和图标的问题 ([#9248](https://github.com/getpaseo/paseo/pull/9248)) +- 修复用量加载前上下文窗口浮层提前打开的问题 ([#9212](https://github.com/getpaseo/paseo/pull/9212)) +- 修复多个侧边栏悬停卡片同时打开的问题 ([#9071](https://github.com/getpaseo/paseo/pull/9071)) + - 修复 Agent 在你离开期间完成后,返回聊天时工作指示器消失的问题 ([#9170](https://github.com/getpaseo/paseo/pull/9170)) -- 修复包含较短折叠轮次的聊天打开时留有空白、需滚动后才填满的问题 ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083)) - 修复空闲的 Claude、Codex 或 OpenCode Agent 恢复后,“折叠轮次”把较早的回复藏进后一轮摘要行的问题 ([#9098](https://github.com/getpaseo/paseo/pull/9098)) -- 修复提示词与其下方的回复或折叠轮次摘要行之间缺少间距的问题 ([#9009](https://github.com/getpaseo/paseo/pull/9009)) - 修复紧跟在段落之后、中间没有空行的 Markdown 表格显示为原始竖线的问题 ([#8485](https://github.com/getpaseo/paseo/pull/8485),贡献者:[@ragokan](https://github.com/ragokan)、[@suk-6](https://github.com/suk-6)、[@thsrite](https://github.com/thsrite)) - 修复网页版和桌面端中与文字同行的带链接徽章图片被渲染成整行宽度的问题 ([#8530](https://github.com/getpaseo/paseo/pull/8530)) - 修复“查看源码”后点击“查看图表”会打开全屏、而不是回到内联 Mermaid 图表的问题 ([#8932](https://github.com/getpaseo/paseo/pull/8932),贡献者:[@luoph](https://github.com/luoph)) @@ -44,20 +119,16 @@ - 修复关闭 Agent 标签页时未发送的 Composer 文本和附件被删除的问题 ([#9079](https://github.com/getpaseo/paseo/pull/9079)) - 修复向 Composer 粘贴带超链接的文本时丢失链接地址的问题;链接现在以 Markdown 形式粘贴 ([#8972](https://github.com/getpaseo/paseo/pull/8972)) - 修复用鼠标点击“发送”后 Composer 失去焦点的问题 ([#9015](https://github.com/getpaseo/paseo/pull/9015)) -- 修复 iPhone 上 Composer 停在距底部边缘 50pt 处的问题 ([#8823](https://github.com/getpaseo/paseo/pull/8823),贡献者:[@zeyugao](https://github.com/zeyugao)) - 修复从侧边栏和“新建工作区”点击“添加主机”会跳转到“设置”的问题 ([#8512](https://github.com/getpaseo/paseo/pull/8512)) - 修复打开失败的 Agent 或选择 Mark as read 后,其红点和“失败”分组仍留在侧边栏的问题 ([#8831](https://github.com/getpaseo/paseo/pull/8831)) -- 修复在 Agent 运行时已关闭的情况下清除未读后,工作区的未读指示仍然亮着的问题 ([#9087](https://github.com/getpaseo/paseo/pull/9087)) +- 修复取消归档工作区时未恢复随之归档的 Agent 的问题 ([#9210](https://github.com/getpaseo/paseo/pull/9210)) - 修复流式回复期间聊天一滚动上下文窗口浮层就自行关闭的问题 ([#8742](https://github.com/getpaseo/paseo/pull/8742),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复侧边栏用量摘要只在打开“使用情况”时才更新的问题 ([#7806](https://github.com/getpaseo/paseo/pull/7806),贡献者:[@ragokan](https://github.com/ragokan)) -- 修复 Android 上位于触发元素上方的提示和菜单在打开后内容变多时短暂盖住触发元素的问题 ([#9247](https://github.com/getpaseo/paseo/pull/9247)) - 修复在“历史”页面刷新网页版后显示“无法加载历史”的问题 ([#9029](https://github.com/getpaseo/paseo/pull/9029)) - 修复 HTML 文件预览中的章节链接把预览替换成 Paseo 应用、而不是在文件内滚动的问题 ([#8559](https://github.com/getpaseo/paseo/pull/8559),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复“文件”刷新期间文件夹处于折叠状态时,新建的文件一直不显示的问题 ([#8582](https://github.com/getpaseo/paseo/pull/8582),贡献者:[@hadan8977](https://github.com/hadan8977)) - 修复分支仍在加载或请求失败时,分支切换器显示“没有找到分支。”的问题 ([#8938](https://github.com/getpaseo/paseo/pull/8938)) - 修复文件被移到上一级目录时,提交历史显示双斜杠、没有重命名状态也没有 diff 的问题 ([#8509](https://github.com/getpaseo/paseo/pull/8509),贡献者:[@hadan8977](https://github.com/hadan8977)) -- 修复检出落后于 PR 头部时,已合并的 PR 从其工作区中消失的问题 -- 修复工作区 Git 监视器在设置超时后一直停留在回退轮询的问题 - 修复网页版或桌面端重连后,被放弃的连接最多保持打开 45 秒的问题 ([#9067](https://github.com/getpaseo/paseo/pull/9067)) - 修复通过另一台主机路由的连接在获取超大时间线时以“The receiving client cannot keep up with host output”关闭的问题 ([#9109](https://github.com/getpaseo/paseo/pull/9109)) - 修复已连接的主机在更新到受支持的版本后仍停留在错误状态的问题 ([#8423](https://github.com/getpaseo/paseo/pull/8423),贡献者:[@DAnaeto](https://github.com/DAnaeto)) @@ -73,11 +144,13 @@ - 修复 Codex 的“Apply file changes”审批在你接受之前不显示文件名和 diff 的问题 ([#8585](https://github.com/getpaseo/paseo/pull/8585),贡献者:[@ragokan](https://github.com/ragokan)) - 修复 Codex 在一个补丁中编辑多个文件时,时间线只显示第一个文件的 diff 的问题 ([#8613](https://github.com/getpaseo/paseo/pull/8613),贡献者:[@ragokan](https://github.com/ragokan)) - 修复多个 Codex 操作同时启动时,Codex 会话发现和启动偶发 SQLite 初始化错误的问题 ([#9008](https://github.com/getpaseo/paseo/pull/9008),贡献者:[@colonelpanic8](https://github.com/colonelpanic8)、[@michaelmwu](https://github.com/michaelmwu)) +- 修复 Codex 的重连尝试和警告未显示在时间线中的问题 ([#9370](https://github.com/getpaseo/paseo/pull/9370),贡献者:[@whatamelon](https://github.com/whatamelon)) - 修复 daemon 重启时正处于轮次中的 OpenCode 对话显示为空闲并忽略“停止”的问题 ([#8698](https://github.com/getpaseo/paseo/pull/8698)) - 修复审批待处理期间你发送消息时,OpenCode 被告知你拒绝了工具调用的问题 ([#8477](https://github.com/getpaseo/paseo/pull/8477)) - 修复重新打开的 Pi 对话缺少上下文压缩之前的消息的问题 ([#8523](https://github.com/getpaseo/paseo/pull/8523)) - 修复工作文件夹被移除后,已归档的 Pi 聊天因 `spawn pi ENOENT` 无法打开的问题 ([#8442](https://github.com/getpaseo/paseo/pull/8442),贡献者:[@DAnaeto](https://github.com/DAnaeto)) - 修复关闭空闲运行时清理的情况下,读取已归档的 Pi 聊天会遗留一个 Pi 进程的问题 ([#8554](https://github.com/getpaseo/paseo/pull/8554),贡献者:[@rylwin](https://github.com/rylwin)) +- 修复恢复的 pi-subagents 运行未出现在 Subagent 栏中的问题 ([#9261](https://github.com/getpaseo/paseo/pull/9261),贡献者:[@xxachangxx](https://github.com/xxachangxx)) - 修复向进程已退出的 ACP Agent 发送提示词后一直停留在运行中、而不是报错失败的问题 ([#8406](https://github.com/getpaseo/paseo/pull/8406),贡献者:[@DAnaeto](https://github.com/DAnaeto)) - 修复 ACP Agent 放弃审批请求并结束轮次后一直卡在“waiting for permission”的问题 ([#8548](https://github.com/getpaseo/paseo/pull/8548),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复 ACP Agent 发送配置更新后,更改其模式因 `invalid_params` 失败的问题 ([#8912](https://github.com/getpaseo/paseo/pull/8912),贡献者:[@a-sh](https://github.com/a-sh)) @@ -109,21 +182,29 @@ ### 插件 - 新增插件订阅,可将 daemon 的实时事件流式推送到插件面板;插件 RPC 和事件支持二进制(`Uint8Array`)负载 ([#8527](https://github.com/getpaseo/paseo/pull/8527)) +- 插件的 Agent 快照新增后台任务数量(`backgroundWork.count`)和 `background` 标记,Agent 钩子新增 `background` 标记 ([#9362](https://github.com/getpaseo/paseo/pull/9362)) - “设置 → 插件”改为通过齿轮按钮打开插件设置,每个设置页面对应一个标签页 ([#8675](https://github.com/getpaseo/paseo/pull/8675)) - 为会打开菜单或浮层的插件 Composer 胶囊按钮新增向上的箭头 ([#8673](https://github.com/getpaseo/paseo/pull/8673)) - daemon 启动时改为并发启动已配置的插件,不再逐个启动 ([#8427](https://github.com/getpaseo/paseo/pull/8427),贡献者:[@DAnaeto](https://github.com/DAnaeto)) - 修复主机的 npm 使用镜像源时,从插件库安装插件因“npm artifact changed since review”失败的问题 ([#8756](https://github.com/getpaseo/paseo/pull/8756),贡献者:[@tlipoca9](https://github.com/tlipoca9)) +- 修复 daemon 因无效消息终止插件后,该插件仍留在列表中且未报告退出的问题 ([#9285](https://github.com/getpaseo/paseo/pull/9285),贡献者:[@Brandon168](https://github.com/Brandon168)) +- 修复 ACP Provider 插件丢弃 Agent 在提示词响应中报告的 token 用量的问题 ([#9396](https://github.com/getpaseo/paseo/pull/9396),贡献者:[@Myasuka](https://github.com/Myasuka)) - 修复已发布的 `@getpaseo/*` npm 包未声明许可证的问题;现在声明为 Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816),贡献者:[@mdlawson](https://github.com/mdlawson)、[@ragokan](https://github.com/ragokan)) -- 修复插件更新了自己的某张时间线卡片后,从较早的回复分叉因“This checkpoint changed after it was created”失败的问题 ([#8746](https://github.com/getpaseo/paseo/pull/8746),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) - 修复由插件渲染最终回复时,“折叠轮次”让轮次保持展开或折叠到较早回复的问题 ([#8811](https://github.com/getpaseo/paseo/pull/8811),贡献者:[@geoqiao](https://github.com/geoqiao)) - 修复应用刷新后插件目录仍在加载时,插件页面显示“This plugin surface is unavailable”的问题 ([#8123](https://github.com/getpaseo/paseo/pull/8123),贡献者:[@vs-tahir](https://github.com/vs-tahir)) - 修复插件添加了许多导航项时,矮屏上的工作区列表被挤出移动端侧边栏的问题 ([#8727](https://github.com/getpaseo/paseo/pull/8727),贡献者:[@jaredwang](https://github.com/jaredwang)) - 修复时间线插件在 Agent 消息工具调用上收不到发送方、事件和原始文本的问题 ([#8492](https://github.com/getpaseo/paseo/pull/8492),贡献者:[@RRD-dev](https://github.com/RRD-dev)、[@luoph](https://github.com/luoph)) - 修复输入或输出 schema 使用 transform 时插件 RPC 失败的问题 ([#8550](https://github.com/getpaseo/paseo/pull/8550)) +### 破坏性变更 + +- 移除已弃用且始终返回空列表的 `agent.turn.after.timeline` SDK 字段 ([#9573](https://github.com/getpaseo/paseo/pull/9573),贡献者:[@jtomaszewski](https://github.com/jtomaszewski)) + ### 说明 -- 后台任务、基准分支选择器、归档撤销、后台 Agent、插件订阅和 fx 需要主机和应用都更新到此版本 +- 使用插件库、后台任务、Change base、归档撤销、后台 Agent、插件订阅和 fx 时,请同时更新主机和应用 +- 读取 `agent.turn.after.timeline` 的插件作者必须改用 `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })`,并按 `event.turnId` 筛选条目 +- 归档撤销会恢复工作区,但不会恢复随 worktree 一起移除的未提交文件 ## 0.15.4 - 2026-11-10 diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index dea6c68255..d5eeed4d5c 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -150,12 +150,13 @@ Users can also detach an existing subagent from the subagents track. Detach is d `notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback. -Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches. +Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches. The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued -admission within their original timeout and cancellation scope. +admission within their original timeout and cancellation scope, and return permission checkpoints +while messages are waiting. Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses diff --git a/docs/agent-stream-disclosure.md b/docs/agent-stream-disclosure.md index d2ad7a454b..ec320dc916 100644 --- a/docs/agent-stream-disclosure.md +++ b/docs/agent-stream-disclosure.md @@ -156,8 +156,10 @@ keeps following. Following resumes only for a gesture that ends within 1 px of the end, either when the finger lifts or when momentum stops. A release past the end counts: iOS bounces back to the end, and lines that -land during the bounce must keep scrolling in. A release anywhere short of the end stays detached -with the scroll-to-bottom pill, so the rows the user let go of never move. +land during the bounce must keep scrolling in. A release short of the end stays detached with the scroll-to-bottom pill unless you submitted +another prompt during that gesture. That submit requests the end after the gesture finishes; +a new drag after submitting takes ownership again. Rewind and tail-fetch completions do not +override a scroll away because they can arrive after the action that requested them. ### Draw distance @@ -186,7 +188,8 @@ Drop a hunk when the installed LegendList ships its fix. `modules/paseo-scroll` replaces React Native's scroll view on both platforms with a subclass: Android's `PaseoScrollView` and iOS's `PaseoScrollViewComponentView`. -`VisibleContentPositionClampTest` covers Android; iOS has no native test harness. +`VisibleContentPositionClampTest` and `SelectableTextTouchTest` cover Android; iOS has no native +test harness. **Content clamp.** A mount that shrinks the content while `maintainVisibleContentPosition` is set applies the shrink twice on both platforms: the scroll view clamps its offset to the new end during @@ -206,5 +209,16 @@ React Native 0.88 skips the adjustment for a removed anchor and skip its correction while the user drags ([user scroll](#user-scroll)). This one has no React Native counterpart; it stays while the timeline uses the pin. +**Touched text (Android).** Chat text is selectable, and Android focuses selectable text when it is +touched. React Native scrolls a newly focused view fully into view, so tapping a link or a word, or +long-pressing to select, in a message partly off screen moved the timeline by up to a screen. +`PaseoScrollView` skips that scroll when the focused view is selectable, non-editable text in touch +mode. The text keeps focus, and a streaming reply's new text collapses its selection to the start, +which asks to reveal the reply's first line; that request is skipped too while nothing is selected. +A change in the timeline's height, such as the composer below it growing, also reveals the focused +view, and is skipped the same way. Inputs, focus moved by a keyboard, and a selection the user drags +still scroll into view. The inverted timeline guarded this with a rule tied to the inversion, which +went with it; keep this one while chat text is selectable. + Remove the content clamp and removed-anchor overrides once the installed React Native includes their fixes. diff --git a/docs/android.md b/docs/android.md index 8b6201ae91..f4fcfa27c0 100644 --- a/docs/android.md +++ b/docs/android.md @@ -112,6 +112,23 @@ need an artifact. `android:clear` removes the generated Android project. Run `npm run test:android --workspace=@getpaseo/app` explicitly with a local Android toolchain to prebuild Android and run native module unit tests. Ordinary CI does not prebuild Android or run these tests. +With an emulator or device connected, run the hardware keyboard's window-dispatch regression tests +from `packages/app/android`: + +```bash +./gradlew :paseo-hardware-keyboard:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false +``` + +These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing. + +Run the display density regression tests the same way: + +```bash +./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false +``` + +These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX. + ### Diagnostic logs without ADB In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all @@ -177,10 +194,10 @@ This is the Android counterpart of the iOS local-simulator flow in [development. ## Scroll view corrections `modules/paseo-scroll` replaces React Native's vertical scroll view with `PaseoScrollView`, which -keeps React Native's scroll manager interface and corrects `maintainVisibleContentPosition` for the -chat timeline. [agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections) -lists the corrections and the React Native issues they work around. Its instrumentation test, -`VisibleContentPositionClampTest`, mounts through React Native's own mounting manager: +keeps React Native's scroll manager interface and corrects how the chat timeline holds its position. +[agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections) lists the +corrections and the React Native issues they work around. Its instrumentation tests run the scroll +view in a real window, mounting through React Native's own mounting manager and injecting touches: ```bash cd packages/app/android diff --git a/docs/architecture.md b/docs/architecture.md index de6c619ae3..f74d6456c9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -506,5 +506,5 @@ Agent and terminal environments are unchanged. System proxy settings and SOCKS-o ## Deployment models 1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767` -2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only a matching `{pid, startedAt}` from a spawn in the current Desktop session authorizes automatic stop or binary replacement. Preexisting instances, including legacy `desktopManaged` records, are attach-only. Keep-running survivors attach in the next session. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform. +2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only Desktop's own launch writes `desktopManaged: true` to `paseo.pid`. The CLI launch path removes the flag. While Desktop manages the built-in daemon, an app update or a version mismatch replaces any `desktopManaged` daemon, including one that an earlier Desktop session left running. Bundled CLIs before v0.9.0 exported the flag, so a daemon that one of them started also carries it and is replaced. Quit, Settings, and host removal stop only a daemon that the current session launched, matched by `{pid, startedAt}`. A daemon that the user started through the CLI is attach-only. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform. 3. **Remote + relay**: Daemon behind firewall, relay bridges with E2E encryption diff --git a/docs/browser-capture-harness.md b/docs/browser-capture-harness.md index f760fafa67..0458356b2d 100644 --- a/docs/browser-capture-harness.md +++ b/docs/browser-capture-harness.md @@ -117,7 +117,10 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov Screenshot capture temporarily enables frame production inside the shared serialized queue, restores the previous throttling policy on success or failure, and retains a 5-second capture budget. The browser tool takes one viewport frame through Electron's frame subscription and releases the -subscription on completion or cancellation. A resized resident guest can produce fresh pixels +subscription on completion or cancellation. Guest pages have a transparent base background, so a page +that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where +every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame` +when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout metrics and screenshot clip. diff --git a/docs/data-model.md b/docs/data-model.md index aa0f201ce6..ff77593e5d 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision. +### Saved hosts + +**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles. + +Every app build on a device shares this key, including an older build after a downgrade and a newer +one that saves a connection kind this build doesn't know. The key holds every saved host and its +password, so never remove it. Read each host and connection on its own, skip the ones this build +can't read, and write them back on every save. A value that isn't a JSON array is copied to +`@paseo:daemon-registry:unreadable` before the next save overwrites it. + ### Draft Store **AsyncStorage key:** `paseo-drafts` (version 2) diff --git a/docs/design.md b/docs/design.md index f86565e97e..810b10c582 100644 --- a/docs/design.md +++ b/docs/design.md @@ -20,7 +20,7 @@ A semantic element used in three or more places is a primitive. One of a kind is Primitives live in `packages/app/src/components/ui/` and `packages/app/src/components/headers/`. Card and row layout live in `packages/app/src/styles/settings.ts`. Section structure lives in `packages/app/src/screens/settings/settings-section.tsx`. -A pressable styled to look like a button is wrong; the button is `; +} + +describe("tool detail interaction", () => { + it("keeps detail controls in the tab order", async () => { + function Badge() { + const [expanded, setExpanded] = React.useState(true); + const toggle = React.useCallback(() => setExpanded(!expanded), [expanded]); + return ( + + ); + } + act(() => root.render()); + const header = view().getByRole("button", { name: "Probe" }); + act(() => header.focus()); + await userEvent.keyboard("{Tab}"); + expect(document.activeElement).toBe(view().getByRole("button", { name: "Copy output" })); + }); +}); diff --git a/packages/app/src/agent-stream/strategy-web.browser.test.tsx b/packages/app/src/agent-stream/strategy-web.browser.test.tsx index 12127ea630..188e8d8edf 100644 --- a/packages/app/src/agent-stream/strategy-web.browser.test.tsx +++ b/packages/app/src/agent-stream/strategy-web.browser.test.tsx @@ -49,8 +49,21 @@ afterEach(() => { host.remove(); }); -function mountTimeline(historyMounted: StreamItem[]) { - const strategy = createWebStreamStrategy({ isMobileBreakpoint: true }); +type OlderHistoryInput = Pick< + StreamRenderInput, + "onNearHistoryStart" | "hasOlderHistory" | "olderHistoryProgressKey" +>; + +interface MountTimelineOptions { + olderHistory?: OlderHistoryInput; + isMobileBreakpoint?: boolean; +} + +function mountTimeline( + historyMounted: StreamItem[], + { olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {}, +) { + const strategy = createWebStreamStrategy({ isMobileBreakpoint }); const viewportRef = React.createRef(); const input: StreamRenderInput = { agentId: "agent", @@ -76,6 +89,7 @@ function mountTimeline(historyMounted: StreamItem[]) { baseListContentContainerStyle: null, forwardListContentContainerStyle: null, contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + ...olderHistory, }; const render = (segments: Partial) => root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } })); @@ -100,8 +114,20 @@ function mountTimeline(historyMounted: StreamItem[]) { scrollTo: (top: number) => { scrollContainer.scrollTop = top; }, + // A wheel listener runs before the browser applies the scroll the wheel causes. + wheelUpTo: (top: number) => { + scrollContainer.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1000 })); + scrollContainer.scrollTop = top; + }, distanceFromEnd: () => scrollContainer.scrollHeight - scrollContainer.clientHeight - scrollContainer.scrollTop, + scrollTop: () => scrollContainer.scrollTop, + scrollUp: (distance: number) => + act(() => { + scrollContainer.dispatchEvent(new WheelEvent("wheel", { deltaY: -distance })); + scrollContainer.scrollTop -= distance; + scrollContainer.dispatchEvent(new Event("scroll")); + }), // Resize observers and the hold's settle run on animation frames. settle: () => act(async () => { @@ -113,6 +139,53 @@ function mountTimeline(historyMounted: StreamItem[]) { } describe("web disclosure hold", () => { + it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])( + "keeps the reading position when mounted history becomes virtualized (compact: $isMobileBreakpoint)", + async (options) => { + const history = Array.from({ length: 80 }, (_, index) => row(index)); + const timeline = mountTimeline(history, options); + await timeline.settle(); + timeline.scrollUp(600); + await timeline.settle(); + const offset = timeline.scrollTop(); + const readingTop = timeline.rowTop("message-64"); + expect(offset).toBeGreaterThan(0); + + timeline.render({ + historyVirtualized: history.slice(0, 60), + historyMounted: history.slice(60), + }); + await timeline.settle(); + + expect(timeline.scrollTop()).toBe(offset); + expect(timeline.rowTop("message-64")).toBe(readingTop); + }, + ); + + it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])( + "keeps following output when mounted history becomes virtualized at the end (compact: $isMobileBreakpoint)", + async (options) => { + const history = Array.from({ length: 80 }, (_, index) => row(index)); + const timeline = mountTimeline(history, options); + await timeline.settle(); + + timeline.render({ + historyVirtualized: history.slice(0, 60), + historyMounted: history.slice(60), + }); + await timeline.settle(); + expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1); + + timeline.render({ + historyVirtualized: history.slice(0, 60), + historyMounted: history.slice(60), + liveHead: [row(80)], + }); + await timeline.settle(); + expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1); + }, + ); + it("keeps the trigger's top when an anchored toggle at the bottom opens rows below it, and stops following", async () => { const history = [1, 2, 3, 4, 5, 6].map((index) => row(index)); const timeline = mountTimeline(history); @@ -208,3 +281,32 @@ describe("web disclosure hold", () => { expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1); }); }); + +describe("web history start", () => { + it("loads older history when an upward wheel lands at the start after the reader stopped following", async () => { + let olderHistoryLoads = 0; + const history = [1, 2, 3, 4, 5, 6].map((index) => row(index)); + const timeline = mountTimeline(history, { + olderHistory: { + hasOlderHistory: true, + olderHistoryProgressKey: "epoch:1", + onNearHistoryStart: async () => { + olderHistoryLoads += 1; + return true; + }, + }, + }); + await timeline.settle(); + // Opening a row at the bottom stops following output without any scroll. + timeline.hold("message-5", () => + timeline.render({ historyMounted: [...history.slice(0, 5), row(7, 200), history[5]!] }), + ); + await timeline.settle(); + expect(olderHistoryLoads).toBe(0); + + timeline.wheelUpTo(0); + await timeline.settle(); + + expect(olderHistoryLoads).toBe(1); + }); +}); diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index c47e0720f4..465d98e8d8 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -457,6 +457,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const rowVirtualizer = useVirtualizer({ count: segments.historyVirtualized.length, enabled: shouldUseVirtualizer, + // History can become virtualized after the reader has already scrolled the mounted rows. + initialOffset: () => scrollContainerRef.current?.scrollTop ?? 0, initialRect: { width: scrollContainerRef.current?.clientWidth ?? 0, height: scrollContainerRef.current?.clientHeight ?? 0, @@ -605,6 +607,15 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool window.performance.now() + UPWARD_INPUT_EVIDENCE_TIMEOUT_MS; }, []); + const hasUpwardInputEvidence = useCallback(() => { + const mouseGesture = mouseScrollGestureRef.current; + return ( + mouseGesture?.kind === "scrollbar" || + (mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) || + window.performance.now() < upwardInputEvidenceUntilRef.current + ); + }, []); + useLayoutEffect(() => { if (isActive) { return; @@ -791,16 +802,16 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - USER_SCROLL_DELTA_EPSILON; const scrolledDown = currentScrollTop > lastKnownScrollTopRef.current + USER_SCROLL_DELTA_EPSILON; - const mouseGesture = mouseScrollGestureRef.current; - const hasUpwardInputEvidence = - mouseGesture?.kind === "scrollbar" || - (mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) || - window.performance.now() < upwardInputEvidenceUntilRef.current; + const userScrolledUp = scrolledUp && hasUpwardInputEvidence(); if (!followOutputRef.current && isAtBottom && scrolledDown && !isJumpSettling()) { setFollowOutput(true); - } else if (followOutputRef.current && scrolledUp && hasUpwardInputEvidence) { + } else if (followOutputRef.current && userScrolledUp) { stopFollowingOutputFromUserIntent(); + } else if (userScrolledUp) { + // Wheel listeners can run before or after the browser applies the scroll, so the + // upward scroll itself re-arms loading when it reaches the start. + rearmHistoryStartFromUserIntent(); } lastKnownScrollTopRef.current = currentScrollTop; @@ -811,8 +822,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool evaluateHistoryStart(); }, [ evaluateHistoryStart, + hasUpwardInputEvidence, isJumpSettling, readingAnchor, + rearmHistoryStartFromUserIntent, stopFollowingOutputFromUserIntent, updateScrollMetrics, ]); diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 7ea2c7e5d9..9f71998a41 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -883,6 +883,7 @@ const AgentStreamViewComponent = forwardRef @@ -1375,6 +1376,7 @@ interface ThoughtSlotProps { isLastInSequence: boolean; defaultExpanded: boolean; standalone?: boolean; + maxDetailHeight?: number; } // Reasoning text is paced the same way assistant text is; see @/hooks/use-revealed-text. @@ -1386,6 +1388,7 @@ function ThoughtSlot({ isLastInSequence, defaultExpanded, standalone, + maxDetailHeight, }: ThoughtSlotProps) { const revealedText = useRevealedText(text, status === "ready" ? "complete" : "streaming"); return ( @@ -1398,6 +1401,7 @@ function ThoughtSlot({ isLastInSequence={isLastInSequence} defaultExpanded={defaultExpanded} standalone={standalone} + maxDetailHeight={maxDetailHeight} forceInline={defaultExpanded} /> ); diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index b4ca122f77..c9d9bf4ebb 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -87,7 +87,10 @@ import { type StartupBlocker, } from "@/navigation/host-runtime-bootstrap"; import { registerWorkspaceRouteNavigationRef } from "@/navigation/workspace-route-navigation"; -import { useSettingsRouteEntry } from "@/navigation/settings-presentation"; +import { + useSettingsRouteEntry, + useSettingsSidebarPresentation, +} from "@/navigation/settings-presentation"; import { ThemedStack } from "@/navigation/themed-stack"; import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon"; import { AgentNavigationListener } from "@/desktop/agent-navigation"; @@ -473,12 +476,16 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon viewportWidth, }), }); - const sidebarPresentation = resolveLeftSidebarPresentation({ - chromeEnabled, - isCompactLayout, - isFocusModeEnabled: isWorkspaceFocusModeEnabled, - desktopSidebarVisible, - }); + const { presentation: sidebarPresentation, visible: sidebarVisible } = + useSettingsSidebarPresentation({ + visible: chromeEnabled, + presentation: resolveLeftSidebarPresentation({ + chromeEnabled, + isCompactLayout, + isFocusModeEnabled: isWorkspaceFocusModeEnabled, + desktopSidebarVisible, + }), + }); const applyPanelLayout = usePanelStore((state) => state.applyPanelLayout); // Publishes the layout to the store, which owns the panel targets each layout allows. useLayoutEffect(() => { @@ -546,7 +553,11 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon - {isCompactLayout ? themedSidebarChrome : null} + {isCompactLayout ? ( + + {themedSidebarChrome} + + ) : null} @@ -584,6 +595,34 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon ); } +// Keep native scroll ranges and gesture hosts intact while Settings covers the sidebar. +function CompactSidebarHost({ + visible, + interactive, + children, +}: { + visible: boolean; + interactive: boolean; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + function AppContainerLifetime({ children, sidebarGesturesEnabled, @@ -614,14 +653,18 @@ function SidebarChrome({ const isCompactLayout = useIsCompactFormFactor(); const isMobileActive = useIsMobilePanelActive("agent-list"); const overlay = presentation === "overlay"; - const active = resolveSidebarActivity(presentation !== "hidden", overlay, isMobileActive); + const active = resolveSidebarActivity( + presentation !== "hidden" && presentation !== "suspended", + overlay, + isMobileActive, + ); const hardwareKeyboardPresent = useHardwareKeyboardPresent(); return ( - {mounted ? ( + {mounted || presentation === "suspended" ? ( ) : null} @@ -864,6 +907,8 @@ const ROOT_STACK_SCREEN_OPTIONS = { animation: "none" as const, }; const ROOT_STACK_NESTED_NAVIGATOR_SCREENS = ["h/[serverId]"] as const; +// Settings owns reactive typography leaves; its scroll and form state survive appearance edits. +const ROOT_STACK_SCREEN_OWNED_APPEARANCE = ["settings/[section]"] as const; function RootStack() { const storeReady = useStoreReady(); @@ -871,6 +916,7 @@ function RootStack() { @@ -885,7 +931,9 @@ function RootStack() { + + @@ -1004,6 +1052,7 @@ export default function RootLayout() { } const layoutStyles = StyleSheet.create((theme) => ({ + compactSidebarHost: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }, surfaceFill: { flex: 1, backgroundColor: theme.colors.surface0, diff --git a/packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx b/packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx new file mode 100644 index 0000000000..01cab4d2d9 --- /dev/null +++ b/packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx @@ -0,0 +1,23 @@ +import { useMemo } from "react"; + +import { useLocalSearchParams } from "expo-router"; +import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; +import SettingsScreen from "@/screens/settings-screen"; + +/** A plugin directory listing's page, by its `owner/slug` ID. */ +export default function PluginListingRoute() { + const { serverId, owner, slug } = useLocalSearchParams<{ + serverId: string; + owner: string; + slug: string; + }>(); + const view = useMemo( + () => ({ kind: "pluginListing" as const, serverId, listingId: `${owner}/${slug}` }), + [serverId, owner, slug], + ); + return ( + + + + ); +} diff --git a/packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx b/packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx new file mode 100644 index 0000000000..a99bc5d4d6 --- /dev/null +++ b/packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx @@ -0,0 +1,23 @@ +import { useMemo } from "react"; + +import { useLocalSearchParams } from "expo-router"; +import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; +import SettingsScreen from "@/screens/settings-screen"; + +/** An installed plugin's page. A settings tab chosen on it arrives as `screenId`. */ +export default function PluginPageRoute() { + const { serverId, pluginId, screenId } = useLocalSearchParams<{ + serverId: string; + pluginId: string; + screenId?: string; + }>(); + const view = useMemo( + () => ({ kind: "plugin" as const, serverId, pluginId, screenId }), + [serverId, pluginId, screenId], + ); + return ( + + + + ); +} diff --git a/packages/app/src/appearance/text.tsx b/packages/app/src/appearance/text.tsx new file mode 100644 index 0000000000..ab1508dc70 --- /dev/null +++ b/packages/app/src/appearance/text.tsx @@ -0,0 +1,3 @@ +import { Text } from "react-native"; + +export { Text as AppearanceText }; diff --git a/packages/app/src/appearance/text.web.tsx b/packages/app/src/appearance/text.web.tsx new file mode 100644 index 0000000000..1ba56de360 --- /dev/null +++ b/packages/app/src/appearance/text.web.tsx @@ -0,0 +1,12 @@ +import { Text as NativeText } from "react-native"; +import { withUnistyles } from "react-native-unistyles"; +import type { Theme } from "@/styles/theme"; + +// Web numeric tokens are baked into classes. Subscribe this leaf so withUnistyles +// resolves its style prop again without replacing the surrounding form or scroll view. +function typographyChanges(theme: Theme) { + void theme.fontSize; + return {}; +} + +export const AppearanceText = withUnistyles(NativeText, typographyChanges); diff --git a/packages/app/src/appearance/theme-picker.tsx b/packages/app/src/appearance/theme-picker.tsx index cb2ebf5983..cd68bd27a0 100644 --- a/packages/app/src/appearance/theme-picker.tsx +++ b/packages/app/src/appearance/theme-picker.tsx @@ -1,6 +1,7 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Text, View, type PressableStateCallbackType } from "react-native"; +import { View, type PressableStateCallbackType } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { PressHighlight } from "@/components/ui/press-highlight"; import { DEFAULT_THEME_PREFERENCE, useAppSettings, type AppSettings } from "@/hooks/use-settings"; diff --git a/packages/app/src/archived-workspaces/index.ts b/packages/app/src/archived-workspaces/index.ts new file mode 100644 index 0000000000..795e6ef6e6 --- /dev/null +++ b/packages/app/src/archived-workspaces/index.ts @@ -0,0 +1,5 @@ +export type { ArchivedWorkspace, ArchivedWorkspaceAgent } from "./internal/group"; +export { + useArchivedWorkspaceSearch, + type ArchivedWorkspaceSearch, +} from "./internal/use-archived-workspace-search"; diff --git a/packages/app/src/archived-workspaces/internal/group.test.ts b/packages/app/src/archived-workspaces/internal/group.test.ts new file mode 100644 index 0000000000..33f844a8df --- /dev/null +++ b/packages/app/src/archived-workspaces/internal/group.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import type { AggregatedAgent } from "@/hooks/use-aggregated-agents"; +import { groupArchivedWorkspaces } from "./group"; + +const T0 = Date.parse("2026-11-01T10:00:00.000Z"); +const minutes = (count: number) => new Date(T0 + count * 60_000); + +function historyAgent(input: { + id: string; + serverId?: string; + workspaceId?: string | null; + title?: string | null; + activeAt: number; + archivedAt?: number | null; + workspaceName?: string | null; + branch?: string | null; + cwd?: string; +}): AggregatedAgent { + const cwd = input.cwd ?? "/repos/payments"; + return { + id: input.id, + serverId: input.serverId ?? "host-a", + serverLabel: input.serverId ?? "host-a", + title: input.title ?? null, + status: "closed", + turn: { phase: "open", turnId: null, startedAt: null, cancellationRequestId: null }, + lastActivityAt: minutes(input.activeAt), + cwd, + workspaceId: input.workspaceId === undefined ? "ws-1" : input.workspaceId, + provider: "claude", + requiresAttention: false, + attentionReason: null, + attentionTimestamp: null, + archivedAt: input.archivedAt == null ? null : minutes(input.archivedAt), + createdAt: minutes(0), + labels: {}, + projectPlacement: { + projectKey: "prj-payments", + projectName: "payments", + workspaceName: input.workspaceName === undefined ? "Billing cleanup" : input.workspaceName, + checkout: { + cwd, + isGit: true, + currentBranch: input.branch === undefined ? "billing-cleanup" : input.branch, + remoteUrl: null, + worktreeRoot: cwd, + isPaseoOwnedWorktree: false, + mainRepoRoot: null, + }, + }, + } as AggregatedAgent; +} + +const NO_ACTIVE = new Map>(); + +describe("groupArchivedWorkspaces", () => { + it("folds a workspace's agents into one entry led by its most recent agent", () => { + const [workspace] = groupArchivedWorkspaces({ + agents: [ + historyAgent({ id: "older", title: "Audit invoices", activeAt: 1, archivedAt: 5 }), + historyAgent({ id: "newer", title: "Fix totals", activeAt: 3, archivedAt: 4 }), + ], + activeIds: NO_ACTIVE, + }); + + expect(workspace).toMatchObject({ + key: "host-a:ws-1", + serverId: "host-a", + workspaceId: "ws-1", + name: "Billing cleanup", + projectName: "payments", + projectKey: "prj-payments", + branch: "billing-cleanup", + archivedAt: minutes(5), + }); + expect(workspace.agents.map((agent) => agent.id)).toEqual(["newer", "older"]); + }); + + it("leaves out workspaces that are still active on their host", () => { + const workspaces = groupArchivedWorkspaces({ + agents: [historyAgent({ id: "a", activeAt: 1, archivedAt: 2 })], + activeIds: new Map([["host-a", new Set(["ws-1"])]]), + }); + + expect(workspaces).toEqual([]); + }); + + it("leaves out an inactive workspace none of whose agents were archived", () => { + const workspaces = groupArchivedWorkspaces({ + agents: [historyAgent({ id: "a", activeAt: 1, archivedAt: null })], + activeIds: NO_ACTIVE, + }); + + expect(workspaces).toEqual([]); + }); + + it("keeps the same workspace ID on two hosts apart and lists the latest archive first", () => { + const workspaces = groupArchivedWorkspaces({ + agents: [ + historyAgent({ id: "a", serverId: "host-a", activeAt: 1, archivedAt: 2 }), + historyAgent({ id: "b", serverId: "host-b", activeAt: 1, archivedAt: 9 }), + ], + activeIds: NO_ACTIVE, + }); + + expect(workspaces.map((workspace) => workspace.key)).toEqual(["host-b:ws-1", "host-a:ws-1"]); + }); + + it("skips agents with no workspace and names an unnamed workspace after its folder", () => { + const workspaces = groupArchivedWorkspaces({ + agents: [ + historyAgent({ id: "loose", workspaceId: null, activeAt: 1, archivedAt: 2 }), + historyAgent({ + id: "a", + workspaceName: null, + branch: null, + cwd: "/repos/receipts", + activeAt: 1, + archivedAt: 2, + }), + ], + activeIds: NO_ACTIVE, + }); + + expect(workspaces).toHaveLength(1); + expect(workspaces[0]).toMatchObject({ name: "receipts", branch: null }); + }); +}); diff --git a/packages/app/src/archived-workspaces/internal/group.ts b/packages/app/src/archived-workspaces/internal/group.ts new file mode 100644 index 0000000000..1b733ece52 --- /dev/null +++ b/packages/app/src/archived-workspaces/internal/group.ts @@ -0,0 +1,87 @@ +import type { AggregatedAgent } from "@/hooks/use-aggregated-agents"; + +export interface ArchivedWorkspaceAgent { + id: string; + title: string | null; + provider: string; +} + +/** A workspace the user archived, as agent history describes it. */ +export interface ArchivedWorkspace { + /** `serverId:workspaceId` */ + key: string; + serverId: string; + workspaceId: string; + name: string; + projectName: string | null; + /** The host's project ID. */ + projectKey: string | null; + branch: string | null; + /** The latest archive time among its agents. */ + archivedAt: Date; + /** Its agents in this history page, most recently active first. Never empty. */ + agents: ArchivedWorkspaceAgent[]; +} + +/** Which workspaces each host still lists as active. */ +export type ActiveWorkspaceIdsByServer = ReadonlyMap>; + +function lastPathSegment(path: string): string { + const parts = path.split(/[\\/]/).filter(Boolean); + return parts[parts.length - 1] ?? path; +} + +function checkoutBranch(agent: AggregatedAgent): string | null { + const checkout = agent.projectPlacement?.checkout; + return checkout?.isGit ? checkout.currentBranch : null; +} + +/** + * Folds agent history into one entry per archived workspace, newest archive first. A + * workspace its host still lists is active, so it is left out. So is an inactive workspace + * with no archived agent: the user never put it away (a background workspace, for example). + */ +export function groupArchivedWorkspaces(input: { + agents: readonly AggregatedAgent[]; + activeIds: ActiveWorkspaceIdsByServer; +}): ArchivedWorkspace[] { + const byKey = new Map(); + const newestFirst = [...input.agents].sort( + (left, right) => right.lastActivityAt.getTime() - left.lastActivityAt.getTime(), + ); + for (const agent of newestFirst) { + const workspaceId = agent.workspaceId; + if (!workspaceId || input.activeIds.get(agent.serverId)?.has(workspaceId)) continue; + const key = `${agent.serverId}:${workspaceId}`; + const archivedAt = agent.archivedAt ? new Date(agent.archivedAt) : null; + const summary = { id: agent.id, title: agent.title ?? null, provider: agent.provider }; + const existing = byKey.get(key); + if (existing) { + existing.agents.push(summary); + if (archivedAt && (!existing.archivedAtOrNull || archivedAt > existing.archivedAtOrNull)) { + existing.archivedAtOrNull = archivedAt; + } + continue; + } + // The most recent agent describes the workspace: it saw its latest name and branch. + const placement = agent.projectPlacement; + byKey.set(key, { + key, + serverId: agent.serverId, + workspaceId, + name: placement?.workspaceName || lastPathSegment(agent.cwd), + projectName: placement?.projectName ?? null, + projectKey: placement?.projectKey ?? null, + branch: checkoutBranch(agent), + archivedAt: archivedAt ?? new Date(0), + archivedAtOrNull: archivedAt, + agents: [summary], + }); + } + + const archived: ArchivedWorkspace[] = []; + for (const { archivedAtOrNull, ...workspace } of byKey.values()) { + if (archivedAtOrNull) archived.push({ ...workspace, archivedAt: archivedAtOrNull }); + } + return archived.sort((left, right) => right.archivedAt.getTime() - left.archivedAt.getTime()); +} diff --git a/packages/app/src/archived-workspaces/internal/use-archived-workspace-search.ts b/packages/app/src/archived-workspaces/internal/use-archived-workspace-search.ts new file mode 100644 index 0000000000..0f656c3833 --- /dev/null +++ b/packages/app/src/archived-workspaces/internal/use-archived-workspace-search.ts @@ -0,0 +1,83 @@ +import { useMemo } from "react"; +import { useShallow } from "zustand/shallow"; +import { useAgentHistory } from "@/hooks/use-agent-history"; +import { useDebouncedValue } from "@/hooks/use-debounced-value"; +import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store"; +import { + groupArchivedWorkspaces, + type ActiveWorkspaceIdsByServer, + type ArchivedWorkspace, +} from "./group"; + +const SEARCH_DEBOUNCE_MS = 200; +const NO_WORKSPACES: Record> = {}; +const NO_ARCHIVED_WORKSPACES: ArchivedWorkspace[] = []; + +export interface ArchivedWorkspaceSearch { + /** Newest archive first. Empty without a query. */ + workspaces: ArchivedWorkspace[]; + /** + * The host matched these for the current query. Its search forgives typos, so its matches + * can include rows the caller cannot match itself. False while the previous query's + * results stand in for the next one; those rows must still match the query on their own. + */ + matchedByHost: boolean; + /** Still searching for the current query, debounce included. */ + pending: boolean; +} + +function useActiveWorkspaceIds(enabled: boolean): ActiveWorkspaceIdsByServer { + // Each host's workspace map is replaced only when its workspaces change, so this does not + // re-render on agent activity. + const workspacesByServer = useSessionStore( + useShallow((state) => + enabled + ? Object.fromEntries( + Object.entries(state.sessions).map(([serverId, session]) => [ + serverId, + session.workspaces, + ]), + ) + : NO_WORKSPACES, + ), + ); + return useMemo( + () => + new Map( + Object.entries(workspacesByServer).map(([serverId, workspaces]) => [ + serverId, + new Set(workspaces.keys()), + ]), + ), + [workspacesByServer], + ); +} + +/** + * Archived workspaces whose name, project, branch, or agent titles match `query`, searched on + * every host that supports history search. Hosts that predate it contribute nothing. + */ +export function useArchivedWorkspaceSearch( + query: string, + options: { enabled: boolean }, +): ArchivedWorkspaceSearch { + const trimmed = query.trim(); + const search = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS); + const enabled = options.enabled && trimmed.length > 0; + const activeIds = useActiveWorkspaceIds(enabled); + const history = useAgentHistory({ + search, + enabled: enabled && search.length > 0, + searchableHostsOnly: true, + keepPreviousResults: true, + }); + const workspaces = useMemo( + () => + enabled + ? groupArchivedWorkspaces({ agents: history.agents, activeIds }) + : NO_ARCHIVED_WORKSPACES, + [activeIds, enabled, history.agents], + ); + const matchedByHost = search === trimmed && !history.isLoading && !history.isPreviousResults; + return { workspaces, matchedByHost, pending: enabled && !matchedByHost }; +} diff --git a/packages/app/src/assistant-file-links/use-file-link.test.tsx b/packages/app/src/assistant-file-links/use-file-link.test.tsx index 18d2727e82..db2995088f 100644 --- a/packages/app/src/assistant-file-links/use-file-link.test.tsx +++ b/packages/app/src/assistant-file-links/use-file-link.test.tsx @@ -39,6 +39,21 @@ function createDeferred() { return { promise, resolve, reject }; } +/** + * Resolves a pending lookup and waits until React Query has delivered the result. It delivers on a + * timer, which would otherwise fire after the test, when jsdom is gone. + */ +async function resolveLookupAndDeliver( + lookup: ReturnType>, + result: DirectorySuggestionResult, +): Promise { + await act(async () => { + lookup.resolve(result); + await lookup.promise; + await new Promise((resolve) => setTimeout(resolve, 0)); + }); +} + interface OpenedFile { target: InlinePathTarget; disposition: OpenFileDisposition; @@ -322,11 +337,12 @@ describe("useFileLink", () => { act(() => { result.current.setWorkspaceRoot("/Users/test/other"); }); - deferred.resolve(resolvedSuggestions([{ path: "docs/dumm.md", kind: "file" }])); + await resolveLookupAndDeliver( + deferred, + resolvedSuggestions([{ path: "docs/dumm.md", kind: "file" }]), + ); - await waitFor(() => { - expect(getDirectorySuggestions).toHaveBeenCalledTimes(1); - }); + expect(getDirectorySuggestions).toHaveBeenCalledTimes(1); expect(openedFiles).toEqual([]); }); }); diff --git a/packages/app/src/assistant-selection-copy/content.browser.test.ts b/packages/app/src/assistant-selection-copy/content.browser.test.ts index 5c4fcfb331..f4e240c690 100644 --- a/packages/app/src/assistant-selection-copy/content.browser.test.ts +++ b/packages/app/src/assistant-selection-copy/content.browser.test.ts @@ -759,6 +759,56 @@ describe("assistant selection copy inside highlighted code", () => { "```typescript\nconst answer = 1;\n if (answer) {\n doThing();\n```\n\nAfter the block.", ); }); + + it("keeps line breaks when a quote selection ends partway through code", () => { + const message = mountHighlighted(); + const quote = document.createElement("div"); + quote.setAttribute("data-paseo-markdown-tag", "blockquote"); + quote.textContent = "Quoted context"; + message.querySelector('[data-paseo-markdown-tag="pre"]')!.before(quote); + + const content = copyBetween( + [tokenText(message, "Quoted context"), 0], + [tokenText(message, " (answer)"), 9], + ); + + expect(content?.plainText).toBe( + "> Quoted context\n\n```typescript\nconst answer = 1;\n if (answer)\n```", + ); + }); + + it("keeps indented code lines inside their list item", () => { + const host = document.createElement("div"); + host.innerHTML = [ + '
', + '
', + '
', + '
1.
', + '
Item text
', + highlightedCodeBlock("typescript"), + "
", + ].join(""); + document.body.append(host); + + const content = copyBetween([tokenText(host, "1."), 0], [tokenText(host, " (answer)"), 9]); + + expect(content?.plainText).toBe( + "1. Item text\n\n ```typescript\n const answer = 1;\n if (answer)\n ```", + ); + }); + + it("keeps line breaks when a selection starts partway through code", () => { + const message = mountHighlighted(); + + const content = copyBetween( + [tokenText(message, " answer"), 1], + [tokenText(message, "After the block."), "After the block.".length], + ); + + expect(content?.plainText).toBe( + "```typescript\nanswer = 1;\n if (answer) {\n doThing();\n```\n\nAfter the block.", + ); + }); }); describe("semantic library output", () => { diff --git a/packages/app/src/assistant-selection-copy/content.web.ts b/packages/app/src/assistant-selection-copy/content.web.ts index 250d60d761..58a2a8fd85 100644 --- a/packages/app/src/assistant-selection-copy/content.web.ts +++ b/packages/app/src/assistant-selection-copy/content.web.ts @@ -81,7 +81,8 @@ turndown.addRule("compactListItem", { const item = content .replace(/^\n+/, "") .replace(/\n+$/, "\n") - .replace(/\n(?=\S)/g, "\n "); + // Every non-empty line, so indented code lines stay inside the item. + .replace(/\n(?=[^\n])/g, "\n "); const parent = node.parentElement; if (parent?.nodeName !== "OL") { return `${options.bulletListMarker} ${item}\n`; @@ -359,6 +360,9 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean if (tag === "p" || tag === "img" || isTableStructure(tag)) { return true; } + if (isCrossBoundaryCodeElement(range, element, tag)) { + return true; + } const isSelectableSemantic = tag !== null && tag !== "li" && tag !== "ol" && tag !== "ul"; if ( (isSelectableSemantic || element.tagName === "A") && @@ -386,6 +390,11 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean return hasSelectedAllContents(range, element, tag === "li"); } +function isCrossBoundaryCodeElement(range: Range, element: Element, tag: string | null): boolean { + const isCode = tag === "pre" || (tag === "code" && Boolean(element.closest(CODE_BLOCK_SELECTOR))); + return isCode && !selectionStaysInsideElement(range, element); +} + function selectionStaysInsideElement(range: Range, element: Element): boolean { return ( range.startContainer !== element && diff --git a/packages/app/src/attachments/use-attachment-preview-url.browser.test.tsx b/packages/app/src/attachments/use-attachment-preview-url.browser.test.tsx new file mode 100644 index 0000000000..2d56efa1af --- /dev/null +++ b/packages/app/src/attachments/use-attachment-preview-url.browser.test.tsx @@ -0,0 +1,71 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { persistAttachmentFromBlob } from "@/attachments/service"; +import type { AttachmentMetadata } from "@/attachments/types"; +import { type AttachmentPreviewUrl, useAttachmentPreviewUrl } from "./use-attachment-preview-url"; + +let root: Root; +let container: HTMLDivElement; +let latest: AttachmentPreviewUrl | null = null; + +function PreviewProbe({ attachment }: { attachment: AttachmentMetadata | null }) { + latest = useAttachmentPreviewUrl(attachment); + return null; +} + +async function render(attachment: AttachmentMetadata | null) { + await act(async () => root.render()); +} + +async function waitForReady(): Promise { + await vi.waitFor(() => expect(latest?.status).toBe("ready")); + if (latest?.status !== "ready") throw new Error("preview never resolved"); + return latest.url; +} + +beforeEach(() => { + vi.stubGlobal("React", React); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + latest = null; +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); + +it("never hands back a URL it already released when the same attachment returns", async () => { + const attachment = await persistAttachmentFromBlob({ + blob: new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }), + mimeType: "image/png", + fileName: "shot.png", + }); + + await render(attachment); + const released = await waitForReady(); + await render(null); + await render(attachment); + + expect(latest).not.toEqual({ status: "ready", url: released }); + expect(await waitForReady()).not.toBe(released); +}); + +it("retries a failed attachment from loading when it returns", async () => { + const stored = await persistAttachmentFromBlob({ + blob: new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }), + mimeType: "image/png", + fileName: "shot.png", + }); + const missing = { ...stored, id: "missing-attachment", storageKey: "missing-attachment" }; + + await render(missing); + await vi.waitFor(() => expect(latest?.status).toBe("failed")); + await render(null); + await render(missing); + + expect(latest).toEqual({ status: "loading" }); +}); diff --git a/packages/app/src/attachments/use-attachment-preview-url.ts b/packages/app/src/attachments/use-attachment-preview-url.ts index d54db61498..183dfa7d90 100644 --- a/packages/app/src/attachments/use-attachment-preview-url.ts +++ b/packages/app/src/attachments/use-attachment-preview-url.ts @@ -2,62 +2,75 @@ import { useEffect, useRef, useState } from "react"; import type { AttachmentMetadata } from "@/attachments/types"; import { releaseAttachmentPreviewUrl, resolveAttachmentPreviewUrl } from "@/attachments/service"; +export type AttachmentPreviewUrl = + | { status: "loading" } + | { status: "ready"; url: string } + | { status: "failed" }; + +const LOADING: AttachmentPreviewUrl = { status: "loading" }; +const FAILED: AttachmentPreviewUrl = { status: "failed" }; + +function attachmentKey(attachment: AttachmentMetadata | null | undefined): string | null { + if (!attachment) return null; + return [attachment.id, attachment.storageType, attachment.storageKey, attachment.mimeType].join( + "\u0000", + ); +} + +/** + * Resolves a displayable URL for a stored attachment. Stays `loading` until the URL for the + * current attachment resolves, so a caller never shows a failure, or the previous attachment's + * URL, while the next one is still resolving. A missing attachment stays `loading`. + */ export function useAttachmentPreviewUrl( attachment: AttachmentMetadata | null | undefined, -): string | null { - const [url, setUrl] = useState(null); - const activeAttachmentRef = useRef(null); +): AttachmentPreviewUrl { + const [resolved, setResolved] = useState<{ + key: string; + preview: AttachmentPreviewUrl; + } | null>(null); const attachmentRef = useRef(attachment); attachmentRef.current = attachment; - - const id = attachment?.id; - const storageType = attachment?.storageType; - const storageKey = attachment?.storageKey; - const mimeType = attachment?.mimeType; + const key = attachmentKey(attachment); useEffect(() => { - let disposed = false; - let currentUrl: string | null = null; const current = attachmentRef.current; - - activeAttachmentRef.current = current ?? null; - if (!current) { - setUrl(null); + if (!current || key === null) { return; } + let disposed = false; + let currentUrl: string | null = null; void (async () => { try { - const resolved = await resolveAttachmentPreviewUrl(current); + const url = await resolveAttachmentPreviewUrl(current); if (disposed) { - await releaseAttachmentPreviewUrl({ attachment: current, url: resolved }); + await releaseAttachmentPreviewUrl({ attachment: current, url }); return; } - currentUrl = resolved; - setUrl(resolved); + currentUrl = url; + setResolved({ key, preview: { status: "ready", url } }); } catch (error) { console.error("[attachments] Failed to resolve preview URL", { attachmentId: current.id, error, }); if (!disposed) { - setUrl(null); + setResolved({ key, preview: FAILED }); } } })(); return () => { disposed = true; - const activeAttachment = activeAttachmentRef.current; - if (!currentUrl || !activeAttachment) { - return; + if (currentUrl) { + void releaseAttachmentPreviewUrl({ attachment: current, url: currentUrl }); } - void releaseAttachmentPreviewUrl({ - attachment: activeAttachment, - url: currentUrl, - }); + // A result lives only as long as its lookup. Kept, the same attachment coming back would + // read a released URL, or an old failure, until the next lookup lands. + setResolved((previous) => (previous?.key === key ? null : previous)); }; - }, [id, storageType, storageKey, mimeType]); + }, [key]); - return url; + return resolved !== null && resolved.key === key ? resolved.preview : LOADING; } diff --git a/packages/app/src/background-work/index.tsx b/packages/app/src/background-work/index.tsx index 34dfbb83ff..bafa953fa6 100644 --- a/packages/app/src/background-work/index.tsx +++ b/packages/app/src/background-work/index.tsx @@ -10,8 +10,8 @@ import { createHostBackgroundWorkModel } from "./host"; import { backgroundWorkText } from "./presentation"; export { createHostBackgroundWorkModel } from "./host"; -function kindKey(kind: string): "shell" | "monitor" | "other" { - if (kind === "shell" || kind === "monitor") return kind; +function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" { + if (kind === "shell" || kind === "monitor" || kind === "heartbeat") return kind; return "other"; } diff --git a/packages/app/src/changelog/internal/changelog-sheet.tsx b/packages/app/src/changelog/internal/changelog-sheet.tsx index fd7bc82450..fb367af667 100644 --- a/packages/app/src/changelog/internal/changelog-sheet.tsx +++ b/packages/app/src/changelog/internal/changelog-sheet.tsx @@ -1,18 +1,18 @@ import { memo, useCallback, useMemo, useState } from "react"; -import { Pressable, Text, View, type PressableStateCallbackType } from "react-native"; +import { Text, View } from "react-native"; import { ExternalLink, Gift } from "lucide-react-native"; import { useTranslation } from "react-i18next"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { + AdaptiveModalSheet, + SheetHeaderIconButton, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; import { MarkdownRenderer } from "@/components/markdown/renderer"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { - iconButtonChromeGlyphSize, - iconButtonChromeStyle, -} from "@/components/ui/icon-button-chrome"; import { StatusBadge } from "@/components/ui/status-badge"; import { ICON_SIZE, type Theme } from "@/styles/theme"; import { resolveAppVersion } from "@/utils/app-version"; @@ -28,12 +28,9 @@ import { const WEBSITE_CHANGELOG_URL = "https://paseo.sh/changelog"; const ThemedGift = withUnistyles(Gift); -const ThemedExternalLink = withUnistyles(ExternalLink); const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); const sheetLeadingIcon = ; -const websiteButtonStyle = (state: PressableStateCallbackType & { hovered?: boolean }) => - iconButtonChromeStyle({ size: "large", state }); interface ChangelogSheetProps { visible: boolean; @@ -54,19 +51,12 @@ export function ChangelogSheet({ visible, onClose }: ChangelogSheetProps) { title: t("changelog.title"), leading: sheetLeadingIcon, actions: ( - - - + /> ), }), [handleOpenWebsite, t], diff --git a/packages/app/src/command-center/command-center.tsx b/packages/app/src/command-center/command-center.tsx index 1c20f0725d..8d92e779b0 100644 --- a/packages/app/src/command-center/command-center.tsx +++ b/packages/app/src/command-center/command-center.tsx @@ -24,10 +24,12 @@ import { useSyncExternalStore, } from "react"; import { useTranslation } from "react-i18next"; -import { Check, ChevronRight, Folder, X } from "lucide-react-native"; +import { Check, ChevronRight } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { BottomSheetFlatList, type BottomSheetFlatListMethods } from "@gorhom/bottom-sheet"; -import { useAgentDescriptor, resolveAgentLabel } from "@/agent-presentation"; +import { resolveAgentLabel } from "@/agent-presentation"; +import { useArchivedWorkspaceSearch, type ArchivedWorkspace } from "@/archived-workspaces"; +import { ArchivedBadge } from "@/components/archived-badge"; import { StatusIcon } from "@/components/status-icon"; import { useWorkspaceStatus } from "@/workspace-status"; import type { SurfaceBackdrop } from "@/styles/surface-backdrop"; @@ -35,12 +37,14 @@ import type { Theme } from "@/styles/theme"; import { HighlightedText, type HighlightedTextProps } from "@/components/ui/highlighted-text"; import { findHighlightRanges } from "@/components/ui/highlighted-text-segments"; import { MaterialFileIcon } from "@/components/material-file-icon"; +import { useProviderIcon } from "@/components/provider-icons"; import { ProjectIconView } from "@/components/project-icon-view"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { EditingTextInput as TextInput, type EditingTextInputHandle, } from "@/components/ui/text-input"; +import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; import { Shortcut } from "@/components/ui/shortcut"; import { IsolatedBottomSheetModal, @@ -48,18 +52,20 @@ import { } from "@/components/ui/isolated-bottom-sheet-modal"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isNative, isWeb } from "@/constants/platform"; -import { useAggregatedAgents } from "@/hooks/use-aggregated-agents"; +import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents"; import { useProjects } from "@/hooks/use-projects"; import { useTimeAgo } from "@/hooks/use-time-ago"; import { createProjectIconTarget } from "@/projects/icon-target"; import { useProjectIcons } from "@/projects/icons"; import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root"; -import { useHosts } from "@/runtime/host-runtime"; +import { useHostRuntimeConnectionStatuses, useHosts } from "@/runtime/host-runtime"; +import { useHydratedWorkspaceServerIds } from "@/stores/session-store-hooks"; +import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store"; +import { useSidebarViewStore } from "@/stores/sidebar-view-store"; import { - useKeyboardShortcutsStore, - type CommandCenterScope, -} from "@/stores/keyboard-shortcuts-store"; -import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store"; + navigateToWorkspace, + useActiveWorkspaceSelection, +} from "@/stores/navigation-active-workspace-store"; import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context"; import { clearCommandCenterFocusRestoreElement, @@ -67,8 +73,8 @@ import { } from "@/utils/command-center-focus-restore"; import { focusWithRetries } from "@/utils/web-focus"; import { navigateToAgent } from "@/utils/navigate-to-agent"; -import { shortenPath } from "@/utils/shorten-path"; import { projectIconPlaceholderLabelFromDisplayName } from "@/utils/project-display-name"; +import { getProjectSummaryForHostProject } from "@/utils/projects"; import { COMMAND_CENTER_LINE_HEIGHT, COMMAND_CENTER_LIST_METRICS, @@ -76,21 +82,23 @@ import { type CommandCenterListMetrics, } from "./list-metrics"; import { useCommandCenterContributions } from "./provider"; -import { filterAndRankWorkspaces } from "./workspace-search"; +import { createWorkspaceRanker } from "./workspace-search"; import { - buildContributionSections, - filterAndRankBuiltInResults, joinSubtitleParts, - PINNED_SECTION_BAND, projectCommandCenterRows, - type CommandCenterAgentResult, type CommandCenterFileResult, type CommandCenterListRow, type CommandCenterResult, - type CommandCenterResultSection, - type CommandCenterSearchFields, + type CommandCenterWorkspaceAgent, type CommandCenterWorkspaceResult, } from "./results"; +import { buildCommandCenterSections } from "./sections"; +import { + availableCommandCenterTabs, + resolveCommandCenterTab, + rotateCommandCenterTab, + type CommandCenterTab, +} from "./tabs"; import { createCommandCenterInteraction, type CommandCenterInteraction } from "./interaction"; import { useWorkspaceFileSearch } from "./workspace-file-search"; @@ -100,23 +108,16 @@ const ThemedBottomSheetTextInput = withUnistyles(TextInput, (theme) => ({ const ThemedTextInput = withUnistyles(TextInput, (theme) => ({ placeholderTextColor: theme.colors.foregroundMuted, })); -const ThemedFolder = withUnistyles(Folder, (theme) => ({ color: theme.colors.foregroundMuted })); const ThemedCheck = withUnistyles(Check, (theme) => ({ color: theme.colors.foreground })); const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({ color: theme.colors.foregroundMuted, })); -const ThemedX = withUnistyles(X, (theme) => ({ color: theme.colors.foregroundMuted })); const ThemedLoadingSpinner = withUnistyles(LoadingSpinner, (theme) => ({ color: theme.colors.foregroundMuted, })); const COMMAND_CENTER_SNAP_POINTS = ["60%", "90%"]; const KEYBOARD_SHOULD_PERSIST_TAPS = "always" as const; -/** `cwd` is not rendered, so a path match must never outrank a match on text the user can see. */ -function agentSearchFields(result: CommandCenterAgentResult): CommandCenterSearchFields { - return { visible: [result.title, result.subtitle], hidden: [result.agent.cwd] }; -} - function createWorkspaceResultAction(serverId: string, workspaceId: string) { return () => { clearCommandCenterFocusRestoreElement(); @@ -124,28 +125,73 @@ function createWorkspaceResultAction(serverId: string, workspaceId: string) { }; } -function createAgentResultAction(serverId: string, agentId: string) { - return () => { +function createAgentResultAction(serverId: string) { + return (agentId: string) => { clearCommandCenterFocusRestoreElement(); navigateToAgent({ serverId, agentId }); }; } -/** - * Build every pinned row. Deliberately not keyed on `query`: none of this work depends on what - * was typed. Ordering belongs to `filterAndRankBuiltInResults`, which ranks on every keystroke. - */ -function useBuiltInRows(open: boolean): { - workspaces: CommandCenterWorkspaceResult[]; - agents: CommandCenterAgentResult[]; -} { - const { t } = useTranslation(); - const previousRows = useRef( - new Map(), +const NO_WORKSPACE_AGENTS: readonly CommandCenterWorkspaceAgent[] = []; + +/** Each workspace's titled agents, most recent first, keyed `serverId:workspaceId`. */ +function groupWorkspaceAgents( + agents: readonly AggregatedAgent[], +): Map { + const byWorkspace = new Map(); + const newestFirst = [...agents].sort( + (left, right) => right.lastActivityAt.getTime() - left.lastActivityAt.getTime(), ); - const { agents } = useAggregatedAgents({ demand: open }); - const { projects } = useProjects({ enabled: open }); - const showHost = useHosts().length > 1; + for (const agent of newestFirst) { + const title = resolveAgentLabel(agent.title); + if (!agent.workspaceId || !title) continue; + const key = `${agent.serverId}:${agent.workspaceId}`; + const list = byWorkspace.get(key) ?? []; + list.push({ id: agent.id, title, provider: agent.provider }); + byWorkspace.set(key, list); + } + return byWorkspace; +} + +function createArchivedAgentAction(serverId: string, workspaceId: string) { + // Opening on an agent with the tab pinned is what offers Unarchive, as History does. + return (agentId: string) => { + clearCommandCenterFocusRestoreElement(); + navigateToAgent({ serverId, agentId, workspaceId, pin: true }); + }; +} + +function titledAgents( + agents: readonly { id: string; title: string | null; provider: string }[], +): CommandCenterWorkspaceAgent[] { + return agents.flatMap((agent) => { + const title = resolveAgentLabel(agent.title); + return title ? [{ id: agent.id, title, provider: agent.provider }] : []; + }); +} + +interface WorkspaceRows { + active: CommandCenterWorkspaceResult[]; + archived: CommandCenterWorkspaceResult[]; + /** The workspace list has not loaded yet, so rows are still arriving. */ + loading: boolean; +} + +/** + * Build every workspace row. Deliberately not keyed on `query`: none of this work depends on + * what was typed. Ordering belongs to the workspace ranker, which ranks on every keystroke. + * Archived rows come from the host's history search, so they change with its results. + */ +function useWorkspaceRows( + open: boolean, + archivedWorkspaces: readonly ArchivedWorkspace[], +): WorkspaceRows { + const previousRows = useRef(new Map()); + const { agents, isInitialLoad: agentsLoading } = useAggregatedAgents({ demand: open }); + const { projects, isLoading: projectsLoading } = useProjects({ enabled: open }); + const hosts = useHosts(); + const workspacesArriving = useWorkspacesArriving(open, hosts); + const showHost = hosts.length > 1; const iconTargets = useMemo( () => open @@ -163,24 +209,26 @@ function useBuiltInRows(open: boolean): { ); const iconDataByProjectViewKey = useProjectIcons({ projects: iconTargets }); - return useMemo(() => { + const active = useMemo(() => { if (!open) { previousRows.current.clear(); - return { workspaces: [], agents: [] }; + return []; } - // Built-in IDs identify immutable navigation targets. Reuse their callbacks and unchanged + // Workspace IDs identify immutable navigation targets. Reuse their callbacks and unchanged // row data so a directory update does not invalidate every mounted ResultRow. - const nextRows = new Map(); - const preserve = ( - row: T, - ): T => { + const nextRows = new Map(); + const preserve = (row: CommandCenterWorkspaceResult): CommandCenterWorkspaceResult => { const previous = previousRows.current.get(row.id); - if (previous) row.run = previous.run; - const stable = previous && equal(previous, row) ? (previous as T) : row; + if (previous) { + row.run = previous.run; + row.openAgent = previous.openAgent; + } + const stable = previous && equal(previous, row) ? previous : row; nextRows.set(row.id, stable); return stable; }; - const allWorkspaces: CommandCenterWorkspaceResult[] = []; + const agentsByWorkspace = groupWorkspaceAgents(agents); + const rows: CommandCenterWorkspaceResult[] = []; for (const project of projects) { const workspaceProject = { viewKey: project.viewKey, @@ -190,10 +238,11 @@ function useBuiltInRows(open: boolean): { for (const host of project.hosts) { for (const workspace of host.workspaces) { if (workspace.archivingAt) continue; - allWorkspaces.push( + const key = `${host.serverId}:${workspace.id}`; + rows.push( preserve({ kind: "workspace", - id: `workspace:${host.serverId}:${workspace.id}`, + id: `workspace:${key}`, title: workspace.title ?? workspace.name, subtitle: joinSubtitleParts([ showHost ? host.serverName : null, @@ -205,66 +254,93 @@ function useBuiltInRows(open: boolean): { project: workspaceProject, changeRequestNumber: workspace.changeRequestNumber, activityAt: workspace.statusEnteredAt, + agents: agentsByWorkspace.get(key) ?? NO_WORKSPACE_AGENTS, + matchedAgent: null, + archived: false, + background: workspace.background, run: createWorkspaceResultAction(host.serverId, workspace.id), + openAgent: createAgentResultAction(host.serverId), }), ); } } } - const workspaceTitleByKey = new Map( - allWorkspaces.map((workspace) => [workspace.id.slice("workspace:".length), workspace.title]), - ); - const agentRows = agents.map((agent) => { - const workspaceTitle = agent.workspaceId - ? workspaceTitleByKey.get(`${agent.serverId}:${agent.workspaceId}`) - : undefined; - return preserve({ - kind: "agent", - id: `agent:${agent.serverId}:${agent.id}`, - agent, - title: resolveAgentLabel(agent.title) ?? t("workspace.tabs.loading"), - subtitle: joinSubtitleParts([ - showHost ? agent.serverLabel : null, - workspaceTitle ?? shortenPath(agent.cwd), - ]), - activityAt: agent.lastActivityAt, - run: createAgentResultAction(agent.serverId, agent.id), - }); - }); previousRows.current = nextRows; - return { workspaces: allWorkspaces, agents: agentRows }; - }, [agents, iconDataByProjectViewKey, open, projects, showHost, t]); + return rows; + }, [agents, iconDataByProjectViewKey, open, projects, showHost]); + + const archived = useMemo(() => { + const activeIds = new Set(active.map((row) => row.id)); + const hostLabels = new Map(hosts.map((host) => [host.serverId, host.label])); + return archivedWorkspaces.flatMap((workspace) => { + const id = `workspace:${workspace.key}`; + // The host's history can trail its workspace list; the active row wins. + if (activeIds.has(id)) return []; + const project = workspace.projectKey + ? getProjectSummaryForHostProject(projects, workspace.serverId, workspace.projectKey) + : undefined; + const projectName = project?.projectName ?? workspace.projectName ?? workspace.name; + const openAgent = createArchivedAgentAction(workspace.serverId, workspace.workspaceId); + const latestAgentId = workspace.agents[0].id; + return [ + { + kind: "workspace", + id, + title: workspace.name, + subtitle: joinSubtitleParts([ + showHost ? (hostLabels.get(workspace.serverId) ?? workspace.serverId) : null, + projectName, + workspace.branch, + ]), + serverId: workspace.serverId, + workspaceId: workspace.workspaceId, + project: { + viewKey: project?.viewKey ?? `archived:${workspace.key}`, + name: projectName, + iconDataUri: project ? (iconDataByProjectViewKey.get(project.viewKey) ?? null) : null, + }, + changeRequestNumber: null, + activityAt: workspace.archivedAt, + agents: titledAgents(workspace.agents), + matchedAgent: null, + archived: true, + background: false, + run: () => openAgent(latestAgentId), + openAgent, + }, + ]; + }); + }, [active, archivedWorkspaces, hosts, iconDataByProjectViewKey, projects, showHost]); + + return { + active, + archived, + // Opening a workspace route loads that workspace before the rest of the directory, so rows + // are no sign that the list is complete. + loading: agentsLoading || projectsLoading || workspacesArriving, + }; } -function useBuiltInSections(open: boolean, query: string): CommandCenterResultSection[] { - const { t } = useTranslation(); - const rows = useBuiltInRows(open); - - return useMemo(() => { - if (!open) return []; - return [ - { - id: "workspaces", - band: PINNED_SECTION_BAND, - rank: 2, - title: t("shell.commandCenter.workspaces"), - results: filterAndRankWorkspaces(rows.workspaces, query), - }, - { - id: "agents", - band: PINNED_SECTION_BAND, - rank: 3, - title: t("shell.commandCenter.agents"), - results: filterAndRankBuiltInResults(rows.agents, query, agentSearchFields), - }, - ]; - }, [open, query, rows, t]); +/** + * An online host's workspaces have not arrived yet. Its agent directory reports ready before + * the workspace snapshot lands, so until then the workspace rows are incomplete. + */ +function useWorkspacesArriving(open: boolean, hosts: readonly { serverId: string }[]): boolean { + const serverIds = useMemo(() => (open ? hosts.map((host) => host.serverId) : []), [hosts, open]); + const connectionStatuses = useHostRuntimeConnectionStatuses(serverIds); + const hydratedServerIds = useHydratedWorkspaceServerIds(serverIds); + return serverIds.some( + (serverId) => + connectionStatuses.get(serverId) === "online" && !hydratedServerIds.includes(serverId), + ); } interface CommandCenterState { open: boolean; - scope: CommandCenterScope; - clearScope(): void; + /** The tabs on offer, in the order Tab walks them. */ + tabs: readonly CommandCenterTab[]; + tab: CommandCenterTab; + selectTab(tab: CommandCenterTab): void; query: string; setQuery(query: string): void; activeId: string | null; @@ -275,7 +351,7 @@ interface CommandCenterState { fileSearchError: string | null; close(): void; select(result: CommandCenterResult): void; - key(key: string): boolean; + key(event: { key: string; shiftKey?: boolean }): boolean; } function useCommandCenterState( @@ -285,62 +361,95 @@ function useCommandCenterState( const keyboardActionDispatcher = useKeyboardActionDispatcher(); const { t } = useTranslation(); const open = useKeyboardShortcutsStore((state) => state.commandCenterOpen); - const scope = useKeyboardShortcutsStore((state) => state.commandCenterScope); + const requestedTab = useKeyboardShortcutsStore((state) => state.commandCenterTab); const setOpen = useKeyboardShortcutsStore((state) => state.setCommandCenterOpen); - const setScope = useKeyboardShortcutsStore((state) => state.setCommandCenterScope); + const setTab = useKeyboardShortcutsStore((state) => state.setCommandCenterTab); const snapshot = useCommandCenterContributions(); const inputRef = useRef(null); const previousOpenRef = useRef(open); const { query, activeId } = useSyncExternalStore(interaction.subscribe, interaction.getSnapshot); - const builtInSections = useBuiltInSections(open, query); + const activeWorkspace = useActiveWorkspaceSelection(); + const hasWorkspace = activeWorkspace !== null; + const tabs = useMemo(() => availableCommandCenterTabs({ hasWorkspace }), [hasWorkspace]); + const tab = resolveCommandCenterTab(requestedTab, tabs); + const showBackground = useSidebarViewStore((state) => state.showBackground); + const listsWorkspaces = tab === "all" || tab === "workspaces"; + const archivedSearch = useArchivedWorkspaceSearch(query, { + enabled: open && listsWorkspaces, + }); + const workspaceRows = useWorkspaceRows(open, archivedSearch.workspaces); + const [rankWorkspaces] = useState(createWorkspaceRanker); + const currentWorkspaceId = activeWorkspace + ? `workspace:${activeWorkspace.serverId}:${activeWorkspace.workspaceId}` + : null; const { entries: fileSearchEntries, loading: fileSearchLoading, error: fileSearchError, openFile, } = useWorkspaceFileSearch({ - enabled: open && (scope === "files" || Boolean(query.trim())), + enabled: + open && + tabs.includes("files") && + (tab === "files" || (tab === "all" && Boolean(query.trim()))), query, }); - const fileSections = useMemo(() => { - const results = fileSearchEntries.map((entry) => ({ - kind: "file", - id: `file:${entry.path}`, - filePath: entry.path, - title: entry.name, - subtitle: entry.directory, - run: () => openFile(entry.path), - })); - // File rows are matched by the daemon, so they carry no client-side score and cannot be - // relevance-compared against the rows that do. Pinning them keeps the section comparator - // total: band is decided before any score is read. - return [ - { - id: "files", - band: PINNED_SECTION_BAND, - rank: 4, - title: t("shell.commandCenter.files"), - results, - }, - ]; - }, [fileSearchEntries, openFile, t]); - const contributionSections = useMemo( - () => buildContributionSections(snapshot.contributions, query), - [query, snapshot.contributions], + const files = useMemo( + () => + fileSearchEntries.map((entry) => ({ + kind: "file", + id: `file:${entry.path}`, + filePath: entry.path, + title: entry.name, + subtitle: entry.directory, + run: () => openFile(entry.path), + })), + [fileSearchEntries, openFile], + ); + const sections = useMemo( + () => + open + ? buildCommandCenterSections({ + tab, + query, + rankWorkspaces, + workspaces: workspaceRows.active, + archivedWorkspaces: workspaceRows.archived, + archivedMatchedByHost: archivedSearch.matchedByHost, + showBackground, + currentWorkspaceId, + contributions: snapshot.contributions, + files, + titles: { + recentWorkspaces: t("shell.commandCenter.recentWorkspaces"), + workspaces: t("shell.commandCenter.workspaces"), + files: t("shell.commandCenter.files"), + }, + }) + : [], + [ + archivedSearch.matchedByHost, + currentWorkspaceId, + files, + open, + query, + rankWorkspaces, + showBackground, + snapshot.contributions, + t, + tab, + workspaceRows, + ], ); const projection = useMemo( - () => - projectCommandCenterRows( - scope === "files" - ? fileSections - : [...contributionSections, ...fileSections, ...builtInSections], - listMetrics, - ), - [builtInSections, contributionSections, fileSections, listMetrics, scope], + () => projectCommandCenterRows(sections, listMetrics), + [listMetrics, sections], ); + const loading = + fileSearchLoading || (listsWorkspaces && (archivedSearch.pending || workspaceRows.loading)); useLayoutEffect(() => { - interaction.update({ open, scope, query, projection, loading: fileSearchLoading }); - }, [interaction, open, scope, query, projection, fileSearchLoading]); + interaction.update({ open, tab, query, projection, loading }); + }, [interaction, open, tab, query, projection, loading]); const close = useCallback(() => setOpen(false), [setOpen]); const select = useCallback( @@ -350,16 +459,29 @@ function useCommandCenterState( }, [setOpen], ); + const selectTab = useCallback( + (next: CommandCenterTab) => { + setTab(next); + // A tab click must not take typing away from the search field. + inputRef.current?.focus(); + }, + [setTab], + ); const key = useCallback( - (pressed: string): boolean => { + (event: { key: string; shiftKey?: boolean }): boolean => { if (!open) return false; + const pressed = event.key; const results = projection.selectableResults; if (pressed === "Escape") { close(); return true; } - if (pressed === "Backspace" && !query.trim() && scope) { - setScope(null); + if (pressed === "Tab") { + setTab(rotateCommandCenterTab(tab, event.shiftKey ? "previous" : "next", tabs)); + return true; + } + if (pressed === "Backspace" && !query.trim() && tab !== "all") { + setTab("all"); return true; } if (pressed === "Enter") { @@ -377,9 +499,10 @@ function useCommandCenterState( projection.selectableResults, query, activeId, - scope, + tab, + tabs, select, - setScope, + setTab, interaction, ], ); @@ -405,8 +528,9 @@ function useCommandCenterState( return { open, - scope, - clearScope: () => setScope(null), + tabs, + tab, + selectTab, query, setQuery: interaction.setQuery, activeId, @@ -536,55 +660,38 @@ function SubtitleWithTimestamp({ ); } -const providerIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); - -function AgentResultContent({ - result, +/** + * The third line of a workspace that matched only through one of its agents: which agent, so the + * user can tell why the row is here. It starts on the title's rail. + */ +function MatchedAgentLine({ + agent, + serverId, query, - backdrop, }: { - result: CommandCenterAgentResult; + agent: CommandCenterWorkspaceAgent; + serverId: string; query: string; - backdrop: SurfaceBackdrop; }) { - const agent = result.agent; - const descriptor = useAgentDescriptor( - { kind: "agent", agentId: agent.id }, - { serverId: agent.serverId }, - ); - const Icon = useMemo( - () => withUnistyles(descriptor.icon, providerIconMapping), - [descriptor.icon], - ); + const ProviderIcon = useProviderIcon(agent.provider, serverId); + const Icon = useMemo(() => withUnistyles(ProviderIcon, providerIconMapping), [ProviderIcon]); return ( - - - - - - - - - - - - - + + + + ); } +const providerIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + function WorkspaceResultIcon({ result, backdrop, @@ -595,24 +702,27 @@ function WorkspaceResultIcon({ const statusBucket = useWorkspaceStatus(result.serverId, result.workspaceId); return ( - - - + ); } -/** The same project icon the sidebar's workspace rows lead with: its image, or a lettered square. */ -function WorkspaceProjectIcon({ project }: { project: CommandCenterWorkspaceResult["project"] }) { +/** + * The same project icon the sidebar's workspace rows lead with: its image, or a lettered square. + * Hidden from assistive tech so the fallback's initial does not prefix the row's name. + */ +function DecorativeProjectIcon({ project }: { project: CommandCenterWorkspaceResult["project"] }) { const initial = projectIconPlaceholderLabelFromDisplayName(project.name).charAt(0).toUpperCase(); return ( - + + + ); } @@ -650,17 +760,18 @@ function ResultContent({ ); } - if (result.kind === "agent") { - return ; - } if (result.kind === "workspace") { const key = result.id.slice("workspace:".length); return ( - {/* Decorative: the fallback icon's initial must not prefix the row's accessible name. */} - + {/* An archived workspace runs nothing, so it has no status to show. */} + {result.archived ? ( + + ) : ( + + )} + {result.matchedAgent ? ( + + ) : null} + {result.archived ? : null} ); } @@ -761,9 +880,24 @@ function SectionRow({ row }: { row: Extract; + +/** The search field names what the tab searches; All names only the kinds on offer. */ +function placeholderKey(tab: CommandCenterTab, tabs: readonly CommandCenterTab[]) { + if (tab === "all" && !tabs.includes("files")) { + return "shell.commandCenter.placeholderWithoutFiles"; + } + return TAB_PLACEHOLDER_KEYS[tab]; +} + export function CommandCenter() { const { t } = useTranslation(); const isCompact = useIsCompactFormFactor(); @@ -875,22 +1009,42 @@ export function CommandCenter() { : {}), scrollEventThrottle: 16, }; - const submit = useCallback(() => state.key("Enter"), [state]); + const submit = useCallback(() => state.key({ key: "Enter" }), [state]); const handleOverlayKeyDown = useCallback( (event: KeyboardInputEvent) => { - if (!state.key(event.key)) return false; + if (!state.key(event)) return false; event.preventDefault(); return true; }, [state], ); const setOverlayScope = useOverlayRegistration({ - keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"], + keys: ["Escape", "Enter", "ArrowUp", "ArrowDown", "Tab"], active: state.open, layer: modalLayer, onKeyDown: handleOverlayKeyDown, }); + const tabOptions = useMemo[]>( + () => + state.tabs.map((tab) => ({ + value: tab, + label: t(`shell.commandCenter.tabs.${tab}`), + testID: `command-center-tab-${tab}`, + })), + [state.tabs, t], + ); + const tabs = ( + + ); + const placeholder = t(placeholderKey(state.tab, state.tabs)); + if (showBottomSheet) { return ( - - {state.scope === "files" ? ( - - ) : null} - - + + + + + + {tabs} {fileSearchError} @@ -949,30 +1099,26 @@ export function CommandCenter() { - - {state.scope === "files" ? ( - - ) : null} - - + + + + + + {tabs} {fileSearchError} @@ -998,25 +1144,6 @@ function FileSearchLoadingIndicator({ loading, label }: { loading: boolean; labe ); } -// The chip sits at the input's own height and type size so it reads as the scope of the field -// rather than a badge dropped into the query. Its 28px matches the input's line box, so showing or -// dropping the scope cannot resize the header. -function ScopeChip({ label, onRemove }: { label: string; onRemove(): void }) { - return ( - - - {label} - - - ); -} - const styles = StyleSheet.create((theme) => ({ overlay: { flex: 1, @@ -1043,11 +1170,12 @@ const styles = StyleSheet.create((theme) => ({ borderBottomWidth: 1, borderBottomColor: theme.colors.border, }, - bottomSheetHeader: { + // Below the divider, above the list. The first section label brings its own top gap, so the + // pills sit with equal space above and below. A fixed bar, so switching tabs never moves the + // field or the list. + tabBar: { paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[3], - borderBottomWidth: 1, - borderBottomColor: theme.colors.border, + paddingTop: COMMAND_CENTER_SECTION_GAP, }, input: { fontSize: theme.fontSize.base, @@ -1058,25 +1186,6 @@ const styles = StyleSheet.create((theme) => ({ growingInput: { flex: 1, minWidth: 0 }, searchRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, fileSearchStatus: { width: 14, height: 14, alignItems: "center", justifyContent: "center" }, - scopeChip: { - // Stretching to the row rather than setting a height keeps the chip exactly as tall as the - // input's line box, so showing or dropping the scope can never resize the header. - alignSelf: "stretch", - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1.5], - marginRight: theme.spacing[1], - paddingHorizontal: theme.spacing[2], - borderRadius: theme.borderRadius.md, - borderWidth: 1, - borderColor: theme.colors.borderAccent, - backgroundColor: theme.colors.surface2, - }, - scopeChipLabel: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: "500", - }, results: { flex: 1 }, // Sections and rows take their height from list-metrics; these styles only place content in it. section: { justifyContent: "flex-end" }, @@ -1129,6 +1238,14 @@ const styles = StyleSheet.create((theme) => ({ }, subtitleLine: { flexDirection: "row", minWidth: 0 }, subtitleText: { flexShrink: 1, minWidth: 0 }, + agentLine: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1.5], + minWidth: 0, + height: COMMAND_CENTER_LINE_HEIGHT.agent, + }, + agentLineIcon: { width: 12, alignItems: "center", justifyContent: "center" }, iconSlot: { width: 16, height: COMMAND_CENTER_LINE_HEIGHT.singleLine, diff --git a/packages/app/src/command-center/interaction.test.ts b/packages/app/src/command-center/interaction.test.ts index 5b5d8bdef9..2a2922b961 100644 --- a/packages/app/src/command-center/interaction.test.ts +++ b/packages/app/src/command-center/interaction.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { createCommandCenterInteraction } from "./interaction"; import { projectCommandCenterRows, type CommandCenterFileResult } from "./results"; -import type { CommandCenterScope } from "@/stores/keyboard-shortcuts-store"; +import type { CommandCenterTab } from "./tabs"; function results(ids = ["a", "b", "c", "d"]) { return projectCommandCenterRows( @@ -21,17 +21,17 @@ function results(ids = ["a", "b", "c", "d"]) { })), }, ], - { singleLineRow: 40, twoLineRow: 60, sectionTitle: 20, sectionDivider: 10 }, + { singleLineRow: 40, twoLineRow: 60, threeLineRow: 80, sectionTitle: 20, sectionDivider: 10 }, ); } -function setup(options: { scope?: CommandCenterScope; measured?: boolean } = {}) { +function setup(options: { tab?: CommandCenterTab; measured?: boolean } = {}) { const offsets: number[] = []; const model = createCommandCenterInteraction((offset) => offsets.push(offset)); const publish = (ids = ["a", "b", "c", "d"], loading = false) => model.update({ open: true, - scope: options.scope ?? null, + tab: options.tab ?? "all", query: model.getSnapshot().query, projection: results(ids), loading, @@ -53,6 +53,45 @@ describe("Command Center interaction", () => { expect(offsets).toEqual([]); }); + it("follows the first result while results load, so Enter does not run what rendered first", () => { + const { model, publish } = setup(); + model.setQuery(""); + // Recent workspaces lead All and arrive after the actions below them. + publish(["new-workspace", "settings"], true); + expect(model.getSnapshot().activeId).toBe("new-workspace"); + publish(["recent", "new-workspace", "settings"]); + expect(model.getSnapshot().activeId).toBe("recent"); + }); + + it("keeps the selected row when settled results reorder", () => { + const { model, publish } = setup(); + expect(model.getSnapshot().activeId).toBe("a"); + // Another workspace's agent changed status, so it moves to the top of Recent workspaces. + publish(["b", "a", "c", "d"]); + expect(model.getSnapshot().activeId).toBe("a"); + }); + + it("keeps the selected row when results land above it after the query settled", () => { + const { model, publish } = setup(); + model.setQuery("invoice"); + // Files arrive while archived workspaces are still being searched. + publish(["file-1", "file-2"], true); + expect(model.getSnapshot().activeId).toBe("file-1"); + publish(["archived", "file-1", "file-2"]); + expect(model.getSnapshot().activeId).toBe("archived"); + publish(["archived-2", "archived", "file-1", "file-2"]); + expect(model.getSnapshot().activeId).toBe("archived"); + }); + + it("keeps the user's pick while results are still loading", () => { + const { model, publish } = setup(); + model.setQuery("q"); + publish(["a", "b"], true); + model.move("next"); + publish(["z", "a", "b"], true); + expect(model.getSnapshot().activeId).toBe("b"); + }); + it("reveals only clipped keyboard selections and wraps around", () => { const { model, offsets } = setup(); expect(model.move("next")).toBe(true); @@ -120,7 +159,7 @@ describe("Command Center interaction", () => { }); it("waits for scoped search results instead of revealing the previous query's rows", () => { - const { model, offsets, publish } = setup({ scope: "files" }); + const { model, offsets, publish } = setup({ tab: "files" }); model.scrolled(100); model.setQuery("new"); publish(["a", "b"], true); @@ -132,7 +171,7 @@ describe("Command Center interaction", () => { }); it("manual interaction cancels a reveal awaiting search results", () => { - const { model, offsets, publish } = setup({ scope: "files" }); + const { model, offsets, publish } = setup({ tab: "files" }); model.setQuery("new"); publish([], true); model.beginManualScroll(); @@ -153,13 +192,29 @@ describe("Command Center interaction", () => { expect(offsets).toEqual([]); }); - it("scope changes reset selection and request a reveal", () => { + it("tab changes select the first result and return the list to the top", () => { const { model, offsets } = setup(); model.move("next"); + model.move("next"); + model.move("next"); model.scrolled(100); - model.update({ open: true, scope: "files", query: "", projection: results(), loading: false }); + model.update({ open: true, tab: "files", query: "", projection: results(), loading: false }); expect(model.getSnapshot().activeId).toBe("a"); - expect(offsets).toEqual([20, 20]); + expect(offsets.at(-1)).toBe(0); + }); + + it("tab changes keep the query", () => { + const { model, publish } = setup(); + model.setQuery("b"); + publish(["b"]); + model.update({ + open: true, + tab: "workspaces", + query: "b", + projection: results(["b"]), + loading: false, + }); + expect(model.getSnapshot()).toEqual({ query: "b", activeId: "b" }); }); it("close discards the old query, metrics, and deferred reveal", () => { @@ -167,7 +222,7 @@ describe("Command Center interaction", () => { model.setQuery("old"); publish(); model.move("previous"); - model.update({ open: false, scope: null, query: "old", projection: results(), loading: false }); + model.update({ open: false, tab: "all", query: "old", projection: results(), loading: false }); model.layout(80); expect(model.getSnapshot()).toEqual({ query: "", activeId: null }); expect(offsets).toEqual([]); diff --git a/packages/app/src/command-center/interaction.ts b/packages/app/src/command-center/interaction.ts index 8ac0acce15..a8f9ddc371 100644 --- a/packages/app/src/command-center/interaction.ts +++ b/packages/app/src/command-center/interaction.ts @@ -1,9 +1,9 @@ -import type { CommandCenterScope } from "@/stores/keyboard-shortcuts-store"; import { moveActiveResultId, preserveActiveResultId, type CommandCenterListProjection, } from "./results"; +import type { CommandCenterTab } from "./tabs"; interface Snapshot { query: string; @@ -12,21 +12,28 @@ interface Snapshot { interface ResultsInput { open: boolean; - scope: CommandCenterScope; + tab: CommandCenterTab; query: string; projection: CommandCenterListProjection; + /** A source of this query's and tab's results is still loading. */ loading: boolean; } -/** Selection persists; permission to move the viewport lasts for one user command. */ +/** + * While a query's or tab's results are still loading, the selection follows the first result, + * so Enter right after opening runs what ends up on top rather than whatever rendered first. + * Once they have all loaded, or the user moves the selection, it stays on its row by ID through + * any later reordering. Permission to move the viewport lasts for one user command. + */ export function createCommandCenterInteraction(scrollToOffset: (offset: number) => void) { let snapshot: Snapshot = { query: "", activeId: null }; const listeners = new Set<() => void>(); let open = false; - let scope: CommandCenterScope = null; + let tab: CommandCenterTab = "all"; let projection: CommandCenterListProjection | null = null; let loading = false; let revealPending = false; + let followingFirst = true; let offset = 0; let visibleLength = 0; @@ -38,8 +45,8 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number) function reveal() { if (!open || !revealPending || !projection || visibleLength <= 0) return; - // Scoped file search keeps its previous entries while the next query is loading. - if (scope === "files" && loading) return; + // The Files tab keeps its previous entries while the next query is loading. + if (tab === "files" && loading) return; if (!snapshot.activeId) { if (!loading) revealPending = false; return; @@ -67,9 +74,10 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number) }; }, update(input: ResultsInput) { - const resetSelection = input.open && (!open || scope !== input.scope); + const tabChanged = open && input.open && tab !== input.tab; + const resetSelection = input.open && (!open || tabChanged); open = input.open; - scope = input.scope; + tab = input.tab; if (!open) { projection = null; revealPending = false; @@ -80,33 +88,44 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number) } if (resetSelection) { revealPending = true; + followingFirst = true; publish({ ...snapshot, activeId: null }); } + // A tab is a different list: it starts at its top, section label included. + if (tabChanged && offset !== 0) { + offset = 0; + scrollToOffset(0); + } // A query command invalidates the old projection until React supplies its new results. if (input.query !== snapshot.query) return; projection = input.projection; loading = input.loading; - if (scope !== "files" || !loading) { + if (tab !== "files" || !loading) { publish({ ...snapshot, - activeId: preserveActiveResultId(snapshot.activeId, projection.selectableResults), + activeId: followingFirst + ? (projection.selectableResults[0]?.id ?? null) + : preserveActiveResultId(snapshot.activeId, projection.selectableResults), }); + if (!loading) followingFirst = false; } reveal(); }, setQuery(query: string) { projection = null; revealPending = true; + followingFirst = true; publish({ query, activeId: null }); }, move(direction: "next" | "previous"): boolean { if ( !open || !projection || - (scope === "files" && loading) || + (tab === "files" && loading) || projection.selectableResults.length === 0 ) return false; + followingFirst = false; publish({ ...snapshot, activeId: moveActiveResultId(snapshot.activeId, projection.selectableResults, direction), diff --git a/packages/app/src/command-center/list-metrics.ts b/packages/app/src/command-center/list-metrics.ts index 603fc91e4c..3ec0394803 100644 --- a/packages/app/src/command-center/list-metrics.ts +++ b/packages/app/src/command-center/list-metrics.ts @@ -16,6 +16,8 @@ export const COMMAND_CENTER_LINE_HEIGHT = { singleLine: 20, title: 18, subtitle: 16, + /** The matched-agent line under a workspace's subtitle. */ + agent: 16, sectionLabel: 16, } as const; @@ -26,6 +28,8 @@ const SECTION_DIVIDER_THICKNESS = 1; export interface CommandCenterListMetrics { singleLineRow: number; twoLineRow: number; + /** A workspace row that also names the agent the query matched. */ + threeLineRow: number; /** A section label and the gaps around it. */ sectionTitle: number; /** The rule between two sections and the gaps around it. */ @@ -37,6 +41,7 @@ function listMetrics(rowInset: number): CommandCenterListMetrics { return { singleLineRow: rowInset + line.singleLine + rowInset, twoLineRow: rowInset + line.title + line.subtitle + rowInset, + threeLineRow: rowInset + line.title + line.subtitle + line.agent + rowInset, sectionTitle: COMMAND_CENTER_SECTION_GAP + line.sectionLabel + COMMAND_CENTER_SECTION_GAP, sectionDivider: COMMAND_CENTER_SECTION_GAP + SECTION_DIVIDER_THICKNESS + COMMAND_CENTER_SECTION_GAP, diff --git a/packages/app/src/command-center/results.test.ts b/packages/app/src/command-center/results.test.ts index fe7bec5897..f18bbdd234 100644 --- a/packages/app/src/command-center/results.test.ts +++ b/packages/app/src/command-center/results.test.ts @@ -3,7 +3,6 @@ import type { CommandCenterContribution } from "./contributions"; import { COMMAND_CENTER_LIST_METRICS } from "./list-metrics"; import { buildContributionSections, - filterAndRankBuiltInResults, joinSubtitleParts, moveActiveResultId, PINNED_SECTION_BAND, @@ -11,6 +10,7 @@ import { projectCommandCenterRows, type CommandCenterWorkspaceResult, } from "./results"; +import { createWorkspaceRanker } from "./workspace-search"; function contribution(input: { id: string; @@ -118,7 +118,12 @@ function workspace( project: { viewKey: "project", name: "project", iconDataUri: null }, changeRequestNumber: null, activityAt, + agents: [], + matchedAgent: null, + archived: false, + background: false, run: () => undefined, + openAgent: () => undefined, }; } @@ -184,6 +189,40 @@ describe("Command Center result projection", () => { expect(sectionResultIds(buildContributionSections(contributions, "home"))).toEqual(["home"]); }); + it("lists query-only actions without a query when asked to browse them", () => { + const contributions = [ + contribution({ id: "settings", group: "actions", groupRank: 0 }), + contribution({ id: "opus", group: "models", groupRank: 1, visibility: "query" }), + ]; + + expect( + sectionResultIds(buildContributionSections(contributions, "", { includeQueryOnly: true })), + ).toEqual(["settings", "opus"]); + }); + + it("gives a workspace row matched through an agent room for its agent line", () => { + const matched = { + ...workspace("workspace:matched"), + matchedAgent: { id: "agent", title: "Add receipt emails", provider: "mock" }, + }; + const projection = projectCommandCenterRows( + [ + { + id: "workspaces", + band: PINNED_SECTION_BAND, + rank: 2, + results: [workspace("workspace:plain"), matched], + }, + ], + metrics, + ); + expect(projection.rows.map((row) => row.height)).toEqual([ + metrics.twoLineRow, + metrics.threeLineRow, + ]); + expect(metrics.threeLineRow).toBeGreaterThan(metrics.twoLineRow); + }); + it("preserves active selection by id and falls back to the first result", () => { const first = workspace("workspace:first"); const second = workspace("workspace:second"); @@ -486,25 +525,9 @@ describe("Command Center query tokenization", () => { }); }); -describe("filterAndRankBuiltInResults", () => { - const visibleOnly = (row: CommandCenterWorkspaceResult) => ({ - visible: [row.title, row.subtitle], - hidden: [], - }); - - it("shows the five most recent rows for an empty query", () => { - const rows = Array.from({ length: 8 }, (_, index) => - workspace(`w${index}`, `w${index}`, "host", minutesAgo(8 - index)), - ); - - expect(filterAndRankBuiltInResults(rows, "", visibleOnly).map((row) => row.id)).toEqual([ - "w7", - "w6", - "w5", - "w4", - "w3", - ]); - }); +describe("workspace ranking", () => { + const rank = (rows: readonly CommandCenterWorkspaceResult[], query: string) => + createWorkspaceRanker()(rows, query).map((row) => row.id); it("puts the best match first even when it sorts last alphabetically", () => { const rows = [ @@ -514,22 +537,7 @@ describe("filterAndRankBuiltInResults", () => { ]; // Alphabetically this is Alpha, Label, Zebra. "lab des" only matches Label as Design. - expect(filterAndRankBuiltInResults(rows, "lab des", visibleOnly).map((row) => row.id)).toEqual([ - "c", - ]); - }); - - it("ranks a title match above a match that only the hidden field reached", () => { - const rows = [workspace("hidden-hit", "Unrelated"), workspace("title-hit", "Deploy")]; - const fields = (row: CommandCenterWorkspaceResult) => - row.id === "hidden-hit" - ? { visible: [row.title], hidden: ["deploy"] } - : { visible: [row.title], hidden: [] }; - - expect(filterAndRankBuiltInResults(rows, "deploy", fields).map((row) => row.id)).toEqual([ - "title-hit", - "hidden-hit", - ]); + expect(rank(rows, "lab des")).toEqual(["c"]); }); it("orders rows in the same match tier by recency, not by where the word sits", () => { @@ -539,10 +547,7 @@ describe("filterAndRankBuiltInResults", () => { workspace("newer", "design the cli interface to expose usage data", "host", minutesAgo(5)), ]; - expect(filterAndRankBuiltInResults(rows, "usage", visibleOnly).map((row) => row.id)).toEqual([ - "newer", - "older", - ]); + expect(rank(rows, "usage")).toEqual(["newer", "older"]); }); it("keeps a better match tier above a more recent weaker match", () => { @@ -551,16 +556,13 @@ describe("filterAndRankBuiltInResults", () => { workspace("whole-word", "Usage hover card", "host", minutesAgo(600)), ]; - expect(filterAndRankBuiltInResults(rows, "usage", visibleOnly).map((row) => row.id)).toEqual([ - "whole-word", - "subsequence", - ]); + expect(rank(rows, "usage")).toEqual(["whole-word", "subsequence"]); }); it("drops a row when one token matches nothing", () => { const rows = [workspace("a", "Label as Design")]; - expect(filterAndRankBuiltInResults(rows, "lab zzz", visibleOnly)).toEqual([]); + expect(rank(rows, "lab zzz")).toEqual([]); }); }); diff --git a/packages/app/src/command-center/results.ts b/packages/app/src/command-center/results.ts index 52034ca893..8fe63c9b16 100644 --- a/packages/app/src/command-center/results.ts +++ b/packages/app/src/command-center/results.ts @@ -1,12 +1,15 @@ -import type { AggregatedAgent } from "@/hooks/use-aggregated-agents"; import { compareMatchScores, + type MatchClass, type MatchScore, scoreTextFields, + textFieldsMatchClass, } from "@getpaseo/protocol/search/text-match"; import type { CommandCenterContribution } from "./contributions"; import type { CommandCenterListMetrics } from "./list-metrics"; +/** Sections pinned above every contribution section. */ +export const LEADING_SECTION_BAND = -1; /** Sections that reorder by how well they match the query. */ export const CONTRIBUTION_SECTION_BAND = 0; /** Sections pinned below every contribution section regardless of match quality. */ @@ -50,6 +53,13 @@ export interface CommandCenterWorkspaceProject { iconDataUri: string | null; } +/** An agent a workspace can be found by. Agents are never results of their own. */ +export interface CommandCenterWorkspaceAgent { + id: string; + title: string; + provider: string; +} + export interface CommandCenterWorkspaceResult { kind: "workspace"; id: string; @@ -60,18 +70,19 @@ export interface CommandCenterWorkspaceResult { project: CommandCenterWorkspaceProject; /** PR/MR number backing this workspace, so a number query can match it exactly. */ changeRequestNumber: number | null; + /** Last activity, or when it was archived for an archived workspace. */ activityAt: Date | null; + /** The workspace's agents, most recent first. Part of what the workspace matches on. */ + agents: readonly CommandCenterWorkspaceAgent[]; + /** The agent the query matched better than the workspace's own text. Drawn as a third line. */ + matchedAgent: CommandCenterWorkspaceAgent | null; + archived: boolean; + /** Started by automation rather than the user. Found by a query, never listed as recent. */ + background: boolean; + /** Opens the workspace and lets its default tab selection apply. */ run(): void; -} - -export interface CommandCenterAgentResult { - kind: "agent"; - id: string; - agent: AggregatedAgent; - title: string; - subtitle: string; - activityAt: Date | null; - run(): void; + /** Opens the workspace on this agent's tab. */ + openAgent(agentId: string): void; } export interface CommandCenterFileResult { @@ -94,13 +105,12 @@ export interface CommandCenterContributionResult { export type CommandCenterResult = | CommandCenterWorkspaceResult - | CommandCenterAgentResult | CommandCenterFileResult | CommandCenterContributionResult; export interface CommandCenterResultSection { id: string; - /** CONTRIBUTION_SECTION_BAND or PINNED_SECTION_BAND. Compared before anything else. */ + /** LEADING, CONTRIBUTION or PINNED_SECTION_BAND. Compared before anything else. */ band: number; rank: number; title?: string; @@ -162,6 +172,14 @@ export function scoreSearchFields( return match ? { fieldRank: KEYWORD_FIELD_RANK, match } : null; } +/** How closely the query matched the fields; see `MatchClass`. Null when it does not match. */ +export function searchFieldsMatchClass( + query: string, + fields: CommandCenterSearchFields, +): MatchClass | null { + return textFieldsMatchClass(query, [...fields.visible, ...fields.hidden]); +} + /** Join non-empty subtitle parts with " · ", dropping null/undefined/empty. */ export function joinSubtitleParts(parts: readonly (string | null | undefined)[]): string { return parts.filter((part): part is string => Boolean(part)).join(" · "); @@ -181,12 +199,18 @@ function contributionSearchFields( return { visible, hidden: contribution.keywords }; } -/** Whether the row draws a second, subtitle line under its title. */ -function hasSubtitleLine(result: CommandCenterResult): boolean { - if (result.kind === "workspace" || result.kind === "agent") return true; - if (result.kind === "file") return false; +/** How many lines of text the row draws, which decides its height. */ +function resultLineCount(result: CommandCenterResult): 1 | 2 | 3 { + if (result.kind === "workspace") return result.matchedAgent ? 3 : 2; + if (result.kind === "file") return 1; const presentation = result.contribution.presentation; - return presentation.kind === "action" && Boolean(presentation.subtitle); + return presentation.kind === "action" && presentation.subtitle ? 2 : 1; +} + +function resultHeight(result: CommandCenterResult, metrics: CommandCenterListMetrics): number { + const lines = resultLineCount(result); + if (lines === 3) return metrics.threeLineRow; + return lines === 2 ? metrics.twoLineRow : metrics.singleLineRow; } /** @@ -211,10 +235,7 @@ function resultScore(result: CommandCenterResult): CommandCenterScore | undefine return result.kind === "contribution" ? result.score : undefined; } -/** Rows shown when nothing has been typed, per pinned category. */ -const DEFAULT_CATEGORY_RESULT_LIMIT = 5; - -/** A built-in row (workspace or agent) that orders by how recently it saw activity. */ +/** A built-in row that orders by how recently it saw activity. */ export interface CommandCenterRecentRow { activityAt: Date | null; } @@ -235,44 +256,20 @@ export function compareBuiltInScores(left: CommandCenterScore, right: CommandCen } /** - * Filter and rank already-built rows. Rows in, rows out — building them needs translations, - * navigation callbacks and the project tree, none of which matching cares about, so that stays - * with the caller and this stays testable without mounting React. - * - * Rows rank by `compareBuiltInScores`; rows that rank equally, including every row of an empty - * query, go most recent first. + * Group contributions into their sections, ranked by the query. `includeQueryOnly` lists the + * contributions that otherwise wait for a query, for a list whose whole job is browsing them. */ -export function filterAndRankBuiltInResults( - rows: readonly Row[], - query: string, - fieldsOf: (row: Row) => CommandCenterSearchFields, -): Row[] { - if (!query.trim()) { - return [...rows].sort(compareByRecency).slice(0, DEFAULT_CATEGORY_RESULT_LIMIT); - } - - const scored: { row: Row; score: CommandCenterScore }[] = []; - for (const row of rows) { - const score = scoreSearchFields(query, fieldsOf(row)); - if (score) scored.push({ row, score }); - } - scored.sort( - (left, right) => - compareBuiltInScores(left.score, right.score) || compareByRecency(left.row, right.row), - ); - return scored.map((entry) => entry.row); -} - export function buildContributionSections( contributions: readonly CommandCenterContribution[], query: string, + options: { includeQueryOnly?: boolean } = {}, ): CommandCenterResultSection[] { const groups = new Map(); const registryIndexById = new Map(); const hasQuery = Boolean(query.trim()); for (const [index, contribution] of contributions.entries()) { - if (contribution.visibility === "query" && !hasQuery) continue; + if (contribution.visibility === "query" && !hasQuery && !options.includeQueryOnly) continue; let score: CommandCenterScore | undefined; if (hasQuery) { // The score is the filter: null means no token found a home, so the row is out. @@ -351,7 +348,7 @@ export function projectCommandCenterRows( offset += sectionHeight; } for (const result of section.results) { - const height = hasSubtitleLine(result) ? metrics.twoLineRow : metrics.singleLineRow; + const height = resultHeight(result, metrics); offsets.push(offset); rowIndexByResultId.set(result.id, rows.length); rows.push({ kind: "result", key: result.id, result, height }); diff --git a/packages/app/src/command-center/sections.test.ts b/packages/app/src/command-center/sections.test.ts new file mode 100644 index 0000000000..23071c444f --- /dev/null +++ b/packages/app/src/command-center/sections.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from "vitest"; +import type { CommandCenterContribution } from "./contributions"; +import type { CommandCenterFileResult, CommandCenterWorkspaceResult } from "./results"; +import { COMMAND_CENTER_LIST_METRICS } from "./list-metrics"; +import { projectCommandCenterRows } from "./results"; +import { buildCommandCenterSections } from "./sections"; +import type { CommandCenterTab } from "./tabs"; +import { createWorkspaceRanker } from "./workspace-search"; + +function workspace( + id: string, + options: { + daysAgo?: number; + title?: string; + archived?: boolean; + background?: boolean; + agentTitle?: string; + } = {}, +): CommandCenterWorkspaceResult { + return { + kind: "workspace", + id: `workspace:server:${id}`, + serverId: "server", + workspaceId: id, + title: options.title ?? id, + subtitle: "project · main", + project: { viewKey: "project", name: "project", iconDataUri: null }, + changeRequestNumber: null, + activityAt: new Date(Date.UTC(2026, 9, 30) - (options.daysAgo ?? 0) * 86_400_000), + agents: options.agentTitle + ? [{ id: `${id}-agent`, title: options.agentTitle, provider: "mock" }] + : [], + matchedAgent: null, + archived: options.archived ?? false, + background: options.background ?? false, + run: () => undefined, + openAgent: () => undefined, + }; +} + +function action(id: string, group: string, visibility: "always" | "query" = "always") { + return { + id, + group, + groupRank: group === "workspace" ? 0 : 1, + rank: 0, + keywords: [], + visibility, + run: () => undefined, + presentation: { kind: "action", title: id, sectionTitle: group }, + } satisfies CommandCenterContribution; +} + +const file: CommandCenterFileResult = { + kind: "file", + id: "file:src/index.ts", + filePath: "src/index.ts", + title: "index.ts", + subtitle: "src", + run: () => undefined, +}; + +const workspaces = [ + workspace("current", { daysAgo: 0 }), + workspace("payments", { daysAgo: 1, title: "Payments refactor" }), + // Started by automation; more recent than the workspaces below it. + workspace("nightly", { daysAgo: 1.5, title: "Nightly triage", background: true }), + workspace("onboarding", { daysAgo: 2, title: "Onboarding flow", agentTitle: "Add receipts" }), + workspace("docs", { daysAgo: 3, title: "Docs site" }), + workspace("search", { daysAgo: 4, title: "Search ranking" }), +]; +const archived = [workspace("billing", { title: "Billing cleanup", archived: true })]; +const contributions = [ + action("New agent", "workspace"), + action("Settings", "actions"), + action("Group by status", "actions", "query"), +]; + +function listed( + tab: CommandCenterTab, + query: string, + options: { archivedMatchedByHost?: boolean; showBackground?: boolean } = {}, +) { + const sections = buildCommandCenterSections({ + tab, + query, + rankWorkspaces: createWorkspaceRanker(), + workspaces, + archivedWorkspaces: query ? archived : [], + archivedMatchedByHost: options.archivedMatchedByHost ?? true, + showBackground: options.showBackground ?? false, + currentWorkspaceId: "workspace:server:current", + contributions, + files: [file], + titles: { recentWorkspaces: "Recent workspaces", workspaces: "Workspaces", files: "Files" }, + }); + return projectCommandCenterRows(sections, COMMAND_CENTER_LIST_METRICS.desktop).rows.map((row) => + row.kind === "section" ? `# ${row.title ?? ""}` : row.key, + ); +} + +describe("command center tabs", () => { + it("All leads with the three most recent workspaces, then actions, before a query", () => { + expect(listed("all", "")).toEqual([ + "# Recent workspaces", + "workspace:server:payments", + "workspace:server:onboarding", + "workspace:server:docs", + "# workspace", + "New agent", + "# actions", + "Settings", + ]); + }); + + it("lists background workspaces unqueried only as the sidebar does; a query finds them", () => { + expect(listed("all", "")).not.toContain("workspace:server:nightly"); + expect(listed("all", "", { showBackground: true })).not.toContain("workspace:server:nightly"); + expect(listed("workspaces", "")).not.toContain("workspace:server:nightly"); + expect(listed("workspaces", "", { showBackground: true })).toContain( + "workspace:server:nightly", + ); + expect(listed("all", "nightly")).toContain("workspace:server:nightly"); + expect(listed("workspaces", "nightly")).toContain("workspace:server:nightly"); + }); + + it("All ranks every kind of result for a query, archived workspaces after active ones", () => { + expect(listed("all", "i")).toEqual( + expect.arrayContaining(["Settings", "file:src/index.ts", "workspace:server:billing"]), + ); + const rows = listed("all", "ing"); + const workspaceRows = rows.filter((row) => row.startsWith("workspace:")); + expect(workspaceRows.at(-1)).toBe("workspace:server:billing"); + expect(rows).not.toContain("# Recent workspaces"); + }); + + it("Workspaces lists every workspace, current included, most recent first", () => { + expect(listed("workspaces", "")).toEqual([ + "# Workspaces", + "workspace:server:current", + "workspace:server:payments", + "workspace:server:onboarding", + "workspace:server:docs", + "workspace:server:search", + ]); + }); + + it("Workspaces finds a workspace through its agent and appends archived matches", () => { + expect(listed("workspaces", "receipts")).toEqual([ + "# Workspaces", + "workspace:server:onboarding", + "workspace:server:billing", + ]); + }); + + it("keeps archived rows the host did not match for this query only if they match it", () => { + // The previous query's archived results stand in while the next search loads. + expect(listed("workspaces", "receipts", { archivedMatchedByHost: false })).toEqual([ + "# Workspaces", + "workspace:server:onboarding", + ]); + expect(listed("workspaces", "billing", { archivedMatchedByHost: false })).toEqual([ + "# Workspaces", + "workspace:server:billing", + ]); + }); + + it("Files lists only files", () => { + expect(listed("files", "")).toEqual(["# Files", "file:src/index.ts"]); + }); + + it("Actions lists every action, including those that otherwise wait for a query", () => { + expect(listed("actions", "")).toEqual([ + "# workspace", + "New agent", + "# actions", + "Settings", + "Group by status", + ]); + }); +}); diff --git a/packages/app/src/command-center/sections.ts b/packages/app/src/command-center/sections.ts new file mode 100644 index 0000000000..d66ef56ea4 --- /dev/null +++ b/packages/app/src/command-center/sections.ts @@ -0,0 +1,120 @@ +import type { CommandCenterContribution } from "./contributions"; +import { + buildContributionSections, + LEADING_SECTION_BAND, + PINNED_SECTION_BAND, + type CommandCenterFileResult, + type CommandCenterResultSection, + type CommandCenterWorkspaceResult, +} from "./results"; +import type { CommandCenterTab } from "./tabs"; +import type { WorkspaceRanker } from "./workspace-search"; + +/** + * How many workspaces All leads with before anything is typed. Background workspaces are left + * out, as the sidebar leaves them out by default. + */ +const RECENT_WORKSPACE_LIMIT = 3; + +export interface CommandCenterSectionTitles { + recentWorkspaces: string; + workspaces: string; + files: string; +} + +export interface CommandCenterSectionsInput { + tab: CommandCenterTab; + query: string; + rankWorkspaces: WorkspaceRanker; + workspaces: readonly CommandCenterWorkspaceResult[]; + /** Archived workspaces the host found for the query. Empty without a query. */ + archivedWorkspaces: readonly CommandCenterWorkspaceResult[]; + /** + * The host matched the archived workspaces for this exact query. Its search forgives typos, + * so its matches stay even when the client cannot score them. Results from the previous + * query must match on their own. + */ + archivedMatchedByHost: boolean; + /** + * The sidebar's Show background preference. Without a query, Workspaces lists background + * workspaces only when the sidebar does; a query finds them either way. + */ + showBackground: boolean; + /** The open workspace's result ID. Recent workspaces leaves it out: the user is already there. */ + currentWorkspaceId: string | null; + contributions: readonly CommandCenterContribution[]; + files: readonly CommandCenterFileResult[]; + titles: CommandCenterSectionTitles; +} + +function recentWorkspacesSection(input: CommandCenterSectionsInput): CommandCenterResultSection { + const recent = input + .rankWorkspaces(input.workspaces, "") + .filter((workspace) => workspace.id !== input.currentWorkspaceId && !workspace.background) + .slice(0, RECENT_WORKSPACE_LIMIT); + return { + id: "recent-workspaces", + band: LEADING_SECTION_BAND, + rank: 0, + title: input.titles.recentWorkspaces, + results: recent, + }; +} + +/** Active matches first; archived ones are appended, so active rows never move when they land. */ +function workspacesSection(input: CommandCenterSectionsInput): CommandCenterResultSection { + const listed = + input.query.trim() || input.showBackground + ? input.workspaces + : input.workspaces.filter((workspace) => !workspace.background); + const active = input.rankWorkspaces(listed, input.query); + const archived = input.query.trim() + ? input.rankWorkspaces(input.archivedWorkspaces, input.query, { + keepUnmatched: input.archivedMatchedByHost, + }) + : []; + return { + id: "workspaces", + band: PINNED_SECTION_BAND, + rank: 2, + title: input.titles.workspaces, + results: [...active, ...archived], + }; +} + +function filesSection(input: CommandCenterSectionsInput): CommandCenterResultSection { + // File rows are matched by the daemon, so they carry no client-side score and cannot be + // relevance-compared against the rows that do. Pinning them keeps the section comparator + // total: band is decided before any score is read. + return { + id: "files", + band: PINNED_SECTION_BAND, + rank: 4, + title: input.titles.files, + results: input.files, + }; +} + +/** + * The sections a tab shows. All mixes every kind and leads with recent workspaces until + * something is typed; every other tab lists everything of its one kind. + */ +export function buildCommandCenterSections( + input: CommandCenterSectionsInput, +): CommandCenterResultSection[] { + switch (input.tab) { + case "all": { + const actions = buildContributionSections(input.contributions, input.query); + if (!input.query.trim()) return [recentWorkspacesSection(input), ...actions]; + return [...actions, workspacesSection(input), filesSection(input)]; + } + case "workspaces": + return [workspacesSection(input)]; + case "files": + return [filesSection(input)]; + case "actions": + return buildContributionSections(input.contributions, input.query, { + includeQueryOnly: true, + }); + } +} diff --git a/packages/app/src/command-center/tabs.test.ts b/packages/app/src/command-center/tabs.test.ts new file mode 100644 index 0000000000..c0321b0627 --- /dev/null +++ b/packages/app/src/command-center/tabs.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { + availableCommandCenterTabs, + resolveCommandCenterTab, + rotateCommandCenterTab, + type CommandCenterTab, +} from "./tabs"; + +const IN_WORKSPACE = availableCommandCenterTabs({ hasWorkspace: true }); +const NO_WORKSPACE = availableCommandCenterTabs({ hasWorkspace: false }); + +function walk(available: readonly CommandCenterTab[], direction: "next" | "previous") { + const walked: CommandCenterTab[] = ["all"]; + for (let step = 0; step < available.length; step += 1) { + walked.push(rotateCommandCenterTab(walked[walked.length - 1], direction, available)); + } + return walked; +} + +describe("command center tabs", () => { + it("walks All, Workspaces, Files, Actions in a workspace and wraps", () => { + expect(walk(IN_WORKSPACE, "next")).toEqual(["all", "workspaces", "files", "actions", "all"]); + expect(walk(IN_WORKSPACE, "previous")).toEqual([ + "all", + "actions", + "files", + "workspaces", + "all", + ]); + }); + + it("offers no Files tab outside a workspace, and Tab skips it", () => { + expect(NO_WORKSPACE).toEqual(["all", "workspaces", "actions"]); + expect(walk(NO_WORKSPACE, "next")).toEqual(["all", "workspaces", "actions", "all"]); + expect(walk(NO_WORKSPACE, "previous")).toEqual(["all", "actions", "workspaces", "all"]); + }); + + it("opens a requested tab only when it is on offer", () => { + expect(resolveCommandCenterTab("files", IN_WORKSPACE)).toBe("files"); + expect(resolveCommandCenterTab("files", NO_WORKSPACE)).toBe("all"); + expect(resolveCommandCenterTab("actions", NO_WORKSPACE)).toBe("actions"); + }); +}); diff --git a/packages/app/src/command-center/tabs.ts b/packages/app/src/command-center/tabs.ts new file mode 100644 index 0000000000..21e11eabf7 --- /dev/null +++ b/packages/app/src/command-center/tabs.ts @@ -0,0 +1,39 @@ +/** + * The command center's tabs, in the order Tab walks them. All shows every kind of result; each + * other tab shows one kind. + */ +const COMMAND_CENTER_TABS = ["all", "workspaces", "files", "actions"] as const; + +export type CommandCenterTab = (typeof COMMAND_CENTER_TABS)[number]; + +/** + * The tabs on offer, in the order Tab walks them. Files searches the open workspace, so it is + * offered only when a workspace is open; without one, All lists no files either. + */ +export function availableCommandCenterTabs(context: { + hasWorkspace: boolean; +}): readonly CommandCenterTab[] { + return context.hasWorkspace + ? COMMAND_CENTER_TABS + : COMMAND_CENTER_TABS.filter((tab) => tab !== "files"); +} + +/** The tab to show for a requested one: itself when on offer, otherwise All. */ +export function resolveCommandCenterTab( + requested: CommandCenterTab, + available: readonly CommandCenterTab[], +): CommandCenterTab { + return available.includes(requested) ? requested : "all"; +} + +/** The available tab after (or before) `tab`, wrapping at either end. */ +export function rotateCommandCenterTab( + tab: CommandCenterTab, + direction: "next" | "previous", + available: readonly CommandCenterTab[], +): CommandCenterTab { + const index = available.indexOf(tab); + const delta = direction === "next" ? 1 : -1; + const count = available.length; + return available[(index + delta + count) % count]; +} diff --git a/packages/app/src/command-center/workspace-contributions.test.ts b/packages/app/src/command-center/workspace-contributions.test.ts index 076f054146..7fb3071046 100644 --- a/packages/app/src/command-center/workspace-contributions.test.ts +++ b/packages/app/src/command-center/workspace-contributions.test.ts @@ -25,12 +25,13 @@ function source(gitActions: GitActions): { dispatched: KeyboardActionDefinition[]; copiedPaths: number; copiedBranchNames: number; + archivedWorkspaces: number; toggledLabels: Array<{ name: string; assigned: boolean }>; } { const runGitActions: GitAction[] = []; const dispatched: KeyboardActionDefinition[] = []; const toggledLabels: Array<{ name: string; assigned: boolean }> = []; - const counters = { copiedPaths: 0, copiedBranchNames: 0 }; + const counters = { copiedPaths: 0, copiedBranchNames: 0, archivedWorkspaces: 0 }; return { value: { gitActions, @@ -68,6 +69,7 @@ function source(gitActions: GitActions): { closePane: "Close pane", toggleFocusMode: "Toggle focus mode", toggleExplorerSidebar: "Toggle Explorer sidebar", + archiveWorkspace: "Archive workspace", rename: "Rename workspace", copyPath: "Copy workspace path", copyBranchName: "Copy branch name", @@ -93,6 +95,9 @@ function source(gitActions: GitActions): { labelCatalog: null, dispatch: (action) => dispatched.push(action), runGitAction: (action) => runGitActions.push(action), + archiveWorkspace: () => { + counters.archivedWorkspaces += 1; + }, copyPath: () => { counters.copiedPaths += 1; }, @@ -112,10 +117,48 @@ function source(gitActions: GitActions): { get copiedBranchNames() { return counters.copiedBranchNames; }, + get archivedWorkspaces() { + return counters.archivedWorkspaces; + }, }; } describe("workspace command center contributions", () => { + it("offers archive in a non-Git workspace and runs the workspace's archive", () => { + const fixture = source({ primary: null, secondary: [], menu: [] }); + + const archive = buildWorkspaceCommandCenterContributions(fixture.value).find( + (item) => item.id === "workspace:archive", + ); + + expect(archive?.visibility).toBe("query"); + expect(archive?.presentation).toMatchObject({ title: "Archive workspace" }); + archive?.run(); + expect(fixture.archivedWorkspaces).toBe(1); + expect(fixture.dispatched).toEqual([]); + }); + + it("omits archive while the workspace cannot be archived", () => { + const fixture = source({ primary: null, secondary: [], menu: [] }); + fixture.value.archiveWorkspace = null; + + const contributions = buildWorkspaceCommandCenterContributions(fixture.value); + + expect(contributions.some((item) => item.id === "workspace:archive")).toBe(false); + }); + + it("lists archive once in a Git workspace, through its Git action", () => { + const archive = gitAction("archive-workspace", "Archive workspace"); + const fixture = source({ primary: null, secondary: [archive], menu: [] }); + fixture.value.capabilities.isGit = true; + + const contributions = buildWorkspaceCommandCenterContributions(fixture.value); + + expect( + contributions.filter((item) => item.id.includes("archive")).map((item) => item.id), + ).toEqual(["git:archive-workspace"]); + }); + it("makes only the policy-selected primary Git action default-visible and runs it", () => { const primary = gitAction("commit", "Commit"); const fixture = source({ diff --git a/packages/app/src/command-center/workspace-contributions.ts b/packages/app/src/command-center/workspace-contributions.ts index 538905cb4a..f3e6e933f9 100644 --- a/packages/app/src/command-center/workspace-contributions.ts +++ b/packages/app/src/command-center/workspace-contributions.ts @@ -50,6 +50,7 @@ export interface WorkspaceCommandCenterLabels { toggleFocusMode: string; toggleExplorerSidebar: string; // Workspace management actions + archiveWorkspace: string; rename: string; copyPath: string; copyBranchName: string; @@ -79,6 +80,7 @@ export interface WorkspaceCommandCenterIcons { focusMode?: CommandCenterIcon; explorerSidebar?: CommandCenterIcon; // Workspace management action icons + archiveWorkspace?: CommandCenterIcon; copyPath?: CommandCenterIcon; copyBranchName?: CommandCenterIcon; pin?: CommandCenterIcon; @@ -131,6 +133,8 @@ export interface WorkspaceCommandCenterSource { labelCatalog: readonly WorkspaceCommandCenterLabelChoice[] | null; dispatch(action: KeyboardActionDefinition): void; runGitAction(action: GitAction): void; + /** Null while the workspace cannot be archived. A Git workspace archives through `gitActions`. */ + archiveWorkspace: (() => void) | null; copyPath(): void; copyBranchName(): void; toggleLabel(name: string, assigned: boolean): void | Promise; @@ -585,6 +589,23 @@ export function buildWorkspaceCommandCenterContributions( contributions.push(buildGitContribution(source, action, 100 + index, "query")); } + // A Git workspace lists archive among its Git actions; any other workspace archives here. + if (!source.capabilities.isGit && source.archiveWorkspace) { + contributions.push( + buildWorkspaceCallback({ + source, + id: "workspace:archive", + rank: 100, + title: source.labels.archiveWorkspace, + keywords: ["archive", "workspace"], + icon: source.icons.archiveWorkspace, + shortcutKeys: source.shortcuts.archiveWorkspace, + run: source.archiveWorkspace, + visibility: "query", + }), + ); + } + if (source.capabilities.canPin) { contributions.push( buildWorkspaceAction({ diff --git a/packages/app/src/command-center/workspace-registration.tsx b/packages/app/src/command-center/workspace-registration.tsx index 41416d30eb..3de2b6d21b 100644 --- a/packages/app/src/command-center/workspace-registration.tsx +++ b/packages/app/src/command-center/workspace-registration.tsx @@ -203,7 +203,7 @@ export function useWorkspaceCommandCenterActions(): void { supportsSetupObservation, ); const { overrides } = useKeyboardShortcutOverrides(); - const { gitActions, isGit } = useGitActions({ + const { gitActions, isGit, archiveWorkspace } = useGitActions({ serverId: serverId ?? "", cwd: cwd ?? "", icons: GIT_ACTION_ICONS, @@ -270,6 +270,7 @@ export function useWorkspaceCommandCenterActions(): void { toggleFocusMode: t("settings.shortcuts.help.toggleFocusMode"), toggleExplorerSidebar: t("workspace.tabs.explorerSidebar.toggle"), // Workspace management labels + archiveWorkspace: t("workspace.git.actions.archive.label"), rename: t("sidebar.workspace.actions.rename"), copyPath: t("workspace.header.actions.copyPath"), copyBranchName: t("workspace.header.actions.copyBranchName"), @@ -280,6 +281,7 @@ export function useWorkspaceCommandCenterActions(): void { }, icons: { ...WORKSPACE_COMMAND_CENTER_ICONS, + archiveWorkspace: staticIcon(GIT_ACTION_ICONS.archive), git: (action) => staticIcon(action.icon), }, shortcuts: resolveWorkspaceShortcuts(overrides), @@ -301,12 +303,14 @@ export function useWorkspaceCommandCenterActions(): void { keyboardActionDispatcher.dispatch(action); }, runGitAction, + archiveWorkspace, copyPath, copyBranchName, toggleLabel, }), [ activeTabIndex, + archiveWorkspace, activeTabKind, canPin, canShowSetup, diff --git a/packages/app/src/command-center/workspace-search.test.ts b/packages/app/src/command-center/workspace-search.test.ts index b43e9edfbd..07c8ccc7a2 100644 --- a/packages/app/src/command-center/workspace-search.test.ts +++ b/packages/app/src/command-center/workspace-search.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import type { CommandCenterWorkspaceResult } from "./results"; -import { filterAndRankWorkspaces } from "./workspace-search"; +import type { CommandCenterWorkspaceAgent, CommandCenterWorkspaceResult } from "./results"; +import { createWorkspaceRanker } from "./workspace-search"; function workspace(input: { id: string; @@ -8,6 +8,8 @@ function workspace(input: { subtitle?: string; changeRequestNumber?: number | null; activityAt?: Date | null; + agents?: readonly CommandCenterWorkspaceAgent[]; + opened?: string[]; }): CommandCenterWorkspaceResult { return { kind: "workspace", @@ -19,15 +21,24 @@ function workspace(input: { project: { viewKey: "project", name: "project", iconDataUri: null }, changeRequestNumber: input.changeRequestNumber ?? null, activityAt: input.activityAt ?? null, - run: () => undefined, + agents: input.agents ?? [], + matchedAgent: null, + archived: false, + background: false, + run: () => input.opened?.push("workspace"), + openAgent: (agentId) => input.opened?.push(agentId), }; } -function ids(rows: readonly CommandCenterWorkspaceResult[], query: string): string[] { - return filterAndRankWorkspaces(rows, query).map((row) => row.id); +function agent(id: string, title: string): CommandCenterWorkspaceAgent { + return { id, title, provider: "mock" }; } -describe("filterAndRankWorkspaces", () => { +function ids(rows: readonly CommandCenterWorkspaceResult[], query: string): string[] { + return createWorkspaceRanker()(rows, query).map((row) => row.id); +} + +describe("workspace ranking", () => { const subject = workspace({ id: "payments", title: "Payments refactor", @@ -96,4 +107,214 @@ describe("filterAndRankWorkspaces", () => { }); expect(ids([older, newer], "usage")).toEqual(["newer", "older"]); }); + + it("lists every workspace most recent first when the query is empty", () => { + const rows = Array.from({ length: 8 }, (_, index) => + workspace({ id: `w${index}`, activityAt: new Date(2026, 0, index + 1) }), + ); + expect(ids(rows, "")).toEqual(["w7", "w6", "w5", "w4", "w3", "w2", "w1", "w0"]); + }); + + it("matches a workspace through one of its agents and names that agent", () => { + const receipts = agent("agent-receipts", "Add receipt emails"); + const row = workspace({ + id: "onboarding", + title: "Onboarding flow", + agents: [agent("agent-welcome", "Polish welcome screen"), receipts], + }); + const [ranked] = createWorkspaceRanker()([row], "receipt"); + expect(ranked.id).toBe("onboarding"); + expect(ranked.matchedAgent).toEqual(receipts); + }); + + it("names no agent when the workspace's own text matched", () => { + const row = workspace({ + id: "payments", + title: "Payments refactor", + agents: [agent("agent-payments", "Payments retries")], + }); + const [ranked] = createWorkspaceRanker()([row], "payments"); + expect(ranked.matchedAgent).toBeNull(); + }); + + it("ranks a workspace's own match above an equally good match through an agent", () => { + const viaAgent = workspace({ + id: "via-agent", + title: "Onboarding flow", + activityAt: new Date("2026-10-17T00:00:00Z"), + agents: [agent("a", "Receipt emails")], + }); + const own = workspace({ + id: "own", + title: "Receipt redesign", + activityAt: new Date("2026-10-01T00:00:00Z"), + }); + expect(ids([viaAgent, own], "receipt")).toEqual(["own", "via-agent"]); + }); + + it("picks the best-matching agent for the line", () => { + const row = workspace({ + id: "w", + title: "Onboarding", + agents: [agent("loose", "Reconcile cash receipts later"), agent("exact", "receipts")], + }); + const [ranked] = createWorkspaceRanker()([row], "receipts"); + expect(ranked.matchedAgent?.id).toBe("exact"); + }); + + it("matches a query split between the workspace's text and an agent's title", () => { + const login = agent("agent-login", "Fix login retries"); + const row = workspace({ id: "payments", title: "payments", agents: [login] }); + const [ranked] = createWorkspaceRanker()([row], "payments login"); + expect(ranked?.id).toBe("payments"); + expect(ranked?.matchedAgent).toEqual(login); + }); + + it("names the agent when it matches better than a loose match on the workspace's text", () => { + const opened: string[] = []; + const login = agent("agent-login", "Fix login retries"); + const row = workspace({ + id: "long-input", + title: "Long input", + // "login" is a subsequence of "long-input", the weakest kind of match. + subtitle: "Local · paseo · feature/long-input", + agents: [login], + opened, + }); + const [ranked] = createWorkspaceRanker()([row], "login"); + expect(ranked?.matchedAgent).toEqual(login); + ranked?.run(); + expect(opened).toEqual(["agent-login"]); + }); + + it("keeps a change-request hit on the workspace even when an agent's title names the number", () => { + const opened: string[] = []; + const row = workspace({ + id: "payments", + title: "Payments refactor", + changeRequestNumber: 42, + agents: [agent("agent-review", "Address PR 42 review comments")], + opened, + }); + const rank = createWorkspaceRanker(); + for (const query of ["42", "pr 42", "#42"]) { + const [ranked] = rank([row], query); + expect(ranked?.matchedAgent).toBeNull(); + ranked?.run(); + } + expect(opened).toEqual(["workspace", "workspace", "workspace"]); + }); + + it("names no agent while the workspace's own text matches every keystroke contiguously", () => { + const row = workspace({ + id: "fix-login-bug", + title: "fix-login-bug", + subtitle: "paseo · fix/login-bug", + agents: [agent("agent-login", "Login page fix")], + }); + const rank = createWorkspaceRanker(); + for (const query of ["l", "lo", "log", "logi", "login"]) { + expect(rank([row], query)[0]?.matchedAgent).toBeNull(); + } + }); + + it("names no agent whose one-word title matches better than the workspace's whole word", () => { + const row = workspace({ + id: "review-queue", + title: "Review queue", + agents: [agent("agent-review", "Review")], + }); + expect(createWorkspaceRanker()([row], "review")[0]?.matchedAgent).toBeNull(); + }); + + it("ranks a better match through an agent above a looser match on a workspace's own text", () => { + const loose = workspace({ + id: "loose-own", + title: "Long input", + subtitle: "Local · paseo · feature/long-input", + activityAt: new Date("2026-10-17T00:00:00Z"), + }); + const viaAgent = workspace({ + id: "via-agent", + title: "Auth", + activityAt: new Date("2026-10-01T00:00:00Z"), + agents: [agent("a", "login page")], + }); + expect(ids([loose, viaAgent], "login")).toEqual(["via-agent", "loose-own"]); + }); + + it("keeps a workspace that also matches on its own name first while typing an agent's title", () => { + const ownAndAgent = workspace({ + id: "oauth-refactor", + activityAt: new Date("2026-10-17T00:00:00Z"), + agents: [agent("agent-a", "Auth flow fix")], + }); + const agentOnly = workspace({ + id: "cleanup", + activityAt: new Date("2026-10-01T00:00:00Z"), + agents: [agent("agent-b", "Auth flow fix")], + }); + for (const query of ["a", "au", "auth", "auth f", "auth fl", "auth flow"]) { + expect(ids([ownAndAgent, agentOnly], query)).toEqual(["oauth-refactor", "cleanup"]); + } + }); + + it("ranks a word match on a workspace's name above a newer one that matches only inside a word", () => { + const rank = createWorkspaceRanker(); + const authService = workspace({ + id: "auth-service", + activityAt: new Date("2026-10-01T00:00:00Z"), + }); + const oauthRefactor = workspace({ + id: "oauth-refactor", + activityAt: new Date("2026-10-17T00:00:00Z"), + agents: [agent("agent-auth", "Auth flow fix")], + }); + const authRows = rank([oauthRefactor, authService], "auth"); + expect(authRows.map((row) => row.id)).toEqual(["auth-service", "oauth-refactor"]); + // The row that matched through its agent says so. + expect(authRows[1]?.matchedAgent?.title).toBe("Auth flow fix"); + + const fixLogin = workspace({ id: "fix-login", activityAt: new Date("2026-10-17T00:00:00Z") }); + const prefixedThing = workspace({ + id: "prefixed-thing", + activityAt: new Date("2026-10-01T00:00:00Z"), + agents: [agent("agent-fix", "Fix")], + }); + const fixRows = rank([prefixedThing, fixLogin], "fix"); + expect(fixRows.map((row) => row.id)).toEqual(["fix-login", "prefixed-thing"]); + expect(fixRows[1]?.matchedAgent?.title).toBe("Fix"); + }); + + it("opens the matched agent's tab, and the workspace otherwise", () => { + const opened: string[] = []; + const row = workspace({ + id: "w", + title: "Onboarding flow", + agents: [agent("agent-receipts", "Add receipt emails")], + opened, + }); + const rank = createWorkspaceRanker(); + rank([row], "receipt")[0].run(); + rank([row], "onboarding")[0].run(); + expect(opened).toEqual(["agent-receipts", "workspace"]); + }); + + it("returns the same row object across keystrokes while the matched agent holds", () => { + const row = workspace({ + id: "w", + title: "Onboarding flow", + agents: [agent("agent-receipts", "Add receipt emails")], + }); + const rank = createWorkspaceRanker(); + expect(rank([row], "rece")[0]).toBe(rank([row], "receipt")[0]); + expect(rank([row], "onboard")[0]).toBe(row); + }); + + it("keeps rows the host already matched when asked to, without an agent line", () => { + const row = workspace({ id: "archived", title: "Billing cleanup" }); + const rank = createWorkspaceRanker(); + expect(rank([row], "billign")).toEqual([]); + expect(rank([row], "billign", { keepUnmatched: true })).toEqual([row]); + }); }); diff --git a/packages/app/src/command-center/workspace-search.ts b/packages/app/src/command-center/workspace-search.ts index 40c7c34d01..5d5342fd8b 100644 --- a/packages/app/src/command-center/workspace-search.ts +++ b/packages/app/src/command-center/workspace-search.ts @@ -1,9 +1,12 @@ +import { compareMatchClasses, type MatchClass } from "@getpaseo/protocol/search/text-match"; import { compareBuiltInScores, compareByRecency, - filterAndRankBuiltInResults, scoreSearchFields, + searchFieldsMatchClass, type CommandCenterScore, + type CommandCenterSearchFields, + type CommandCenterWorkspaceAgent, type CommandCenterWorkspaceResult, } from "./results"; @@ -24,41 +27,176 @@ function parseChangeRequestQuery(query: string): number | null { return Number.isSafeInteger(number) ? number : null; } +/** Within a match class, a match on the workspace's own text ranks ahead of one through an agent. */ +const OWN_MATCH = 0; +const AGENT_MATCH = 1; +/** The host matched it (typo-tolerant, server-side) but nothing here does. Archived rows only. */ +const HOST_MATCH = 2; + +/** How a row matched: its class decides first, its score within the class. */ +interface Candidate { + matchClass: MatchClass; + score: CommandCenterScore; +} + interface ScoredWorkspace { workspace: CommandCenterWorkspaceResult; - score: CommandCenterScore | null; + via: typeof OWN_MATCH | typeof AGENT_MATCH | typeof HOST_MATCH; + /** The match the row shows, which is also the one it ranks by. */ + candidate: Candidate | null; + agent: CommandCenterWorkspaceAgent | null; changeRequestHit: boolean; } -function searchFields(workspace: CommandCenterWorkspaceResult) { +function ownSearchFields(workspace: CommandCenterWorkspaceResult) { return { visible: [workspace.title, workspace.subtitle], hidden: [] }; } +/** An agent is found through its own title and its workspace's text together. */ +function agentSearchFields( + workspace: CommandCenterWorkspaceResult, + agent: CommandCenterWorkspaceAgent, +) { + return { visible: [workspace.title, workspace.subtitle, agent.title], hidden: [] }; +} + +function scoreCandidate(query: string, fields: CommandCenterSearchFields): Candidate | null { + const score = scoreSearchFields(query, fields); + const matchClass = searchFieldsMatchClass(query, fields); + return score && matchClass ? { matchClass, score } : null; +} + +function compareCandidates(left: Candidate, right: Candidate): number { + return ( + compareMatchClasses(left.matchClass, right.matchClass) || + compareBuiltInScores(left.score, right.score) + ); +} + +/** + * Change-request hits first, host-only matches last; then match class, the workspace's own text + * ahead of an agent, match quality, and recency. + */ function compareScoredWorkspaces(left: ScoredWorkspace, right: ScoredWorkspace): number { if (left.changeRequestHit !== right.changeRequestHit) { return left.changeRequestHit ? -1 : 1; } - if (left.score && right.score) { - const scoreDelta = compareBuiltInScores(left.score, right.score); + if ((left.via === HOST_MATCH) !== (right.via === HOST_MATCH)) { + return left.via === HOST_MATCH ? 1 : -1; + } + if (left.candidate && right.candidate) { + const classDelta = compareMatchClasses(left.candidate.matchClass, right.candidate.matchClass); + if (classDelta !== 0) return classDelta; + } + if (left.via !== right.via) return left.via - right.via; + if (left.candidate && right.candidate) { + const scoreDelta = compareBuiltInScores(left.candidate.score, right.candidate.score); if (scoreDelta !== 0) return scoreDelta; } return compareByRecency(left.workspace, right.workspace); } -export function filterAndRankWorkspaces( +interface AgentMatch extends Candidate { + agent: CommandCenterWorkspaceAgent; +} + +/** + * The workspace's best-matching agent. Each agent is scored together with the workspace's + * text, so a query split across the two finds it. Agents arrive most recent first, so a tie + * keeps the newer one. + */ +function agentMatch(workspace: CommandCenterWorkspaceResult, query: string): AgentMatch | null { + let best: AgentMatch | null = null; + for (const agent of workspace.agents) { + const candidate = scoreCandidate(query, agentSearchFields(workspace, agent)); + if (candidate && (!best || compareCandidates(candidate, best) < 0)) { + best = { agent, ...candidate }; + } + } + return best; +} + +export type WorkspaceRanker = ( workspaces: readonly CommandCenterWorkspaceResult[], query: string, -): CommandCenterWorkspaceResult[] { - if (!query.trim()) return filterAndRankBuiltInResults(workspaces, query, searchFields); + options?: { keepUnmatched?: boolean }, +) => CommandCenterWorkspaceResult[]; - const changeRequestNumber = parseChangeRequestQuery(query); - const matches: ScoredWorkspace[] = []; - for (const workspace of workspaces) { - const score = scoreSearchFields(query, searchFields(workspace)); - const changeRequestHit = - changeRequestNumber !== null && workspace.changeRequestNumber === changeRequestNumber; - if (score || changeRequestHit) matches.push({ workspace, score, changeRequestHit }); +/** + * Rank workspaces for a query, best match first. A workspace matches on its own title, project, + * branch and change request, or on those together with the title of one of its agents. It is + * matched through an agent only when the agent matches in a closer class than its own text + * (see `MatchClass`), never on a change-request hit; such a match comes back naming that agent, + * and opens it. Each row ranks by the match it shows. + * + * An empty query lists every workspace, most recent first. `keepUnmatched` keeps rows nothing + * here matches, ranked last: archived rows come from the host's own search, which is + * typo-tolerant, so the host is the authority on whether they match. + * + * The ranker remembers the row it made for each workspace and agent, so a row matched through + * the same agent is the same object on every keystroke and its list row does not re-render. + */ +export function createWorkspaceRanker(): WorkspaceRanker { + const viaAgent = new WeakMap< + CommandCenterWorkspaceResult, + Map + >(); + + function matchedThrough( + workspace: CommandCenterWorkspaceResult, + agent: CommandCenterWorkspaceAgent, + ): CommandCenterWorkspaceResult { + let rows = viaAgent.get(workspace); + if (!rows) { + rows = new Map(); + viaAgent.set(workspace, rows); + } + let row = rows.get(agent.id); + if (!row) { + row = { ...workspace, matchedAgent: agent, run: () => workspace.openAgent(agent.id) }; + rows.set(agent.id, row); + } + return row; } - matches.sort(compareScoredWorkspaces); - return matches.map((match) => match.workspace); + + return (workspaces, query, options = {}) => { + if (!query.trim()) return [...workspaces].sort(compareByRecency); + + const changeRequestNumber = parseChangeRequestQuery(query); + const matches: ScoredWorkspace[] = []; + for (const workspace of workspaces) { + const changeRequestHit = + changeRequestNumber !== null && workspace.changeRequestNumber === changeRequestNumber; + const own = scoreCandidate(query, ownSearchFields(workspace)); + // A change-request hit is the workspace's own answer to the query. + const throughAgent = changeRequestHit ? null : agentMatch(workspace, query); + // An agent is named only when it matches in a closer class than the workspace's own text. + if ( + throughAgent && + (!own || compareMatchClasses(throughAgent.matchClass, own.matchClass) < 0) + ) { + matches.push({ + workspace, + via: AGENT_MATCH, + candidate: throughAgent, + agent: throughAgent.agent, + changeRequestHit, + }); + } else if (own || changeRequestHit) { + matches.push({ workspace, via: OWN_MATCH, candidate: own, agent: null, changeRequestHit }); + } else if (options.keepUnmatched) { + matches.push({ + workspace, + via: HOST_MATCH, + candidate: null, + agent: null, + changeRequestHit, + }); + } + } + matches.sort(compareScoredWorkspaces); + return matches.map((match) => + match.agent ? matchedThrough(match.workspace, match.agent) : match.workspace, + ); + }; } diff --git a/packages/app/src/components/adaptive-modal-sheet.browser.test.tsx b/packages/app/src/components/adaptive-modal-sheet.browser.test.tsx new file mode 100644 index 0000000000..29a670a988 --- /dev/null +++ b/packages/app/src/components/adaptive-modal-sheet.browser.test.tsx @@ -0,0 +1,76 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { RotateCw, Settings } from "lucide-react-native"; +import { afterEach, describe, expect, it } from "vitest"; +import { + InlineHeaderView, + SheetHeaderIconButton, + SheetHeaderView, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; + +let root: Root | null = null; +let container: HTMLDivElement | null = null; + +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +function noop() {} + +const LONG_TITLE = + "A sheet title long enough to fill the whole header row on a phone and then some more"; + +const header: SheetHeader = { + title: LONG_TITLE, + actions: ( + <> + + + + ), +}; + +function mount(node: React.ReactNode) { + container = document.createElement("div"); + container.style.width = "390px"; + document.body.appendChild(container); + root = createRoot(container); + act(() => root?.render(node)); +} + +function rectOf(testID: string): DOMRect { + const found = document.querySelector(`[data-testid="${testID}"]`); + if (!(found instanceof HTMLElement)) throw new Error(`Nothing rendered as ${testID}`); + return found.getBoundingClientRect(); +} + +/** Each button keeps its own width, follows the previous one and stays inside the row. */ +function expectButtonsInRow(testIDs: string[]) { + const row = container?.getBoundingClientRect(); + if (!row) throw new Error("Nothing mounted"); + const rects = testIDs.map(rectOf); + for (const [index, rect] of rects.entries()) { + expect(rect.width).toBeGreaterThan(0); + expect(rect.right).toBeLessThanOrEqual(row.right + 1); + const previous = rects[index - 1]; + if (previous) expect(rect.left).toBeGreaterThanOrEqual(previous.right); + } +} + +describe("sheet header with a long title", () => { + it("truncates the title and keeps the actions and Close in place", () => { + mount(); + + expectButtonsInRow(["refresh", "settings", "close"]); + }); + + it("does the same in the inline header", () => { + mount(); + + expectButtonsInRow(["refresh", "settings"]); + }); +}); diff --git a/packages/app/src/components/adaptive-modal-sheet.tsx b/packages/app/src/components/adaptive-modal-sheet.tsx index 3ff2020955..a20c4a1a47 100644 --- a/packages/app/src/components/adaptive-modal-sheet.tsx +++ b/packages/app/src/components/adaptive-modal-sheet.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import type { ComponentProps, ReactNode } from "react"; import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; -import { Keyboard, Pressable, Text, View } from "react-native"; +import { Keyboard, Text, View } from "react-native"; import type { DimensionValue, StyleProp, ViewProps, ViewStyle } from "react-native"; import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles"; import { useIsCompactFormFactor } from "@/constants/layout"; @@ -29,6 +29,15 @@ import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; import { AdaptiveTextInput } from "@/components/adaptive-text-input"; import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal"; +import { DismissBackdrop } from "@/components/ui/dismiss-backdrop"; +import { + IconButtonChromeProvider, + iconButtonChromeGlyphSize, + iconButtonChromeHang, + mutedIconColorMapping, +} from "@/components/ui/icon-button-chrome"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; export { AdaptiveTextInput, type AdaptiveTextInputProps } from "@/components/adaptive-text-input"; // Horizontal indent token shared by the sheet header (title, back arrow, @@ -37,11 +46,6 @@ export { AdaptiveTextInput, type AdaptiveTextInputProps } from "@/components/ada // match this padding. export const SHEET_HORIZONTAL_PADDING_SCALE = 6; -// The header's close button grows outward from its glyph, so the glyph's -// trailing rail is the content inset plus this padding. Rows whose trailing -// glyph should line up with the X must reach the same rail. -export const SHEET_HEADER_CLOSE_PADDING_SCALE = 2; - /** The one height a sheet takes when it shows a whole pane rather than sizing to its content. */ export const FULL_SHEET_SNAP_POINTS = ["92%"]; @@ -63,6 +67,7 @@ export interface SheetHeaderBack { export interface SheetHeader { title: string; + titleTestID?: string; subtitle?: ReactNode; back?: SheetHeaderBack; leading?: ReactNode; @@ -71,7 +76,9 @@ export interface SheetHeader { } const SCROLL_CONTENT_GROW = { flexGrow: 1 }; -const ABSOLUTE_FILL_STYLE = { ...StyleSheet.absoluteFill }; +// Header buttons hang by how far their frame reaches past the glyph, so the edge glyphs sit on the +// content rail and a 44pt touch frame does not grow the row. +const HEADER_BUTTON_HANG = iconButtonChromeHang("large"); const NATIVE_DIALOG_SNAP_POINTS = ["100%"]; const styles = StyleSheet.create((theme) => ({ @@ -105,20 +112,24 @@ const styles = StyleSheet.create((theme) => ({ borderBottomWidth: 1, borderBottomColor: theme.colors.surface2, }, + // One height for every sheet header whatever its buttons; a hung 44pt touch frame fits inside it. headerRow: { + minHeight: 64, paddingHorizontal: theme.spacing[SHEET_HORIZONTAL_PADDING_SCALE], paddingVertical: theme.spacing[4], flexDirection: "row", alignItems: "center", gap: theme.spacing[2], }, - headerBackButton: { - borderRadius: theme.borderRadius.lg, + headerBack: { + marginVertical: HEADER_BUTTON_HANG, + marginLeft: HEADER_BUTTON_HANG, }, headerLeadingSlot: { alignItems: "center", justifyContent: "center", }, + // The title takes the room the buttons leave and truncates; the buttons never shrink. headerTitleGroup: { flex: 1, gap: theme.spacing[1], @@ -128,14 +139,17 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.medium, }, - headerActions: { + subtitle: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, + headerTrailing: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2], - }, - closeButton: { - padding: theme.spacing[SHEET_HEADER_CLOSE_PADDING_SCALE], - borderRadius: theme.borderRadius.lg, + flexShrink: 0, + marginVertical: HEADER_BUTTON_HANG, + marginRight: HEADER_BUTTON_HANG, }, // Without a header the close button floats over the card's top-right corner. floatingClose: { @@ -176,6 +190,7 @@ const styles = StyleSheet.create((theme) => ({ }, inlineTitle: { flex: 1, + minWidth: 0, fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.medium, color: theme.colors.foreground, @@ -343,47 +358,92 @@ function SheetContent({ style, children }: { style: StyleProp; childr return {children}; } +const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); +const ThemedHeaderGlyph = withUnistyles(function HeaderGlyph({ + icon: Icon, + size, + color, +}: { + icon: LucideIcon; + size: number; + color?: string; +}) { + return ; +}); + /** - * An icon action in a sheet header's trailing rail, drawn like the Close button so a header's - * actions line up with it at one size. Pass it through `SheetHeader.actions`. + * The one icon button of a sheet header: the back arrow, the close X, and every action passed + * through `SheetHeader.actions`. Inside a header it takes the header island's chrome, so all of them + * share one frame, glyph, colour and hover. `busy` swaps the glyph for a spinner and holds presses. */ export function SheetHeaderIconButton({ - icon: Icon, - accessibilityLabel, + icon, + label, onPress, + busy = false, + disabled = false, testID, }: { icon: LucideIcon; - accessibilityLabel: string; + /** The accessible name, also shown as the desktop tooltip. */ + label: string; onPress: () => void; + busy?: boolean; + disabled?: boolean; testID?: string; }) { - const { theme } = useUnistyles(); + const compact = useIsCompactFormFactor(); + const glyphSize = iconButtonChromeGlyphSize("large", compact); return ( - - {({ pressed }) => ( - + {busy ? ( + + ) : ( + )} - + + ); +} + +function SheetHeaderBackButton({ back }: { back: SheetHeaderBack }) { + const { t } = useTranslation(); + return ( + + + + ); +} + +/** A plain-text header subtitle: one muted line under the title that truncates, never the title. */ +export function SheetHeaderSubtitle({ text, testID }: { text: string; testID?: string }) { + return ( + + {text} + ); } export function SheetHeaderView({ header, onClose, - showCloseButton = true, testID, + closeTestID, }: { header: SheetHeader; onClose: () => void; - showCloseButton?: boolean; testID?: string; + closeTestID?: string; }) { const { theme } = useUnistyles(); const { t } = useTranslation(); @@ -391,8 +451,6 @@ export function SheetHeaderView({ () => [styles.title, { color: theme.colors.foreground }], [theme.colors.foreground], ); - const back = header.back; - const handleBackPress = back?.onPress; const search = header.search; const handleSearchChange = useCallback( (value: string) => { @@ -403,40 +461,27 @@ export function SheetHeaderView({ return ( - - {handleBackPress ? ( - - {({ pressed }) => ( - - )} - - ) : null} - {header.leading ? {header.leading} : null} - - - {header.title} - - {header.subtitle} + + + {header.back ? : null} + {header.leading ? {header.leading} : null} + + + {header.title} + + {header.subtitle} + + + {header.actions} + + - {header.actions ? {header.actions} : null} - {showCloseButton ? ( - - ) : null} - + {search ? ( @@ -462,39 +507,21 @@ export function SheetHeaderView({ export function InlineHeaderView({ header }: { header: SheetHeader }) { const { theme } = useUnistyles(); const { t } = useTranslation(); - const back = header.back; - const handleBackPress = back?.onPress; - const hasInlineRow = Boolean(handleBackPress || header.leading || header.actions); + const hasInlineRow = Boolean(header.back || header.leading || header.actions); if (!hasInlineRow && !header.search) return null; return ( {hasInlineRow ? ( - - {handleBackPress ? ( - - {({ pressed }) => ( - - )} - - ) : null} - {header.leading ? {header.leading} : null} - - {header.title} - - {header.actions ? {header.actions} : null} - + + + {header.back ? : null} + {header.leading ? {header.leading} : null} + + {header.title} + + {header.actions ? {header.actions} : null} + + ) : null} {header.search ? ( @@ -798,24 +825,18 @@ export function AdaptiveModalSheet({ {footerView} {header ? null : ( - - - + + + + + )} ); const desktopContent = ( - + {cardInner} diff --git a/packages/app/src/components/agent-list.tsx b/packages/app/src/components/agent-list.tsx index 8921102f26..afb9a4c258 100644 --- a/packages/app/src/components/agent-list.tsx +++ b/packages/app/src/components/agent-list.tsx @@ -17,11 +17,12 @@ import { useIsCompactFormFactor } from "@/constants/layout"; import { useTimeAgo } from "@/hooks/use-time-ago"; import { type AggregatedAgent } from "@/hooks/use-aggregated-agents"; import { useSessionStore } from "@/stores/session-store"; -import { Archive, ChevronRight } from "lucide-react-native"; +import { ChevronRight } from "lucide-react-native"; import { useProviderIcon } from "@/components/provider-icons"; import { navigateToAgent } from "@/utils/navigate-to-agent"; import { useArchiveAgent } from "@/hooks/use-archive-agent"; import { HighlightedText } from "@/components/ui/highlighted-text"; +import { ArchivedBadge } from "@/components/archived-badge"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/status-badge"; import { findHighlightRanges } from "@/components/ui/highlighted-text-segments"; @@ -99,36 +100,30 @@ function formatDateSectionLabel(t: TFunction, section: DateSectionKey): string { function SessionBadge({ label, - icon, tone = "neutral", }: { label: string; - icon?: ReactElement; tone?: "neutral" | "warning" | "danger"; }) { let variant: StatusBadgeVariant = "muted"; if (tone === "warning") variant = "warning"; else if (tone === "danger") variant = "error"; - return ; + return ; } function SessionRowBadges({ agent, - archivedIcon, pendingPermissionCount, showDesktopAttention, }: { agent: AggregatedAgent; - archivedIcon: ReactElement; pendingPermissionCount: number; showDesktopAttention: boolean; }) { const { t } = useTranslation(); return ( <> - {agent.archivedAt ? ( - - ) : null} + {agent.archivedAt ? : null} {pendingPermissionCount > 0 ? ( onPress(agent), [onPress, agent]); const handleLongPress = useCallback(() => onLongPress(agent), [onLongPress, agent]); - const archivedIcon = useMemo( - () => , - [theme.fontSize.sm, theme.colors.foregroundMuted], - ); const showDesktopAttention = !isMobile && showAttentionIndicator && Boolean(agent.requiresAttention); @@ -261,7 +252,6 @@ function SessionRow({ ) : null} diff --git a/packages/app/src/components/app-diagnostic-sheet.tsx b/packages/app/src/components/app-diagnostic-sheet.tsx index 9cf74a9323..41c2a6b1a2 100644 --- a/packages/app/src/components/app-diagnostic-sheet.tsx +++ b/packages/app/src/components/app-diagnostic-sheet.tsx @@ -1,11 +1,15 @@ import * as Clipboard from "expo-clipboard"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { Platform, Pressable, Text, View, type PressableStateCallbackType } from "react-native"; +import { Platform, Text, View } from "react-native"; import { Copy, RotateCw } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; -import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { + AdaptiveModalSheet, + SheetHeaderIconButton, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface"; import { useToast } from "@/contexts/toast-context"; @@ -42,8 +46,6 @@ interface DiagnosticCollectionResult { } const SNAP_POINTS = ["55%", "88%"]; -const ThemedCopy = withUnistyles(Copy); -const ThemedRotateCw = withUnistyles(RotateCw); const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted, @@ -150,68 +152,31 @@ export function AppDiagnosticSheet({ .catch(() => toast.error(t("settings.diagnostics.app.copyFailed"))); }, [diagnostic, t, toast]); - const iconButtonStyle = useCallback( - ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ - styles.iconButton, - (Boolean(hovered) || pressed) && styles.iconButtonHovered, - ], - [], - ); - - const disabledIconButtonStyle = useCallback( - ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ - styles.iconButton, - (Boolean(hovered) || pressed) && Boolean(diagnostic) && styles.iconButtonHovered, - diagnostic ? null : styles.disabled, - ], - [diagnostic], - ); - const header = useMemo( () => ({ title: t("settings.diagnostics.app.title"), actions: ( - - + - - - + - {loading ? ( - - ) : ( - - )} - - + onPress={handleRefreshPress} + busy={loading} + /> + ), }), - [ - diagnostic, - disabledIconButtonStyle, - handleCopyPress, - handleRefreshPress, - iconButtonStyle, - loading, - t, - ], + [diagnostic, handleCopyPress, handleRefreshPress, loading, t], ); return ( @@ -342,24 +307,6 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, color: theme.colors.foregroundMuted, }, - headerActions: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1], - }, - iconButton: { - width: 28, - height: 28, - borderRadius: theme.borderRadius.full, - alignItems: "center", - justifyContent: "center", - }, - iconButtonHovered: { - backgroundColor: theme.colors.surface2, - }, - disabled: { - opacity: 0.5, - }, statusDot: { width: 8, height: 8, diff --git a/packages/app/src/components/archived-badge.tsx b/packages/app/src/components/archived-badge.tsx new file mode 100644 index 0000000000..0c675906fd --- /dev/null +++ b/packages/app/src/components/archived-badge.tsx @@ -0,0 +1,17 @@ +import { Archive } from "lucide-react-native"; +import { useTranslation } from "react-i18next"; +import { withUnistyles } from "react-native-unistyles"; +import { StatusBadge } from "@/components/ui/status-badge"; + +const ThemedArchive = withUnistyles(Archive, (theme) => ({ + size: theme.fontSize.sm, + color: theme.colors.foregroundMuted, +})); + +const ARCHIVE_ICON = ; + +/** Marks a session or workspace the user archived, wherever archived items are listed. */ +export function ArchivedBadge() { + const { t } = useTranslation(); + return ; +} diff --git a/packages/app/src/components/attachment-lightbox.browser.test.tsx b/packages/app/src/components/attachment-lightbox.browser.test.tsx new file mode 100644 index 0000000000..9719588b7c --- /dev/null +++ b/packages/app/src/components/attachment-lightbox.browser.test.tsx @@ -0,0 +1,149 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { persistAttachmentFromBlob } from "@/attachments/service"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { i18n } from "@/i18n/i18next"; +import { WindowLayoutProvider } from "@/window-layout"; +import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox"; + +interface FrameSample { + image: { x: number; y: number; width: number; height: number } | null; + error: boolean; +} + +function nextFrame(): Promise { + return new Promise((resolve) => requestAnimationFrame(resolve)); +} + +function createPng(width: number, height: number): Promise { + const canvas = new OffscreenCanvas(width, height); + const context = canvas.getContext("2d"); + if (!context) throw new Error("Canvas 2D context unavailable"); + context.fillStyle = "#3a7"; + context.fillRect(0, 0, width, height); + return canvas.convertToBlob({ type: "image/png" }); +} + +function noop() {} + +function isPainted(element: Element): boolean { + for (let node: Element | null = element; node; node = node.parentElement) { + if (Number(getComputedStyle(node).opacity) === 0) return false; + } + return true; +} + +/** What the next paint will show: the visible lightbox image box, and whether the error is up. */ +function sampleFrame(): FrameSample { + const image = document.querySelector('[data-testid="attachment-lightbox-image"]'); + const rect = image?.getBoundingClientRect(); + const visible = image && rect && rect.width > 0 && rect.height > 0 && isPainted(image); + return { + image: visible + ? { + x: Math.round(rect.x), + y: Math.round(rect.y), + width: Math.round(rect.width), + height: Math.round(rect.height), + } + : null, + error: (document.body.textContent ?? "").includes("Couldn't load image"), + }; +} + +/** Samples every frame from the open until the image has held one box for 20 frames. */ +async function recordOpening(open: () => void): Promise { + const samples: FrameSample[] = []; + open(); + let stableFrames = 0; + for (let frame = 0; frame < 300 && stableFrames < 20; frame += 1) { + await nextFrame(); + const sample = sampleFrame(); + const previous = samples.at(-1); + stableFrames = + sample.image && JSON.stringify(sample.image) === JSON.stringify(previous?.image) + ? stableFrames + 1 + : 0; + samples.push(sample); + } + return samples; +} + +let root: Root; +let container: HTMLDivElement; + +beforeEach(async () => { + vi.stubGlobal("React", React); + await i18n.changeLanguage("en"); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(() => { + act(() => root.unmount()); + document.body.replaceChildren(); + vi.unstubAllGlobals(); +}); + +function renderLightbox(source: ImageLightboxSource | null) { + root.render( + + + + + , + ); +} + +async function expectOpeningPaintsOnlyTheFittedImage(source: ImageLightboxSource) { + const samples = await recordOpening(() => renderLightbox(source)); + const fitted = samples.at(-1)?.image; + + expect(fitted, "the image never settled").toBeTruthy(); + expect(samples.filter((sample) => sample.error)).toEqual([]); + expect( + samples.filter( + (sample) => sample.image && JSON.stringify(sample.image) !== JSON.stringify(fitted), + ), + ).toEqual([]); +} + +describe("AttachmentLightbox opening in the browser", () => { + it("paints the fitted attachment image as its first image frame", async () => { + const metadata = await persistAttachmentFromBlob({ + blob: await createPng(2400, 1600), + mimeType: "image/png", + fileName: "screenshot.png", + }); + + await expectOpeningPaintsOnlyTheFittedImage({ type: "attachment", metadata }); + }); + + it("paints only the fitted image when the same attachment opens again", async () => { + const metadata = await persistAttachmentFromBlob({ + blob: await createPng(2400, 1600), + mimeType: "image/png", + fileName: "screenshot.png", + }); + const source: ImageLightboxSource = { type: "attachment", metadata }; + + await expectOpeningPaintsOnlyTheFittedImage(source); + await act(async () => renderLightbox(null)); + await expectOpeningPaintsOnlyTheFittedImage(source); + }); + + it("shows an image the browser reports no natural size for", async () => { + const svg = ''; + const uri = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" })); + + await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri }); + }); + + it("paints the fitted timeline image as its first image frame", async () => { + const uri = URL.createObjectURL(await createPng(2400, 1600)); + + await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri }); + }); +}); diff --git a/packages/app/src/components/attachment-lightbox.test.tsx b/packages/app/src/components/attachment-lightbox.test.tsx index 4920195258..fe6d1842a4 100644 --- a/packages/app/src/components/attachment-lightbox.test.tsx +++ b/packages/app/src/components/attachment-lightbox.test.tsx @@ -4,6 +4,7 @@ import { createRoot, type Root } from "react-dom/client"; import { JSDOM } from "jsdom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { AttachmentMetadata } from "@/attachments/types"; +import type { AttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url"; import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox"; const { theme, imageMetadata, useAttachmentPreviewUrlMock } = vi.hoisted(() => { @@ -38,9 +39,9 @@ const { theme, imageMetadata, useAttachmentPreviewUrlMock } = vi.hoisted(() => { return { theme: hoistedTheme, imageMetadata: hoistedImageMetadata, - useAttachmentPreviewUrlMock: vi.fn<(metadata: AttachmentMetadata | null) => string | null>( - () => "blob:preview", - ), + useAttachmentPreviewUrlMock: vi.fn< + (metadata: AttachmentMetadata | null) => AttachmentPreviewUrl + >(() => ({ status: "ready", url: "blob:preview" })), }; }); const attachmentSource: ImageLightboxSource = { type: "attachment", metadata: imageMetadata }; @@ -73,10 +74,13 @@ vi.mock("react-i18next", () => ({ })); vi.mock("react-native-safe-area-context", () => ({ - SafeAreaProvider: ({ children }: { children?: React.ReactNode }) => children, useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }), })); +vi.mock("@/window-layout", () => ({ + WindowSafeArea: ({ children }: { children?: React.ReactNode }) => children, +})); + vi.mock("react-native-gesture-handler", () => ({ GestureHandlerRootView: ({ children }: { children?: React.ReactNode }) => React.createElement("div", { "data-testid": "gesture-handler-root" }, children), @@ -151,7 +155,7 @@ beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); - useAttachmentPreviewUrlMock.mockReturnValue("blob:preview"); + useAttachmentPreviewUrlMock.mockReturnValue({ status: "ready", url: "blob:preview" }); }); afterEach(() => { @@ -229,14 +233,22 @@ describe("AttachmentLightbox", () => { expect(onClose).toHaveBeenCalledTimes(1); }); - it("shows error text when the preview URL resolves to null", () => { - useAttachmentPreviewUrlMock.mockReturnValue(null); + it("shows error text when the preview URL fails to resolve", () => { + useAttachmentPreviewUrlMock.mockReturnValue({ status: "failed" }); render(); expect(queryByTestId("attachment-lightbox-image")).toBeNull(); expect(document.body.textContent ?? "").toContain("Couldn't load image"); }); + it("shows neither the image nor an error while the preview URL resolves", () => { + useAttachmentPreviewUrlMock.mockReturnValue({ status: "loading" }); + render(); + + expect(queryByTestId("attachment-lightbox-image")).toBeNull(); + expect(document.body.textContent ?? "").not.toContain("Couldn't load image"); + }); + it("closes on Escape key on web", () => { const onClose = vi.fn(); render(); diff --git a/packages/app/src/components/attachment-lightbox.tsx b/packages/app/src/components/attachment-lightbox.tsx index 29ad351976..fd48725c62 100644 --- a/packages/app/src/components/attachment-lightbox.tsx +++ b/packages/app/src/components/attachment-lightbox.tsx @@ -4,17 +4,21 @@ import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react import { Pressable, Text, View } from "react-native"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import { StyleSheet } from "react-native-unistyles"; -import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { X } from "lucide-react-native"; import { useTranslation } from "react-i18next"; import type { AttachmentMetadata } from "@/attachments/types"; -import { useAttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url"; +import { + type AttachmentPreviewUrl, + useAttachmentPreviewUrl, +} from "@/attachments/use-attachment-preview-url"; import { isNative } from "@/constants/platform"; import { SPACING } from "@/styles/theme"; import { WindowChromeRootRegion } from "@/utils/desktop-window"; import { ZoomableImage } from "@/components/zoomable-viewport/image"; import type { ViewportSize } from "@/components/zoomable-viewport/geometry"; import { useGlobalOverlayLayer } from "@/lib/overlay-root"; +import { WindowSafeArea } from "@/window-layout"; export type ImageLightboxSource = | { type: "attachment"; metadata: AttachmentMetadata } @@ -31,10 +35,13 @@ const LIGHTBOX_FIT = { padding: SPACING[4], maxWidth: 960, maxHeight: 640 }; export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps) { const { t } = useTranslation(); const metadata = source?.type === "attachment" ? source.metadata : null; - const attachmentUrl = useAttachmentPreviewUrl(metadata); - const url = source?.type === "uri" ? source.uri : attachmentUrl; + const attachmentPreview = useAttachmentPreviewUrl(metadata); + const image: AttachmentPreviewUrl = + source?.type === "uri" ? { status: "ready", url: source.uri } : attachmentPreview; + const url = image.status === "ready" ? image.url : null; const contentSize = source?.type === "uri" ? source.contentSize : undefined; const [errored, setErrored] = useState(false); + const failed = errored || image.status === "failed"; const modalLayer = useGlobalOverlayLayer("modal", source !== null); useEffect(() => { @@ -76,14 +83,12 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps) return null; } - const hasError = errored || !url; - return ( - {/* The modal is its own window: its insets are the window's, not the ones left where the - image was opened (inside a sheet tab, the bottom one is already spent). */} - + {/* The modal draws over the whole window: its insets are the window's, not the ones left + where the image was opened (inside a sheet tab, the bottom one is already spent). */} + - {hasError ? ( + {failed ? ( {t("message.attachments.imageLoadFailed")} - ) : ( + ) : null} + {!failed && url ? ( - )} + ) : null} - + ); diff --git a/packages/app/src/components/attachment-pill.tsx b/packages/app/src/components/attachment-pill.tsx index 4bf7022528..aaa59e0678 100644 --- a/packages/app/src/components/attachment-pill.tsx +++ b/packages/app/src/components/attachment-pill.tsx @@ -133,9 +133,10 @@ export function AttachmentLabel({ icon, title, subtitle }: AttachmentLabelProps) /** Square image preview pill body. */ export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) { - const uri = useAttachmentPreviewUrl(metadata); - const source = useMemo(() => ({ uri: uri ?? "" }), [uri]); - if (!uri) { + const preview = useAttachmentPreviewUrl(metadata); + const uri = preview.status === "ready" ? preview.url : null; + const source = useMemo(() => (uri ? { uri } : null), [uri]); + if (!source) { return ; } return ; diff --git a/packages/app/src/components/desktop/titlebar-drag-region.tsx b/packages/app/src/components/desktop/titlebar-drag-region.tsx index da115c7349..e39e211bf1 100644 --- a/packages/app/src/components/desktop/titlebar-drag-region.tsx +++ b/packages/app/src/components/desktop/titlebar-drag-region.tsx @@ -17,6 +17,13 @@ import { isNative } from "@/constants/platform"; * On macOS, Electron handles edge resize natively. */ +/** + * Marks a scroll viewport as window content: it and its descendants emit no window + * regions, because Electron does not clip app-region rects to scroll viewports. + * See the `[data-window-content]` rule in public/index.html. + */ +export const WINDOW_CONTENT_DATASET = { "window-content": "" }; + export const titlebarDragSurfaceStyle: React.CSSProperties = { cursor: "default", // @ts-expect-error — WebkitAppRegion is not in CSSProperties diff --git a/packages/app/src/components/diff-viewer.tsx b/packages/app/src/components/diff-viewer.tsx index 8d14effdc6..e2b01dae08 100644 --- a/packages/app/src/components/diff-viewer.tsx +++ b/packages/app/src/components/diff-viewer.tsx @@ -15,7 +15,6 @@ const ScrollView = isWeb ? RNScrollView : GHScrollView; interface DiffViewerProps { diffLines: DiffLine[]; - maxHeight?: number; emptyLabel?: string; fillAvailableHeight?: boolean; } @@ -119,7 +118,6 @@ function DiffSegment({ export function DiffViewer({ diffLines, - maxHeight, emptyLabel, fillAvailableHeight = false, }: DiffViewerProps) { @@ -133,12 +131,8 @@ export function DiffViewer({ ); const outerScrollStyle = React.useMemo( - () => [ - styles.verticalScroll, - maxHeight !== undefined && inlineUnistylesStyle({ maxHeight }), - fillAvailableHeight && styles.fillHeight, - ], - [maxHeight, fillAvailableHeight], + () => [styles.verticalScroll, fillAvailableHeight && styles.fillHeight], + [fillAvailableHeight], ); const linesContainerStyle = React.useMemo( () => [ @@ -184,6 +178,9 @@ export function DiffViewer({ ); + // Capped tool details own vertical scrolling outside the diff. + if (!fillAvailableHeight) return horizontalScroll; + const content = ( { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +function hold() { + const onArm = vi.fn(); + return { onArm, hold: createDragHold({ delayMs: 180, slopPx: 4, onArm }) }; +} + +describe("createDragHold", () => { + it("arms once the finger has stayed within the slop for the delay", () => { + const { onArm, hold: dragHold } = hold(); + dragHold.begin({ x: 10, y: 10 }); + dragHold.move({ x: 12, y: 13 }); + vi.advanceTimersByTime(180); + + expect(onArm).toHaveBeenCalledTimes(1); + }); + + it("never arms when the finger moves past the slop first, as when a scroll starts", () => { + const { onArm, hold: dragHold } = hold(); + dragHold.begin({ x: 10, y: 10 }); + dragHold.move({ x: 10, y: 20 }); + vi.advanceTimersByTime(500); + + expect(onArm).not.toHaveBeenCalled(); + }); + + it("never arms when the finger lifts before the delay", () => { + const { onArm, hold: dragHold } = hold(); + dragHold.begin({ x: 10, y: 10 }); + vi.advanceTimersByTime(100); + dragHold.cancel(); + vi.advanceTimersByTime(500); + + expect(onArm).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/components/drag-reorder/drag-hold.ts b/packages/app/src/components/drag-reorder/drag-hold.ts new file mode 100644 index 0000000000..04ed15231a --- /dev/null +++ b/packages/app/src/components/drag-reorder/drag-hold.ts @@ -0,0 +1,51 @@ +export interface TouchPoint { + x: number; + y: number; +} + +export interface DragHold { + begin: (point: TouchPoint) => void; + move: (point: TouchPoint) => void; + cancel: () => void; +} + +/** + * A hold that arms a drag once the finger has stayed put for `delayMs`. Moving further than + * `slopPx` from where the touch began cancels it, so a scroll that starts on a handle stays a + * scroll. The sidebar rows arm on the same delay and slop. + */ +export function createDragHold({ + delayMs, + slopPx, + onArm, +}: { + delayMs: number; + slopPx: number; + onArm: () => void; +}): DragHold { + let timer: ReturnType | null = null; + let start: TouchPoint | null = null; + + function cancel() { + if (timer) clearTimeout(timer); + timer = null; + start = null; + } + + return { + begin(point) { + cancel(); + start = point; + timer = setTimeout(() => { + timer = null; + start = null; + onArm(); + }, delayMs); + }, + move(point) { + if (!start) return; + if (Math.hypot(point.x - start.x, point.y - start.y) > slopPx) cancel(); + }, + cancel, + }; +} diff --git a/packages/app/src/components/drag-reorder/drag-reducer.test.ts b/packages/app/src/components/drag-reorder/drag-reducer.test.ts index 623f7cdca0..b347bb3c98 100644 --- a/packages/app/src/components/drag-reorder/drag-reducer.test.ts +++ b/packages/app/src/components/drag-reorder/drag-reducer.test.ts @@ -2,31 +2,41 @@ import { describe, expect, it } from "vitest"; import { dragStateInitial, dragStateReducer } from "./drag-reducer"; describe("dragStateReducer", () => { - it("starts tracking the active item with a snapshot of the data", () => { + it("starts tracking the active item with the rows on screen", () => { const next = dragStateReducer(dragStateInitial(), { type: "start", id: "alpha", - data: ["alpha", "beta"], + items: ["alpha", "beta"], }); - expect(next).toEqual({ activeId: "alpha", dragItems: ["alpha", "beta"] }); + expect(next).toEqual({ activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }); }); - it("clears the active item and the snapshot", () => { + it("clears the active item and the rows", () => { const next = dragStateReducer( - { activeId: "alpha", dragItems: ["alpha", "beta"] }, + { activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }, { type: "clear" }, ); - expect(next).toEqual({ activeId: null, dragItems: null }); + expect(next).toEqual({ activeId: null, dragItems: null, dropped: null }); + }); + + it("holds the dropped order in place of the order it replaces", () => { + const dropped = { order: ["beta", "alpha"], replaces: ["alpha", "beta"] }; + const next = dragStateReducer( + { activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }, + { type: "drop", dropped }, + ); + + expect(next).toEqual({ activeId: null, dragItems: null, dropped }); }); it("replaces an in-flight drag when a new one starts", () => { const next = dragStateReducer( - { activeId: "alpha", dragItems: ["alpha", "beta"] }, - { type: "start", id: "beta", data: ["beta", "gamma"] }, + { activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }, + { type: "start", id: "beta", items: ["beta", "gamma"] }, ); - expect(next).toEqual({ activeId: "beta", dragItems: ["beta", "gamma"] }); + expect(next).toEqual({ activeId: "beta", dragItems: ["beta", "gamma"], dropped: null }); }); }); diff --git a/packages/app/src/components/drag-reorder/drag-reducer.ts b/packages/app/src/components/drag-reorder/drag-reducer.ts index b9b508f2d2..7e4acfe055 100644 --- a/packages/app/src/components/drag-reorder/drag-reducer.ts +++ b/packages/app/src/components/drag-reorder/drag-reducer.ts @@ -1,19 +1,33 @@ -export interface DragState { - activeId: string | null; - dragItems: T[] | null; +/** A dropped key order, shown in place of the owner's until the owner's order changes. */ +export interface DroppedOrder { + order: string[]; + /** The owner's key order at the drop. */ + replaces: string[]; } -export type DragAction = { type: "start"; id: string; data: T[] } | { type: "clear" }; +export interface DragState { + activeId: string | null; + /** The rows on screen while a drag is in flight. */ + dragItems: T[] | null; + dropped: DroppedOrder | null; +} + +export type DragAction = + | { type: "start"; id: string; items: T[] } + | { type: "drop"; dropped: DroppedOrder } + | { type: "clear" }; export function dragStateInitial(): DragState { - return { activeId: null, dragItems: null }; + return { activeId: null, dragItems: null, dropped: null }; } export function dragStateReducer(state: DragState, action: DragAction): DragState { switch (action.type) { case "start": - return { activeId: action.id, dragItems: action.data }; + return { activeId: action.id, dragItems: action.items, dropped: null }; + case "drop": + return { activeId: null, dragItems: null, dropped: action.dropped }; case "clear": - return { activeId: null, dragItems: null }; + return dragStateInitial(); } } diff --git a/packages/app/src/components/drag-reorder/native-drop.test.ts b/packages/app/src/components/drag-reorder/native-drop.test.ts new file mode 100644 index 0000000000..f05bf3c819 --- /dev/null +++ b/packages/app/src/components/drag-reorder/native-drop.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { movedItemKey } from "./native-drop"; + +const byValue = (item: string): string => item; + +describe("movedItemKey", () => { + it("names the item at its new slot", () => { + expect(movedItemKey({ data: ["b", "c", "a"], from: 0, to: 2 }, byValue)).toBe("a"); + }); + + it("names nothing when the item is released in the slot it started in", () => { + expect(movedItemKey({ data: ["a", "b", "c"], from: 1, to: 1 }, byValue)).toBeNull(); + }); +}); diff --git a/packages/app/src/components/drag-reorder/native-drop.ts b/packages/app/src/components/drag-reorder/native-drop.ts new file mode 100644 index 0000000000..e155da7796 --- /dev/null +++ b/packages/app/src/components/drag-reorder/native-drop.ts @@ -0,0 +1,17 @@ +export interface NativeDrop { + data: T[]; + from: number; + to: number; +} + +/** + * The key of the item a native drop moved, or null when the item was released in the slot it + * started in. The native list reports every release; web reports only drops that moved an item. + */ +export function movedItemKey( + { data, from, to }: NativeDrop, + keyExtractor: (item: T, index: number) => string, +): string | null { + if (from === to) return null; + return keyExtractor(data[to], to); +} diff --git a/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts b/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts index 400beeb28a..986a2c578b 100644 --- a/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts +++ b/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts @@ -1,6 +1,6 @@ -import { useCallback, useReducer } from "react"; +import { useCallback, useMemo, useReducer } from "react"; import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core"; -import { dragStateInitial, dragStateReducer } from "./drag-reducer"; +import { dragStateInitial, dragStateReducer, type DroppedOrder } from "./drag-reducer"; import { reorderItemsOnDragEnd } from "./reorder-items"; export interface DragReorderHandlers { @@ -15,6 +15,28 @@ export interface DragReorderState { handlers: DragReorderHandlers; } +/** + * The owner's rows in the dropped order, or null once the owner's own order has changed since + * the drop. + */ +function arrangeAsDropped( + data: T[], + keys: string[], + { order, replaces }: DroppedOrder, +): T[] | null { + const ownerOrderUnchanged = + keys.length === replaces.length && keys.every((key, index) => key === replaces[index]); + if (!ownerOrderUnchanged) return null; + + const indexByKey = new Map(keys.map((key, index) => [key, index])); + const arranged: T[] = []; + for (const key of order) { + const index = indexByKey.get(key); + if (index !== undefined) arranged.push(data[index]); + } + return arranged.length === data.length ? arranged : null; +} + export function useDragReorderState({ data, keyExtractor, @@ -24,19 +46,28 @@ export function useDragReorderState({ }: { data: T[]; keyExtractor: (item: T, index: number) => string; - onDragEnd?: (items: T[]) => void; + onDragEnd?: (items: T[], movedKey: string) => void; onDragBegin?: () => void; disabled?: boolean; }): DragReorderState { const [state, dispatch] = useReducer(dragStateReducer, undefined, dragStateInitial); + const keys = useMemo(() => data.map(keyExtractor), [data, keyExtractor]); + const held = useMemo( + () => (state.dropped ? arrangeAsDropped(data, keys, state.dropped) : null), + [data, keys, state.dropped], + ); + // The owner's order changed, so the dropped order has nothing left to stand in for. + if (state.dropped && !held) dispatch({ type: "clear" }); + const items = state.dragItems ?? held ?? data; + const handleDragStart = useCallback( (event: DragStartEvent) => { if (disabled) return; - dispatch({ type: "start", id: String(event.active.id), data }); + dispatch({ type: "start", id: String(event.active.id), items }); onDragBegin?.(); }, - [data, disabled, onDragBegin], + [disabled, items, onDragBegin], ); const clearDragState = useCallback(() => { @@ -46,24 +77,29 @@ export function useDragReorderState({ const handleDragEnd = useCallback( (event: DragEndEvent) => { const { active, over } = event; - const items = state.dragItems ?? data; - dispatch({ type: "clear" }); - if (disabled) return; - - const reordered = reorderItemsOnDragEnd({ - items, - activeId: String(active.id), - overId: over ? String(over.id) : null, - keyExtractor, - }); - if (reordered) onDragEnd?.(reordered); + const activeId = String(active.id); + const reordered = disabled + ? null + : reorderItemsOnDragEnd({ + items, + activeId, + overId: over ? String(over.id) : null, + keyExtractor, + }); + if (!reordered) { + dispatch({ type: "clear" }); + return; + } + // The owner's new order can arrive in a later render. Hold the dropped order until it does. + dispatch({ type: "drop", dropped: { order: reordered.map(keyExtractor), replaces: keys } }); + onDragEnd?.(reordered, activeId); }, - [data, disabled, keyExtractor, onDragEnd, state.dragItems], + [disabled, items, keyExtractor, keys, onDragEnd], ); return { activeId: state.activeId, - items: state.dragItems ?? data, + items, handlers: { onDragStart: handleDragStart, onDragCancel: clearDragState, diff --git a/packages/app/src/components/draggable-list.native.tsx b/packages/app/src/components/draggable-list.native.tsx index ee5acb7f51..c92b04ed32 100644 --- a/packages/app/src/components/draggable-list.native.tsx +++ b/packages/app/src/components/draggable-list.native.tsx @@ -1,16 +1,94 @@ -import { RefreshControl } from "react-native"; -import { useCallback, useMemo, useState } from "react"; +import { RefreshControl, View, type GestureResponderEvent } from "react-native"; +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import * as Haptics from "expo-haptics"; import DraggableFlatList, { NestableDraggableFlatList, type RenderItemParams, } from "react-native-draggable-flatlist"; +import type { GestureType } from "react-native-gesture-handler"; import { useUnistyles } from "react-native-unistyles"; -import type { DraggableListProps, DraggableRenderItemInfo } from "./draggable-list.types"; +import { useContentDrag } from "@/components/ui/scroll-view"; +import { createDragHold } from "./drag-reorder/drag-hold"; +import { movedItemKey } from "./drag-reorder/native-drop"; +import type { + DraggableListHandleProps, + DraggableListProps, + DraggableRenderItemInfo, +} from "./draggable-list.types"; -export type { DraggableListProps, DraggableRenderItemInfo }; +export type { DraggableListHandleProps, DraggableListProps, DraggableRenderItemInfo }; + +/** The row's `drag()`, for its handle. */ +const RowDragContext = createContext<(() => void) | null>(null); + +// The list only accepts drag() once its pan gesture has begun for this touch, and that begin +// reaches JS after the touch does. Same hold and slop as the sidebar rows' drag arm. +const HANDLE_HOLD_MS = 180; +const HANDLE_HOLD_SLOP_PX = 4; + +function touchPoint(event: GestureResponderEvent) { + return { x: event.nativeEvent.pageX, y: event.nativeEvent.pageY }; +} + +/** + * On native the handle has no accessibility role or label: a screen reader cannot hold and drag, + * and announcing a control whose activation does nothing misleads. The label is for web, where + * the keyboard reorders through it. + */ +export function DraggableListHandle({ testID, style, children }: DraggableListHandleProps) { + const drag = useContext(RowDragContext); + const hold = useMemo( + () => + drag + ? createDragHold({ + delayMs: HANDLE_HOLD_MS, + slopPx: HANDLE_HOLD_SLOP_PX, + onArm: () => { + void Haptics.selectionAsync().catch(() => {}); + drag(); + }, + }) + : null, + [drag], + ); + useEffect(() => () => hold?.cancel(), [hold]); + const startHold = useCallback( + (event: GestureResponderEvent) => hold?.begin(touchPoint(event)), + [hold], + ); + const moveHold = useCallback( + (event: GestureResponderEvent) => hold?.move(touchPoint(event)), + [hold], + ); + const cancelHold = useCallback(() => hold?.cancel(), [hold]); + return ( + + {children} + + ); +} const SCROLL_ENABLED_FLEX_STYLE = { flex: 1 }; +// A drop remounts every row between the drag's start and end slots (see the draggable-flatlist +// patch), so state held inside a rendered row resets when a drop moves it. Keep state that must +// survive a reorder in the list's owner, keyed by row. + export function DraggableList({ data, keyExtractor, @@ -37,6 +115,12 @@ export function DraggableList({ }: DraggableListProps) { const { theme } = useUnistyles(); const [isDragging, setIsDragging] = useState(false); + // Inside a sheet the sheet would otherwise take the vertical move from an armed row. + const contentDrag = useContentDrag(); + const { attach: attachContentDrag } = contentDrag; + const dragGestureRef = useRef(undefined); + // Passive effects run after the list's gesture detector has attached and filled the ref. + useEffect(() => attachContentDrag?.(dragGestureRef), [attachContentDrag]); // Pass the ref directly to DraggableFlatList - it handles gesture // coordination internally for nestable lists. @@ -59,27 +143,31 @@ export function DraggableList({ drag, isActive, }; - return renderItem(info); + return {renderItem(info)}; }, [renderItem], ); const handleDragEnd = useCallback( - ({ data: newData }: { data: T[] }) => { + (drop: { data: T[]; from: number; to: number }) => { setIsDragging(false); - onDragEnd(newData); + contentDrag.setActive(false); + const moved = movedItemKey(drop, keyExtractor); + if (moved !== null) onDragEnd(drop.data, moved); }, - [onDragEnd], + [contentDrag, keyExtractor, onDragEnd], ); const handleDragBegin = useCallback(() => { setIsDragging(true); + contentDrag.setActive(true); onDragBeginProp?.(); - }, [onDragBeginProp]); + }, [contentDrag, onDragBeginProp]); const handleRelease = useCallback(() => { setIsDragging(false); - }, []); + contentDrag.setActive(false); + }, [contentDrag]); const showRefreshControl = Boolean(onRefresh) && (!isDragging || Boolean(refreshing)); const resolvedContainerStyle = @@ -117,9 +205,14 @@ export function DraggableList({ ListEmptyComponent={ListEmptyComponent} showsVerticalScrollIndicator={showsVerticalScrollIndicator} scrollEnabled={scrollEnabled} + // A list that doesn't scroll shows every row, so it renders them all in its first commit. + // FlatList's default first render is 10 rows; a nested list remounted by a drop would paint + // 10 rows, then grow on a later commit. + initialNumToRender={scrollEnabled ? undefined : data.length} extraData={extraData} simultaneousHandlers={simultaneousHandlers} dragGestureHostPresented={gestureHostPresented} + dragGestureRef={attachContentDrag ? dragGestureRef : undefined} // Higher activation distance reduces accidental drag capture while nested // lists are inside a scroll container. activationDistance={20} diff --git a/packages/app/src/components/draggable-list.types.ts b/packages/app/src/components/draggable-list.types.ts index d541b5d73f..e9bc66ae68 100644 --- a/packages/app/src/components/draggable-list.types.ts +++ b/packages/app/src/components/draggable-list.types.ts @@ -1,4 +1,4 @@ -import type { ReactElement, MutableRefObject } from "react"; +import type { ReactElement, ReactNode, MutableRefObject } from "react"; import type { StyleProp, ViewStyle } from "react-native"; import type { GestureType } from "react-native-gesture-handler"; @@ -12,6 +12,18 @@ export interface DraggableListDragHandleProps { setActivatorNodeRef?: (node: unknown) => void; } +/** + * The grip a row is dragged by, rendered anywhere inside `renderItem`. Pointer drags start from + * it on web (with `useDragHandle`); touch drags start after a short hold on native. + */ +export interface DraggableListHandleProps { + /** Names the keyboard-reorderable handle on web. Native leaves the handle out of accessibility. */ + accessibilityLabel: string; + testID?: string; + style?: StyleProp; + children: ReactNode; +} + export interface DraggableRenderItemInfo { item: T; index: number; @@ -24,7 +36,11 @@ export interface DraggableListProps { data: T[]; keyExtractor: (item: T, index: number) => string; renderItem: (info: DraggableRenderItemInfo) => ReactElement; - onDragEnd: (data: T[]) => void; + /** + * The new order, and the key of the item the user moved to reach it. The list keeps showing + * this order until `data` arrives in a different order, so the owner must apply it. + */ + onDragEnd: (data: T[], movedKey: string) => void; style?: StyleProp; /** Outer container style (useful for nested, non-scrolling lists). */ containerStyle?: StyleProp; diff --git a/packages/app/src/components/draggable-list.web.browser.test.tsx b/packages/app/src/components/draggable-list.web.browser.test.tsx new file mode 100644 index 0000000000..db4ed66e40 --- /dev/null +++ b/packages/app/src/components/draggable-list.web.browser.test.tsx @@ -0,0 +1,192 @@ +import React, { act, useCallback, useState } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + DraggableList, + DraggableListHandle, + type DraggableRenderItemInfo, +} from "./draggable-list.web"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +interface Item { + id: string; + label?: string; +} + +function keyExtractor(item: Item): string { + return item.id; +} + +function noop() {} + +let root: Root | null = null; +let container: HTMLDivElement | null = null; + +beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +function renderRowWithHandle(info: DraggableRenderItemInfo) { + return ( +
+ + grip + + {info.item.label ?? info.item.id} +
+ ); +} + +function renderList(onDragBegin: () => void) { + act(() => { + root?.render( + , + ); + }); +} + +function byTestId(testID: string): HTMLElement { + const found = container?.querySelector(`[data-testid="${testID}"]`); + if (!(found instanceof HTMLElement)) throw new Error(`Nothing rendered as ${testID}`); + return found; +} + +/** Press on the element's centre, move the mouse down by `distance`, and release. */ +function pressAndMove(element: HTMLElement, distance: number) { + const { left, top, width, height } = element.getBoundingClientRect(); + const x = left + width / 2; + const y = top + height / 2; + act(() => { + element.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, button: 0, clientX: x, clientY: y }), + ); + }); + act(() => { + document.dispatchEvent( + new MouseEvent("mousemove", { bubbles: true, clientX: x, clientY: y + distance }), + ); + }); + act(() => { + document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); + }); +} + +const OWNER_DELAY_MS = 50; + +function wait(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +/** + * An owner that relabels its rows as soon as one is dropped, and whose new order reaches the list + * in a later render, like one that saves to a store. + */ +function ListWithLateOwner() { + const [items, setItems] = useState([{ id: "one" }, { id: "two" }]); + const relabelThenReorderLater = useCallback((next: Item[]) => { + const relabel = (item: Item): Item => ({ id: item.id, label: `${item.id} dropped` }); + setItems((current) => current.map(relabel)); + setTimeout(() => setItems(next.map(relabel)), OWNER_DELAY_MS); + }, []); + return ( + + ); +} + +function rowOrder(): (string | null)[] { + return Array.from(container?.querySelectorAll('[data-testid="row-body"]') ?? []).map( + (row) => row.textContent, + ); +} + +/** Drag the element down by `distance` in two mouse moves, letting dnd-kit measure in between. */ +async function dragDown(element: HTMLElement, distance: number) { + const { left, top, width, height } = element.getBoundingClientRect(); + const x = left + width / 2; + const y = top + height / 2; + await act(async () => { + element.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, button: 0, clientX: x, clientY: y }), + ); + }); + for (const moved of [distance / 2, distance]) { + await act(async () => { + document.dispatchEvent( + new MouseEvent("mousemove", { bubbles: true, clientX: x, clientY: y + moved }), + ); + await wait(20); + }); + } + act(() => { + document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); + }); +} + +describe("DraggableList on web", () => { + it("shows the owner's current rows in the dropped order until its new order arrives", async () => { + act(() => { + root?.render(); + }); + const [firstHandle] = Array.from( + container?.querySelectorAll('[data-testid="row-handle"]') ?? [], + ); + const [firstRow, secondRow] = Array.from( + container?.querySelectorAll('[data-testid="row-body"]') ?? [], + ); + const rowDistance = + secondRow.getBoundingClientRect().top - firstRow.getBoundingClientRect().top; + + await dragDown(firstHandle, rowDistance); + expect(rowOrder()).toEqual(["two dropped", "one dropped"]); + + await act(() => wait(OWNER_DELAY_MS * 2)); + expect(rowOrder()).toEqual(["two dropped", "one dropped"]); + }); +}); + +describe("DraggableListHandle on web", () => { + it("starts the row's drag from the handle, and only from the handle", () => { + const onDragBegin = vi.fn(); + renderList(onDragBegin); + + pressAndMove(byTestId("row-body"), 20); + expect(onDragBegin).not.toHaveBeenCalled(); + + pressAndMove(byTestId("row-handle"), 20); + expect(onDragBegin).toHaveBeenCalledTimes(1); + }); + + it("is a labelled button rather than dnd-kit's sortable", () => { + renderList(noop); + const handle = byTestId("row-handle"); + + expect(handle.getAttribute("role")).toBe("button"); + expect(handle.getAttribute("aria-label")).toBe("Move one"); + expect(handle.getAttribute("aria-roledescription")).toBeNull(); + }); +}); diff --git a/packages/app/src/components/draggable-list.web.tsx b/packages/app/src/components/draggable-list.web.tsx index 92a4d2287e..5f35a3e28e 100644 --- a/packages/app/src/components/draggable-list.web.tsx +++ b/packages/app/src/components/draggable-list.web.tsx @@ -1,4 +1,13 @@ -import { memo, useCallback, useMemo, useRef, type ReactElement } from "react"; +import { + createContext, + memo, + useCallback, + useContext, + useMemo, + useRef, + type ReactElement, + type Ref, +} from "react"; import { ScrollView, View } from "react-native"; import { DndContext, @@ -17,10 +26,52 @@ import { useSortable, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; -import type { DraggableListProps, DraggableRenderItemInfo } from "./draggable-list.types"; +import type { + DraggableListDragHandleProps, + DraggableListHandleProps, + DraggableListProps, + DraggableRenderItemInfo, +} from "./draggable-list.types"; import { getDragActivationConstraints, useDragReorderState } from "./drag-reorder"; -export type { DraggableListProps, DraggableRenderItemInfo }; +export type { DraggableListHandleProps, DraggableListProps, DraggableRenderItemInfo }; + +/** The row's dnd-kit activator, for its handle. Absent unless the list uses drag handles. */ +const RowHandleContext = createContext(undefined); + +// React Native's style types have no `cursor: "grab"`; react-native-web passes it through. +const GRAB_CURSOR = { cursor: "grab" } as object; + +export function DraggableListHandle({ + accessibilityLabel, + testID, + style, + children, +}: DraggableListHandleProps) { + const handle = useContext(RowHandleContext); + // The handle is a labelled button; dnd-kit's own role, focus stop and "sortable" description + // would replace that. + const { + role: _role, + tabIndex: _tabIndex, + "aria-roledescription": _roleDescription, + ...attributes + } = handle?.attributes ?? {}; + const handleStyle = useMemo(() => [GRAB_CURSOR, style], [style]); + return ( + } + accessibilityRole="button" + accessibilityLabel={accessibilityLabel} + style={handleStyle} + testID={testID} + > + {children} + + ); +} const restrictToVerticalAxis: Modifier = ({ transform }) => ({ ...transform, @@ -177,7 +228,9 @@ function SortableItemInner({ return (
- {renderItem(info)} + + {renderItem(info)} +
); } diff --git a/packages/app/src/components/host-status-dot.tsx b/packages/app/src/components/host-status-dot.tsx index 4f7d16dc40..2a6af89613 100644 --- a/packages/app/src/components/host-status-dot.tsx +++ b/packages/app/src/components/host-status-dot.tsx @@ -5,6 +5,8 @@ import { useHostRuntimeConnectionStatus, } from "@/runtime/host-runtime"; +export const HOST_STATUS_DOT_SIZE = 8; + export function HostStatusDot({ serverId }: { serverId: string }) { const status = useHostRuntimeConnectionStatus(serverId); @@ -19,8 +21,8 @@ function statusStyle(status: HostRuntimeConnectionStatus) { const styles = StyleSheet.create((theme) => ({ dot: { - width: 8, - height: 8, + width: HOST_STATUS_DOT_SIZE, + height: HOST_STATUS_DOT_SIZE, borderRadius: theme.borderRadius.full, }, dotOnline: { diff --git a/packages/app/src/components/hosts/host-filter.tsx b/packages/app/src/components/hosts/host-filter.tsx index d073dc943d..9a810f2caf 100644 --- a/packages/app/src/components/hosts/host-filter.tsx +++ b/packages/app/src/components/hosts/host-filter.tsx @@ -1,8 +1,12 @@ import { useCallback, useMemo, useRef, useState, type ReactElement } from "react"; -import { Pressable, Text, View, type PressableStateCallbackType } from "react-native"; -import { ChevronDown, Server } from "lucide-react-native"; +import { Text, View } from "react-native"; +import { Server } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import type { Theme } from "@/styles/theme"; +import { HOST_STATUS_DOT_SIZE } from "@/components/host-status-dot"; +import { ComboboxTrigger } from "@/components/ui/combobox-trigger"; +import { mapLayout } from "@/components/ui/control-sizing"; +import { density } from "@/styles/density"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; import { ALL_HOSTS_OPTION_ID, getHostPickerLabel, @@ -12,7 +16,8 @@ import { } from "@/components/hosts/host-picker"; const ThemedServer = withUnistyles(Server); -const ThemedChevronDown = withUnistyles(ChevronDown); +// The height a hung trigger keeps: one line of its base-size label. +const LABEL_LINE = 20; const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); export interface HostFilterProps { @@ -24,20 +29,28 @@ export interface HostFilterProps { * manager edits a single host's catalog, so "all" is not an answer it could carry out. */ includeAllHost?: boolean; + /** + * Hang the trigger into the surrounding padding, for a trigger that leads a column such as a + * modal body: its leading glyph's ink sits on the content rail and it adds only a label line to + * the column, so the column's own gap sets the rhythm. The frame still grows outward on hover. + */ + hang?: boolean; triggerTestID?: string; hostOptionTestID?: (serverId: string) => string; } /** - * The "All hosts / " host pill shared by History, Schedules, Usage, the label manager and + * The "All hosts / " host picker shared by History, Schedules, Usage, the label manager and * plugin screens: an anchored HostPicker, hidden by the caller when only one host exists. Without - * `includeAllHost` it picks the one host a surface shows. + * `includeAllHost` it picks the one host a surface shows. Its trigger is the Settings host + * trigger; a long host name truncates instead of pushing the row. */ export function HostFilter({ hosts, selectedHost, onSelectHost, includeAllHost = true, + hang = false, triggerTestID, hostOptionTestID, }: HostFilterProps): ReactElement { @@ -50,12 +63,21 @@ export function HostFilter({ ); const handleFilterOpen = useCallback(() => setIsFilterOpen(true), []); + const showsAllHosts = selectedHost === ALL_HOSTS_OPTION_ID; + const slotStyle = useMemo( + () => [ + styles.triggerSlot, + hang && styles.triggerSlotHang, + hang && (showsAllHosts ? styles.glyphHang : styles.dotHang), + ], + [hang, showsAllHosts], + ); - const filterTriggerStyle = useCallback( - ({ pressed, hovered = false }: PressableStateCallbackType & { hovered?: boolean }) => [ - styles.filterTrigger, - Boolean(hovered) && styles.filterTriggerHovered, - pressed && styles.filterTriggerPressed, + const triggerStyle = useCallback( + ({ pressed, hovered }: { pressed: boolean; hovered: boolean }) => [ + styles.trigger, + hovered && styles.triggerHovered, + pressed && styles.triggerPressed, ], [], ); @@ -74,54 +96,73 @@ export function HostFilter({ desktopPlacement="bottom-start" hostOptionTestID={hostOptionTestID} > - - + - {selectedHost === ALL_HOSTS_OPTION_ID ? ( - + {showsAllHosts ? ( + ) : ( )} - + {selectedHostLabel} - - + ); } const styles = StyleSheet.create((theme) => ({ - filterTriggerWrap: { - alignSelf: "flex-start", + // A row around the trigger keeps it as wide as its label in a column, and centred like any other + // item in a row. + triggerSlot: { + flexDirection: "row", + flexShrink: 1, + minWidth: 0, + maxWidth: "100%", }, - filterTrigger: { + // Hangs the frame's height down to a label line. + triggerSlotHang: { + marginVertical: mapLayout(density.tightRowHeight, (height) => (LABEL_LINE - height) / 2), + }, + // Hangs the padding, so the server glyph's box sits on the rail. + glyphHang: { + marginLeft: -theme.spacing[2], + }, + // Hangs the padding and the dot's inset in its icon slot, so the dot's ink sits on the rail. + dotHang: { + marginLeft: -(theme.spacing[2] + (ICON_SIZE.sm - HOST_STATUS_DOT_SIZE) / 2), + }, + // The Settings host trigger: a borderless row that fills on hover and press. + trigger: { + flexShrink: 1, + minWidth: 0, + maxWidth: "100%", flexDirection: "row", alignItems: "center", - gap: theme.spacing[1.5], - alignSelf: "flex-start", - paddingVertical: theme.spacing[1.5], - paddingHorizontal: theme.spacing[3], - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface1, - borderWidth: theme.borderWidth[1], - borderColor: theme.colors.border, + minHeight: density.tightRowHeight, + paddingVertical: theme.spacing[1], + paddingHorizontal: theme.spacing[2], + borderRadius: theme.borderRadius.lg, }, - filterTriggerHovered: { + triggerHovered: { backgroundColor: theme.colors.surface2, }, - filterTriggerPressed: { - backgroundColor: theme.colors.surface3, + triggerPressed: { + backgroundColor: theme.colors.surface2, }, - filterTriggerText: { + label: { + flexShrink: 1, + minWidth: 0, color: theme.colors.foreground, fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, + fontWeight: theme.fontWeight.normal, }, })); diff --git a/packages/app/src/components/hosts/host-menu-item.tsx b/packages/app/src/components/hosts/host-menu-item.tsx new file mode 100644 index 0000000000..6c88152d2a --- /dev/null +++ b/packages/app/src/components/hosts/host-menu-item.tsx @@ -0,0 +1,47 @@ +import { useCallback, useMemo, type ReactElement } from "react"; +import { View } from "react-native"; +import { HostStatusDot } from "@/components/host-status-dot"; +import { MenuItem } from "@/components/ui/menu"; + +interface HostMenuItemProps { + serverId: string; + label: string; + selected: boolean; + onSelect: (serverId: string) => void; + /** Off for a multi-select page, where choosing a host is one of several toggles. */ + closeOnSelect?: boolean; + testID?: string; + statusTestID?: string; +} + +/** A host as a menu option: its live status dot leads, and the chosen host carries the check. */ +export function HostMenuItem({ + serverId, + label, + selected, + onSelect, + closeOnSelect = true, + testID, + statusTestID, +}: HostMenuItemProps): ReactElement { + const handleSelect = useCallback(() => onSelect(serverId), [onSelect, serverId]); + const leading = useMemo( + () => ( + + + + ), + [serverId, statusTestID], + ); + return ( + + {label} + + ); +} diff --git a/packages/app/src/components/import-session-sheet-view-model.ts b/packages/app/src/components/import-session-sheet-view-model.ts index d9f31944c1..188442a449 100644 --- a/packages/app/src/components/import-session-sheet-view-model.ts +++ b/packages/app/src/components/import-session-sheet-view-model.ts @@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number { return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit; } +/** The page Load more grew this limit from, or null for the first page. */ +export function previousPageLimit(limit: number): number | null { + return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null; +} + export function requiresImportSessionsHostUpgrade(input: { supportsSnapshot: boolean; workspaceId?: string | null; diff --git a/packages/app/src/components/import-session-sheet.test.tsx b/packages/app/src/components/import-session-sheet.test.tsx index 35c475e824..0024ba7f20 100644 --- a/packages/app/src/components/import-session-sheet.test.tsx +++ b/packages/app/src/components/import-session-sheet.test.tsx @@ -164,6 +164,25 @@ vi.mock("@/components/adaptive-modal-sheet", () => ({ {children} ) : null, + SheetHeaderIconButton: ({ + label, + onPress, + busy, + testID, + }: { + label: string; + onPress: () => void; + busy?: boolean; + testID?: string; + }) => ( + ); } else { diff --git a/packages/app/src/file-panels/plugin-host.tsx b/packages/app/src/file-panels/plugin-host.tsx index 4cc96cdc3d..d62a17cade 100644 --- a/packages/app/src/file-panels/plugin-host.tsx +++ b/packages/app/src/file-panels/plugin-host.tsx @@ -1,7 +1,4 @@ -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import type { PluginFilePanelProps } from "@getpaseo/plugin/client"; -import { useMemo } from "react"; -import { createPluginClientStateSource } from "@/plugins/client-state/source"; import { PluginInstallationProvider } from "@/plugins/installation-provider"; import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary"; import type { PluginFilePanel } from "./panels"; @@ -11,17 +8,11 @@ export function PluginFilePanelHost({ ...props }: PluginFilePanelProps & { panel: PluginFilePanel }) { const { plugin, contribution } = panel; - const stateSource = useMemo( - () => createPluginClientStateSource(plugin.serverId), - [plugin.serverId], - ); const Component = contribution.Component; return ( - - - + ); diff --git a/packages/app/src/git/checkout-status-cache.test.ts b/packages/app/src/git/checkout-status-cache.test.ts index bbfeb6d758..661b26226a 100644 --- a/packages/app/src/git/checkout-status-cache.test.ts +++ b/packages/app/src/git/checkout-status-cache.test.ts @@ -196,7 +196,7 @@ describe("applyCheckoutStatusUpdateFromEvent", () => { ).toBe(false); }); - it("drops the checkout's cached draft slash commands when its branch changes", () => { + it("marks draft slash commands stale without clearing them when the branch changes", () => { const queryClient = createQueryClient(); queryClient.setQueryData( checkoutStatusQueryKey(serverId, cwd), @@ -219,7 +219,9 @@ describe("applyCheckoutStatusUpdateFromEvent", () => { message: checkoutStatusUpdate(checkoutStatus({ currentBranch: "main" })), }); - expect(queryClient.getQueryData(thisCheckout)).toBeUndefined(); + expect(queryClient.getQueryData(thisCheckout)).toEqual([{ name: "build-paseo" }]); + expect(queryClient.getQueryState(thisCheckout)?.isInvalidated).toBe(true); + expect(queryClient.getQueryState(otherCheckout)?.isInvalidated).toBe(false); expect(queryClient.getQueryData(otherCheckout)).toEqual([{ name: "build-paseo" }]); }); diff --git a/packages/app/src/git/checkout-status-cache.ts b/packages/app/src/git/checkout-status-cache.ts index 7a20e98fa2..42e7fcd6c9 100644 --- a/packages/app/src/git/checkout-status-cache.ts +++ b/packages/app/src/git/checkout-status-cache.ts @@ -8,7 +8,7 @@ import { invalidatePrPaneTimelineForCheckout, } from "@/git/query-keys"; import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status"; -import { resetDraftAgentCommandsForCheckout } from "@/agent-commands/cache"; +import { invalidateDraftAgentCommandsForCheckout } from "@/agent-commands/cache"; export type CheckoutStatusPayload = CheckoutStatusResponse["payload"]; export type { CheckoutPrStatusPayload } from "@/git/pr-status"; @@ -66,7 +66,7 @@ export function applyCheckoutStatusUpdateFromEvent({ ); queryClient.setQueryData(checkoutStatusQueryKey(serverId, payload.cwd), cachePayload); if (previousStatus?.currentBranch !== payload.currentBranch) { - void resetDraftAgentCommandsForCheckout(queryClient, { serverId, cwd: payload.cwd }); + void invalidateDraftAgentCommandsForCheckout(queryClient, { serverId, cwd: payload.cwd }); } void queryClient.invalidateQueries({ queryKey: checkoutCommitsQueryKey(serverId, payload.cwd), diff --git a/packages/app/src/git/file-header.tsx b/packages/app/src/git/file-header.tsx index 39427a612b..4e660b49bd 100644 --- a/packages/app/src/git/file-header.tsx +++ b/packages/app/src/git/file-header.tsx @@ -1,10 +1,5 @@ import { memo, type ReactElement, useCallback, useMemo, useState } from "react"; -import { - Text, - View, - type GestureResponderEvent, - type PressableStateCallbackType, -} from "react-native"; +import { Text, View, type GestureResponderEvent } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { useWorkspaceFileDragSource } from "@/attachments/use-workspace-file-drag-source"; import { DiffStat } from "@/components/diff-stat"; @@ -92,18 +87,17 @@ function useFileHeaderHover(enabled: boolean, onActiveChange?: (active: boolean) return { isHovered, handlePointerEnter, handlePointerLeave }; } +// Press feedback is the pressable's `highlightStyle`, so it is not part of the active fill. function fileHeaderIsActive(input: { isHovered: boolean; - pressed: boolean; showsBodyState: boolean; isSelected: boolean; }): boolean { - return input.isHovered || input.pressed || (!input.showsBodyState && input.isSelected); + return input.isHovered || (!input.showsBodyState && input.isSelected); } function fileHeaderInteractionStyle(input: { isHovered: boolean; - pressed: boolean; showsBodyState: boolean; isSelected: boolean; }) { @@ -217,8 +211,8 @@ export const FileHeader = memo(function FileHeader({ [file.path, onHeaderHeightChange], ), }); - const pressableStyle = useCallback( - ({ pressed }: PressableStateCallbackType) => [ + const pressableStyle = useMemo( + () => [ styles.header, !showsBodyState && workspaceTreeRowStyles.row, showsBodyState && styles.documentHeader, @@ -229,18 +223,14 @@ export const FileHeader = memo(function FileHeader({ : null, fileHeaderInteractionStyle({ isHovered: hover.isHovered, - pressed, showsBodyState, isSelected, }), ], [depth, hover.isHovered, isSelected, showsBodyState], ); - const canvasPressableStyle = useCallback( - (state: PressableStateCallbackType) => [ - pressableStyle(state), - canvasRendered && styles.canvasInteraction, - ], + const canvasPressableStyle = useMemo( + () => [pressableStyle, canvasRendered && styles.canvasInteraction], [canvasRendered, pressableStyle], ); const accessibilityState = useMemo( @@ -324,7 +314,7 @@ export const FileHeader = memo(function FileHeader({ } else { trigger = ( {renderedContent} diff --git a/packages/app/src/git/forge-shorthand/index.tsx b/packages/app/src/git/forge-shorthand/index.tsx index 5e40874c0a..81bbcbf12e 100644 --- a/packages/app/src/git/forge-shorthand/index.tsx +++ b/packages/app/src/git/forge-shorthand/index.tsx @@ -1,3 +1,4 @@ +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import { createContext, useCallback, useContext, useMemo, type ReactNode } from "react"; import { createForgeShorthand, type ForgeShorthand } from "./shorthand"; @@ -9,13 +10,27 @@ const ForgeShorthandContext = createContext(null); export function ForgeShorthandProvider({ forge, remoteUrl, + forgeWeb, children, }: { forge: string | null | undefined; remoteUrl: string | null | undefined; + forgeWeb: ForgeWeb | null | undefined; children: ReactNode; }) { - const value = useMemo(() => createForgeShorthand({ forge, remoteUrl }), [forge, remoteUrl]); + // Keyed on the strings: the descriptor hands over a new `forgeWeb` object whenever any + // other workspace field changes, and a new context value re-renders every Markdown message. + const webHost = forgeWeb?.host; + const referenceRepository = forgeWeb?.referenceRepository; + const value = useMemo( + () => + createForgeShorthand({ + forge, + remoteUrl, + forgeWeb: webHost ? { host: webHost, referenceRepository } : null, + }), + [forge, remoteUrl, webHost, referenceRepository], + ); return {children}; } diff --git a/packages/app/src/git/forge-shorthand/shorthand.test.ts b/packages/app/src/git/forge-shorthand/shorthand.test.ts index 7da4ea1014..f135bbd48a 100644 --- a/packages/app/src/git/forge-shorthand/shorthand.test.ts +++ b/packages/app/src/git/forge-shorthand/shorthand.test.ts @@ -22,6 +22,17 @@ describe("createForgeShorthand", () => { expect(gitlab.resolve("g/sub/q#3")).toBe("https://gitlab.com/g/sub/q/-/issues/3"); }); + it("links numbers to the repository the daemon says owns them, but keeps explicit references", () => { + const fork = createForgeShorthand({ + forge: "github", + remoteUrl: "git@github.com-work:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + })!; + + expect(fork.resolve("#123")).toBe("https://github.com/main-owner/repo/issues/123"); + expect(fork.resolve("acme/tools#4")).toBe("https://github.com/acme/tools/issues/4"); + }); + it("only recognizes the sigils the forge declares", () => { expect(matches(github, "see #1 and !2")).toEqual(["#1"]); expect(github.resolve("!2")).toBeNull(); diff --git a/packages/app/src/git/forge-shorthand/shorthand.ts b/packages/app/src/git/forge-shorthand/shorthand.ts index 84a97bfb29..0b4af83174 100644 --- a/packages/app/src/git/forge-shorthand/shorthand.ts +++ b/packages/app/src/git/forge-shorthand/shorthand.ts @@ -1,3 +1,4 @@ +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import type { ForgeReferenceSigil } from "@/git/client-forge-module"; import { forgeFromRemoteUrl } from "@/git/forge"; import { getClientForgeLogicModule } from "@/git/forges"; @@ -26,12 +27,15 @@ const REFERENCE = new RegExp(String.raw`^(?:(${REPO}))?([#!])(${NUMBER})$`); export function createForgeShorthand(input: { forge: string | null | undefined; remoteUrl: string | null | undefined; + forgeWeb?: ForgeWeb | null; }): ForgeShorthand | null { const remoteUrl = input.remoteUrl; const forge = input.forge || forgeFromRemoteUrl(remoteUrl); if (!forge || !remoteUrl) return null; const sigils = forgeSigils(forge).filter( - (sigil) => buildForgeReferenceUrl(forge, { remoteUrl, sigil, number: 1 }) !== null, + (sigil) => + buildForgeReferenceUrl(forge, { remoteUrl, forgeWeb: input.forgeWeb, sigil, number: 1 }) !== + null, ); if (sigils.length === 0) return null; return { @@ -41,6 +45,7 @@ export function createForgeShorthand(input: { if (!match) return null; return buildForgeReferenceUrl(forge, { remoteUrl, + forgeWeb: input.forgeWeb, repo: match[1] ?? null, sigil: match[2] as ForgeReferenceSigil, number: Number(match[3]), diff --git a/packages/app/src/git/forge-url.test.ts b/packages/app/src/git/forge-url.test.ts index e0deca00ff..c9efa7b9b0 100644 --- a/packages/app/src/git/forge-url.test.ts +++ b/packages/app/src/git/forge-url.test.ts @@ -326,3 +326,81 @@ describe("hasForgeWebUrls", () => { expect(hasForgeWebUrls("bitbucket")).toBe(false); }); }); + +describe("links resolved by the daemon (forgeWeb)", () => { + const sshAliasRemote = "git@github.com-work:acme/repo.git"; + + it("links #N on the web host the daemon resolved for an SSH config alias", () => { + expect( + buildForgeReferenceUrl("github", { + remoteUrl: sshAliasRemote, + forgeWeb: { host: "github.com" }, + sigil: "#", + number: 1, + }), + ).toBe("https://github.com/acme/repo/issues/1"); + }); + + it("opens the branch and a file on the resolved web host for an SSH config alias", () => { + const forgeWeb = { host: "github.com" }; + expect( + buildForgeBranchTreeUrl("github", { remoteUrl: sshAliasRemote, forgeWeb, branch: "main" }), + ).toBe("https://github.com/acme/repo/tree/main"); + expect( + buildForgeBlobUrl("github", { + remoteUrl: sshAliasRemote, + forgeWeb, + branch: "main", + path: "src/index.ts", + }), + ).toBe("https://github.com/acme/repo/blob/main/src/index.ts"); + }); + + it("links #N to the repository that owns the numbers, such as a fork's parent", () => { + expect( + buildForgeReferenceUrl("github", { + remoteUrl: "git@github.com:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + sigil: "#", + number: 123, + }), + ).toBe("https://github.com/main-owner/repo/issues/123"); + }); + + it("keeps an explicit owner/repo#N reference on the named repository", () => { + expect( + buildForgeReferenceUrl("github", { + remoteUrl: "git@github.com:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + repo: "other/tools", + sigil: "#", + number: 7, + }), + ).toBe("https://github.com/other/tools/issues/7"); + }); + + it("keeps the branch and file links on the origin repository for a fork", () => { + const input = { + remoteUrl: "git@github.com:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + branch: "feature/only-on-fork", + }; + expect(buildForgeBranchTreeUrl("github", input)).toBe( + "https://github.com/fork-owner/repo/tree/feature/only-on-fork", + ); + expect(buildForgeBlobUrl("github", { ...input, path: "a.ts" })).toBe( + "https://github.com/fork-owner/repo/blob/feature/only-on-fork/a.ts", + ); + }); + + it("keeps the scheme and port of a self-hosted http remote", () => { + expect( + buildForgeReferenceUrl("gitea", { + remoteUrl: "http://forge.test:3000/team/repo.git", + forgeWeb: { host: "forge.test", referenceRepository: "upstream/repo" }, + sigil: "#", + number: 12, + }), + ).toBe("http://forge.test:3000/upstream/repo/issues/12"); + }); +}); diff --git a/packages/app/src/git/forge-url.ts b/packages/app/src/git/forge-url.ts index 4fd86950e9..b56ed5d7d9 100644 --- a/packages/app/src/git/forge-url.ts +++ b/packages/app/src/git/forge-url.ts @@ -6,17 +6,23 @@ * format); an unknown forge has no grammar and yields null, so the action is * simply absent rather than wrong. * - * URL grammar lives on each client forge module. The repo identity and host - * both ride the manifest's `cloudHosts` only to canonicalize a cloud SSH alias - * (e.g. ssh.github.com -> github.com); a self-hosted host is used as-is. + * URL grammar lives on each client forge module. The daemon resolves the web + * host (SSH config aliases, cloud SSH hosts) and the repository that owns + * issue and change-request numbers (a fork's parent) and publishes them as + * `forgeWeb`; branch and file links stay on the origin repository. */ -import { getForgeDefinition } from "@getpaseo/protocol/forge-manifest"; -import { normalizeHost, parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; +import { + forgeWebHost, + isForgeCloudHost, + parseGitRemoteLocation, +} from "@getpaseo/protocol/git-remote"; +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import type { ForgeReferenceSigil } from "@/git/client-forge-module"; import { getClientForgeLogicModule } from "@/git/forges"; export interface ForgeBlobUrlInput { remoteUrl: string | null | undefined; + forgeWeb?: ForgeWeb | null; branch: string | null | undefined; path: string | null | undefined; lineStart?: number; @@ -25,12 +31,17 @@ export interface ForgeBlobUrlInput { export interface ForgeBranchTreeUrlInput { remoteUrl: string | null | undefined; + forgeWeb?: ForgeWeb | null; branch: string | null | undefined; } export interface ForgeReferenceUrlInput { remoteUrl: string | null | undefined; - /** Repository path of a cross-repository reference; the remote's repository when absent. */ + forgeWeb?: ForgeWeb | null; + /** + * Repository path of a cross-repository reference; the repository that owns + * issue numbers (`forgeWeb.referenceRepository`, else the remote's) when absent. + */ repo?: string | null; sigil: ForgeReferenceSigil; number: number; @@ -62,13 +73,6 @@ interface ForgeWebLocation { repo: string; } -/** - * Web host + repo path from a remote. The host is the remote's host, except a - * cloud SSH alias (a non-first entry in the forge's `cloudHosts`, e.g. - * ssh.github.com) is canonicalized to the forge's web host (`cloudHosts[0]`). - * Self-hosted hosts are returned untouched. The repo path supports nested - * groups (e.g. GitLab subgroups) since it is the full remote path. - */ function isValidRepoPath(path: string): boolean { const segments = path.split("/").filter((segment) => segment.length > 0); if (segments.length === 0) { @@ -77,9 +81,17 @@ function isValidRepoPath(path: string): boolean { return !segments.includes(".."); } +/** + * Web location of the origin repository. The host is the daemon's + * `forgeWeb.host`. A daemon without `forgeWeb` publishes none, so the remote's + * own host is used, with a cloud SSH alias mapped to the forge's web host. + * The repo path supports nested groups (e.g. GitLab subgroups) since it is + * the full remote path. + */ function resolveForgeWebLocation( forge: string, remoteUrl: string | null | undefined, + forgeWeb: ForgeWeb | null | undefined, ): ForgeWebLocation | null { if (!remoteUrl) { return null; @@ -88,9 +100,9 @@ function resolveForgeWebLocation( if (!location || !isValidRepoPath(location.path)) { return null; } - const cloudHosts = (getForgeDefinition(forge)?.cloudHosts ?? []).map(normalizeHost); - const isCloudHost = cloudHosts.includes(location.host); - const webHost = isCloudHost ? cloudHosts[0] : location.host; + // COMPAT(forgeWeb): added in v0.16.0, remove the remote-derived host after 2027-06-01 once daemon floor >= v0.16.0. + const webHost = forgeWeb?.host ?? forgeWebHost(forge, location.host); + const isCloudHost = isForgeCloudHost(forge, location.host); // Carry a non-default port only for a self-hosted http(s) origin (e.g. // `:60443`): the web UI shares that origin. An SSH/scp remote's port is not the // web port, and a canonicalized cloud host always serves on the default port. @@ -139,7 +151,7 @@ export function buildForgeBranchTreeUrl( input: ForgeBranchTreeUrlInput, ): string | null { const grammar = getClientForgeLogicModule(forge)?.urlGrammar; - const location = resolveForgeWebLocation(forge, input.remoteUrl); + const location = resolveForgeWebLocation(forge, input.remoteUrl, input.forgeWeb); const branch = input.branch?.trim(); if (!grammar || !location || !branch || branch === "HEAD") { return null; @@ -149,7 +161,7 @@ export function buildForgeBranchTreeUrl( export function buildForgeBlobUrl(forge: string, input: ForgeBlobUrlInput): string | null { const grammar = getClientForgeLogicModule(forge)?.urlGrammar; - const location = resolveForgeWebLocation(forge, input.remoteUrl); + const location = resolveForgeWebLocation(forge, input.remoteUrl, input.forgeWeb); const branch = input.branch?.trim(); const filePath = normalizeBlobPath(input.path); if (!grammar || !location || !branch || branch === "HEAD" || !filePath) { @@ -175,8 +187,8 @@ export function buildForgeReferenceUrl( const referencePath = getClientForgeLogicModule(forge)?.urlGrammar?.referencePaths?.find( (path) => path.sigil === input.sigil, ); - const location = resolveForgeWebLocation(forge, input.remoteUrl); - const repo = input.repo ?? location?.repo; + const location = resolveForgeWebLocation(forge, input.remoteUrl, input.forgeWeb); + const repo = input.repo ?? input.forgeWeb?.referenceRepository ?? location?.repo; if ( !referencePath || !location || diff --git a/packages/app/src/git/jump-to-file/index.tsx b/packages/app/src/git/jump-to-file/index.tsx index f3363b91ec..1746d02a76 100644 --- a/packages/app/src/git/jump-to-file/index.tsx +++ b/packages/app/src/git/jump-to-file/index.tsx @@ -6,7 +6,6 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { FolderTree } from "lucide-react-native"; import { AdaptiveModalSheet, - SHEET_HEADER_CLOSE_PADDING_SCALE, SHEET_HORIZONTAL_PADDING_SCALE, } from "@/components/adaptive-modal-sheet"; import { @@ -27,14 +26,11 @@ import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme"; // difference so a depth-0 file icon lands on the header glyph's rail. const TREE_LEADING_INSET = SPACING[SHEET_HORIZONTAL_PADDING_SCALE] - treeRowPaddingLeft(0); -// The header's close glyph sits at the content inset plus the button's own -// padding, while a tree row ends its trailing glyph at -// `WORKSPACE_PANE_TRAILING_GLYPH_RAIL`. The body carries the difference so row -// change icons land on the header X's rail. +// The header's close glyph ends on the sheet's content inset, while a tree row +// ends its trailing glyph at `WORKSPACE_PANE_TRAILING_GLYPH_RAIL`. The body +// carries the difference so row change icons land on the header X's rail. const TREE_TRAILING_INSET = - SPACING[SHEET_HORIZONTAL_PADDING_SCALE] + - SPACING[SHEET_HEADER_CLOSE_PADDING_SCALE] - - WORKSPACE_PANE_TRAILING_GLYPH_RAIL; + SPACING[SHEET_HORIZONTAL_PADDING_SCALE] - WORKSPACE_PANE_TRAILING_GLYPH_RAIL; const ThemedFolderTree = withUnistyles(FolderTree); diff --git a/packages/app/src/git/pull-request-panel/checks-section.tsx b/packages/app/src/git/pull-request-panel/checks-section.tsx index ad542c8695..a8b08a0281 100644 --- a/packages/app/src/git/pull-request-panel/checks-section.tsx +++ b/packages/app/src/git/pull-request-panel/checks-section.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo } from "react"; -import { Pressable, ScrollView, Text, View, type GestureResponderEvent } from "react-native"; +import { Pressable, Text, View, type GestureResponderEvent } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import { ChevronDown, ChevronRight, MessageSquarePlus } from "lucide-react-native"; @@ -18,12 +18,6 @@ import { useCheckGroupState } from "./check-group-state"; const ThemedChevronDown = withUnistyles(ChevronDown); const ThemedChevronRight = withUnistyles(ChevronRight); -/** - * Roughly eight rows. A repo with thirty checks would otherwise push the activity - * timeline off the pane entirely, so past this height the list scrolls in place. - */ -const LIST_MAX_HEIGHT = 268; - /** * The three statuses the pane has always labelled for tests. Skipped has no id because * nothing asserts on it. @@ -112,11 +106,7 @@ export function ChecksSection({
{open && summary.groups.length > 0 ? ( - + {summary.groups.map((group) => ( ))} - +
) : null}
); @@ -263,9 +253,6 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.foregroundMuted, }, list: { - maxHeight: LIST_MAX_HEIGHT, - }, - listContent: { paddingBottom: theme.spacing[2], }, groupHeader: { diff --git a/packages/app/src/git/pull-request-panel/pane.browser.test.tsx b/packages/app/src/git/pull-request-panel/pane.browser.test.tsx new file mode 100644 index 0000000000..a25b5c72a6 --- /dev/null +++ b/packages/app/src/git/pull-request-panel/pane.browser.test.tsx @@ -0,0 +1,231 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { within } from "@testing-library/dom"; +import { SafeAreaInsetsContext } from "react-native-safe-area-context"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { i18n } from "@/i18n/i18next"; +import { ToastApiProvider } from "@/contexts/toast-context"; +import type { ToastApi } from "@/components/toast-host"; +import type { PrPaneCheck, PrPaneData } from "./data"; +import { PullRequestPane } from "./pane"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +const PANE_HEIGHT = 600; + +const silentToasts: ToastApi = { + show: () => () => {}, + copied: () => {}, + error: () => {}, +}; + +let root: Root | null = null; +let container: HTMLDivElement | null = null; + +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +function successfulChecks(count: number): PrPaneCheck[] { + return Array.from({ length: count }, (_, index) => ({ + provider: "github", + name: `check-${index + 1}`, + status: "success", + url: `https://example.test/checks/${index + 1}`, + })); +} + +function pullRequest(checks: PrPaneCheck[]): PrPaneData { + return { + provider: { id: "github", label: "GitHub" }, + forge: "github", + number: 42, + repoOwner: "acme", + repoName: "widgets", + title: "Ship the widget", + state: "open", + url: "https://example.test/pull/42", + reviewDecision: "pending", + awaitingReviewers: [], + checks, + activity: [], + }; +} + +/** A phone's home indicator: the pane clears it with bottom padding. */ +const HOME_INDICATOR_INSETS = { top: 0, right: 0, bottom: 34, left: 0 }; + +const NO_INSETS = { top: 0, right: 0, bottom: 0, left: 0 }; + +function renderPane(data: PrPaneData, insets = NO_INSETS) { + act(() => + root?.render( + + + + + , + ), + ); +} + +function mountPane(data: PrPaneData, insets = NO_INSETS) { + container = document.createElement("div"); + container.style.height = `${PANE_HEIGHT}px`; + container.style.width = "600px"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + document.body.appendChild(container); + root = createRoot(container); + renderPane(data, insets); + const pane = container.querySelector('[data-testid="pr-pane"]'); + if (!pane) throw new Error("The pull request pane did not render"); + return pane; +} + +/** The pressable row holding the Activity title. */ +function activityHeader(pane: HTMLElement): HTMLElement { + const title = within(pane).getByText(i18n.t("workspace.git.pr.sections.activity")); + const header = title.closest("[tabindex]"); + if (!header) throw new Error("The Activity title is not inside a pressable header"); + return header; +} + +function checksRegionBottom(pane: HTMLElement): number { + return within(pane).getByRole("separator").getBoundingClientRect().top; +} + +/** Whether a user sees the element: no scroll container clips it out of view. */ +function isOnScreen(element: HTMLElement): boolean { + const rect = element.getBoundingClientRect(); + const hit = document.elementFromPoint(rect.left + 8, rect.top + rect.height / 2); + return hit !== null && element.contains(hit); +} + +/** React Native Web reports layout from a ResizeObserver, a frame or two after mounting. */ +async function settleLayout() { + for (let frame = 0; frame < 2; frame++) { + await act(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); + } +} + +/** Drags the separator through each offset from where it starts, releasing at the last one. */ +function dragSeparator(pane: HTMLElement, ...deltasY: number[]) { + const separator = within(pane).getByRole("separator"); + const rect = separator.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const startY = rect.top + rect.height / 2; + const pointer = { pointerId: 1, bubbles: true, cancelable: true, clientX: x, button: 0 }; + act(() => { + separator.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientY: startY })); + }); + for (const deltaY of deltasY) { + act(() => { + window.dispatchEvent( + new PointerEvent("pointermove", { ...pointer, clientY: startY + deltaY }), + ); + }); + } + const endY = startY + (deltasY.at(-1) ?? 0); + act(() => { + window.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientY: endY })); + }); +} + +describe("pull request pane layout", () => { + it("docks a collapsed Activity section to the bottom and gives the checks the pane", async () => { + const pane = mountPane(pullRequest(successfulChecks(10))); + + act(() => activityHeader(pane).click()); + + await expect + .poll(() => Math.round(activityHeader(pane).getBoundingClientRect().bottom)) + .toBe(Math.round(pane.getBoundingClientRect().bottom)); + const rows = within(pane).getAllByTestId("pr-pane-check-row"); + expect(rows).toHaveLength(10); + expect(rows.every(isOnScreen)).toBe(true); + }); + + it("keeps keyboard focus on the Activity header while it collapses and expands", () => { + const pane = mountPane(pullRequest(successfulChecks(3))); + const header = activityHeader(pane); + act(() => header.focus()); + + act(() => header.click()); + expect(document.activeElement).toBe(header); + act(() => header.click()); + expect(document.activeElement).toBe(header); + }); + + it("exposes whether Activity is expanded to assistive technology", () => { + const pane = mountPane(pullRequest(successfulChecks(3))); + expect(activityHeader(pane).getAttribute("aria-expanded")).toBe("true"); + + act(() => activityHeader(pane).click()); + + expect(activityHeader(pane).getAttribute("aria-expanded")).toBe("false"); + }); + + it("keeps the Activity header inside the pane when a dragged pane gets short", async () => { + const pane = mountPane(pullRequest(successfulChecks(30))); + await settleLayout(); + dragSeparator(pane, PANE_HEIGHT); + await settleLayout(); + + act(() => { + if (container) container.style.height = "160px"; + }); + await settleLayout(); + + await expect + .poll(() => activityHeader(pane).getBoundingClientRect().bottom) + .toBeLessThanOrEqual(pane.getBoundingClientRect().bottom); + expect(isOnScreen(activityHeader(pane))).toBe(true); + }); + + it.each([ + ["5px down", [5]], + ["400px down", [400]], + ["up past their end and back down", [-20, 100]], + ])("gives the checks their earlier share when they grow after a drag %s", async (_name, path) => { + const pane = mountPane(pullRequest(successfulChecks(2))); + await settleLayout(); + const drawn = checksRegionBottom(pane); + + dragSeparator(pane, ...path); + await settleLayout(); + expect(checksRegionBottom(pane)).toBeCloseTo(drawn, 0); + + renderPane(pullRequest(successfulChecks(30))); + await settleLayout(); + const overview = within(pane).getByTestId("pr-pane-overview"); + expect(overview.getBoundingClientRect().height).toBeCloseTo(PANE_HEIGHT / 2, 0); + }); + + it("resizes the checks against Activity by dragging the separator between them", async () => { + const pane = mountPane(pullRequest(successfulChecks(30))); + await settleLayout(); + const before = checksRegionBottom(pane); + + dragSeparator(pane, 120); + + await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120); + expect(activityHeader(pane).getBoundingClientRect().top).toBeGreaterThan(before + 100); + }); + + it("keeps the separator under the pointer when the pane clears a bottom inset", async () => { + const pane = mountPane(pullRequest(successfulChecks(30)), HOME_INDICATOR_INSETS); + await settleLayout(); + const before = checksRegionBottom(pane); + + dragSeparator(pane, 120); + + await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120); + }); +}); diff --git a/packages/app/src/git/pull-request-panel/pane.tsx b/packages/app/src/git/pull-request-panel/pane.tsx index 1f36a8749e..ff2b9c8682 100644 --- a/packages/app/src/git/pull-request-panel/pane.tsx +++ b/packages/app/src/git/pull-request-panel/pane.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useState } from "react"; -import { Image, Pressable, ScrollView, Text, View, type ViewStyle } from "react-native"; +import { Image, Pressable, Text, View, type ViewStyle } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { CircleCheck, @@ -74,13 +74,14 @@ import { type PrTimelineEntry, } from "./timeline"; import { - Section, + SectionHeader, SummaryPill, dangerColorMapping, foregroundMutedColorMapping, sectionKitStyles, successColorMapping, } from "./section-kit"; +import { PullRequestPaneSplit } from "./split"; const ThemedCircleCheck = withUnistyles(CircleCheck); const ThemedCircleX = withUnistyles(CircleX); @@ -478,8 +479,8 @@ export function PullRequestPane({ : null; return ( - - + + <> + + ) : null} + {activityLoading ? : null} + {!activityLoading && visibleEntries.length === 0 ? ( + {t("workspace.git.pr.empty.noActivity")} + ) : null} + {!activityLoading + ? visibleEntries.map(({ entry, collapsed }) => ( + - - - } - > - {timelineEntries.length > 0 && attachEnabled && visibleEntries.length > 0 ? ( - - - - ) : null} - {activityLoading ? : null} - {!activityLoading && visibleEntries.length === 0 ? ( - {t("workspace.git.pr.empty.noActivity")} - ) : null} - {!activityLoading - ? visibleEntries.map(({ entry, collapsed }) => ( - - )) - : null} - - - + )) + : null} +
+ ); } @@ -1192,15 +1193,6 @@ function ThreadComment({ } const styles = StyleSheet.create((theme) => ({ - root: { - flex: 1, - minHeight: 0, - backgroundColor: theme.colors.surfaceSidebar, - }, - scroll: { - flex: 1, - minHeight: 0, - }, invisible: { opacity: 0, }, @@ -1261,10 +1253,6 @@ const styles = StyleSheet.create((theme) => ({ marginLeft: theme.spacing[1], opacity: 0, }, - divider: { - height: 1, - backgroundColor: theme.colors.border, - }, toolbar: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/git/pull-request-panel/section-kit.tsx b/packages/app/src/git/pull-request-panel/section-kit.tsx index b4a9d00a3a..e28f0ac050 100644 --- a/packages/app/src/git/pull-request-panel/section-kit.tsx +++ b/packages/app/src/git/pull-request-panel/section-kit.tsx @@ -1,8 +1,9 @@ -import React, { type ReactNode } from "react"; +import React, { useMemo, type ReactNode } from "react"; import { Pressable, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import type { CountedCheckPresentation } from "@/git/check-presentation"; import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry"; +import { isWeb } from "@/constants/platform"; import { CheckPresentationIcon, getCheckPresentationTone, @@ -21,39 +22,57 @@ export const successColorMapping = (theme: Theme) => ({ color: theme.colors.stat export const dangerColorMapping = (theme: Theme) => ({ color: theme.colors.statusDanger }); export const warningColorMapping = (theme: Theme) => ({ color: theme.colors.statusWarning }); -interface SectionProps { +interface SectionHeaderProps { title: string; open: boolean; onToggle: () => void; summary: ReactNode; - children: ReactNode; accessibilityLabel?: string; } -export function Section({ +interface SectionProps extends SectionHeaderProps { + children: ReactNode; +} + +/** The disclosure row of a section, for layouts that place the section's body themselves. */ +export function SectionHeader({ title, open, onToggle, summary, - children, accessibilityLabel, -}: SectionProps) { +}: SectionHeaderProps) { + const accessibilityState = useMemo(() => ({ expanded: open }), [open]); + // React Native Web does not map `accessibilityState.expanded` to `aria-expanded`. + const webExpandedProps = useMemo( + () => (isWeb ? ({ "aria-expanded": open } as const) : null), + [open], + ); + return ( + + {open ? ( + + ) : ( + + )} + {title} + {summary} + + ); +} + +export function Section({ children, ...header }: SectionProps) { return ( - - {open ? ( - - ) : ( - - )} - {title} - {summary} - - {open ? {children} : null} + + {header.open ? {children} : null} ); } diff --git a/packages/app/src/git/pull-request-panel/split.tsx b/packages/app/src/git/pull-request-panel/split.tsx new file mode 100644 index 0000000000..1491e6d406 --- /dev/null +++ b/packages/app/src/git/pull-request-panel/split.tsx @@ -0,0 +1,162 @@ +import { Children, useCallback, useMemo, useState, type ReactNode } from "react"; +import { ScrollView, View, type LayoutChangeEvent } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { ResizeHandle } from "@/components/resize-handle"; + +/** Most of the pane the overview may take before it scrolls, until the user drags the separator. */ +const DEFAULT_OVERVIEW_SHARE = 0.5; +const SPLIT_GROUP_ID = "pr-pane"; + +interface PullRequestPaneSplitProps { + /** + * Exactly three children, in order: + * 1. the overview (the PR's header and checks), which scrolls in its own region; + * 2. the Activity disclosure row, docked to the bottom of the pane while collapsed; + * 3. the Activity timeline, filling the space below the separator while open. + * + * Slots are children because `react-perf/jsx-no-jsx-as-prop` rejects JSX in a prop. Pass all + * three unconditionally, the way `TreeRail` takes its slots. + */ + children: ReactNode; + activityOpen: boolean; +} + +/** + * Lays the pane out the way stacked sidebar sections behave: the overview and Activity share the + * height, a separator between them resizes the share, and a collapsed Activity gives its space + * back by docking its header to the bottom. + */ +export function PullRequestPaneSplit({ children, activityOpen }: PullRequestPaneSplitProps) { + const [overview, activityHeader, activityTimeline] = Children.toArray(children); + const insets = useSafeAreaInsets(); + const [overviewShare, setOverviewShare] = useState(DEFAULT_OVERVIEW_SHARE); + // The pointer's share while a drag is in progress. The saved share is decided once, when the + // drag ends, so moves along the way cannot overwrite the share the overview had before it. + const [dragShare, setDragShare] = useState(null); + const [splitHeight, setSplitHeight] = useState(0); + const [overviewHeight, setOverviewHeight] = useState(0); + const [overviewContentHeight, setOverviewContentHeight] = useState(0); + + const handleSplitLayout = useCallback((event: LayoutChangeEvent) => { + setSplitHeight(event.nativeEvent.layout.height); + }, []); + const handleOverviewLayout = useCallback((event: LayoutChangeEvent) => { + setOverviewHeight(event.nativeEvent.layout.height); + }, []); + const handleOverviewContentSizeChange = useCallback((_width: number, height: number) => { + setOverviewContentHeight(height); + }, []); + const handlePreviewResize = useCallback((_groupId: string, sizes: number[]) => { + const [share] = sizes; + if (share !== undefined) setDragShare(share); + }, []); + const handleResize = useCallback( + (_groupId: string, sizes: number[]) => { + setDragShare(null); + const [share] = sizes; + if (share === undefined || splitHeight <= 0) return; + const contentShare = overviewContentHeight / splitHeight; + setOverviewShare((current) => resolveDraggedShare(share, current, contentShare)); + }, + [overviewContentHeight, splitHeight], + ); + + // The overview stops at its content height, so a drag starts from where the separator is + // drawn rather than from the share the overview may grow to. + const separatorSizes = useMemo(() => { + const share = splitHeight > 0 ? overviewHeight / splitHeight : DEFAULT_OVERVIEW_SHARE; + return [share, 1 - share]; + }, [overviewHeight, splitHeight]); + // The Activity header docks to the bottom edge, so it clears the home indicator the way the + // Changes pane's docked Commits section does. The split is measured inside that padding: the + // overview's percentage height resolves against this box, so the drag must use the same one. + const rootStyle = useMemo(() => [styles.root, { paddingBottom: insets.bottom }], [insets.bottom]); + const drawnShare = dragShare ?? overviewShare; + const overviewStyle = useMemo( + () => + activityOpen + ? [styles.overviewShared, { maxHeight: `${drawnShare * 100}%` as const }] + : styles.overviewFill, + [activityOpen, drawnShare], + ); + + return ( + + + + {overview} + + {activityOpen ? ( + + ) : ( + + )} + {/* The header keeps one slot in both states, so toggling it does not remount the row + and drop keyboard focus. Only the timeline mounts and unmounts. */} + {activityHeader} + {activityOpen ? ( + + {activityTimeline} + + ) : null} + + + ); +} + +/** + * The share a drag leaves the overview. Short content stops the separator at the content's + * bottom, so a drag that ends there or below saves what was drawn and keeps any larger share + * the overview already had. The separator then neither jumps to the pointer nor stays pinned + * at the old content height when the content grows. + */ +function resolveDraggedShare(pointerShare: number, currentShare: number, contentShare: number) { + if (pointerShare < contentShare) return pointerShare; + return Math.max(currentShare, contentShare); +} + +const styles = StyleSheet.create((theme) => ({ + root: { + flex: 1, + minHeight: 0, + backgroundColor: theme.colors.surfaceSidebar, + }, + split: { + flex: 1, + minHeight: 0, + }, + overviewShared: { + flexGrow: 0, + flexShrink: 1, + minHeight: 0, + }, + overviewFill: { + flex: 1, + minHeight: 0, + }, + // Same 1px line the separator draws, so collapsing Activity does not move the boundary's look. + divider: { + height: 1, + backgroundColor: theme.colors.border, + }, + activityScroll: { + flex: 1, + minHeight: 0, + }, +})); diff --git a/packages/app/src/git/use-actions.tsx b/packages/app/src/git/use-actions.tsx index 13f7587623..649a8ec5ce 100644 --- a/packages/app/src/git/use-actions.tsx +++ b/packages/app/src/git/use-actions.tsx @@ -209,6 +209,8 @@ interface UseGitActionsResult { gitActions: GitActions; branchLabel: string; isGit: boolean; + /** Archives this workspace, Git or not. Null while it cannot be archived. */ + archiveWorkspace: (() => void) | null; } interface UseWorkspaceScreenArchiveControllerInput { @@ -266,6 +268,13 @@ function canArchiveWorkspace( ); } +function availableArchive( + controller: { canArchive: boolean; isArchiving: boolean }, + archive: () => void, +): (() => void) | null { + return controller.canArchive && !controller.isArchiving ? archive : null; +} + function useWorkspaceScreenArchiveController({ serverId, activeWorkspaceSelection, @@ -291,21 +300,13 @@ function useWorkspaceScreenArchiveController({ serverId, workspaceId: workspaceDescriptor?.id ?? "", workspaceKind: workspaceDescriptor?.workspaceKind ?? "directory", + workspaceDirectory: workspaceDescriptor?.workspaceDirectory ?? "", name: workspaceDescriptor?.name ?? branchLabel, - isDirty: archiveRisk.isDirty, - aheadOfOrigin: archiveRisk.aheadOfOrigin, diffStat: workspaceDescriptor?.diffStat ?? null, warningLabels: getWorktreeArchiveWarningLabels(t), onSetHiding: setIsHidingWorkspace, - onArchiveStarted: () => { - if (!activeWorkspaceSelection) { - return; - } - redirectIfArchivingActiveWorkspace({ - serverId, - workspaceId: activeWorkspaceSelection.workspaceId, - activeWorkspaceSelection, - }); + onArchiveStarted: (archived) => { + redirectIfArchivingActiveWorkspace({ ...archived, activeWorkspaceSelection }); }, }); @@ -872,7 +873,12 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use [gitActionsInput, baseRefLabel, hasPullRequest, forge, t], ); - return { gitActions, branchLabel, isGit }; + return { + gitActions, + branchLabel, + isGit, + archiveWorkspace: availableArchive(archiveController, handleArchiveWorkspace), + }; } function translateGitActions( diff --git a/packages/app/src/git/worktree-archive-warning.test.ts b/packages/app/src/git/worktree-archive-warning.test.ts index ddf60c7746..185c37dcb1 100644 --- a/packages/app/src/git/worktree-archive-warning.test.ts +++ b/packages/app/src/git/worktree-archive-warning.test.ts @@ -1,11 +1,87 @@ import { describe, expect, it } from "vitest"; +import type { CheckoutStatusClient, CheckoutStatusPayload } from "@/git/checkout-status-cache"; import { buildWorktreeArchiveConfirmationMessage, buildWorktreeArchiveRiskReasons, + readWorktreeArchiveRisk, toWorktreeArchiveRisk, } from "@/git/worktree-archive-warning"; +const WORKTREE = "/home/me/.paseo/worktrees/repo/feature"; + +function hostAnswering(status: CheckoutStatusPayload): CheckoutStatusClient & { asked: string[] } { + const asked: string[] = []; + return { + asked, + getCheckoutStatus: async (cwd) => { + asked.push(cwd); + return status; + }, + }; +} + +const NOT_GIT = { + cwd: WORKTREE, + requestId: "status", + isGit: false, + isPaseoOwnedWorktree: false, + repoRoot: null, + currentBranch: null, + isDirty: null, + baseRef: null, + aheadBehind: null, + aheadOfOrigin: null, + behindOfOrigin: null, + hasRemote: false, + remoteUrl: null, + error: null, +} satisfies CheckoutStatusPayload; + +describe("reading a worktree's archive risk from its host", () => { + it("reads uncommitted changes and unpushed commits from the worktree's checkout status", async () => { + const host = hostAnswering({ + cwd: WORKTREE, + requestId: "status", + isGit: true, + isPaseoOwnedWorktree: true, + repoRoot: WORKTREE, + mainRepoRoot: "/home/me/repo", + currentBranch: "feature", + isDirty: true, + baseRef: "main", + aheadBehind: { ahead: 2, behind: 0 }, + aheadOfOrigin: 2, + behindOfOrigin: 0, + hasRemote: true, + remoteUrl: "git@example.com:me/repo.git", + error: null, + }); + + expect(await readWorktreeArchiveRisk(host, WORKTREE)).toEqual({ + isDirty: true, + aheadOfOrigin: 2, + }); + expect(host.asked).toEqual([WORKTREE]); + }); + + it("finds nothing to lose in a directory that is no longer a git checkout", async () => { + expect(await readWorktreeArchiveRisk(hostAnswering(NOT_GIT), WORKTREE)).toEqual({ + isDirty: false, + aheadOfOrigin: null, + }); + }); + + it("rejects with the host's error when it can't read the worktree", async () => { + const host = hostAnswering({ + ...NOT_GIT, + error: { code: "UNKNOWN", message: "git status failed" }, + }); + + await expect(readWorktreeArchiveRisk(host, WORKTREE)).rejects.toThrow("git status failed"); + }); +}); + describe("workspace archive warning for worktree backing", () => { it("does not require a confirmation for clean and pushed worktrees", () => { expect( diff --git a/packages/app/src/git/worktree-archive-warning.ts b/packages/app/src/git/worktree-archive-warning.ts index f7405cd2bd..3935eef3cd 100644 --- a/packages/app/src/git/worktree-archive-warning.ts +++ b/packages/app/src/git/worktree-archive-warning.ts @@ -1,3 +1,4 @@ +import type { CheckoutStatusClient } from "@/git/checkout-status-cache"; import { confirmDialog } from "@/utils/confirm-dialog"; import { i18n } from "@/i18n/i18next"; @@ -49,6 +50,21 @@ export const DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS: WorktreeArchiveWarningLabe : i18n.t("workspace.git.actions.archiveWarning.unpushedCommits", { count }), }; +/** + * Reads the worktree's uncommitted changes and unpushed commits from its host. A directory the + * host no longer reads as a git checkout has neither. Rejects when the host can't read it. + */ +export async function readWorktreeArchiveRisk( + client: CheckoutStatusClient, + workspaceDirectory: string, +): Promise> { + const status = await client.getCheckoutStatus(workspaceDirectory); + if (status.error) { + throw new Error(status.error.message); + } + return { isDirty: status.isDirty ?? false, aheadOfOrigin: status.aheadOfOrigin }; +} + export function toWorktreeArchiveRisk(input: WorktreeArchiveRiskInput): WorktreeArchiveRisk { return { isDirty: input.archiveHasUncommittedChanges, diff --git a/packages/app/src/hooks/pointer-capabilities.test.ts b/packages/app/src/hooks/pointer-capabilities.test.ts index 167db7c553..412eff7924 100644 --- a/packages/app/src/hooks/pointer-capabilities.test.ts +++ b/packages/app/src/hooks/pointer-capabilities.test.ts @@ -23,10 +23,18 @@ class FakeMediaQueryList { } } -function createFakeDisplay(initial: { finePointer: boolean; touchScreen: boolean }) { +function createFakeDisplay(initial: { + finePointer: boolean; + touchScreen: boolean; + touchPrimaryPointer?: boolean; +}) { const queries = { finePointer: new FakeMediaQueryList("(hover: hover) and (pointer: fine)", initial.finePointer), touchScreen: new FakeMediaQueryList("(any-pointer: coarse)", initial.touchScreen), + touchPrimaryPointer: new FakeMediaQueryList( + "(pointer: coarse)", + initial.touchPrimaryPointer ?? false, + ), }; const matchMedia = (query: string) => { const match = Object.values(queries).find((list) => list.media === query); @@ -75,3 +83,25 @@ describe("pointer capabilities", () => { }); }); }); + +describe("hasTouchPrimaryPointer", () => { + it("is false on a touch-screen laptop driven by its trackpad", () => { + const display = createFakeDisplay({ finePointer: true, touchScreen: true }); + expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe( + false, + ); + }); + + it("is true when the primary pointer is coarse", () => { + const display = createFakeDisplay({ + finePointer: false, + touchScreen: true, + touchPrimaryPointer: true, + }); + expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe(true); + }); + + it("is false without media queries", () => { + expect(createPointerCapabilitiesSource(null).hasTouchPrimaryPointer()).toBe(false); + }); +}); diff --git a/packages/app/src/hooks/pointer-capabilities.ts b/packages/app/src/hooks/pointer-capabilities.ts index 360ff88c24..bc6d802ac0 100644 --- a/packages/app/src/hooks/pointer-capabilities.ts +++ b/packages/app/src/hooks/pointer-capabilities.ts @@ -8,6 +8,7 @@ import { isWeb } from "@/constants/platform"; // (detachable keyboards, tablet mode, devtools touch emulation). const FINE_POINTER_QUERY = "(hover: hover) and (pointer: fine)"; const TOUCH_SCREEN_QUERY = "(any-pointer: coarse)"; +const TOUCH_PRIMARY_POINTER_QUERY = "(pointer: coarse)"; export interface PointerCapabilities { /** A mouse-like pointer drives the UI. */ @@ -21,6 +22,7 @@ type MatchMedia = (query: string) => MediaQueryList; export interface PointerCapabilitiesSource { getSnapshot: () => PointerCapabilities; subscribe: (onChange: () => void) => () => void; + hasTouchPrimaryPointer: () => boolean; } export function createPointerCapabilitiesSource( @@ -28,9 +30,11 @@ export function createPointerCapabilitiesSource( ): PointerCapabilitiesSource { const finePointerQuery = matchMedia?.(FINE_POINTER_QUERY) ?? null; const touchScreenQuery = matchMedia?.(TOUCH_SCREEN_QUERY) ?? null; + const touchPrimaryPointerQuery = matchMedia?.(TOUCH_PRIMARY_POINTER_QUERY) ?? null; let snapshot: PointerCapabilities = { finePointer: false, touchScreen: false }; return { + hasTouchPrimaryPointer: () => touchPrimaryPointerQuery?.matches ?? false, getSnapshot() { const finePointer = finePointerQuery?.matches ?? false; const touchScreen = touchScreenQuery?.matches ?? false; @@ -61,6 +65,7 @@ const NATIVE_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: false, t const nativeSource: PointerCapabilitiesSource = { getSnapshot: () => NATIVE_POINTER_CAPABILITIES, subscribe: () => () => {}, + hasTouchPrimaryPointer: () => true, }; const source = isWeb ? createPointerCapabilitiesSource(browserMatchMedia()) : nativeSource; @@ -79,10 +84,11 @@ export function hasFinePointer(): boolean { return source.getSnapshot().finePointer; } -/** Touch sizing remains enabled on hybrid browsers that report touch points. */ -export function hasTouchScreen(): boolean { - return ( - source.getSnapshot().touchScreen || - (isWeb && typeof window !== "undefined" && window.navigator.maxTouchPoints > 0) - ); +/** + * True when touch is the primary input, read at call time. iPadOS keeps touch primary with a + * trackpad attached; a laptop with a touch screen that its trackpad drives reports a fine primary + * pointer. + */ +export function hasTouchPrimaryPointer(): boolean { + return source.hasTouchPrimaryPointer(); } diff --git a/packages/app/src/hooks/use-agent-history.ts b/packages/app/src/hooks/use-agent-history.ts index efd17c74b3..b28f5e5a0c 100644 --- a/packages/app/src/hooks/use-agent-history.ts +++ b/packages/app/src/hooks/use-agent-history.ts @@ -3,9 +3,10 @@ import type { FetchAgentHistoryOptions, FetchAgentHistoryPageInfo, } from "@getpaseo/client/internal/daemon-client"; -import { useInfiniteQuery } from "@tanstack/react-query"; +import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query"; import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; +import { useShallow } from "zustand/shallow"; import type { AggregatedAgent } from "@/hooks/use-aggregated-agents"; import { getHostRuntimeStore, @@ -34,6 +35,8 @@ export interface AgentHistoryResult { isSearchSupported: boolean; /** More sessions matched than the ranked page holds. Narrow the query. */ isSearchTruncated: boolean; + /** The agents answer the previous query; the current one is loading (`keepPreviousResults`). */ + isPreviousResults: boolean; /** Hosts that failed while others succeeded. The list still renders. */ hostErrors: AgentHistoryHostError[]; refreshAll: () => Promise; @@ -222,6 +225,13 @@ export function useAgentHistory(options: { serverId?: string | null; enabled?: boolean; search?: string; + /** + * Leave out hosts that predate search, instead of searching no host. For a surface that adds + * history matches to other results, where a missing host is not a claim of "no matches". + */ + searchableHostsOnly?: boolean; + /** Keep the previous query's results until the next query's arrive. */ + keepPreviousResults?: boolean; }): AgentHistoryResult { const { t } = useTranslation(); const daemons = useHosts(); @@ -231,10 +241,18 @@ export function useAgentHistory(options: { return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; }, [options.serverId]); const enabled = options.enabled ?? true; - const serverIds = useMemo( + const requestedServerIds = useMemo( () => (serverId ? [serverId] : daemons.map((daemon) => daemon.serverId)), [daemons, serverId], ); + const searchableServerIds = useSessionStore( + useShallow((state) => + requestedServerIds.filter( + (id) => state.sessions[id]?.serverInfo?.features?.agentHistorySearch === true, + ), + ), + ); + const serverIds = options.searchableHostsOnly ? searchableServerIds : requestedServerIds; const connectionStatuses = useHostRuntimeConnectionStatuses(serverIds); // A host the user asked about splits two ways: one this fetch can reach, and // one whose sessions will be missing from the answer. Both come out of here, @@ -287,6 +305,7 @@ export function useAgentHistory(options: { [daemons], ); + const queryEnabled = Boolean(enabled && targetHosts.length > 0); const historyQuery = useInfiniteQuery< AgentHistoryBatchPage, Error, @@ -295,8 +314,11 @@ export function useAgentHistory(options: { AgentHistoryCursorByServerId | null >({ queryKey, - enabled: Boolean(enabled && targetHosts.length > 0), + enabled: queryEnabled, staleTime: 30_000, + // Previous results stand in only until the next query's arrive. With no host to search, + // nothing will arrive, so they would stand in, and read as still loading, indefinitely. + ...(options.keepPreviousResults && queryEnabled ? { placeholderData: keepPreviousData } : {}), initialPageParam: null, getNextPageParam: getNextAgentHistoryPageParam, queryFn: async ({ pageParam }) => { @@ -318,6 +340,7 @@ export function useAgentHistory(options: { isFetching, isFetchingNextPage, isLoading, + isPlaceholderData, refetch, } = historyQuery; @@ -363,6 +386,7 @@ export function useAgentHistory(options: { isLoadingMore: isFetchingNextPage, isSearchSupported, isSearchTruncated, + isPreviousResults: isPlaceholderData, hostErrors, refreshAll, loadMore, diff --git a/packages/app/src/hooks/use-aggregated-agents.ts b/packages/app/src/hooks/use-aggregated-agents.ts index 910caf1d64..ffce971ca6 100644 --- a/packages/app/src/hooks/use-aggregated-agents.ts +++ b/packages/app/src/hooks/use-aggregated-agents.ts @@ -1,10 +1,11 @@ -import { useMemo, useCallback, useEffect, useRef, useSyncExternalStore } from "react"; +import { useMemo, useCallback, useRef, useSyncExternalStore } from "react"; import equal from "fast-deep-equal"; import { useShallow } from "zustand/shallow"; import { useSessionStore } from "@/stores/session-store"; import type { AgentDirectoryEntry } from "@/types/agent-directory"; import type { Agent } from "@/stores/session-store"; import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime"; +import { useAllDirectoryDemand } from "./use-directory-demand"; export interface AggregatedAgent extends AgentDirectoryEntry { serverId: string; @@ -19,6 +20,9 @@ export interface AggregatedAgentsResult { refreshAll: () => void; } +const NO_AGENT_MAPS: Record | undefined> = Object.freeze({}); +const NO_AGENTS: AggregatedAgent[] = []; + export function useAggregatedAgents(options?: { includeArchived?: boolean; demand?: boolean; @@ -28,19 +32,21 @@ export function useAggregatedAgents(options?: { const includeArchived = options?.includeArchived ?? false; const demand = options?.demand ?? true; const serverIds = useMemo(() => daemons.map((daemon) => daemon.serverId), [daemons]); - useEffect(() => { - if (!demand) return; - const releases = serverIds.map((serverId) => runtime.acquireDirectoryDemand(serverId)); - return () => releases.forEach((release) => release()); - }, [demand, runtime, serverIds]); + useAllDirectoryDemand({ serverIds, enabled: demand }); const runtimeVersion = useSyncExternalStore( (onStoreChange) => runtime.subscribeAll(onStoreChange), () => runtime.getVersion(), () => runtime.getVersion(), ); + // The caller has said it does not need the directory, so stay off the agent maps entirely: + // every map change otherwise re-renders this hook and rebuilds the whole list for a surface + // that is not on screen (the command center while it is closed). const sessionAgents = useSessionStore( useShallow((state) => { + if (!demand) { + return NO_AGENT_MAPS; + } const result: Record | undefined> = {}; for (const [serverId, session] of Object.entries(state.sessions)) { result[serverId] = session.agents; @@ -64,6 +70,16 @@ export function useAggregatedAgents(options?: { const result = useMemo(() => { // runtimeVersion is referenced so the memo recomputes when runtime state changes. void runtimeVersion; + if (!demand) { + prevAgentsRef.current = new Map(); + prevSortedRef.current = NO_AGENTS; + return { + agents: NO_AGENTS, + isLoading: false, + isInitialLoad: false, + isRevalidating: false, + }; + } const allAgents: AggregatedAgent[] = []; const serverLabelById = new Map( daemons.map((daemon) => [daemon.serverId, daemon.label] as const), @@ -158,7 +174,7 @@ export function useAggregatedAgents(options?: { isInitialLoad, isRevalidating, }; - }, [daemons, includeArchived, runtime, runtimeVersion, sessionAgents]); + }, [daemons, demand, includeArchived, runtime, runtimeVersion, sessionAgents]); return { ...result, diff --git a/packages/app/src/hooks/use-directory-demand.ts b/packages/app/src/hooks/use-directory-demand.ts index f4d2953ab0..b9e8ccb9a2 100644 --- a/packages/app/src/hooks/use-directory-demand.ts +++ b/packages/app/src/hooks/use-directory-demand.ts @@ -14,3 +14,21 @@ export function useDirectoryDemand(serverId: string | null | undefined): void { return getHostRuntimeStore().acquireDirectoryDemand(serverId); }, [serverId]); } + +/** + * Holds directory demand for several hosts at once, so a caller that needs the whole fleet + * (the favicon, the aggregated agent list) does not have to subscribe to every agent map to + * keep the directories loading. + */ +export function useAllDirectoryDemand(input: { + serverIds: readonly string[]; + enabled: boolean; +}): void { + const { serverIds, enabled } = input; + useEffect(() => { + if (!enabled) return; + const runtime = getHostRuntimeStore(); + const releases = serverIds.map((serverId) => runtime.acquireDirectoryDemand(serverId)); + return () => releases.forEach((release) => release()); + }, [enabled, serverIds]); +} diff --git a/packages/app/src/hooks/use-favicon-status.ts b/packages/app/src/hooks/use-favicon-status.ts index 5fcce9a24c..f6e8ac6693 100644 --- a/packages/app/src/hooks/use-favicon-status.ts +++ b/packages/app/src/hooks/use-favicon-status.ts @@ -1,12 +1,14 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { getIsElectronRuntimeMac } from "@/constants/layout"; -import { useAggregatedAgents } from "./use-aggregated-agents"; +import { useAllDirectoryDemand } from "./use-directory-demand"; import { getDesktopHost } from "@/desktop/host"; -import { useWorkspaceStatusesForBadges } from "@/stores/session-store-hooks"; -import { deriveMacDockBadgeCountFromWorkspaceStatuses } from "@/utils/desktop-badge-state"; +import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state"; +import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status"; import { isNative } from "@/constants/platform"; +import { useSessionStore } from "@/stores/session-store"; +import { useSidebarViewStore } from "@/stores/sidebar-view-store"; +import { useHosts } from "@/runtime/host-runtime"; -type FaviconStatus = "none" | "running" | "attention"; type ColorScheme = "dark" | "light"; /* eslint-disable @typescript-eslint/no-require-imports */ @@ -24,21 +26,6 @@ const FAVICON_IMAGES: Record["agents"], -): FaviconStatus { - const hasRunning = agents.some((agent) => agent.status === "running"); - if (hasRunning) { - return "running"; - } - const hasAttention = agents.some((agent) => agent.requiresAttention); - const hasNeedsInput = agents.some((agent) => (agent.pendingPermissionCount ?? 0) > 0); - if (hasAttention || hasNeedsInput) { - return "attention"; - } - return "none"; -} - function getFaviconUri(status: FaviconStatus, colorScheme: ColorScheme): string { const image = FAVICON_IMAGES[colorScheme][status]; if (typeof image === "object" && "uri" in image) { @@ -94,8 +81,23 @@ async function updateMacDockBadge(count?: number) { } export function useFaviconStatus() { - const { agents } = useAggregatedAgents({ demand: !isNative }); - const workspaceStatuses = useWorkspaceStatusesForBadges(); + const daemons = useHosts(); + const serverIds = useMemo(() => daemons.map((daemon) => daemon.serverId), [daemons]); + // The favicon reads the whole fleet, so it has to keep every host's directory loading even + // though it no longer subscribes to the agent maps. + useAllDirectoryDemand({ serverIds, enabled: !isNative }); + // Background workspaces count exactly when the sidebar shows them. + const showBackground = useSidebarViewStore((state) => state.showBackground); + const selectFaviconStatus = useMemo( + () => createFaviconStatusSelector({ showBackground }), + [showBackground], + ); + const selectMacDockBadgeCount = useMemo( + () => createMacDockBadgeCountSelector({ showBackground }), + [showBackground], + ); + const status = useSessionStore(selectFaviconStatus); + const dockBadgeCount = useSessionStore(selectMacDockBadgeCount); const [colorScheme, setColorScheme] = useState(getSystemColorScheme); const lastDockBadgeCountRef = useRef(undefined); @@ -112,17 +114,15 @@ export function useFaviconStatus() { return () => mediaQuery.removeEventListener("change", handler); }, []); - // Update favicon when agents or color scheme changes useEffect(() => { if (isNative) return; - - const status = deriveFaviconStatus(agents); updateFavicon(status, colorScheme); + }, [status, colorScheme]); - const dockBadgeCount = deriveMacDockBadgeCountFromWorkspaceStatuses(workspaceStatuses); - if (dockBadgeCount !== lastDockBadgeCountRef.current) { - lastDockBadgeCountRef.current = dockBadgeCount; - void updateMacDockBadge(dockBadgeCount); - } - }, [agents, colorScheme, workspaceStatuses]); + useEffect(() => { + if (isNative) return; + if (dockBadgeCount === lastDockBadgeCountRef.current) return; + lastDockBadgeCountRef.current = dockBadgeCount; + void updateMacDockBadge(dockBadgeCount); + }, [dockBadgeCount]); } diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index 0b169b5214..8f426f9f2b 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -330,6 +330,8 @@ describe("loadAppSettingsFromStorage", () => { displayAs: "used", pins: null, serverId: null, + cardOrder: [], + cardsOff: [], }); const deps = makeDeps({ @@ -354,6 +356,8 @@ describe("loadAppSettingsFromStorage", () => { { sourceId: "claude", windowId: "five-hour" }, ], serverId: "server", + cardOrder: [], + cardsOff: [], }); }); @@ -369,6 +373,8 @@ describe("loadAppSettingsFromStorage", () => { displayAs: "remaining", pins: [], serverId: "server", + cardOrder: [], + cardsOff: [], }); }); @@ -389,6 +395,8 @@ describe("loadAppSettingsFromStorage", () => { displayAs: "used", pins: [{ sourceId: "claude", windowId: "weekly" }], serverId: null, + cardOrder: [], + cardsOff: [], }); }); diff --git a/packages/app/src/hooks/use-settings/storage.ts b/packages/app/src/hooks/use-settings/storage.ts index 424536ac69..f04b7b6d94 100644 --- a/packages/app/src/hooks/use-settings/storage.ts +++ b/packages/app/src/hooks/use-settings/storage.ts @@ -96,6 +96,8 @@ export interface AppSettings { sidebarWorkspaceTrailing: SidebarWorkspaceTrailing; sidebarRowItems: SidebarRowItems; sidebarChecksDisplay: SidebarChecksDisplay; + /** Plugin workspace row badge items by `/`; a missing key shows. */ + sidebarPluginRowBadgeItems: Record; /** Top-level sidebar rows in display order; empty means the default order, all visible. */ sidebarNavItems: SidebarNavPreference[]; /** Sidebar footer items in display order; empty means the default order, all visible. */ @@ -156,6 +158,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = { sidebarWorkspaceTrailing: "timestamp", sidebarRowItems: DEFAULT_SIDEBAR_ROW_ITEMS, sidebarChecksDisplay: DEFAULT_SIDEBAR_CHECKS_DISPLAY, + sidebarPluginRowBadgeItems: {}, sidebarNavItems: [], sidebarFooterItems: [], usage: DEFAULT_USAGE_PREFERENCES, @@ -253,6 +256,7 @@ const StoredAppSettingsSchema = z .enum(["iconAndText", "icon", "none"]) .optional() .catch(DEFAULT_SIDEBAR_CHECKS_DISPLAY), + sidebarPluginRowBadgeItems: z.record(z.string(), z.boolean()).catch({}), sidebarNavItems: z.array(z.object({ key: z.string(), visible: z.boolean() })).catch([]), sidebarFooterItems: z.array(z.object({ key: z.string(), visible: z.boolean() })).catch([]), usage: UsagePreferencesSchema, diff --git a/packages/app/src/hosts/add-host/internal/add-host-modal.tsx b/packages/app/src/hosts/add-host/internal/add-host-modal.tsx index 5379e5f4bd..f9ea7a2f86 100644 --- a/packages/app/src/hosts/add-host/internal/add-host-modal.tsx +++ b/packages/app/src/hosts/add-host/internal/add-host-modal.tsx @@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod {t("pairing.direct.fields.host")} - {t("pairing.direct.fields.port")} - {t("pairing.direct.fields.password")} - {t("pairing.direct.advanced.label")} {isAdvancedOpen ? ( - ({ const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted })); const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted })); - -const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, -})); diff --git a/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx b/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx index f817bdc5cf..02653010ba 100644 --- a/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx +++ b/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx @@ -212,7 +212,7 @@ function PairLinkModalContent({ {t("pairing.link.label")} - {t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })} - @@ -275,7 +277,3 @@ function PairLinkModalContent({ } const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground })); - -const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, -})); diff --git a/packages/app/src/i18n/resources.test.ts b/packages/app/src/i18n/resources.test.ts index af4c059fb2..7eb0072736 100644 --- a/packages/app/src/i18n/resources.test.ts +++ b/packages/app/src/i18n/resources.test.ts @@ -319,15 +319,15 @@ describe("translation resources", () => { expect(en.shell.menu.toggleSidebar).toBe("Toggle sidebar"); expect(en.shell.menu.open).toBe("Open menu"); expect(en.shell.menu.close).toBe("Close menu"); - expect(en.shell.commandCenter.placeholder).toBe( - "Search commands, files, workspaces, and agents...", - ); + expect(en.shell.commandCenter.placeholder).toBe("Search workspaces, files, and actions..."); + expect(en.shell.commandCenter.placeholderWithoutFiles).toBe("Search workspaces and actions..."); expect(en.shell.commandCenter.filePlaceholder).toBe("Search files..."); expect(en.shell.commandCenter.files).toBe("Files"); expect(en.shell.commandCenter.noMatches).toBe("No matches"); expect(en.shell.commandCenter.actions).toBe("Actions"); expect(en.shell.commandCenter.workspaces).toBe("Workspaces"); - expect(en.shell.commandCenter.agents).toBe("Agents"); + expect(en.shell.commandCenter.recentWorkspaces).toBe("Recent workspaces"); + expect(en.shell.commandCenter.tabs.all).toBe("All"); expect(en.shell.commandCenter.newAgent).toBe("New agent"); expect(en.shell.commandCenter.addProject).toBe("Add project"); expect(en.shell.commandCenter.home).toBe("Home"); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 498dc66e22..4dc4784e07 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -90,14 +90,23 @@ export const ar: TranslationResources = { close: "إغلاق القائمة", }, commandCenter: { - placeholder: "ابحث في الأوامر والملفات ومساحات العمل والوكلاء...", + placeholder: "البحث في مساحات العمل والملفات والإجراءات...", + placeholderWithoutFiles: "البحث في مساحات العمل والإجراءات...", filePlaceholder: "البحث في الملفات...", + workspacePlaceholder: "البحث في مساحات العمل...", + actionPlaceholder: "البحث في الإجراءات...", searchingFiles: "جارٍ البحث في الملفات...", noMatches: "لا توجد مباريات", actions: "الإجراءات", files: "الملفات", workspaces: "مساحات العمل", - agents: "الوكلاء", + recentWorkspaces: "مساحات العمل الأخيرة", + tabs: { + all: "الكل", + workspaces: "مساحات العمل", + files: "الملفات", + actions: "الإجراءات", + }, newAgent: "وكيل جديد", open: "فتح {{name}}", openInSidePane: "فتح {{name}} في اللوحة الجانبية", @@ -261,7 +270,7 @@ export const ar: TranslationResources = { states: { notFound: "لم يتم العثور على Agent", failedToLoad: "فشل تحميل الوكيل", - reconnecting: "جارٍ إعادة الاتصال بالمضيف", + reconnecting: "جارٍ إعادة الاتصال", updating: "جارٍ تحديث الرسائل", timelineSyncFailed: "تعذر تحديث سجل الوكيل.", timelineSyncRetrying: "جارٍ إعادة المحاولة…", @@ -385,6 +394,7 @@ export const ar: TranslationResources = { otherPlaceholder: "آخر...", }, backgroundWork: { + heartbeat: "نبضة دورية", pillOne: "مهمة واحدة في الخلفية", pillMany: "{{count}} مهمة في الخلفية", notRunning: "لم يعد قيد التشغيل", @@ -475,8 +485,7 @@ export const ar: TranslationResources = { archivedTitle: "مساحة العمل مؤرشفة", restoreDescription: "استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.", - restoreWithoutBranchDescription: - "استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.", + restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.", unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.", restoreAction: "استعادة", unarchiveAction: "إلغاء الأرشفة", @@ -2008,6 +2017,7 @@ export const ar: TranslationResources = { hostUnavailable: "مضيف التنزيل غير متاح.", cancelled: "تم إلغاء التنزيل.", failed: "فشل تنزيل الملف.", + httpFailed: "فشل تنزيل الملف (HTTP {{status}}).", shareFile: "مشاركة الملف", shareFileNamed: "مشاركة{{fileName}}", }, @@ -2201,6 +2211,7 @@ export const ar: TranslationResources = { turnOn: "تشغيل", options: "الإعدادات", + host: "المضيف", refreshFailed: "تعذّر تحديث الاستخدام", noHosts: "لا توجد مضيفات متصلة", agentError: "تعذّر تحميل الاستخدام: {{reason}}", @@ -2217,6 +2228,8 @@ export const ar: TranslationResources = { loginExpired: "انتهت صلاحية تسجيل الدخول {{relativeTime}}. {{remedy}}", title: "استخدام الخطة", refresh: "تحديث", + reorderCard: "إعادة ترتيب {{source}}", + showCard: "إظهار {{source}}", refreshAll: "تحديث الكل", refreshing: "جارٍ التحديث...", loading: "جارٍ تحميل بيانات الاستخدام...", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 806403e0b8..87241cad0a 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1,3 +1,5 @@ +import { pluginGallery } from "./plugin-gallery"; + export const en = { pluginCombobox: { searching: "Searching…", @@ -86,14 +88,23 @@ export const en = { close: "Close menu", }, commandCenter: { - placeholder: "Search commands, files, workspaces, and agents...", + placeholder: "Search workspaces, files, and actions...", + placeholderWithoutFiles: "Search workspaces and actions...", filePlaceholder: "Search files...", + workspacePlaceholder: "Search workspaces...", + actionPlaceholder: "Search actions...", searchingFiles: "Searching files...", noMatches: "No matches", actions: "Actions", files: "Files", workspaces: "Workspaces", - agents: "Agents", + recentWorkspaces: "Recent workspaces", + tabs: { + all: "All", + workspaces: "Workspaces", + files: "Files", + actions: "Actions", + }, newAgent: "New agent", open: "Open {{name}}", openInSidePane: "Open {{name}} in side pane", @@ -257,7 +268,7 @@ export const en = { states: { notFound: "Agent not found", failedToLoad: "Failed to load agent", - reconnecting: "Reconnecting to host", + reconnecting: "Reconnecting", updating: "Updating messages", timelineSyncFailed: "Couldn't refresh agent history.", timelineSyncRetrying: "Retrying…", @@ -382,6 +393,7 @@ export const en = { otherPlaceholder: "Other...", }, backgroundWork: { + heartbeat: "Heartbeat", pillOne: "1 background task", pillMany: "{{count}} background tasks", notRunning: "No longer running", @@ -472,8 +484,7 @@ export const en = { archivedTitle: "Workspace archived", restoreDescription: "Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.", - restoreWithoutBranchDescription: - "Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.", + restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.", unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.", restoreAction: "Restore", unarchiveAction: "Unarchive", @@ -2034,6 +2045,7 @@ export const en = { hostUnavailable: "Download host is unavailable.", cancelled: "Download was cancelled.", failed: "Failed to download file.", + httpFailed: "Failed to download file (HTTP {{status}}).", shareFile: "Share file", shareFileNamed: "Share {{fileName}}", }, @@ -2227,6 +2239,7 @@ export const en = { turnOn: "Turn on", options: "Settings", + host: "Host", refreshFailed: "Unable to refresh usage", noHosts: "No connected hosts", agentError: "Unable to load usage: {{reason}}", @@ -2243,6 +2256,8 @@ export const en = { loginExpired: "Login expired {{relativeTime}}. {{remedy}}", title: "Plan usage", refresh: "Refresh", + reorderCard: "Reorder {{source}}", + showCard: "Show {{source}}", refreshAll: "Refresh all", refreshing: "Refreshing...", loading: "Loading usage...", @@ -2409,6 +2424,7 @@ export const en = { host: "Overview", }, plugins: { + gallery: pluginGallery.en, title: "Plugins", screens: { open: "Open", @@ -2446,21 +2462,22 @@ export const en = { enabling: "Enabling…", disable: "Disable", disabling: "Disabling…", - remove: "Remove", - removing: "Removing…", + remove: "Uninstall", + removing: "Uninstalling…", }, feedback: { installed: "Installed {{name}}", reload: "Reloaded {{name}}", enable: "Enabled {{name}}", disable: "Disabled {{name}}", - remove: "Removed {{name}}", + remove: "Uninstalled {{name}}", kept: "Kept {{name}}", globalEnabled: "Plugins enabled", globalDisabled: "Plugins disabled", }, - removeConfirmTitle: "Remove {{name}}?", - removeConfirmMessage: "This removes the configuration. The source directory is not deleted.", + removeConfirmTitle: "Uninstall {{name}}?", + removeConfirmMessage: "Its download and settings on this host are deleted.", + removeConfirmLocalMessage: "Its settings are deleted. Its folder stays on disk.", states: { offlineTitle: "Plugin host is offline", offlineDescription: "Reconnect to this host to manage its plugins.", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 884e7d39ef..5768982f14 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -91,14 +91,23 @@ export const es: TranslationResources = { close: "Cerrar menú", }, commandCenter: { - placeholder: "Buscar comandos, archivos, espacios de trabajo y agentes...", + placeholder: "Buscar espacios de trabajo, archivos y acciones...", + placeholderWithoutFiles: "Buscar espacios de trabajo y acciones...", filePlaceholder: "Buscar archivos...", + workspacePlaceholder: "Buscar espacios de trabajo...", + actionPlaceholder: "Buscar acciones...", searchingFiles: "Buscando archivos...", noMatches: "No hay coincidencias", actions: "Comportamiento", files: "Archivos", workspaces: "Espacios de trabajo", - agents: "Agentes", + recentWorkspaces: "Espacios de trabajo recientes", + tabs: { + all: "Todo", + workspaces: "Espacios de trabajo", + files: "Archivos", + actions: "Acciones", + }, newAgent: "Nuevo agente", open: "Abrir {{name}}", openInSidePane: "Abrir {{name}} en el panel lateral", @@ -263,7 +272,7 @@ export const es: TranslationResources = { states: { notFound: "Agentno encontrado", failedToLoad: "No se pudo cargar el agente", - reconnecting: "Reconectando al host", + reconnecting: "Reconectando", updating: "Actualizando mensajes", timelineSyncFailed: "No se pudo actualizar el historial del agente.", timelineSyncRetrying: "Reintentando…", @@ -390,6 +399,7 @@ export const es: TranslationResources = { otherPlaceholder: "Otro...", }, backgroundWork: { + heartbeat: "Latido", pillOne: "1 tarea en segundo plano", pillMany: "{{count}} tareas en segundo plano", notRunning: "Ya no está en ejecución", @@ -480,8 +490,7 @@ export const es: TranslationResources = { archivedTitle: "Espacio de trabajo archivado", restoreDescription: "Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.", - restoreWithoutBranchDescription: - "Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.", + restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.", unarchiveDescription: "{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.", restoreAction: "Restaurar", @@ -2057,6 +2066,7 @@ export const es: TranslationResources = { hostUnavailable: "El host de descarga no está disponible.", cancelled: "La descarga fue cancelada.", failed: "No se pudo descargar el archivo.", + httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).", shareFile: "compartir archivo", shareFileNamed: "Compartir{{fileName}}", }, @@ -2250,6 +2260,7 @@ export const es: TranslationResources = { turnOn: "Activar", options: "Configuración", + host: "Host", refreshFailed: "No se pudo actualizar el uso", noHosts: "No hay hosts conectados", agentError: "No se pudo cargar el uso: {{reason}}", @@ -2266,6 +2277,8 @@ export const es: TranslationResources = { loginExpired: "La sesión caducó {{relativeTime}}. {{remedy}}", title: "Uso del plan", refresh: "Actualizar", + reorderCard: "Reordenar {{source}}", + showCard: "Mostrar {{source}}", refreshAll: "Actualizar todo", refreshing: "Actualizando...", loading: "Cargando uso...", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 30fbb34d3a..cb64c3652f 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -91,14 +91,23 @@ export const fr: TranslationResources = { close: "Fermer le menu", }, commandCenter: { - placeholder: "Rechercher des commandes, fichiers, espaces de travail et agents…", + placeholder: "Rechercher des espaces de travail, fichiers et actions…", + placeholderWithoutFiles: "Rechercher des espaces de travail et des actions…", filePlaceholder: "Rechercher des fichiers…", + workspacePlaceholder: "Rechercher des espaces de travail…", + actionPlaceholder: "Rechercher des actions…", searchingFiles: "Recherche de fichiers…", noMatches: "Aucun résultat", actions: "Actions", files: "Fichiers", workspaces: "Espaces de travail", - agents: "Agents", + recentWorkspaces: "Espaces de travail récents", + tabs: { + all: "Tout", + workspaces: "Espaces de travail", + files: "Fichiers", + actions: "Actions", + }, newAgent: "Nouvel agent", open: "Ouvrir {{name}}", openInSidePane: "Ouvrir {{name}} dans le panneau latéral", @@ -264,7 +273,7 @@ export const fr: TranslationResources = { states: { notFound: "Agent introuvable", failedToLoad: "Impossible de charger l’agent", - reconnecting: "Reconnexion à l’hôte…", + reconnecting: "Reconnexion…", updating: "Mise à jour des messages…", timelineSyncFailed: "Impossible d’actualiser l’historique de l’agent.", timelineSyncRetrying: "Nouvelle tentative…", @@ -390,6 +399,7 @@ export const fr: TranslationResources = { otherPlaceholder: "Autre…", }, backgroundWork: { + heartbeat: "Battement périodique", pillOne: "1 tâche en arrière-plan", pillMany: "{{count}} tâches en arrière-plan", notRunning: "N’est plus en cours", @@ -480,8 +490,7 @@ export const fr: TranslationResources = { archivedTitle: "Espace de travail archivé", restoreDescription: "Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.", - restoreWithoutBranchDescription: - "Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.", + restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.", unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.", restoreAction: "Restaurer", unarchiveAction: "Désarchiver", @@ -2056,6 +2065,7 @@ export const fr: TranslationResources = { hostUnavailable: "L’hôte de téléchargement est indisponible.", cancelled: "Téléchargement annulé.", failed: "Impossible de télécharger le fichier.", + httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).", shareFile: "Partager le fichier", shareFileNamed: "Partager {{fileName}}", }, @@ -2251,6 +2261,7 @@ export const fr: TranslationResources = { turnOn: "Activer", options: "Paramètres", + host: "Hôte", refreshFailed: "Impossible d’actualiser l’utilisation", noHosts: "Aucun hôte connecté", agentError: "Impossible de charger l’utilisation : {{reason}}", @@ -2267,6 +2278,8 @@ export const fr: TranslationResources = { loginExpired: "Connexion expirée {{relativeTime}}. {{remedy}}", title: "Utilisation du forfait", refresh: "Actualiser", + reorderCard: "Réorganiser {{source}}", + showCard: "Afficher {{source}}", refreshAll: "Tout actualiser", refreshing: "Actualisation...", loading: "Chargement de l’utilisation...", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 118aa2cc56..689a676deb 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -91,14 +91,23 @@ export const ja: TranslationResources = { close: "メニューを閉じる", }, commandCenter: { - placeholder: "コマンド、ファイル、ワークスペース、エージェントを検索...", + placeholder: "ワークスペース、ファイル、アクションを検索...", + placeholderWithoutFiles: "ワークスペースとアクションを検索...", filePlaceholder: "ファイルを検索...", + workspacePlaceholder: "ワークスペースを検索...", + actionPlaceholder: "アクションを検索...", searchingFiles: "ファイルを検索中...", noMatches: "一致なし", actions: "アクション", files: "ファイル", workspaces: "ワークスペース", - agents: "エージェント", + recentWorkspaces: "最近のワークスペース", + tabs: { + all: "すべて", + workspaces: "ワークスペース", + files: "ファイル", + actions: "アクション", + }, newAgent: "新しいエージェント", open: "{{name}}を開く", openInSidePane: "{{name}}をサイドパネルで開く", @@ -263,7 +272,7 @@ export const ja: TranslationResources = { states: { notFound: "エージェントが見つかりません", failedToLoad: "エージェントの読み込みに失敗しました", - reconnecting: "ホストに再接続中", + reconnecting: "再接続中", updating: "メッセージを更新中", timelineSyncFailed: "エージェントの履歴を更新できませんでした。", timelineSyncRetrying: "再試行しています…", @@ -390,6 +399,7 @@ export const ja: TranslationResources = { otherPlaceholder: "その他...", }, backgroundWork: { + heartbeat: "ハートビート", pillOne: "バックグラウンドタスク1件", pillMany: "バックグラウンドタスク{{count}}件", notRunning: "実行は終了しました", @@ -480,8 +490,7 @@ export const ja: TranslationResources = { archivedTitle: "ワークスペースはアーカイブ済みです", restoreDescription: "{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。", - restoreWithoutBranchDescription: - "{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。", + restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。", unarchiveDescription: "{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。", restoreAction: "復元", @@ -2029,6 +2038,7 @@ export const ja: TranslationResources = { hostUnavailable: "ダウンロードホストが利用できません。", cancelled: "ダウンロードがキャンセルされました。", failed: "ファイルのダウンロードに失敗しました。", + httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).", shareFile: "ファイルを共有", shareFileNamed: "{{fileName}}を共有", }, @@ -2224,6 +2234,7 @@ export const ja: TranslationResources = { turnOn: "オンにする", options: "設定", + host: "ホスト", refreshFailed: "使用状況を更新できません", noHosts: "接続中のホストがありません", agentError: "使用状況を読み込めません: {{reason}}", @@ -2240,6 +2251,8 @@ export const ja: TranslationResources = { loginExpired: "ログインは{{relativeTime}}に期限切れになりました。{{remedy}}", title: "プラン使用量", refresh: "更新", + reorderCard: "{{source}} を並べ替え", + showCard: "{{source}} を表示", refreshAll: "すべて更新", refreshing: "更新中...", loading: "使用状況を読み込み中...", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 13792621f3..aaea487a26 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -90,14 +90,23 @@ export const ko: TranslationResources = { close: "메뉴 닫기", }, commandCenter: { - placeholder: "명령, 파일, 워크스페이스 및 에이전트 검색...", + placeholder: "워크스페이스, 파일 및 작업 검색...", + placeholderWithoutFiles: "워크스페이스 및 작업 검색...", filePlaceholder: "파일 검색...", + workspacePlaceholder: "워크스페이스 검색...", + actionPlaceholder: "작업 검색...", searchingFiles: "파일 검색 중...", noMatches: "일치 항목 없음", actions: "작업", files: "파일", workspaces: "워크스페이스", - agents: "에이전트", + recentWorkspaces: "최근 워크스페이스", + tabs: { + all: "전체", + workspaces: "워크스페이스", + files: "파일", + actions: "작업", + }, newAgent: "새 에이전트", open: "{{name}} 열기", openInSidePane: "사이드 패널에서 {{name}} 열기", @@ -261,7 +270,7 @@ export const ko: TranslationResources = { states: { notFound: "에이전트를 찾을 수 없습니다", failedToLoad: "에이전트를 불러오지 못했습니다", - reconnecting: "호스트에 다시 연결하는 중", + reconnecting: "다시 연결하는 중", updating: "메시지 업데이트 중", timelineSyncFailed: "에이전트 기록을 새로고침할 수 없습니다.", timelineSyncRetrying: "재시도 중…", @@ -386,6 +395,7 @@ export const ko: TranslationResources = { otherPlaceholder: "기타...", }, backgroundWork: { + heartbeat: "하트비트", pillOne: "백그라운드 작업 1개", pillMany: "백그라운드 작업 {{count}}개", notRunning: "더 이상 실행 중이 아님", @@ -476,8 +486,7 @@ export const ko: TranslationResources = { archivedTitle: "워크스페이스가 보관되었습니다", restoreDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.", - restoreWithoutBranchDescription: - "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.", + restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.", unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.", restoreAction: "복원", unarchiveAction: "보관 취소", @@ -2019,6 +2028,7 @@ export const ko: TranslationResources = { hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.", cancelled: "다운로드가 취소되었습니다.", failed: "파일을 다운로드하지 못했습니다.", + httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).", shareFile: "파일 공유", shareFileNamed: "{{fileName}} 공유", }, @@ -2212,6 +2222,7 @@ export const ko: TranslationResources = { turnOn: "켜기", options: "설정", + host: "호스트", refreshFailed: "사용량을 새로 고칠 수 없습니다", noHosts: "연결된 호스트가 없습니다", agentError: "사용량을 불러올 수 없습니다: {{reason}}", @@ -2228,6 +2239,8 @@ export const ko: TranslationResources = { loginExpired: "로그인이 {{relativeTime}}에 만료되었습니다. {{remedy}}", title: "플랜 사용량", refresh: "새로 고침", + reorderCard: "{{source}} 순서 변경", + showCard: "{{source}} 표시", refreshAll: "모두 새로 고침", refreshing: "새로 고치는 중...", loading: "사용량 불러오는 중...", diff --git a/packages/app/src/i18n/resources/plugin-gallery.ts b/packages/app/src/i18n/resources/plugin-gallery.ts new file mode 100644 index 0000000000..959f1c4077 --- /dev/null +++ b/packages/app/src/i18n/resources/plugin-gallery.ts @@ -0,0 +1,559 @@ +/** Settings → Plugins: the installed list, the directory and a plugin's page. */ +export const pluginGallery = { + en: { + tabs: { installed: "Installed", installedCount: "Installed · {{count}}", browse: "Browse" }, + search: { installed: "Search installed", browse: "Search plugins", clear: "Clear search" }, + filters: { + category: "Category", + allCategories: "All categories", + sort: "Sort", + popular: "Most installed", + recent: "Recently updated", + name: "Name", + }, + sections: { + updates: "Updates", + installed: "Installed", + featured: "Featured", + all: "All plugins", + overview: "Overview", + details: "Details", + }, + installs: "{{installs}} installs", + installs_one: "{{installs}} install", + menu: "More plugin actions", + actions: { + install: "Install", + installing: "Installing…", + installed: "Installed", + retry: "Retry", + update: "Update", + updating: "Updating…", + updateAll: "Update all", + turnOn: "Turn on", + turnOnAll: "Turn on plugins", + turnOff: "Turn off plugins", + installFromSource: "Install from source", + submit: "Submit a plugin", + repository: "Repository", + showMore: "Show more", + browse: "Browse plugins", + }, + off: { title: "Plugins are off on {{host}}" }, + empty: { noMatches: "No plugins match" }, + directory: { + errorTitle: "Unable to load the plugin directory", + update: "Update this host to browse plugins", + }, + install: { + title: "Install {{name}}?", + sourceTitle: "Install from source", + author: "Author", + source: "Source", + version: "Version", + warningTitle: "Runs with your access on {{host}}", + warningDescription: "Plugins are not sandboxed. Install only code you trust.", + turnsOn: "Plugins are not sandboxed. Installing also turns plugins on.", + }, + update: { updated: "{{name}} updated", updatedMany: "{{count}} plugins updated" }, + details: { license: "License", updated: "Updated", openImage: "Open image" }, + missing: "This plugin is not installed or listed", + }, + ar: { + tabs: { installed: "المثبّتة", installedCount: "المثبّتة · {{count}}", browse: "تصفّح" }, + search: { installed: "ابحث في المثبّتة", browse: "ابحث عن إضافات", clear: "مسح البحث" }, + filters: { + category: "الفئة", + allCategories: "كل الفئات", + sort: "الترتيب", + popular: "الأكثر تثبيتًا", + recent: "المحدّثة مؤخرًا", + name: "الاسم", + }, + sections: { + updates: "التحديثات", + installed: "المثبّتة", + featured: "مميّزة", + all: "كل الإضافات", + overview: "نظرة عامة", + details: "التفاصيل", + }, + installs: "{{installs}} تثبيت", + installs_one: "{{installs}} تثبيت", + menu: "إجراءات أخرى للإضافات", + actions: { + install: "تثبيت", + installing: "جارٍ التثبيت…", + installed: "مثبّتة", + retry: "إعادة المحاولة", + update: "تحديث", + updating: "جارٍ التحديث…", + updateAll: "تحديث الكل", + turnOn: "تشغيل", + turnOnAll: "تشغيل الإضافات", + turnOff: "إيقاف الإضافات", + installFromSource: "التثبيت من مصدر", + submit: "إرسال إضافة", + repository: "المستودع", + showMore: "عرض المزيد", + browse: "تصفّح الإضافات", + }, + off: { title: "الإضافات متوقفة على {{host}}" }, + empty: { noMatches: "لا توجد إضافات مطابقة" }, + directory: { + errorTitle: "تعذّر تحميل دليل الإضافات", + update: "حدّث هذا المضيف لتصفّح الإضافات", + }, + install: { + title: "تثبيت {{name}}؟", + sourceTitle: "التثبيت من مصدر", + author: "المؤلف", + source: "المصدر", + version: "الإصدار", + warningTitle: "تعمل بصلاحياتك على {{host}}", + warningDescription: "الإضافات غير معزولة. ثبّت فقط التعليمات البرمجية التي تثق بها.", + turnsOn: "الإضافات غير معزولة. يؤدي التثبيت أيضًا إلى تشغيل الإضافات.", + }, + update: { updated: "تم تحديث {{name}}", updatedMany: "تم تحديث {{count}} إضافات" }, + details: { license: "الترخيص", updated: "آخر تحديث", openImage: "فتح الصورة" }, + missing: "هذه الإضافة غير مثبّتة وغير مدرجة", + }, + es: { + tabs: { installed: "Instalados", installedCount: "Instalados · {{count}}", browse: "Explorar" }, + search: { installed: "Buscar instalados", browse: "Buscar plugins", clear: "Borrar búsqueda" }, + filters: { + category: "Categoría", + allCategories: "Todas las categorías", + sort: "Orden", + popular: "Más instalados", + recent: "Actualizados recientemente", + name: "Nombre", + }, + sections: { + updates: "Actualizaciones", + installed: "Instalados", + featured: "Destacados", + all: "Todos los plugins", + overview: "Descripción general", + details: "Detalles", + }, + installs: "{{installs}} instalaciones", + installs_one: "{{installs}} instalación", + menu: "Más acciones de plugins", + actions: { + install: "Instalar", + installing: "Instalando…", + installed: "Instalado", + retry: "Reintentar", + update: "Actualizar", + updating: "Actualizando…", + updateAll: "Actualizar todo", + turnOn: "Activar", + turnOnAll: "Activar plugins", + turnOff: "Desactivar plugins", + installFromSource: "Instalar desde una fuente", + submit: "Enviar un plugin", + repository: "Repositorio", + showMore: "Mostrar más", + browse: "Explorar plugins", + }, + off: { title: "Los plugins están desactivados en {{host}}" }, + empty: { noMatches: "Ningún plugin coincide" }, + directory: { + errorTitle: "No se pudo cargar el directorio de plugins", + update: "Actualiza este host para explorar plugins", + }, + install: { + title: "¿Instalar {{name}}?", + sourceTitle: "Instalar desde una fuente", + author: "Autor", + source: "Fuente", + version: "Versión", + warningTitle: "Se ejecuta con tu acceso en {{host}}", + warningDescription: "Los plugins no están aislados. Instala solo código de confianza.", + turnsOn: "Los plugins no están aislados. Instalar también activa los plugins.", + }, + update: { updated: "{{name}} actualizado", updatedMany: "{{count}} plugins actualizados" }, + details: { license: "Licencia", updated: "Actualizado", openImage: "Abrir imagen" }, + missing: "Este plugin no está instalado ni publicado", + }, + fr: { + tabs: { installed: "Installés", installedCount: "Installés · {{count}}", browse: "Parcourir" }, + search: { + installed: "Rechercher dans les installés", + browse: "Rechercher des plugins", + clear: "Effacer la recherche", + }, + filters: { + category: "Catégorie", + allCategories: "Toutes les catégories", + sort: "Tri", + popular: "Les plus installés", + recent: "Mis à jour récemment", + name: "Nom", + }, + sections: { + updates: "Mises à jour", + installed: "Installés", + featured: "À la une", + all: "Tous les plugins", + overview: "Présentation", + details: "Détails", + }, + installs: "{{installs}} installations", + installs_one: "{{installs}} installation", + menu: "Autres actions sur les plugins", + actions: { + install: "Installer", + installing: "Installation…", + installed: "Installé", + retry: "Réessayer", + update: "Mettre à jour", + updating: "Mise à jour…", + updateAll: "Tout mettre à jour", + turnOn: "Activer", + turnOnAll: "Activer les plugins", + turnOff: "Désactiver les plugins", + installFromSource: "Installer depuis une source", + submit: "Proposer un plugin", + repository: "Dépôt", + showMore: "Afficher plus", + browse: "Parcourir les plugins", + }, + off: { title: "Les plugins sont désactivés sur {{host}}" }, + empty: { noMatches: "Aucun plugin ne correspond" }, + directory: { + errorTitle: "Impossible de charger l’annuaire des plugins", + update: "Mettez à jour cet hôte pour parcourir les plugins", + }, + install: { + title: "Installer {{name}} ?", + sourceTitle: "Installer depuis une source", + author: "Auteur", + source: "Source", + version: "Version", + warningTitle: "S’exécute avec vos accès sur {{host}}", + warningDescription: "Les plugins ne sont pas isolés. N’installez que du code de confiance.", + turnsOn: "Les plugins ne sont pas isolés. L’installation active aussi les plugins.", + }, + update: { updated: "{{name}} mis à jour", updatedMany: "{{count}} plugins mis à jour" }, + details: { license: "Licence", updated: "Mis à jour", openImage: "Ouvrir l’image" }, + missing: "Ce plugin n’est ni installé ni publié", + }, + ja: { + tabs: { + installed: "インストール済み", + installedCount: "インストール済み · {{count}}", + browse: "見つける", + }, + search: { + installed: "インストール済みを検索", + browse: "プラグインを検索", + clear: "検索をクリア", + }, + filters: { + category: "カテゴリ", + allCategories: "すべてのカテゴリ", + sort: "並び順", + popular: "インストール数順", + recent: "最近の更新順", + name: "名前順", + }, + sections: { + updates: "アップデート", + installed: "インストール済み", + featured: "おすすめ", + all: "すべてのプラグイン", + overview: "概要", + details: "詳細", + }, + installs: "{{installs}} 件のインストール", + installs_one: "{{installs}} 件のインストール", + menu: "その他のプラグイン操作", + actions: { + install: "インストール", + installing: "インストール中…", + installed: "インストール済み", + retry: "再試行", + update: "アップデート", + updating: "アップデート中…", + updateAll: "すべてアップデート", + turnOn: "オンにする", + turnOnAll: "プラグインをオンにする", + turnOff: "プラグインをオフにする", + installFromSource: "ソースからインストール", + submit: "プラグインを申請", + repository: "リポジトリ", + showMore: "さらに表示", + browse: "プラグインを見つける", + }, + off: { title: "{{host}} ではプラグインがオフです" }, + empty: { noMatches: "一致するプラグインはありません" }, + directory: { + errorTitle: "プラグインディレクトリを読み込めません", + update: "プラグインを探すにはこのホストをアップデートしてください", + }, + install: { + title: "{{name}} をインストールしますか?", + sourceTitle: "ソースからインストール", + author: "作者", + source: "ソース", + version: "バージョン", + warningTitle: "{{host}} であなたの権限で動作します", + warningDescription: + "プラグインはサンドボックス化されていません。信頼できるコードのみインストールしてください。", + turnsOn: + "プラグインはサンドボックス化されていません。インストールするとプラグインもオンになります。", + }, + update: { + updated: "{{name}} をアップデートしました", + updatedMany: "{{count}} 個のプラグインをアップデートしました", + }, + details: { license: "ライセンス", updated: "更新日", openImage: "画像を開く" }, + missing: "このプラグインはインストールも公開もされていません", + }, + ko: { + tabs: { installed: "설치됨", installedCount: "설치됨 · {{count}}", browse: "찾아보기" }, + search: { installed: "설치된 항목 검색", browse: "플러그인 검색", clear: "검색 지우기" }, + filters: { + category: "카테고리", + allCategories: "모든 카테고리", + sort: "정렬", + popular: "설치 많은 순", + recent: "최근 업데이트 순", + name: "이름순", + }, + sections: { + updates: "업데이트", + installed: "설치됨", + featured: "추천", + all: "모든 플러그인", + overview: "개요", + details: "세부 정보", + }, + installs: "{{installs}}회 설치", + installs_one: "{{installs}}회 설치", + menu: "기타 플러그인 작업", + actions: { + install: "설치", + installing: "설치 중…", + installed: "설치됨", + retry: "다시 시도", + update: "업데이트", + updating: "업데이트 중…", + updateAll: "모두 업데이트", + turnOn: "켜기", + turnOnAll: "플러그인 켜기", + turnOff: "플러그인 끄기", + installFromSource: "소스에서 설치", + submit: "플러그인 제출", + repository: "저장소", + showMore: "더 보기", + browse: "플러그인 찾아보기", + }, + off: { title: "{{host}}에서 플러그인이 꺼져 있습니다" }, + empty: { noMatches: "일치하는 플러그인이 없습니다" }, + directory: { + errorTitle: "플러그인 디렉터리를 로드할 수 없습니다", + update: "플러그인을 찾아보려면 이 호스트를 업데이트하세요", + }, + install: { + title: "{{name}}을(를) 설치할까요?", + sourceTitle: "소스에서 설치", + author: "작성자", + source: "소스", + version: "버전", + warningTitle: "{{host}}에서 사용자 권한으로 실행됩니다", + warningDescription: "플러그인은 격리되지 않습니다. 신뢰하는 코드만 설치하세요.", + turnsOn: "플러그인은 격리되지 않습니다. 설치하면 플러그인도 켜집니다.", + }, + update: { updated: "{{name}} 업데이트됨", updatedMany: "플러그인 {{count}}개 업데이트됨" }, + details: { license: "라이선스", updated: "업데이트", openImage: "이미지 열기" }, + missing: "이 플러그인은 설치되지 않았고 등록되어 있지도 않습니다", + }, + "pt-BR": { + tabs: { installed: "Instalados", installedCount: "Instalados · {{count}}", browse: "Explorar" }, + search: { installed: "Buscar instalados", browse: "Buscar plugins", clear: "Limpar busca" }, + filters: { + category: "Categoria", + allCategories: "Todas as categorias", + sort: "Ordem", + popular: "Mais instalados", + recent: "Atualizados recentemente", + name: "Nome", + }, + sections: { + updates: "Atualizações", + installed: "Instalados", + featured: "Destaques", + all: "Todos os plugins", + overview: "Visão geral", + details: "Detalhes", + }, + installs: "{{installs}} instalações", + installs_one: "{{installs}} instalação", + menu: "Mais ações de plugins", + actions: { + install: "Instalar", + installing: "Instalando…", + installed: "Instalado", + retry: "Tentar novamente", + update: "Atualizar", + updating: "Atualizando…", + updateAll: "Atualizar tudo", + turnOn: "Ativar", + turnOnAll: "Ativar plugins", + turnOff: "Desativar plugins", + installFromSource: "Instalar de uma fonte", + submit: "Enviar um plugin", + repository: "Repositório", + showMore: "Mostrar mais", + browse: "Explorar plugins", + }, + off: { title: "Os plugins estão desativados em {{host}}" }, + empty: { noMatches: "Nenhum plugin corresponde" }, + directory: { + errorTitle: "Não foi possível carregar o diretório de plugins", + update: "Atualize este host para explorar plugins", + }, + install: { + title: "Instalar {{name}}?", + sourceTitle: "Instalar de uma fonte", + author: "Autor", + source: "Fonte", + version: "Versão", + warningTitle: "Roda com o seu acesso em {{host}}", + warningDescription: "Plugins não são isolados. Instale apenas código confiável.", + turnsOn: "Plugins não são isolados. Instalar também ativa os plugins.", + }, + update: { updated: "{{name}} atualizado", updatedMany: "{{count}} plugins atualizados" }, + details: { license: "Licença", updated: "Atualizado", openImage: "Abrir imagem" }, + missing: "Este plugin não está instalado nem publicado", + }, + ru: { + tabs: { + installed: "Установленные", + installedCount: "Установленные · {{count}}", + browse: "Обзор", + }, + search: { + installed: "Поиск среди установленных", + browse: "Поиск плагинов", + clear: "Очистить поиск", + }, + filters: { + category: "Категория", + allCategories: "Все категории", + sort: "Сортировка", + popular: "По установкам", + recent: "Недавно обновлённые", + name: "По названию", + }, + sections: { + updates: "Обновления", + installed: "Установленные", + featured: "Рекомендуемые", + all: "Все плагины", + overview: "Обзор", + details: "Подробности", + }, + installs: "Установок: {{installs}}", + installs_one: "Установок: {{installs}}", + menu: "Другие действия с плагинами", + actions: { + install: "Установить", + installing: "Установка…", + installed: "Установлен", + retry: "Повторить", + update: "Обновить", + updating: "Обновление…", + updateAll: "Обновить все", + turnOn: "Включить", + turnOnAll: "Включить плагины", + turnOff: "Выключить плагины", + installFromSource: "Установить из источника", + submit: "Предложить плагин", + repository: "Репозиторий", + showMore: "Показать ещё", + browse: "Обзор плагинов", + }, + off: { title: "Плагины выключены на {{host}}" }, + empty: { noMatches: "Нет подходящих плагинов" }, + directory: { + errorTitle: "Не удалось загрузить каталог плагинов", + update: "Обновите этот хост, чтобы просматривать плагины", + }, + install: { + title: "Установить {{name}}?", + sourceTitle: "Установить из источника", + author: "Автор", + source: "Источник", + version: "Версия", + warningTitle: "Работает с вашим доступом на {{host}}", + warningDescription: "Плагины не изолированы. Устанавливайте только код, которому доверяете.", + turnsOn: "Плагины не изолированы. Установка также включит плагины.", + }, + update: { updated: "{{name}} обновлён", updatedMany: "Обновлено плагинов: {{count}}" }, + details: { license: "Лицензия", updated: "Обновлён", openImage: "Открыть изображение" }, + missing: "Этот плагин не установлен и не опубликован", + }, + "zh-CN": { + tabs: { installed: "已安装", installedCount: "已安装 · {{count}}", browse: "浏览" }, + search: { installed: "搜索已安装", browse: "搜索插件", clear: "清除搜索" }, + filters: { + category: "分类", + allCategories: "全部分类", + sort: "排序", + popular: "安装最多", + recent: "最近更新", + name: "名称", + }, + sections: { + updates: "更新", + installed: "已安装", + featured: "精选", + all: "全部插件", + overview: "概览", + details: "详情", + }, + installs: "{{installs}} 次安装", + installs_one: "{{installs}} 次安装", + menu: "更多插件操作", + actions: { + install: "安装", + installing: "正在安装…", + installed: "已安装", + retry: "重试", + update: "更新", + updating: "正在更新…", + updateAll: "全部更新", + turnOn: "开启", + turnOnAll: "开启插件", + turnOff: "关闭插件", + installFromSource: "从来源安装", + submit: "提交插件", + repository: "仓库", + showMore: "显示更多", + browse: "浏览插件", + }, + off: { title: "{{host}} 上的插件已关闭" }, + empty: { noMatches: "没有匹配的插件" }, + directory: { + errorTitle: "无法加载插件目录", + update: "请更新此主机以浏览插件", + }, + install: { + title: "安装 {{name}}?", + sourceTitle: "从来源安装", + author: "作者", + source: "来源", + version: "版本", + warningTitle: "以你在 {{host}} 上的权限运行", + warningDescription: "插件没有沙箱隔离。只安装你信任的代码。", + turnsOn: "插件没有沙箱隔离。安装后也会开启插件。", + }, + update: { updated: "已更新 {{name}}", updatedMany: "已更新 {{count}} 个插件" }, + details: { license: "许可证", updated: "更新于", openImage: "打开图片" }, + missing: "此插件既未安装也未上架", + }, +} as const; diff --git a/packages/app/src/i18n/resources/plugin-settings.ts b/packages/app/src/i18n/resources/plugin-settings.ts index a5d829bff1..9069063137 100644 --- a/packages/app/src/i18n/resources/plugin-settings.ts +++ b/packages/app/src/i18n/resources/plugin-settings.ts @@ -1,3 +1,5 @@ +import { pluginGallery } from "./plugin-gallery"; + const shared = { logs: { action: "Logs", @@ -13,6 +15,7 @@ const shared = { export const pluginSettings = { ar: { ...shared, + gallery: pluginGallery.ar, screens: { open: "فتح", offline: "اتصل بهذا المضيف لفتح إعدادات الإضافة.", @@ -41,21 +44,22 @@ export const pluginSettings = { enabling: "جارٍ التفعيل…", disable: "تعطيل", disabling: "جارٍ التعطيل…", - remove: "إزالة", - removing: "جارٍ الإزالة…", + remove: "إلغاء التثبيت", + removing: "جارٍ إلغاء التثبيت…", }, feedback: { installed: "تم تثبيت {{name}}", reload: "تمت إعادة تحميل {{name}}", enable: "تم تفعيل {{name}}", disable: "تم تعطيل {{name}}", - remove: "تمت إزالة {{name}}", + remove: "تم إلغاء تثبيت {{name}}", kept: "تم الإبقاء على {{name}}", globalEnabled: "تم تفعيل الإضافات", globalDisabled: "تم تعطيل الإضافات", }, - removeConfirmTitle: "إزالة {{name}}؟", - removeConfirmMessage: "يؤدي هذا إلى إزالة الإعداد فقط. لن يُحذف مجلد المصدر.", + removeConfirmTitle: "إلغاء تثبيت {{name}}؟", + removeConfirmMessage: "تُحذف نسختها المنزّلة وإعداداتها على هذا المضيف.", + removeConfirmLocalMessage: "تُحذف إعداداتها. يبقى مجلدها على القرص.", states: { offlineTitle: "مضيف الإضافات غير متصل", offlineDescription: "أعد الاتصال بهذا المضيف لإدارة إضافاته.", @@ -69,6 +73,7 @@ export const pluginSettings = { }, es: { ...shared, + gallery: pluginGallery.es, screens: { open: "Abrir", offline: "Conéctate a este host para abrir los ajustes del plugin.", @@ -97,21 +102,22 @@ export const pluginSettings = { enabling: "Activando…", disable: "Desactivar", disabling: "Desactivando…", - remove: "Eliminar", - removing: "Eliminando…", + remove: "Desinstalar", + removing: "Desinstalando…", }, feedback: { installed: "{{name}} instalado", reload: "{{name}} recargado", enable: "{{name}} activado", disable: "{{name}} desactivado", - remove: "{{name}} eliminado", + remove: "{{name}} desinstalado", kept: "Se conservó {{name}}", globalEnabled: "Plugins activados", globalDisabled: "Plugins desactivados", }, - removeConfirmTitle: "¿Eliminar {{name}}?", - removeConfirmMessage: "Esto elimina la configuración. El directorio de origen no se borra.", + removeConfirmTitle: "¿Desinstalar {{name}}?", + removeConfirmMessage: "Se borran su descarga y sus ajustes en este host.", + removeConfirmLocalMessage: "Se borran sus ajustes. Su carpeta se queda en el disco.", states: { offlineTitle: "El host de plugins está sin conexión", offlineDescription: "Vuelve a conectar este host para gestionar sus plugins.", @@ -125,6 +131,7 @@ export const pluginSettings = { }, fr: { ...shared, + gallery: pluginGallery.fr, screens: { open: "Ouvrir", offline: "Connectez-vous à cet hôte pour ouvrir les paramètres du plugin.", @@ -153,21 +160,22 @@ export const pluginSettings = { enabling: "Activation…", disable: "Désactiver", disabling: "Désactivation…", - remove: "Supprimer", - removing: "Suppression…", + remove: "Désinstaller", + removing: "Désinstallation…", }, feedback: { installed: "{{name}} installé", reload: "{{name}} rechargé", enable: "{{name}} activé", disable: "{{name}} désactivé", - remove: "{{name}} supprimé", + remove: "{{name}} désinstallé", kept: "{{name}} conservé", globalEnabled: "Plugins activés", globalDisabled: "Plugins désactivés", }, - removeConfirmTitle: "Supprimer {{name}} ?", - removeConfirmMessage: "La configuration sera supprimée. Le dossier source ne sera pas effacé.", + removeConfirmTitle: "Désinstaller {{name}} ?", + removeConfirmMessage: "Son téléchargement et ses réglages sur cet hôte sont supprimés.", + removeConfirmLocalMessage: "Ses réglages sont supprimés. Son dossier reste sur le disque.", states: { offlineTitle: "L’hôte des plugins est hors ligne", offlineDescription: "Reconnectez cet hôte pour gérer ses plugins.", @@ -181,6 +189,7 @@ export const pluginSettings = { }, ja: { ...shared, + gallery: pluginGallery.ja, screens: { open: "開く", offline: "このホストに接続してプラグイン設定を開いてください。", @@ -209,21 +218,22 @@ export const pluginSettings = { enabling: "有効化中…", disable: "無効化", disabling: "無効化中…", - remove: "削除", - removing: "削除中…", + remove: "アンインストール", + removing: "アンインストール中…", }, feedback: { installed: "{{name}} をインストールしました", reload: "{{name}} を再読み込みしました", enable: "{{name}} を有効にしました", disable: "{{name}} を無効にしました", - remove: "{{name}} を削除しました", + remove: "{{name}} をアンインストールしました", kept: "{{name}} を保持しました", globalEnabled: "プラグインを有効にしました", globalDisabled: "プラグインを無効にしました", }, - removeConfirmTitle: "{{name}} を削除しますか?", - removeConfirmMessage: "設定のみを削除します。ソースディレクトリは削除されません。", + removeConfirmTitle: "{{name}} をアンインストールしますか?", + removeConfirmMessage: "このホスト上のダウンロードと設定が削除されます。", + removeConfirmLocalMessage: "設定が削除されます。フォルダはディスクに残ります。", states: { offlineTitle: "プラグインホストはオフラインです", offlineDescription: "プラグインを管理するにはホストに再接続してください。", @@ -237,6 +247,7 @@ export const pluginSettings = { }, ko: { ...shared, + gallery: pluginGallery.ko, screens: { open: "열기", offline: "플러그인 설정을 열려면 이 호스트에 연결하세요.", @@ -278,7 +289,8 @@ export const pluginSettings = { globalDisabled: "플러그인 비활성화됨", }, removeConfirmTitle: "{{name}}을(를) 제거할까요?", - removeConfirmMessage: "설정만 제거합니다. 소스 디렉터리는 삭제되지 않습니다.", + removeConfirmMessage: "이 호스트의 다운로드와 설정이 삭제됩니다.", + removeConfirmLocalMessage: "설정이 삭제됩니다. 폴더는 디스크에 남습니다.", states: { offlineTitle: "플러그인 호스트가 오프라인입니다", offlineDescription: "플러그인을 관리하려면 호스트에 다시 연결하세요.", @@ -292,6 +304,7 @@ export const pluginSettings = { }, "pt-BR": { ...shared, + gallery: pluginGallery["pt-BR"], screens: { open: "Abrir", offline: "Conecte-se a este host para abrir as configurações do plugin.", @@ -320,21 +333,22 @@ export const pluginSettings = { enabling: "Ativando…", disable: "Desativar", disabling: "Desativando…", - remove: "Remover", - removing: "Removendo…", + remove: "Desinstalar", + removing: "Desinstalando…", }, feedback: { installed: "{{name}} instalado", reload: "{{name}} recarregado", enable: "{{name}} ativado", disable: "{{name}} desativado", - remove: "{{name}} removido", + remove: "{{name}} desinstalado", kept: "{{name}} mantido", globalEnabled: "Plugins ativados", globalDisabled: "Plugins desativados", }, - removeConfirmTitle: "Remover {{name}}?", - removeConfirmMessage: "Isso remove a configuração. O diretório de origem não será excluído.", + removeConfirmTitle: "Desinstalar {{name}}?", + removeConfirmMessage: "O download e as configurações neste host são apagados.", + removeConfirmLocalMessage: "As configurações são apagadas. A pasta continua no disco.", states: { offlineTitle: "O host de plugins está offline", offlineDescription: "Reconecte este host para gerenciar seus plugins.", @@ -348,6 +362,7 @@ export const pluginSettings = { }, ru: { ...shared, + gallery: pluginGallery.ru, screens: { open: "Открыть", offline: "Подключитесь к этому хосту, чтобы открыть настройки плагина.", @@ -390,7 +405,8 @@ export const pluginSettings = { globalDisabled: "Плагины отключены", }, removeConfirmTitle: "Удалить {{name}}?", - removeConfirmMessage: "Конфигурация будет удалена. Исходный каталог останется на месте.", + removeConfirmMessage: "Загруженные файлы и настройки на этом хосте будут удалены.", + removeConfirmLocalMessage: "Настройки будут удалены. Папка останется на диске.", states: { offlineTitle: "Хост плагинов не в сети", offlineDescription: "Подключите хост снова, чтобы управлять плагинами.", @@ -404,6 +420,7 @@ export const pluginSettings = { }, "zh-CN": { ...shared, + gallery: pluginGallery["zh-CN"], screens: { open: "打开", offline: "连接到此主机以打开插件设置。", @@ -431,21 +448,22 @@ export const pluginSettings = { enabling: "正在启用…", disable: "禁用", disabling: "正在禁用…", - remove: "移除", - removing: "正在移除…", + remove: "卸载", + removing: "正在卸载…", }, feedback: { installed: "已安装 {{name}}", reload: "已重新加载 {{name}}", enable: "已启用 {{name}}", disable: "已禁用 {{name}}", - remove: "已移除 {{name}}", + remove: "已卸载 {{name}}", kept: "已保留 {{name}}", globalEnabled: "插件已启用", globalDisabled: "插件已禁用", }, - removeConfirmTitle: "移除 {{name}}?", - removeConfirmMessage: "这会移除配置,但不会删除源目录。", + removeConfirmTitle: "卸载 {{name}}?", + removeConfirmMessage: "将删除此主机上的下载内容和设置。", + removeConfirmLocalMessage: "将删除其设置。文件夹保留在磁盘上。", states: { offlineTitle: "插件主机离线", offlineDescription: "重新连接此主机以管理其插件。", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index dd6e87d430..0f64a803fb 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -91,14 +91,23 @@ export const ptBR: TranslationResources = { close: "Fechar menu", }, commandCenter: { - placeholder: "Buscar comandos, arquivos, espaços de trabalho e agentes...", + placeholder: "Pesquisar espaços de trabalho, arquivos e ações...", + placeholderWithoutFiles: "Pesquisar espaços de trabalho e ações...", filePlaceholder: "Pesquisar arquivos...", + workspacePlaceholder: "Pesquisar espaços de trabalho...", + actionPlaceholder: "Pesquisar ações...", searchingFiles: "Pesquisando arquivos...", noMatches: "Nenhuma correspondência", actions: "Ações", files: "Arquivos", workspaces: "Espaços de trabalho", - agents: "Agentes", + recentWorkspaces: "Espaços de trabalho recentes", + tabs: { + all: "Tudo", + workspaces: "Espaços de trabalho", + files: "Arquivos", + actions: "Ações", + }, newAgent: "Novo agente", open: "Abrir {{name}}", openInSidePane: "Abrir {{name}} no painel lateral", @@ -262,7 +271,7 @@ export const ptBR: TranslationResources = { states: { notFound: "Agente não encontrado", failedToLoad: "Falha ao carregar agente", - reconnecting: "Reconectando ao host", + reconnecting: "Reconectando", updating: "Atualizando mensagens", timelineSyncFailed: "Não foi possível atualizar o histórico do agente.", timelineSyncRetrying: "Tentando novamente…", @@ -389,6 +398,7 @@ export const ptBR: TranslationResources = { otherPlaceholder: "Outro...", }, backgroundWork: { + heartbeat: "Batimento", pillOne: "1 tarefa em segundo plano", pillMany: "{{count}} tarefas em segundo plano", notRunning: "Não está mais em execução", @@ -479,8 +489,7 @@ export const ptBR: TranslationResources = { archivedTitle: "Workspace arquivado", restoreDescription: "Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.", - restoreWithoutBranchDescription: - "Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.", + restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.", unarchiveDescription: "{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.", restoreAction: "Restaurar", @@ -2042,6 +2051,7 @@ export const ptBR: TranslationResources = { hostUnavailable: "Host de download indisponível.", cancelled: "Download cancelado.", failed: "Falha ao baixar arquivo.", + httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).", shareFile: "Compartilhar arquivo", shareFileNamed: "Compartilhar {{fileName}}", }, @@ -2235,6 +2245,7 @@ export const ptBR: TranslationResources = { turnOn: "Ativar", options: "Configurações", + host: "Host", refreshFailed: "Não foi possível atualizar o uso", noHosts: "Nenhum host conectado", agentError: "Não foi possível carregar o uso: {{reason}}", @@ -2251,6 +2262,8 @@ export const ptBR: TranslationResources = { loginExpired: "O login expirou {{relativeTime}}. {{remedy}}", title: "Uso do plano", refresh: "Atualizar", + reorderCard: "Reordenar {{source}}", + showCard: "Mostrar {{source}}", refreshAll: "Atualizar tudo", refreshing: "Atualizando...", loading: "Carregando uso...", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 08e29d0317..d59121a130 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -91,14 +91,23 @@ export const ru: TranslationResources = { close: "Закрыть меню", }, commandCenter: { - placeholder: "Поиск команд, файлов, рабочих пространств и агентов...", + placeholder: "Поиск рабочих пространств, файлов и действий...", + placeholderWithoutFiles: "Поиск рабочих пространств и действий...", filePlaceholder: "Поиск файлов...", + workspacePlaceholder: "Поиск рабочих пространств...", + actionPlaceholder: "Поиск действий...", searchingFiles: "Поиск файлов...", noMatches: "Нет совпадений", actions: "Действия", files: "Файлы", workspaces: "Рабочие пространства", - agents: "Агенты", + recentWorkspaces: "Недавние рабочие пространства", + tabs: { + all: "Все", + workspaces: "Рабочие пространства", + files: "Файлы", + actions: "Действия", + }, newAgent: "Новый агент", open: "Открыть {{name}}", openInSidePane: "Открыть {{name}} в боковой панели", @@ -263,7 +272,7 @@ export const ru: TranslationResources = { states: { notFound: "Агент не найден", failedToLoad: "Не удалось загрузить агента", - reconnecting: "Повторное подключение к хосту", + reconnecting: "Повторное подключение", updating: "Обновление сообщений", timelineSyncFailed: "Не удалось обновить историю агента.", timelineSyncRetrying: "Повторная попытка…", @@ -389,6 +398,7 @@ export const ru: TranslationResources = { otherPlaceholder: "Другой ответ...", }, backgroundWork: { + heartbeat: "Периодический сигнал", pillOne: "1 фоновая задача", pillMany: "Фоновые задачи: {{count}}", notRunning: "Больше не выполняется", @@ -480,7 +490,7 @@ export const ru: TranslationResources = { restoreDescription: "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.", restoreWithoutBranchDescription: - "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.", + "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.", unarchiveDescription: "Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.", restoreAction: "Восстановить", @@ -2042,6 +2052,7 @@ export const ru: TranslationResources = { hostUnavailable: "Хост загрузки недоступен.", cancelled: "Загрузка отменена.", failed: "Не удалось загрузить файл.", + httpFailed: "Не удалось загрузить файл (HTTP {{status}}).", shareFile: "Поделиться файлом", shareFileNamed: "Поделиться {{fileName}}", }, @@ -2236,6 +2247,7 @@ export const ru: TranslationResources = { turnOn: "Включить", options: "Настройки", + host: "Хост", refreshFailed: "Не удалось обновить использование", noHosts: "Нет подключённых хостов", agentError: "Не удалось загрузить использование: {{reason}}", @@ -2252,6 +2264,8 @@ export const ru: TranslationResources = { loginExpired: "Срок входа истёк {{relativeTime}}. {{remedy}}", title: "Использование плана", refresh: "Обновить", + reorderCard: "Переместить {{source}}", + showCard: "Показывать {{source}}", refreshAll: "Обновить всё", refreshing: "Обновление...", loading: "Загрузка данных об использовании...", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 626d427eff..8b863abcd8 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -90,14 +90,23 @@ export const zhCN: TranslationResources = { close: "关闭菜单", }, commandCenter: { - placeholder: "搜索命令、文件、工作区和 Agent...", + placeholder: "搜索工作区、文件和操作...", + placeholderWithoutFiles: "搜索工作区和操作...", filePlaceholder: "搜索文件...", + workspacePlaceholder: "搜索工作区...", + actionPlaceholder: "搜索操作...", searchingFiles: "正在搜索文件...", noMatches: "没有匹配项", actions: "操作", files: "文件", workspaces: "工作区", - agents: "Agents", + recentWorkspaces: "最近的工作区", + tabs: { + all: "全部", + workspaces: "工作区", + files: "文件", + actions: "操作", + }, newAgent: "新建 Agent", open: "打开{{name}}", openInSidePane: "在侧边面板中打开{{name}}", @@ -261,7 +270,7 @@ export const zhCN: TranslationResources = { states: { notFound: "未找到 Agent", failedToLoad: "加载 Agent 失败", - reconnecting: "正在重新连接主机", + reconnecting: "正在重新连接", updating: "正在更新消息", timelineSyncFailed: "无法刷新代理历史记录。", timelineSyncRetrying: "正在重试…", @@ -385,6 +394,7 @@ export const zhCN: TranslationResources = { otherPlaceholder: "其他...", }, backgroundWork: { + heartbeat: "心跳", pillOne: "1 个后台任务", pillMany: "{{count}} 个后台任务", notRunning: "已不再运行", @@ -475,8 +485,7 @@ export const zhCN: TranslationResources = { archivedTitle: "Workspace 已归档", restoreDescription: "恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。", - restoreWithoutBranchDescription: - "恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。", + restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。", unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。", restoreAction: "恢复", unarchiveAction: "取消归档", @@ -1985,6 +1994,7 @@ export const zhCN: TranslationResources = { hostUnavailable: "下载 Host 不可用。", cancelled: "下载已取消。", failed: "下载文件失败。", + httpFailed: "下载文件失败 (HTTP {{status}}).", shareFile: "共享文件", shareFileNamed: "共享 {{fileName}}", }, @@ -2178,6 +2188,7 @@ export const zhCN: TranslationResources = { turnOn: "开启", options: "设置", + host: "主机", refreshFailed: "无法刷新用量", noHosts: "没有已连接的主机", agentError: "无法加载用量:{{reason}}", @@ -2194,6 +2205,8 @@ export const zhCN: TranslationResources = { loginExpired: "登录已于{{relativeTime}}过期。{{remedy}}", title: "套餐用量", refresh: "刷新", + reorderCard: "重新排序 {{source}}", + showCard: "显示 {{source}}", refreshAll: "全部刷新", refreshing: "刷新中...", loading: "正在加载用量...", diff --git a/packages/app/src/keyboard/index.ts b/packages/app/src/keyboard/index.ts index c8836c8e08..7659ba333b 100644 --- a/packages/app/src/keyboard/index.ts +++ b/packages/app/src/keyboard/index.ts @@ -8,6 +8,8 @@ export { subscribeOverlays, } from "./internal/overlay-dispatch"; export { useKeyboardFocusSurface } from "./internal/use-focus-surface"; +export { subscribeHardwareKeyboard } from "./internal/sources/hardware"; +export type { HardwareKeyboardEvent } from "./internal/sources/hardware"; export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions"; export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser"; export { useHardwareKeyboardPresent } from "./availability"; diff --git a/packages/app/src/keyboard/internal/focus-surfaces.ts b/packages/app/src/keyboard/internal/focus-surfaces.ts index 5bdeb6fa0d..e13526176e 100644 --- a/packages/app/src/keyboard/internal/focus-surfaces.ts +++ b/packages/app/src/keyboard/internal/focus-surfaces.ts @@ -4,20 +4,32 @@ export type KeyboardFocusSurface = "message-input" | "terminal"; export function createKeyboardFocusScope(hasEditableFocus: () => boolean = () => false) { const surfaces = new Map(); + const listeners = new Set<() => void>(); + const notify = () => { + for (const listener of listeners) listener(); + }; return { declare(surface: KeyboardFocusSurface) { const token = Symbol(surface); surfaces.set(token, surface); + notify(); return () => { - surfaces.delete(token); + if (surfaces.delete(token)) notify(); }; }, - resolve(commandCenterOpen: boolean): KeyboardFocusScope { + /** Pass `editableFocused` to resolve for a text control that is not a declared surface. */ + resolve(commandCenterOpen: boolean, editableFocused = hasEditableFocus()): KeyboardFocusScope { if (commandCenterOpen) return "command-center"; - let focused: KeyboardFocusScope = hasEditableFocus() ? "editable" : "other"; + let focused: KeyboardFocusScope = editableFocused ? "editable" : "other"; for (const surface of surfaces.values()) focused = surface; return focused; }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, }; } export const focusSurfaces = createKeyboardFocusScope(hasFocusedTextInput); diff --git a/packages/app/src/keyboard/internal/overlay-contract.ts b/packages/app/src/keyboard/internal/overlay-contract.ts index 1061ecc42a..d5152e3518 100644 --- a/packages/app/src/keyboard/internal/overlay-contract.ts +++ b/packages/app/src/keyboard/internal/overlay-contract.ts @@ -3,6 +3,10 @@ import type { KeyboardInputEvent } from "./overlays"; export interface OverlayRegistration { active: boolean; layer: number; + /** + * Keys the overlay handles. Native forwards only these. On web, declaring "Tab" hands Tab to + * `onKeyDown` instead of the focus trap. + */ keys: readonly string[]; onKeyDown(event: KeyboardInputEvent): boolean; restoreFocusRef?: RefObject; diff --git a/packages/app/src/keyboard/internal/overlay-registration.web.ts b/packages/app/src/keyboard/internal/overlay-registration.web.ts index 92beb60acf..1d579c5e31 100644 --- a/packages/app/src/keyboard/internal/overlay-registration.web.ts +++ b/packages/app/src/keyboard/internal/overlay-registration.web.ts @@ -85,7 +85,9 @@ function dispatchOverlayEntry(entry: WebOverlayEntry, event: KeyboardInputEvent) const scope = entry.getScope(); if (!scope) return top.getKeyHandler()(event); - if (top.manageFocus && event.key === "Tab") { + // An overlay that declares Tab owns it (the command center rotates its tabs); the focus trap + // only moves focus for overlays that leave Tab alone. + if (top.manageFocus && event.key === "Tab" && !top.getKeys().includes("Tab")) { const focusable = getFocusableElements(scope); const first = focusable[0]; const last = focusable[focusable.length - 1]; diff --git a/packages/app/src/keyboard/internal/sources/contract.ts b/packages/app/src/keyboard/internal/sources/contract.ts index 886dbc3548..69de22f09e 100644 --- a/packages/app/src/keyboard/internal/sources/contract.ts +++ b/packages/app/src/keyboard/internal/sources/contract.ts @@ -10,6 +10,7 @@ export interface KeyboardSourceHandlers { keyUp(event: KeyboardInputEvent): void; blur(): void; commandCenterOpen(): boolean; + subscribeCommandCenter(listener: () => void): () => void; } export function nativeKeyboardInput( event: KeyboardInputEvent, @@ -23,5 +24,6 @@ export interface KeyboardPolicyInput { bindings: readonly ParsedShortcutBinding[]; chordState?: ChordState; isMac: boolean; + usesDesktopBindings: boolean; enabled: boolean; } diff --git a/packages/app/src/keyboard/internal/sources/electron-browser.test.ts b/packages/app/src/keyboard/internal/sources/electron-browser.test.ts index abcc98b7fd..8ac3ac9949 100644 --- a/packages/app/src/keyboard/internal/sources/electron-browser.test.ts +++ b/packages/app/src/keyboard/internal/sources/electron-browser.test.ts @@ -366,7 +366,13 @@ describe("Electron guest source through shared resolution", () => { }, captureFocusRestore: (id) => restored.push(id), }, - { keyDown: pipeline.keyDown, keyUp() {}, blur() {}, commandCenterOpen: () => false }, + { + keyDown: pipeline.keyDown, + keyUp() {}, + blur() {}, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }, ); receive({ browserId: "tab-1", diff --git a/packages/app/src/keyboard/internal/sources/hardware.android.ts b/packages/app/src/keyboard/internal/sources/hardware.android.ts index cfe7a15cb9..b0e0d41155 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.android.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.android.ts @@ -1,5 +1,5 @@ import { requireNativeModule } from "expo-modules-core"; -import type { HardwareKeyboardEvent } from "./hardware"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeyboardModule { getHardwareKeyboardPresent(): boolean; addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void }; @@ -19,6 +19,9 @@ export function subscribeHardwareKeyboard( export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void { module.setOverlayKeys(keys); } +// A focused Android EditText types nothing for Tab, Shift+Tab or Alt+Shift+[, +// so there is no character to take from it. +export function setHardwareKeyboardClaimedShortcuts(_shortcuts: readonly ClaimedShortcut[]): void {} export function getHardwareKeyboardPresent(): boolean { return module.getHardwareKeyboardPresent(); diff --git a/packages/app/src/keyboard/internal/sources/hardware.ios.ts b/packages/app/src/keyboard/internal/sources/hardware.ios.ts index cfe7a15cb9..2745b51ba9 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.ios.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.ios.ts @@ -1,9 +1,10 @@ import { requireNativeModule } from "expo-modules-core"; -import type { HardwareKeyboardEvent } from "./hardware"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeyboardModule { getHardwareKeyboardPresent(): boolean; addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void }; setOverlayKeys(keys: readonly string[]): void; + setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; addListener( event: "onHardwareKeyboardShortcut", handler: (event: HardwareKeyboardEvent) => void, @@ -19,6 +20,9 @@ export function subscribeHardwareKeyboard( export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void { module.setOverlayKeys(keys); } +export function setHardwareKeyboardClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void { + module.setClaimedShortcuts(shortcuts); +} export function getHardwareKeyboardPresent(): boolean { return module.getHardwareKeyboardPresent(); diff --git a/packages/app/src/keyboard/internal/sources/hardware.ts b/packages/app/src/keyboard/internal/sources/hardware.ts index c6631886d1..33afb7eabb 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.ts @@ -3,12 +3,19 @@ export interface HardwareKeyboardEvent extends KeyboardShortcutInput { isComposing: boolean; phase: "down" | "up"; } +/** A shortcut the native window takes from the focused text control, by DOM `code`. */ +export interface ClaimedShortcut { + code: string; + shift: boolean; + alt: boolean; +} export function subscribeHardwareKeyboard( _handler: (event: HardwareKeyboardEvent) => void, ): () => void { return () => {}; } export function setHardwareKeyboardOverlayKeys(_keys: readonly string[]): void {} +export function setHardwareKeyboardClaimedShortcuts(_shortcuts: readonly ClaimedShortcut[]): void {} export function getHardwareKeyboardPresent(): boolean { return false; diff --git a/packages/app/src/keyboard/internal/sources/index.ts b/packages/app/src/keyboard/internal/sources/index.ts index 5d886b979a..570251a083 100644 --- a/packages/app/src/keyboard/internal/sources/index.ts +++ b/packages/app/src/keyboard/internal/sources/index.ts @@ -1,11 +1,19 @@ -import type { KeyboardSourceHandlers } from "./contract"; -import { setHardwareKeyboardOverlayKeys, subscribeHardwareKeyboard } from "./hardware"; -import { attachHardwareKeyboardSource } from "./native"; +import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract"; +import { + setHardwareKeyboardClaimedShortcuts, + setHardwareKeyboardOverlayKeys, + subscribeHardwareKeyboard, +} from "./hardware"; +import { createHardwareKeyboardSource } from "./native"; +const hardwareKeyboard = createHardwareKeyboardSource({ + subscribe: subscribeHardwareKeyboard, + setOverlayKeys: setHardwareKeyboardOverlayKeys, + setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts, +}); export function attachKeyboardSources(handlers: KeyboardSourceHandlers): () => void { - return attachHardwareKeyboardSource( - { subscribe: subscribeHardwareKeyboard, setOverlayKeys: setHardwareKeyboardOverlayKeys }, - handlers, - ); + return hardwareKeyboard.attach(handlers); } -export function publishKeyboardPolicy(_input: import("./contract").KeyboardPolicyInput): void {} +export function publishKeyboardPolicy(input: KeyboardPolicyInput): void { + hardwareKeyboard.publishPolicy(input); +} diff --git a/packages/app/src/keyboard/internal/sources/index.web.ts b/packages/app/src/keyboard/internal/sources/index.web.ts index da6023be5b..e915c38180 100644 --- a/packages/app/src/keyboard/internal/sources/index.web.ts +++ b/packages/app/src/keyboard/internal/sources/index.web.ts @@ -1,4 +1,3 @@ -import { usesDesktopBindings } from "../conventions"; import { getDesktopHost } from "@/desktop/host"; import { getResidentBrowserWebview } from "@/desktop/browser/resident-webviews"; import { setCommandCenterFocusRestoreElement } from "@/utils/command-center-focus-restore"; @@ -26,7 +25,7 @@ export function attachKeyboardSources(handlers: KeyboardSourceHandlers): () => v } export function publishKeyboardPolicy(input: import("./contract").KeyboardPolicyInput): void { const policy = input.enabled - ? buildBrowserKeyboardPolicy({ ...input, usesDesktopBindings: usesDesktopBindings }) + ? buildBrowserKeyboardPolicy(input) : { menuPrefixes: [], prefixes: [] }; void getDesktopHost()?.browser?.setShortcutPolicy?.(policy); } diff --git a/packages/app/src/keyboard/internal/sources/native.ts b/packages/app/src/keyboard/internal/sources/native.ts index 995e9df491..9d76abe0a6 100644 --- a/packages/app/src/keyboard/internal/sources/native.ts +++ b/packages/app/src/keyboard/internal/sources/native.ts @@ -1,31 +1,92 @@ +import { matchesKeyboardShortcutContext } from "../../keyboard-shortcuts"; import { focusSurfaces } from "../focus-surfaces"; import { overlays } from "../overlays"; -import { nativeKeyboardInput, type KeyboardSourceHandlers } from "./contract"; -import type { HardwareKeyboardEvent } from "./hardware"; +import { + nativeKeyboardInput, + type KeyboardPolicyInput, + type KeyboardSourceHandlers, +} from "./contract"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeySource { subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void; setOverlayKeys(keys: readonly string[]): void; + setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; } -export function attachHardwareKeyboardSource( - source: HardwareKeySource, - handlers: KeyboardSourceHandlers, -): () => void { - const updateKeys = () => source.setOverlayKeys(overlays.getKeys()); - updateKeys(); - const unsubscribeOverlays = overlays.subscribe(updateKeys); - const unsubscribeHardware = source.subscribe((input) => { - const event = { ...input, preventDefault() {}, stopPropagation() {} }; - if (input.phase === "up") { - handlers.keyUp(event); - return; + +const DIGIT_CODES = Array.from({ length: 9 }, (_, index) => `Digit${index + 1}`); + +/** + * The shortcuts a focused text control would otherwise type or act on. + * + * The native window observes every press but cannot wait for the pipeline to + * decide, so it has to claim these keys up front: without a claim, Shift+Tab + * cycles the agent mode and the composer also inserts a tab. Cmd and Ctrl + * combos do not type, and the platform's own editing combos stay with the text + * control through `editable: false`. Unmodified keys belong to overlays and the + * composer's Return. + */ +function claimedShortcuts( + policy: KeyboardPolicyInput | null, + commandCenterOpen: boolean, +): ClaimedShortcut[] { + if (!policy?.enabled) return []; + const context = { + isMac: policy.isMac, + usesDesktopBindings: policy.usesDesktopBindings, + commandCenterOpen, + focusScope: focusSurfaces.resolve(commandCenterOpen, true), + }; + const claimed = new Map(); + for (const binding of policy.bindings) { + const combo = binding.parsedChord[0]; + if (!combo || binding.preventDefault === false) continue; + if (combo.meta || combo.ctrl || combo.mod || !(combo.shift || combo.alt)) continue; + if (!matchesKeyboardShortcutContext(binding.when, context)) continue; + const shift = combo.shift === true; + const alt = combo.alt === true; + for (const code of combo.code === "Digit" ? DIGIT_CODES : [combo.code]) { + claimed.set(`${code}:${shift}:${alt}`, { code, shift, alt }); } - handlers.keyDown( - nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), - ); - }); - return () => { - unsubscribeHardware(); - unsubscribeOverlays(); - source.setOverlayKeys([]); + } + return [...claimed.values()]; +} + +export function createHardwareKeyboardSource(source: HardwareKeySource) { + let policy: KeyboardPolicyInput | null = null; + let updateClaims = () => {}; + return { + publishPolicy(next: KeyboardPolicyInput) { + policy = next; + updateClaims(); + }, + attach(handlers: KeyboardSourceHandlers): () => void { + const updateKeys = () => source.setOverlayKeys(overlays.getKeys()); + updateClaims = () => + source.setClaimedShortcuts(claimedShortcuts(policy, handlers.commandCenterOpen())); + updateKeys(); + updateClaims(); + const unsubscribeOverlays = overlays.subscribe(updateKeys); + const unsubscribeFocus = focusSurfaces.subscribe(() => updateClaims()); + const unsubscribeCommandCenter = handlers.subscribeCommandCenter(() => updateClaims()); + const unsubscribeHardware = source.subscribe((input) => { + const event = { ...input, preventDefault() {}, stopPropagation() {} }; + if (input.phase === "up") { + handlers.keyUp(event); + return; + } + handlers.keyDown( + nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), + ); + }); + return () => { + unsubscribeHardware(); + unsubscribeFocus(); + unsubscribeCommandCenter(); + unsubscribeOverlays(); + updateClaims = () => {}; + source.setOverlayKeys([]); + source.setClaimedShortcuts([]); + }; + }, }; } diff --git a/packages/app/src/keyboard/keyboard-shortcuts.test.ts b/packages/app/src/keyboard/keyboard-shortcuts.test.ts index 9eddf4b5b5..03066dedd7 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.test.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.test.ts @@ -226,6 +226,20 @@ describe("keyboard-shortcuts", () => { action: "workspace.tab.navigate.relative", payload: { delta: 1 }, }, + { + name: "matches tab relative navigation on macOS desktop via Cmd+Shift+[", + event: { key: "{", code: "BracketLeft", metaKey: true, shiftKey: true }, + context: { isMac: true, usesDesktopBindings: true }, + action: "workspace.tab.navigate.relative", + payload: { delta: -1 }, + }, + { + name: "matches tab relative navigation on macOS desktop via Cmd+Shift+]", + event: { key: "}", code: "BracketRight", metaKey: true, shiftKey: true }, + context: { isMac: true, usesDesktopBindings: true }, + action: "workspace.tab.navigate.relative", + payload: { delta: 1 }, + }, { name: "matches Mod+T to open new tab", event: { key: "t", code: "KeyT", metaKey: true }, @@ -479,6 +493,11 @@ describe("keyboard-shortcuts", () => { event: { key: "w", code: "KeyW", ctrlKey: true }, context: { isMac: false, usesDesktopBindings: true, focusScope: "terminal" }, }, + { + name: "does not switch tabs with Alt+Shift+] on mac desktop (Cmd+Shift+] only)", + event: { key: "’", code: "BracketRight", altKey: true, shiftKey: true }, + context: { isMac: true, usesDesktopBindings: true }, + }, { name: "does not match Ctrl+T on mac (Cmd only)", event: { key: "t", code: "KeyT", ctrlKey: true }, @@ -1306,6 +1325,17 @@ describe("unassigned shortcuts", () => { expect(getBindingIdForAction("workspace-tab-new", desktopNonMac)).toBe(TAB_NEW_BINDING); }); + it("advertises Cmd+Shift+brackets for tab navigation on macOS desktop", () => { + const desktopMac = { isMac: true, usesDesktopBindings: true }; + + expect(getDefaultKeysForAction("workspace-tab-prev", desktopMac)).toEqual([ + ["mod", "shift", "["], + ]); + expect(getDefaultKeysForAction("workspace-tab-next", desktopMac)).toEqual([ + ["mod", "shift", "]"], + ]); + }); + it("still lists the default keys when nothing is overridden", () => { const sections = buildKeyboardShortcutHelpSections(desktopNonMac); diff --git a/packages/app/src/keyboard/keyboard-shortcuts.ts b/packages/app/src/keyboard/keyboard-shortcuts.ts index d6db467da3..ef929903c6 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.ts @@ -715,11 +715,37 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ }, // --- Tab relative navigation --- + // macOS desktop uses Cmd+Shift+brackets; the browser owns those keys, so + // macOS web keeps Alt+Shift alongside every non-mac platform. + { + id: "workspace-tab-navigate-relative-cmd-shift-left-mac", + action: "workspace.tab.navigate.relative", + combo: "Cmd+Shift+[", + when: { mac: true, desktopBindings: true, commandCenter: false }, + payload: { type: "delta", delta: -1 }, + help: { + id: "workspace-tab-prev", + section: "tabs-panes", + label: "Previous tab", + }, + }, + { + id: "workspace-tab-navigate-relative-cmd-shift-right-mac", + action: "workspace.tab.navigate.relative", + combo: "Cmd+Shift+]", + when: { mac: true, desktopBindings: true, commandCenter: false }, + payload: { type: "delta", delta: 1 }, + help: { + id: "workspace-tab-next", + section: "tabs-panes", + label: "Next tab", + }, + }, { id: "workspace-tab-navigate-relative-alt-shift-left", action: "workspace.tab.navigate.relative", combo: "Alt+Shift+[", - when: { commandCenter: false }, + when: { mac: false, commandCenter: false }, payload: { type: "delta", delta: -1 }, help: { id: "workspace-tab-prev", @@ -731,7 +757,31 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ id: "workspace-tab-navigate-relative-alt-shift-right", action: "workspace.tab.navigate.relative", combo: "Alt+Shift+]", - when: { commandCenter: false }, + when: { mac: false, commandCenter: false }, + payload: { type: "delta", delta: 1 }, + help: { + id: "workspace-tab-next", + section: "tabs-panes", + label: "Next tab", + }, + }, + { + id: "workspace-tab-navigate-relative-alt-shift-left-mac-web", + action: "workspace.tab.navigate.relative", + combo: "Alt+Shift+[", + when: { mac: true, desktopBindings: false, commandCenter: false }, + payload: { type: "delta", delta: -1 }, + help: { + id: "workspace-tab-prev", + section: "tabs-panes", + label: "Previous tab", + }, + }, + { + id: "workspace-tab-navigate-relative-alt-shift-right-mac-web", + action: "workspace.tab.navigate.relative", + combo: "Alt+Shift+]", + when: { mac: true, desktopBindings: false, commandCenter: false }, payload: { type: "delta", delta: 1 }, help: { id: "workspace-tab-next", diff --git a/packages/app/src/keyboard/native-shortcuts.browser.test.ts b/packages/app/src/keyboard/native-shortcuts.browser.test.ts index 004eb912b2..22bd6e16ad 100644 --- a/packages/app/src/keyboard/native-shortcuts.browser.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.browser.test.ts @@ -25,6 +25,7 @@ describe("DOM source adapter", () => { keyUp() {}, blur() {}, commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, }); const event = new KeyboardEvent("keydown", { key: "j", diff --git a/packages/app/src/keyboard/native-shortcuts.test.ts b/packages/app/src/keyboard/native-shortcuts.test.ts index e155fa2ba1..d4c4edc24f 100644 --- a/packages/app/src/keyboard/native-shortcuts.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.test.ts @@ -130,7 +130,7 @@ describe("hardware source adapter", () => { it.each([true, false])( "delivers hardware down/up and declared focus with mac=%s", async (isMac) => { - const { attachHardwareKeyboardSource } = await import("./internal/sources/native"); + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); const { focusSurfaces } = await import("./internal/focus-surfaces"); const actions: string[] = []; const releases: string[] = []; @@ -148,23 +148,22 @@ describe("hardware source adapter", () => { }, overlays: createOverlayRegistry(), }); - const detach = attachHardwareKeyboardSource( - { - subscribe(handler) { - events.add(handler); - return () => { - events.delete(handler); - }; - }, - setOverlayKeys() {}, + const detach = createHardwareKeyboardSource({ + subscribe(handler) { + events.add(handler); + return () => { + events.delete(handler); + }; }, - { - keyDown: pipeline.keyDown, - keyUp: (event) => releases.push(event.key), - blur() {}, - commandCenterOpen: () => false, - }, - ); + setOverlayKeys() {}, + setClaimedShortcuts() {}, + }).attach({ + keyDown: pipeline.keyDown, + keyUp: (event) => releases.push(event.key), + blur() {}, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }); const down = { ...keyboardEvent("k", "KeyK", isMac), isComposing: false, @@ -180,4 +179,94 @@ describe("hardware source adapter", () => { expect(events.size).toBe(0); }, ); + + it("claims the Shift and Option shortcuts a focused text control would otherwise type", async () => { + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); + const { focusSurfaces } = await import("./internal/focus-surfaces"); + let claimed: string[] = []; + const source = createHardwareKeyboardSource({ + subscribe: () => () => {}, + setOverlayKeys() {}, + setClaimedShortcuts(shortcuts) { + claimed = shortcuts + .map(({ code, shift, alt }) => [alt && "Alt", shift && "Shift", code]) + .map((parts) => parts.filter(Boolean).join("+")) + .sort(); + }, + }); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + let commandCenterOpen = false; + const commandCenterListeners = new Set<() => void>(); + const detach = source.attach({ + keyDown() {}, + keyUp() {}, + blur() {}, + commandCenterOpen: () => commandCenterOpen, + subscribeCommandCenter(listener) { + commandCenterListeners.add(listener); + return () => commandCenterListeners.delete(listener); + }, + }); + const setCommandCenterOpen = (open: boolean) => { + commandCenterOpen = open; + for (const listener of commandCenterListeners) listener(); + }; + // iPad tab switching uses Cmd+Shift+[ / ], which no text control types. + expect(claimed).toEqual([]); + + const releaseComposer = focusSurfaces.declare("message-input"); + expect(claimed).toEqual(["Shift+Tab"]); + setCommandCenterOpen(true); + expect(claimed).toEqual([]); + setCommandCenterOpen(false); + expect(claimed).toEqual(["Shift+Tab"]); + releaseComposer(); + expect(claimed).toEqual([]); + + source.publishPolicy({ + bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Alt+M" }), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + const releaseRebound = focusSurfaces.declare("message-input"); + expect(claimed).toEqual(["Alt+KeyM"]); + releaseRebound(); + + // A chord's later step is only a shortcut while the chord is in progress; + // claiming it always would stop the composer typing a capital A. + source.publishPolicy({ + bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Mod+J Shift+A" }), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + const releaseChord = focusSurfaces.declare("message-input"); + expect(claimed).toEqual([]); + releaseChord(); + + const releaseFinal = focusSurfaces.declare("message-input"); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: false, + }); + expect(claimed).toEqual([]); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + expect(claimed).toEqual(["Shift+Tab"]); + detach(); + expect(claimed).toEqual([]); + releaseFinal(); + }); }); diff --git a/packages/app/src/keyboard/route-shortcut.test.ts b/packages/app/src/keyboard/route-shortcut.test.ts index 5eddf3eeff..0aa8ac0cff 100644 --- a/packages/app/src/keyboard/route-shortcut.test.ts +++ b/packages/app/src/keyboard/route-shortcut.test.ts @@ -376,10 +376,10 @@ describe("routeKeyboardShortcut — callbacks and pickers", () => { }); describe("routeKeyboardShortcut — toggle dialogs", () => { - it("opens the command center scoped to files from a workspace", () => { + it("opens the command center on the Files tab from a workspace", () => { expect( routeKeyboardShortcut({ action: "command-center.files", payload: null }, makeCtx()), - ).toEqual({ kind: "command-center-toggle", nextOpen: true, scope: "files" }); + ).toEqual({ kind: "command-center-toggle", nextOpen: true, tab: "files" }); }); it("leaves the file-search shortcut to the project-picker host outside a workspace", () => { diff --git a/packages/app/src/keyboard/route-shortcut.ts b/packages/app/src/keyboard/route-shortcut.ts index 79579689fd..b6207d6f04 100644 --- a/packages/app/src/keyboard/route-shortcut.ts +++ b/packages/app/src/keyboard/route-shortcut.ts @@ -32,7 +32,7 @@ export type ShortcutAction = | { kind: "router-push"; route: string } | { kind: "open-project-picker" } | { kind: "callback"; name: ShortcutCallbackName } - | { kind: "command-center-toggle"; nextOpen: boolean; scope?: "files" } + | { kind: "command-center-toggle"; nextOpen: boolean; tab?: "files" } | { kind: "shortcuts-dialog-toggle"; nextOpen: boolean }; const NONE: ShortcutAction = { kind: "none" }; @@ -212,7 +212,7 @@ export function routeKeyboardShortcut( return { kind: "command-center-toggle", nextOpen: !ctx.commandCenterOpen }; case "command-center.files": if (parseHostWorkspaceRouteFromPathname(ctx.pathname)) { - return { kind: "command-center-toggle", nextOpen: true, scope: "files" }; + return { kind: "command-center-toggle", nextOpen: true, tab: "files" }; } return dispatch({ id: "workspace.project.pick", scope: "workspace" }); case "shortcuts.dialog.toggle": diff --git a/packages/app/src/keyboard/use-shortcuts.ts b/packages/app/src/keyboard/use-shortcuts.ts index b762d8dfcf..700bfb7dc0 100644 --- a/packages/app/src/keyboard/use-shortcuts.ts +++ b/packages/app/src/keyboard/use-shortcuts.ts @@ -62,7 +62,7 @@ export function useKeyboardShortcuts({ const keyboardWorkspaceSelectionRef = useRef(null); const publishBrowserShortcutPolicy = useCallback( (chordState?: ChordState) => { - publishKeyboardPolicy({ bindings, chordState, isMac, enabled }); + publishKeyboardPolicy({ bindings, chordState, isMac, usesDesktopBindings, enabled }); }, [bindings, enabled, isMac], ); @@ -152,9 +152,7 @@ export function useKeyboardShortcuts({ if (action.nextOpen) { captureFocusRestore(); } - useKeyboardShortcutsStore - .getState() - .setCommandCenterOpen(action.nextOpen, action.scope ?? null); + useKeyboardShortcutsStore.getState().setCommandCenterOpen(action.nextOpen, action.tab); return true; } case "shortcuts-dialog-toggle": @@ -265,6 +263,10 @@ export function useKeyboardShortcuts({ keyUp: handleKeyUp, blur: resetModifiers, commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen, + subscribeCommandCenter: (listener) => + useKeyboardShortcutsStore.subscribe((state, previous) => { + if (state.commandCenterOpen !== previous.commandCenterOpen) listener(); + }), }); return () => { detach(); diff --git a/packages/app/src/lib/overlay-root.browser.test.tsx b/packages/app/src/lib/overlay-root.browser.test.tsx index 7f0d5115ac..299c036fc9 100644 --- a/packages/app/src/lib/overlay-root.browser.test.tsx +++ b/packages/app/src/lib/overlay-root.browser.test.tsx @@ -134,6 +134,7 @@ describe("DOM source through the shared resolver", () => { keyUp() {}, blur() {}, commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, }); const event = new KeyboardEvent("keydown", { key: "j", diff --git a/packages/app/src/mobile-panels/model.test.ts b/packages/app/src/mobile-panels/model.test.ts index ca4ef04a8a..a77c9684bc 100644 --- a/packages/app/src/mobile-panels/model.test.ts +++ b/packages/app/src/mobile-panels/model.test.ts @@ -305,3 +305,22 @@ describe("mobile panel ownership", () => { }); }); }); + +it("lands an explicit destination while the sidebar is suspended without a slide", () => { + const state = createMobilePanelMotionState({ target: "agent-list", revision: 1 }); + const result = transitionMobilePanel(state, { + type: "command", + selection: { target: "agent", revision: 2 }, + immediate: true, + }); + expect(result).toEqual({ + immediateTarget: "agent", + state: { + target: "agent", + revision: 2, + gesture: null, + motionTarget: "agent", + settledTarget: "agent", + }, + }); +}); diff --git a/packages/app/src/mobile-panels/model.ts b/packages/app/src/mobile-panels/model.ts index 363bcfc450..9b59eea3c6 100644 --- a/packages/app/src/mobile-panels/model.ts +++ b/packages/app/src/mobile-panels/model.ts @@ -17,6 +17,7 @@ export interface MobilePanelCommit { export interface MobilePanelTransition { animationTarget?: MobilePanelView; + immediateTarget?: MobilePanelView; commit?: MobilePanelCommit; state: MobilePanelMotionState; } @@ -48,7 +49,7 @@ function settleMobilePanelAtPosition( } export type MobilePanelEvent = - | { type: "command"; selection: MobilePanelSelection } + | { type: "command"; selection: MobilePanelSelection; immediate?: boolean } | { type: "gesture.begin"; origin: MobilePanelView } | { type: "gesture.finish"; @@ -78,6 +79,17 @@ export function transitionMobilePanel( if (event.selection.revision <= state.revision) { return { state }; } + if (event.immediate) { + return { + immediateTarget: event.selection.target, + state: { + ...event.selection, + gesture: null, + motionTarget: event.selection.target, + settledTarget: event.selection.target, + }, + }; + } // An interrupted drag left the position between anchors, so it moves back even when the // target is unchanged. Without a drag, the command adopts motion already heading there. const continuesCurrentMotion = !state.gesture && state.motionTarget === event.selection.target; diff --git a/packages/app/src/mobile-panels/provider.tsx b/packages/app/src/mobile-panels/provider.tsx index 77c00558ce..8fdf4ab5dc 100644 --- a/packages/app/src/mobile-panels/provider.tsx +++ b/packages/app/src/mobile-panels/provider.tsx @@ -157,6 +157,11 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) { const animateTransition = useCallback( (transition: MobilePanelTransition) => { "worklet"; + if (transition.immediateTarget) { + cancelAnimation(position); + position.value = getMobilePanelAnchor(transition.immediateTarget); + return; + } if (!transition.animationTarget) { return; } @@ -170,25 +175,27 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) { ); const applySelection = useCallback( - (selection: MobilePanelSelection) => { + (selection: MobilePanelSelection, immediate: boolean) => { "worklet"; const currentState = motionState.value; const transition = transitionMobilePanel(currentState, { type: "command", selection, + immediate, }); if (transition.state === currentState) { return; } motionState.value = transition.state; animateTransition(transition); + if (immediate) scheduleOnRN(publishActivePanel, selection.target, selection.revision); }, - [animateTransition, motionState], + [animateTransition, motionState, publishActivePanel], ); useEffect(() => { - return subscribeMobilePanelSelection((selection) => { - scheduleOnUI(applySelection, selection); + return subscribeMobilePanelSelection((selection, immediate) => { + scheduleOnUI(applySelection, selection, immediate); }); }, [applySelection]); diff --git a/packages/app/src/mobile-panels/selection.ts b/packages/app/src/mobile-panels/selection.ts index f47d9e737c..2ee7769b37 100644 --- a/packages/app/src/mobile-panels/selection.ts +++ b/packages/app/src/mobile-panels/selection.ts @@ -2,13 +2,14 @@ import { usePanelStore, type MobilePanelSelection } from "@/stores/panel-store"; /** Observe panel commands, including layout commands published before subscription. */ export function subscribeMobilePanelSelection( - onSelection: (selection: MobilePanelSelection) => void, + onSelection: (selection: MobilePanelSelection, immediate: boolean) => void, ) { const unsubscribe = usePanelStore.subscribe((state, previousState) => { if (state.mobilePanel !== previousState.mobilePanel) { - onSelection(state.mobilePanel); + onSelection(state.mobilePanel, state.layout.leftSidebar === "suspended"); } }); - onSelection(usePanelStore.getState().mobilePanel); + const state = usePanelStore.getState(); + onSelection(state.mobilePanel, state.layout.leftSidebar === "suspended"); return unsubscribe; } diff --git a/packages/app/src/navigation/settings-navigation.ts b/packages/app/src/navigation/settings-navigation.ts index 123b23077a..34989d9d21 100644 --- a/packages/app/src/navigation/settings-navigation.ts +++ b/packages/app/src/navigation/settings-navigation.ts @@ -1,5 +1,8 @@ import { router, type Href } from "expo-router"; -import { navigateToLastWorkspace } from "@/stores/navigation-active-workspace-store"; +import { + navigateToWorkspace, + navigateToLastWorkspace, +} from "@/stores/navigation-active-workspace-store"; import { buildOpenProjectRoute, buildProjectSettingsRoute, @@ -10,8 +13,30 @@ import { type SettingsSectionSlug, } from "@/utils/host-routes"; +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; +import { usePanelStore } from "@/stores/panel-store"; +import { + beginSettingsSidebarVisit, + getSettingsSidebarReturn, +} from "@/navigation/settings-presentation/session"; + +export function openSettingsFromSidebar(input: { + workspace: ActiveWorkspaceSelection | null; + isCompact: boolean; + route?: Href; +}): void { + const panels = usePanelStore.getState(); + if (input.isCompact && input.workspace && panels.mobilePanel.target === "agent-list") { + beginSettingsSidebarVisit(input.workspace); + } else { + panels.showMobileAgent(); + } + router.push(input.route ?? buildSettingsRoute()); +} + export type SettingsView = - | { kind: "plugin"; serverId: string; pluginId: string; screenId: string } + | { kind: "plugin"; serverId: string; pluginId: string; screenId?: string } + | { kind: "pluginListing"; serverId: string; listingId: string } | { kind: "root" } | { kind: "section"; section: SettingsSectionSlug } | { kind: "host"; serverId: string; section: HostSectionSlug } @@ -27,14 +52,27 @@ export function openProjectSettings(serverId: string, projectId: string): void { export function returnFromSettings(view: SettingsView): void { if (view.kind === "root") { + const destination = getSettingsSidebarReturn(); + if (destination && usePanelStore.getState().mobilePanel.target === "agent-list") { + navigateToWorkspace({ + serverId: destination.serverId, + workspaceId: destination.workspaceId, + surface: "sidebar", + }); + return; + } if (!navigateToLastWorkspace()) { + // Detail pages such as a plugin's page are pushed onto Settings; replacing only the top + // entry would leave the rest of Settings mounted underneath. + if (router.canDismiss()) router.dismissAll(); router.replace(buildOpenProjectRoute()); } return; } let parent: Href = buildSettingsRoute(); - if (view.kind === "plugin") parent = buildSettingsHostSectionRoute(view.serverId, "plugins"); + if (view.kind === "plugin" || view.kind === "pluginListing") + parent = buildSettingsHostSectionRoute(view.serverId, "plugins"); if (view.kind === "project") parent = buildProjectsSettingsRoute(view.serverId); router.dismissTo(parent as Href); } diff --git a/packages/app/src/navigation/settings-presentation/index.ts b/packages/app/src/navigation/settings-presentation/index.ts index cdf86b0d19..62dbb30223 100644 --- a/packages/app/src/navigation/settings-presentation/index.ts +++ b/packages/app/src/navigation/settings-presentation/index.ts @@ -1,19 +1,24 @@ +import { useIsCompactFormFactor } from "@/constants/layout"; +import { usePanelStore, type LeftSidebarPresentation } from "@/stores/panel-store"; import { useCallback, useLayoutEffect, useRef } from "react"; import { ScrollView, type NativeScrollEvent, type NativeSyntheticEvent } from "react-native"; import { usePathname, useRootNavigationState } from "expo-router"; +import { useIsFocused, type ParamListBase } from "expo-router/react-navigation"; +import { useNavigation } from "expo-router"; +import type { NativeStackNavigationProp } from "expo-router/native-stack"; +import { isWeb } from "@/constants/platform"; import { useStore } from "zustand"; import { useIsLastWorkspaceSelectionHydrated, useLastWorkspaceSelection, } from "@/stores/navigation-active-workspace-store"; -import { createSettingsPresentation } from "./model"; - -const selection = createSettingsPresentation(); +import { settingsPresentation as selection } from "./session"; // Mount once above the sibling Settings routes so replacements and Back share // one visit, and leaving Settings gives the next workspace entry a fresh default. export function useSettingsRouteEntry(): void { const pathname = usePathname(); + const isCompact = useIsCompactFormFactor(); const navigationState = useRootNavigationState(); const routeKey = navigationState?.routes[navigationState.index]?.key; const workspace = useLastWorkspaceSelection(); @@ -21,15 +26,46 @@ export function useSettingsRouteEntry(): void { const workspaceServerId = workspace?.serverId ?? null; useLayoutEffect(() => { if (isWorkspaceHydrated && routeKey) { - selection.enterRoute({ key: routeKey, pathname }, workspaceServerId); + if (!isCompact) selection.clearSidebarReturn(); + if (selection.enterRoute({ key: routeKey, pathname }, workspaceServerId)) { + usePanelStore.getState().showMobileAgent(); + } } - }, [pathname, routeKey, workspaceServerId, isWorkspaceHydrated]); + }, [pathname, routeKey, workspaceServerId, isWorkspaceHydrated, isCompact]); } export function useSettingsHostSelection(): string | null { return useStore(selection.store, (state) => state.selectedServerId); } +export function useSettingsSidebarPresentation(input: { + presentation: LeftSidebarPresentation; + visible: boolean; +}): { presentation: LeftSidebarPresentation; visible: boolean } { + const origin = useStore(selection.store, (state) => state.sidebarReturn); + const pathname = usePathname(); + const compact = useIsCompactFormFactor(); + if (compact && origin && (pathname === "/settings" || pathname.startsWith("/settings/"))) { + return { presentation: "suspended", visible: origin.phase === "opening" }; + } + return input; +} + +// Native layout precedes screen appearance; only the navigator can finish that handoff. +export function useSettingsContentPresented() { + const focused = useIsFocused(); + const navigation = useNavigation>(); + useLayoutEffect(() => { + if (isWeb) return; + return navigation.addListener("transitionEnd", ({ data }) => { + if (!data.closing) selection.presentContent(); + }); + }, [navigation]); + return useCallback(() => { + if (isWeb && focused) selection.presentContent(); + }, [focused]); +} + export const selectSettingsHost = selection.selectHost; // Sibling routes remount the wide sidebar. Only the current mount owns its diff --git a/packages/app/src/navigation/settings-presentation/model.test.ts b/packages/app/src/navigation/settings-presentation/model.test.ts index a8970b17b4..73188bb39e 100644 --- a/packages/app/src/navigation/settings-presentation/model.test.ts +++ b/packages/app/src/navigation/settings-presentation/model.test.ts @@ -130,3 +130,39 @@ describe("Settings sidebar presentation", () => { expect(settings.attachSidebar().offset).toBe(0); }); }); + +describe("Settings sidebar return", () => { + it("retains the origin through nested Settings and consumes it on return", () => { + const settings = createSettingsPresentation(); + const origin = { serverId: "host", workspaceId: "workspace" }; + settings.beginSidebarVisit(origin); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + settings.enterRoute({ key: "appearance", pathname: "/settings/appearance" }, "host"); + expect(settings.store.getState().sidebarReturn).toEqual({ ...origin, phase: "opening" }); + settings.presentContent(); + expect(settings.store.getState().sidebarReturn).toEqual({ ...origin, phase: "covered" }); + expect( + settings.enterRoute({ key: "workspace", pathname: "/h/host/workspace/workspace" }, "host"), + ).toBe(false); + expect(settings.store.getState().sidebarReturn).toBeNull(); + }); + + it("discards the sidebar when returning to a different workspace", () => { + const settings = createSettingsPresentation(); + settings.beginSidebarVisit({ serverId: "host", workspaceId: "workspace" }); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + expect(settings.enterRoute({ key: "other", pathname: "/h/host/workspace/other" }, "host")).toBe( + true, + ); + expect(settings.store.getState().sidebarReturn).toBeNull(); + }); + + it("does not carry sidebar returns into another visit or a wide layout", () => { + const settings = createSettingsPresentation(); + settings.beginSidebarVisit({ serverId: "host", workspaceId: "workspace" }); + settings.clearSidebarReturn(); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + expect(settings.store.getState().sidebarReturn).toBeNull(); + expect(createSettingsPresentation().store.getState().sidebarReturn).toBeNull(); + }); +}); diff --git a/packages/app/src/navigation/settings-presentation/model.ts b/packages/app/src/navigation/settings-presentation/model.ts index 2a88e9d82b..c6784a11cf 100644 --- a/packages/app/src/navigation/settings-presentation/model.ts +++ b/packages/app/src/navigation/settings-presentation/model.ts @@ -1,3 +1,5 @@ +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; +import { parseHostWorkspaceRouteFromPathname } from "@/utils/host-routes"; import { createStore } from "zustand/vanilla"; interface SettingsRouteEntry { @@ -7,15 +9,34 @@ interface SettingsRouteEntry { interface SettingsSelectionState { selectedServerId: string | null; + sidebarReturn: (ActiveWorkspaceSelection & { phase: "opening" | "covered" }) | null; } export function createSettingsPresentation() { - const store = createStore(() => ({ selectedServerId: null })); + const store = createStore(() => ({ + selectedServerId: null, + sidebarReturn: null, + })); const enteredRoutes = new Map(); let inSettings = false; let sidebarOffset = 0; let sidebarOwner: object | null = null; + function beginSidebarVisit(workspace: ActiveWorkspaceSelection) { + store.setState({ sidebarReturn: { ...workspace, phase: "opening" } }); + } + + function presentContent() { + const origin = store.getState().sidebarReturn; + if (origin?.phase === "opening") { + store.setState({ sidebarReturn: { ...origin, phase: "covered" } }); + } + } + + function clearSidebarReturn() { + if (store.getState().sidebarReturn) store.setState({ sidebarReturn: null }); + } + function attachSidebar() { const owner = {}; sidebarOwner = owner; @@ -35,17 +56,24 @@ export function createSettingsPresentation() { function enterRoute( { key, pathname }: SettingsRouteEntry, workspaceServerId: string | null, - ): void { + ): boolean { const isSettings = pathname === "/settings" || pathname.startsWith("/settings/"); if (!isSettings) { + const origin = store.getState().sidebarReturn; + const destination = parseHostWorkspaceRouteFromPathname(pathname); + const discardSidebar = + origin !== null && + (origin.serverId !== destination?.serverId || + origin.workspaceId !== destination?.workspaceId); + clearSidebarReturn(); sidebarOffset = 0; sidebarOwner = null; inSettings = false; enteredRoutes.clear(); - return; + return discardSidebar; } // A retained route returning through Back must not replay its old host intent. - if (enteredRoutes.get(key) === pathname) return; + if (enteredRoutes.get(key) === pathname) return false; const isNewVisit = !inSettings; inSettings = true; enteredRoutes.set(key, pathname); @@ -56,11 +84,20 @@ export function createSettingsPresentation() { } else if (isNewVisit) { store.setState({ selectedServerId: workspaceServerId }); } + return false; } function selectHost(serverId: string): void { store.setState({ selectedServerId: serverId }); } - return { store, enterRoute, selectHost, attachSidebar }; + return { + store, + enterRoute, + selectHost, + attachSidebar, + beginSidebarVisit, + clearSidebarReturn, + presentContent, + }; } diff --git a/packages/app/src/navigation/settings-presentation/session/index.ts b/packages/app/src/navigation/settings-presentation/session/index.ts new file mode 100644 index 0000000000..519539966e --- /dev/null +++ b/packages/app/src/navigation/settings-presentation/session/index.ts @@ -0,0 +1,6 @@ +import { createSettingsPresentation } from "../model"; + +/** @package */ +export const settingsPresentation = createSettingsPresentation(); +export const beginSettingsSidebarVisit = settingsPresentation.beginSidebarVisit; +export const getSettingsSidebarReturn = () => settingsPresentation.store.getState().sidebarReturn; diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index cf582a99f5..709281ed7d 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -762,7 +762,7 @@ function ChatAgentContent({ }); const reportAttentionError = useCallback( (error: unknown) => { - toastApi.show(String(error), { variant: "error", durationMs: null }); + toastApi.error(toErrorMessage(error)); }, [toastApi], ); diff --git a/packages/app/src/panels/file-panel.tsx b/packages/app/src/panels/file-panel.tsx index d26bd3271d..a57059fc31 100644 --- a/packages/app/src/panels/file-panel.tsx +++ b/packages/app/src/panels/file-panel.tsx @@ -43,6 +43,7 @@ function FilePanel() { return ( { plugin.addSettingsScreen({ id: "display", title: "Display", icon: "Settings", Component }), plugin.addSidebarHeaderItem({ id: "main", title: "Main", Component }), plugin.addSidebarFooterItem({ id: "status", title: "Status", Component }), + plugin.addWorkspaceRowBadgeItem({ id: "status", title: "Status", icon: "Blocks", Component }), plugin.addWorkspacePanel({ id: "panel", title: "Panel", icon: "Blocks", context: "workspace", Component }), plugin.addCommandCenterItem({ id: "command", title: "Command", icon: "Blocks", context: "global", onSelect() {} }), plugin.addSlashCommand({ name: "review", description: "Review", argumentHint: "", context: "workspace", onSubmit() {} }), @@ -132,6 +133,7 @@ describe("evaluatePluginClientBundle", () => { plugin.settingsScreens, plugin.sidebarItems.header, plugin.sidebarItems.footer, + plugin.workspaceRowBadgeItems, plugin.workspacePanels, plugin.commandCenterItems, plugin.clientSlashCommands, @@ -152,6 +154,7 @@ describe("evaluatePluginClientBundle", () => { plugin.settingsScreens, plugin.sidebarItems.header, plugin.sidebarItems.footer, + plugin.workspaceRowBadgeItems, plugin.workspacePanels, plugin.commandCenterItems, plugin.clientSlashCommands, @@ -282,6 +285,44 @@ describe("evaluatePluginClientBundle", () => { ).toThrow("Sidebar item main has no title"); }); + it("collects workspace row badge items and rejects duplicate and malformed ones", () => { + const plugin = evaluatePluginClientBundle( + "example", + bundle(` + function Item() { return null; } + plugin.addWorkspaceRowBadgeItem({ id: "status", title: " Status ", icon: "Blocks", Component: Item }); + `), + ); + expect( + plugin.workspaceRowBadgeItems.map(({ id, title, icon }) => ({ id, title, icon })), + ).toEqual([{ id: "status", title: "Status", icon: "Blocks" }]); + + const row = (fields: string) => + bundle(`function Item() { return null; } plugin.addWorkspaceRowBadgeItem({ ${fields} });`); + expect(() => + evaluatePluginClientBundle( + "example", + bundle(` + function Item() { return null; } + plugin.addWorkspaceRowBadgeItem({ id: "status", title: "One", icon: "Blocks", Component: Item }); + plugin.addWorkspaceRowBadgeItem({ id: "status", title: "Two", icon: "Blocks", Component: Item }); + `), + ), + ).toThrow("Duplicate workspace row badge item: status"); + expect(() => + evaluatePluginClientBundle( + "example", + row(`id: "status", title: " ", icon: "Blocks", Component: Item`), + ), + ).toThrow("Workspace row badge item status has no title"); + expect(() => + evaluatePluginClientBundle( + "example", + row(`id: "status", title: "Status", icon: "Blocks", Component: "Item"`), + ), + ).toThrow("Workspace row badge item status is not a component"); + }); + it("expands the addSurface and addSidebarItem aliases to a screen and a legacy header item", () => { const plugin = evaluatePluginClientBundle( "example", diff --git a/packages/app/src/plugins/evaluate.ts b/packages/app/src/plugins/evaluate.ts index f3e89122dd..db31415ecb 100644 --- a/packages/app/src/plugins/evaluate.ts +++ b/packages/app/src/plugins/evaluate.ts @@ -37,6 +37,7 @@ import type { PluginScreenContribution, PluginSidebarItemContribution, PluginWorkspacePanelContribution, + PluginWorkspaceRowBadgeItemContribution, } from "./types"; import type { ComponentType } from "react"; import { parsePluginIcon, parseSerializablePluginIcon } from "./icons"; @@ -133,6 +134,7 @@ export function runPluginClientBundle( sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], @@ -151,6 +153,7 @@ export function runPluginClientBundle( header: new Set(), footer: new Set(), }; + const workspaceRowItemIds = new Set(); const filePanelIds = new Set(); const composerItemIds = new Set(); const newWorkspaceItemIds = new Set(); @@ -323,6 +326,23 @@ export function runPluginClientBundle( addSidebarFooterItem(contribution: PluginSidebarItemContribution) { return addSidebarItem("footer", contribution); }, + addWorkspaceRowBadgeItem(contribution: PluginWorkspaceRowBadgeItemContribution) { + const itemId = requireId(contribution.id, "workspace row badge item id"); + if (workspaceRowItemIds.has(itemId)) + throw new Error(`Duplicate workspace row badge item: ${itemId}`); + const title = normalizePluginText(contribution.title); + if (!title) throw new Error(`Workspace row badge item ${itemId} has no title`); + const icon = parsePluginIcon(`Workspace row badge item ${itemId}`, contribution.icon); + if (!isComponentType(contribution.Component)) { + throw new Error(`Workspace row badge item ${itemId} is not a component`); + } + workspaceRowItemIds.add(itemId); + return register( + collector.workspaceRowBadgeItems, + { id: itemId, title, icon, Component: contribution.Component }, + () => workspaceRowItemIds.delete(itemId), + ); + }, // COMPAT(pluginSidebarAliases): added in v0.11.0, remove after 2027-03-29 // Titled by its id; a legacy item pointing at it lends the header its own title instead. addSurface(surfaceId: string, Component: ComponentType) { @@ -634,6 +654,7 @@ export function runPluginClientBundle( sidebarViews: collector.sidebarViews, sidebarItems: collector.sidebarItems, legacySidebarItems: collector.legacySidebarItems, + workspaceRowBadgeItems: collector.workspaceRowBadgeItems, filePanels: collector.filePanels, composerItems: collector.composerItems, newWorkspaceItems: collector.newWorkspaceItems, diff --git a/packages/app/src/plugins/gallery/actions.ts b/packages/app/src/plugins/gallery/actions.ts new file mode 100644 index 0000000000..0647d85720 --- /dev/null +++ b/packages/app/src/plugins/gallery/actions.ts @@ -0,0 +1,78 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import { useToast } from "@/contexts/toast-api-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { pluginDisplayName, pluginListQueryKey } from "@/plugins/plugin-list"; +import { confirmDialog } from "@/utils/confirm-dialog"; +import { pluginErrorText } from "./error-text"; +import { dismissFailedOperation } from "./operations"; + +export type PluginAction = "enable" | "disable" | "reload" | "remove"; + +/** + * Turning a plugin on or off, reloading and removing it. Each action writes its result into the + * plugin list, so every row and page showing the plugin agrees. Toggling says nothing; the switch + * already shows the result. + */ +export function usePluginActions(serverId: string) { + const { t } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + const [pending, setPending] = useState<{ pluginId: string; action: PluginAction } | null>(null); + + const replace = useCallback( + (plugin: PluginListItem) => + queryClient.setQueryData(pluginListQueryKey(serverId), (plugins) => + plugins?.map((candidate) => (candidate.id === plugin.id ? plugin : candidate)), + ), + [queryClient, serverId], + ); + + const run = useCallback( + /** Resolves true once the action is done; false when it was cancelled or failed. */ + async (action: PluginAction, plugin: PluginListItem): Promise => { + if (!client) return false; + const name = pluginDisplayName(plugin); + if (action === "remove") { + const confirmed = await confirmDialog({ + title: t("settings.plugins.removeConfirmTitle", { name }), + // A plugin installed from a source has its download deleted; a local folder is kept. + message: plugin.installation + ? t("settings.plugins.removeConfirmMessage") + : t("settings.plugins.removeConfirmLocalMessage"), + confirmLabel: t("settings.plugins.actions.remove"), + destructive: true, + }); + if (!confirmed) return false; + } + setPending({ pluginId: plugin.id, action }); + try { + if (action === "remove") { + await client.removePlugin(plugin.id); + // A failed update belonged to this installation, not to a later one with the same ID. + dismissFailedOperation(serverId, plugin.id); + queryClient.setQueryData(pluginListQueryKey(serverId), (plugins) => + plugins?.filter((candidate) => candidate.id !== plugin.id), + ); + toast.show(t("settings.plugins.feedback.remove", { name }), { variant: "success" }); + } else { + replace(await client[`${action}Plugin`](plugin.id)); + if (action === "reload") + toast.show(t("settings.plugins.feedback.reload", { name }), { variant: "success" }); + } + return true; + } catch (error) { + toast.error(pluginErrorText(error)); + return false; + } finally { + setPending(null); + } + }, + [client, queryClient, replace, serverId, t, toast], + ); + + return useMemo(() => ({ run, pending }), [pending, run]); +} diff --git a/packages/app/src/plugins/gallery/browse-tab.tsx b/packages/app/src/plugins/gallery/browse-tab.tsx new file mode 100644 index 0000000000..a7c8d08d34 --- /dev/null +++ b/packages/app/src/plugins/gallery/browse-tab.tsx @@ -0,0 +1,459 @@ +import { router } from "expo-router"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Image, ScrollView, Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import type { PluginListingIndex, PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { SettingsCard, SettingsSection } from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"; +import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useContainerWidthBelow } from "@/hooks/use-container-width"; +import { settingsStyles } from "@/styles/settings"; +import { usePluginActions } from "./actions"; +import { ListingInstallControl } from "./install-control"; +import { + ALL_CATEGORIES, + categoryLabel, + featuredListings, + filterDirectory, + formatInstallCount, + listingAuthor, + listingAuthorAvatar, + listingImages, + listingText, + type DirectorySort, +} from "./listing"; +import { usePluginOperation } from "./operations"; +import { PluginMeta, PluginRow, PluginTile } from "./plugin-row"; +import { usePluginDirectory } from "./queries"; +import { buildPluginListingRoute } from "./routes"; +import { PluginRowsSkeleton } from "./skeletons"; +import { pluginErrorText } from "./error-text"; + +const SORTS: DirectorySort[] = ["popular", "recent", "name"]; +// Below this width the featured grid has two columns instead of four. +const FEATURED_FOUR_COLUMNS = 760; +const LISTING_PAGE = 50; + +/** "author · 1.1k installs". */ +export function useListingMeta() { + const { t } = useTranslation(); + return useCallback( + (listing: PluginListing) => + listing.installs === undefined + ? listingAuthor(listing) + : `${listingAuthor(listing)} · ${t("settings.plugins.gallery.installs", { + count: listing.installs, + installs: formatInstallCount(listing.installs), + })}`, + [t], + ); +} + +function ListingRow({ + serverId, + listing, + installedPlugin, + uninstalling, + onInstall, + onUninstall, +}: { + serverId: string; + listing: PluginListing; + installedPlugin?: PluginListItem; + uninstalling: boolean; + onInstall(listing: PluginListing): void; + onUninstall(plugin: PluginListItem): void; +}) { + const { i18n } = useTranslation(); + const meta = useListingMeta(); + const operation = usePluginOperation(serverId, listing.id); + const { name, description } = listingText(listing, i18n.language); + const open = useCallback( + () => router.push(buildPluginListingRoute(serverId, listing.id)), + [listing.id, serverId], + ); + return ( + + + + ); +} + +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +function FeaturedCard({ serverId, listing }: { serverId: string; listing: PluginListing }) { + const { i18n } = useTranslation(); + const meta = useListingMeta(); + const { name, description } = listingText(listing, i18n.language); + const image = listingImages(listing)[0]; + const source = useMemo(() => (image ? { uri: image } : null), [image]); + const open = useCallback( + () => router.push(buildPluginListingRoute(serverId, listing.id)), + [listing.id, serverId], + ); + const cardStyle = useCallback( + ({ hovered }: HoverState) => [styles.featured, hovered && styles.featuredHovered], + [], + ); + return ( + + + {source ? : null} + + + + + + {name} + + + + {description} + + + + + ); +} + +/** Every featured listing: a row to swipe on a phone, a grid of four or two columns otherwise. */ +function Featured({ serverId, listings }: { serverId: string; listings: PluginListing[] }) { + const { t } = useTranslation(); + const compact = useIsCompactFormFactor(); + const grid = useContainerWidthBelow(FEATURED_FOUR_COLUMNS, { initialIsBelow: false }); + const cellStyle = grid.isBelow ? styles.cellHalf : styles.cellQuarter; + return ( + + {compact ? ( + + {listings.map((listing) => ( + + + + ))} + + ) : ( + + {listings.map((listing) => ( + + + + ))} + + )} + + ); +} + +function FilterOption({ + option, + selected, + onChange, +}: { + option: { value: Value; label: string }; + selected: boolean; + onChange(value: Value): void; +}) { + const select = useCallback(() => onChange(option.value), [onChange, option.value]); + return ( + + {option.label} + + ); +} + +function FilterMenu({ + label, + value, + options, + onChange, + testID, +}: { + label: string; + value: Value; + options: { value: Value; label: string }[]; + onChange(value: Value): void; + testID: string; +}) { + const selected = options.find((option) => option.value === value)?.label ?? value; + return ( + + + {selected} + + + {options.map((option) => ( + + ))} + + + ); +} + +/** + * The listings in pages: the directory has hundreds, and rendering them all makes switching to + * Browse and typing in search lag. A new query, category or sort starts again at the first page. + */ +function ListingList({ + serverId, + listings, + installed, + onInstall, +}: { + serverId: string; + listings: PluginListing[]; + installed: ReadonlyMap; + onInstall(listing: PluginListing): void; +}) { + const { t } = useTranslation(); + const actions = usePluginActions(serverId); + const uninstall = useCallback( + (plugin: PluginListItem) => void actions.run("remove", plugin), + [actions], + ); + const [limit, setLimit] = useState(LISTING_PAGE); + const showMore = useCallback(() => setLimit((value) => value + LISTING_PAGE), []); + if (!listings.length) + return ( + + + + {t("settings.plugins.gallery.empty.noMatches")} + + + + ); + return ( + <> + + {listings.slice(0, limit).map((listing) => ( + + ))} + + {listings.length > limit ? ( + + + + ) : null} + + ); +} + +function Directory({ + serverId, + index, + installed, + query, + onInstall, +}: { + serverId: string; + index: PluginListingIndex; + installed: ReadonlyMap; + query: string; + onInstall(listing: PluginListing): void; +}) { + const { t, i18n } = useTranslation(); + const [category, setCategory] = useState(ALL_CATEGORIES); + const [sort, setSort] = useState("popular"); + const listings = filterDirectory(index, { query, category, sort }, i18n.language); + const browsing = !query.trim() && category === ALL_CATEGORIES; + const featured = browsing ? featuredListings(index) : []; + const categoryOptions = useMemo( + () => [ + { value: ALL_CATEGORIES, label: t("settings.plugins.gallery.filters.allCategories") }, + ...index.categories.map((entry) => ({ value: entry.slug, label: entry.label })), + ], + [index.categories, t], + ); + const sortOptions = useMemo( + (): { value: DirectorySort; label: string }[] => + SORTS.map((value) => ({ value, label: t(`settings.plugins.gallery.filters.${value}`) })), + [t], + ); + const listTitle = + category === ALL_CATEGORIES + ? t("settings.plugins.gallery.sections.all") + : categoryLabel(index, category); + return ( + <> + + + + label={t("settings.plugins.gallery.filters.sort")} + value={sort} + options={sortOptions} + onChange={setSort} + testID="plugin-sort" + /> + + {featured.length ? : null} + + + + + ); +} + +export function BrowseTab({ + serverId, + installed, + query, + onInstall, +}: { + serverId: string; + /** Installed plugins by the listing they came from. */ + installed: ReadonlyMap; + query: string; + onInstall(listing: PluginListing): void; +}) { + const { t } = useTranslation(); + const directory = usePluginDirectory(serverId); + const retry = useCallback(() => void directory.query.refetch(), [directory.query]); + if (!directory.supported) + return ( + + ); + if (directory.query.isError) + return ( + + + + ); + if (!directory.query.data) return ; + return ( + + ); +} + +const styles = StyleSheet.create((theme) => ({ + filters: { + flexDirection: "row", + flexWrap: "wrap", + gap: theme.spacing[2], + marginBottom: theme.spacing[6], + }, + featuredRow: { flexDirection: "row", gap: theme.spacing[3] }, + // Percent widths and a gap would overflow the row, so each cell carries half the gap on each side + // and the grid pulls out by the same amount to keep the cards on the section's edges. + featuredGrid: { + flexDirection: "row", + flexWrap: "wrap", + marginHorizontal: -theme.spacing[3] / 2, + marginBottom: -theme.spacing[3], + }, + cellQuarter: { + width: "25%", + paddingHorizontal: theme.spacing[3] / 2, + marginBottom: theme.spacing[3], + }, + cellHalf: { + width: "50%", + paddingHorizontal: theme.spacing[3] / 2, + marginBottom: theme.spacing[3], + }, + cellSwipe: { width: 260 }, + featured: { + flexGrow: 1, + backgroundColor: theme.colors.surface1, + borderRadius: theme.borderRadius.lg, + borderWidth: 1, + borderColor: theme.colors.border, + overflow: "hidden", + }, + featuredHovered: { backgroundColor: theme.colors.surface2 }, + featuredPressed: { backgroundColor: theme.colors.surface3 }, + media: { + aspectRatio: 16 / 10, + backgroundColor: theme.colors.surface2, + borderBottomWidth: 1, + borderBottomColor: theme.colors.border, + }, + mediaImage: { width: "100%", height: "100%" }, + featuredBody: { padding: theme.spacing[3], gap: theme.spacing[1] }, + featuredTitle: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + featuredName: { flex: 1, color: theme.colors.foreground, fontSize: theme.fontSize.base }, + featuredDescription: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm }, + empty: { padding: theme.spacing[6], alignItems: "center" }, + more: { alignItems: "center", marginTop: theme.spacing[3] }, +})); diff --git a/packages/app/src/plugins/gallery/error-text.test.ts b/packages/app/src/plugins/gallery/error-text.test.ts new file mode 100644 index 0000000000..04c01d1891 --- /dev/null +++ b/packages/app/src/plugins/gallery/error-text.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { pluginErrorText } from "./error-text"; + +describe("pluginErrorText", () => { + it("shows the daemon's text without the request details an RPC error adds", () => { + const rpcError = Object.assign( + new Error( + "Registry credentials require HTTPS requestType=plugin.registry.list.request code=handler_error", + ), + { userMessage: "Registry credentials require HTTPS" }, + ); + expect(pluginErrorText(rpcError)).toBe("Registry credentials require HTTPS"); + }); + + it("shows any other error's message", () => { + expect(pluginErrorText(new Error("Socket closed"))).toBe("Socket closed"); + expect(pluginErrorText("offline")).toBe("offline"); + }); +}); diff --git a/packages/app/src/plugins/gallery/error-text.ts b/packages/app/src/plugins/gallery/error-text.ts new file mode 100644 index 0000000000..151a071456 --- /dev/null +++ b/packages/app/src/plugins/gallery/error-text.ts @@ -0,0 +1,9 @@ +/** + * What a failed plugin request tells the user. A daemon RPC error keeps the daemon's text in + * `userMessage`; its `message` adds the request type and code for logs. + */ +export function pluginErrorText(error: unknown): string { + if (!(error instanceof Error)) return String(error); + const userMessage: unknown = Reflect.get(error, "userMessage"); + return typeof userMessage === "string" ? userMessage : error.message; +} diff --git a/packages/app/src/plugins/gallery/gallery-page.tsx b/packages/app/src/plugins/gallery/gallery-page.tsx new file mode 100644 index 0000000000..68cebe165e --- /dev/null +++ b/packages/app/src/plugins/gallery/gallery-page.tsx @@ -0,0 +1,157 @@ +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { SearchField } from "@/components/ui/search-field"; +import { SegmentedControl } from "@/components/ui/segmented-control"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { useInstalledPlugins } from "@/plugins/registry"; +import { BrowseTab } from "./browse-tab"; +import { InstallPluginSheet, type InstallTarget } from "./install-sheet"; +import { InstalledTab } from "./installed-tab"; +import { installedByListing } from "./listing"; +import { PluginsOffAlert } from "./plugins-off-alert"; +import { useLivePluginList, usePluginDirectory } from "./queries"; +import { PluginRowsSkeleton } from "./skeletons"; +import { pluginErrorText } from "./error-text"; + +type GalleryTab = "installed" | "browse"; + +/** + * Settings → Plugins: the plugins on this host and the directory to add more, behind one switch. + * Opens on Installed when something is installed, otherwise on Browse. + */ +export function PluginGalleryPage({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const connected = useHostRuntimeIsConnected(serverId); + const supported = useHostFeature(serverId, "pluginManagement"); + useInstalledPlugins(); + const plugins = useLivePluginList(serverId); + const directory = usePluginDirectory(serverId); + const [chosenTab, setChosenTab] = useState(null); + const [query, setQuery] = useState(""); + const [installTarget, setInstallTarget] = useState(null); + const installed = useMemo(() => plugins.data ?? [], [plugins.data]); + // The opening tab is chosen once, so installing the first plugin does not move the user off Browse. + if (chosenTab === null && plugins.data) + setChosenTab(plugins.data.length === 0 ? "browse" : "installed"); + const tab: GalleryTab = chosenTab ?? "installed"; + const byListing = useMemo(() => installedByListing(installed), [installed]); + const listings = useMemo( + () => new Map((directory.query.data?.plugins ?? []).map((listing) => [listing.id, listing])), + [directory.query.data], + ); + const tabs = useMemo( + () => [ + { + value: "installed" as const, + label: plugins.data + ? t("settings.plugins.gallery.tabs.installedCount", { count: plugins.data.length }) + : t("settings.plugins.gallery.tabs.installed"), + testID: "plugin-tab-installed", + }, + { + value: "browse" as const, + label: t("settings.plugins.gallery.tabs.browse"), + testID: "plugin-tab-browse", + }, + ], + [plugins.data, t], + ); + const browse = useCallback(() => setChosenTab("browse"), []); + const install = useCallback( + (listing: PluginListing) => setInstallTarget({ kind: "listing", listing }), + [], + ); + const closeInstall = useCallback(() => setInstallTarget(null), []); + const retry = useCallback(() => void plugins.refetch(), [plugins]); + + if (!connected) + return ( + + ); + if (!supported) + return ; + + let content = ; + if (plugins.isError) { + content = ( + + + + ); + } else if (plugins.data) { + content = + tab === "installed" ? ( + + ) : ( + + ); + } + + return ( + + + + + + + + {tab === "installed" ? : null} + {content} + {installTarget ? ( + + ) : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + toolbar: { + flexDirection: "row", + flexWrap: "wrap", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[6], + }, + // The search box sits at the end of the row, as on the website, and takes the whole row when the + // tabs leave it too little room. + search: { flexGrow: 1, flexBasis: 220, flexDirection: "row", justifyContent: "flex-end" }, +})); diff --git a/packages/app/src/plugins/gallery/index.ts b/packages/app/src/plugins/gallery/index.ts new file mode 100644 index 0000000000..9c78298a41 --- /dev/null +++ b/packages/app/src/plugins/gallery/index.ts @@ -0,0 +1,4 @@ +export { PluginGalleryPage } from "./gallery-page"; +export { PluginGalleryMenu } from "./menus"; +export { PluginPage, type PluginPageSubject } from "./plugin-page"; +export { buildPluginListingRoute, buildPluginPageRoute } from "./routes"; diff --git a/packages/app/src/plugins/gallery/install-control.tsx b/packages/app/src/plugins/gallery/install-control.tsx new file mode 100644 index 0000000000..218bfd9eb2 --- /dev/null +++ b/packages/app/src/plugins/gallery/install-control.tsx @@ -0,0 +1,72 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { Button } from "@/components/ui/button"; +import type { PluginOperation } from "./operations"; + +function useInstallLabel(operation: PluginOperation | undefined): string { + const { t } = useTranslation(); + if (operation?.status === "running") return t("settings.plugins.gallery.actions.installing"); + if (operation?.status === "failed") return t("settings.plugins.gallery.actions.retry"); + return t("settings.plugins.gallery.actions.install"); +} + +/** + * A listing's install state where the user is looking: Install, Installing… while it runs, Retry + * after a failure (the row or page shows why), and Uninstall once it is on the host. Both ask + * before they act. + */ +export function ListingInstallControl({ + listing, + installedPlugin, + operation, + uninstalling = false, + onInstall, + onUninstall, + primary = false, +}: { + listing: PluginListing; + /** The plugin this listing installed on the host, when it is installed. */ + installedPlugin?: PluginListItem; + operation: PluginOperation | undefined; + uninstalling?: boolean; + onInstall(listing: PluginListing): void; + onUninstall?(plugin: PluginListItem): void; + /** The page's one accent action, on the plugin's own page. */ + primary?: boolean; +}) { + const { t } = useTranslation(); + const installLabel = useInstallLabel(operation); + const install = useCallback(() => onInstall(listing), [listing, onInstall]); + const uninstall = useCallback(() => { + if (installedPlugin) onUninstall?.(installedPlugin); + }, [installedPlugin, onUninstall]); + if (installedPlugin) { + const label = uninstalling + ? t("settings.plugins.actions.removing") + : t("settings.plugins.actions.remove"); + return ( + + ); + } + return ( + + ); +} diff --git a/packages/app/src/plugins/gallery/install-sheet.tsx b/packages/app/src/plugins/gallery/install-sheet.tsx new file mode 100644 index 0000000000..e07ec7ee7f --- /dev/null +++ b/packages/app/src/plugins/gallery/install-sheet.tsx @@ -0,0 +1,191 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { SettingsCard, SettingsRow } from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { ExternalLink } from "@/components/ui/external-link"; +import { Field, FormTextInput } from "@/components/ui/form-field"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import { listingAuthor, listingSource, listingText, listingVersion } from "./listing"; +import { dismissFailedOperation, installPlugin, usePluginOperation } from "./operations"; + +const PLUGIN_SOURCE_DOCS_URL = "https://paseo.sh/docs/plugins/reference#plugin-sources"; +const SOURCE_SUBJECT = "source"; + +/** What the sheet installs: a directory listing, or a source the user types. */ +export type InstallTarget = { kind: "listing"; listing: PluginListing } | { kind: "source" }; + +export function useHostLabel(serverId: string): string { + const hosts = useHosts(); + return hosts.find((host) => host.serverId === serverId)?.label ?? serverId; +} + +/** + * Every install is confirmed here: who made the plugin, where its code comes from, and that it runs + * unsandboxed on the host. A listing install closes the sheet and reports on the listing's row; an + * install from source has no row, so the sheet stays open until it finishes. + */ +export function InstallPluginSheet({ + serverId, + target, + onClose, +}: { + serverId: string; + target: InstallTarget; + onClose(): void; +}) { + const { t, i18n } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + const hostLabel = useHostLabel(serverId); + const { config } = useDaemonConfig(serverId); + const pluginsOff = config?.pluginsEnabled !== true; + const [source, setSource] = useState(""); + const sourceRun = usePluginOperation(serverId, target.kind === "source" ? SOURCE_SUBJECT : ""); + const sourceRunning = target.kind === "source" && sourceRun?.status === "running"; + const close = useCallback(() => { + if (target.kind === "source") dismissFailedOperation(serverId, SOURCE_SUBJECT); + onClose(); + }, [onClose, serverId, target.kind]); + const name = + target.kind === "listing" + ? listingText(target.listing, i18n.language).name + : t("settings.plugins.gallery.install.sourceTitle"); + + const onInstalled = useCallback( + (plugin: PluginListItem) => { + toast.show(t("settings.plugins.feedback.installed", { name: pluginDisplayName(plugin) }), { + variant: "success", + }); + }, + [t, toast], + ); + const confirm = useCallback(() => { + if (!client) return; + const request = { client, queryClient, serverId, enablePlugins: pluginsOff, onInstalled }; + if (target.kind === "listing") { + void installPlugin({ ...request, source: target.listing.id, subject: target.listing.id }); + onClose(); + return; + } + void installPlugin({ + ...request, + source: source.trim(), + subject: SOURCE_SUBJECT, + onInstalled: (plugin) => { + onInstalled(plugin); + close(); + }, + }); + }, [client, close, onClose, onInstalled, pluginsOff, queryClient, serverId, source, target]); + + const header = useMemo( + () => ({ + title: + target.kind === "listing" + ? t("settings.plugins.gallery.install.title", { name }) + : t("settings.plugins.gallery.install.sourceTitle"), + }), + [name, t, target.kind], + ); + // Until the config loads, the sheet cannot say whether installing also turns plugins on. + const canInstall = + Boolean(client && config) && (target.kind === "listing" || source.trim().length > 0); + const footer = useMemo( + () => ( + + + + + ), + [canInstall, close, confirm, sourceRunning, t], + ); + const docsLink = useMemo( + () => , + [t], + ); + + return ( + + + {target.kind === "listing" ? ( + + + {listingAuthor(target.listing)} + + + + {listingSource(target.listing)} + + + + {listingVersion(target.listing)} + + + ) : ( + + + + )} + + {target.kind === "source" && sourceRun?.status === "failed" ? ( + + ) : null} + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + body: { gap: theme.spacing[4] }, + value: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.base, maxWidth: 260 }, + actions: { flex: 1, flexDirection: "row", justifyContent: "flex-end", gap: theme.spacing[2] }, +})); diff --git a/packages/app/src/plugins/gallery/installed-tab.tsx b/packages/app/src/plugins/gallery/installed-tab.tsx new file mode 100644 index 0000000000..ee84b2a35a --- /dev/null +++ b/packages/app/src/plugins/gallery/installed-tab.tsx @@ -0,0 +1,276 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { router } from "expo-router"; +import { useCallback, useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem, PluginUpdatePreview } from "@getpaseo/protocol/messages"; +import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { SettingsCard, SettingsSection } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { StatusBadge } from "@/components/ui/status-badge"; +import { Switch } from "@/components/ui/switch"; +import { useToast } from "@/contexts/toast-api-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { usePluginEvaluationError } from "@/plugins/registry"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import { settingsStyles } from "@/styles/settings"; +import { usePluginActions } from "./actions"; +import { listingAuthor, listingAuthorAvatar, installedListingId } from "./listing"; +import { updatePlugins, usePluginOperation } from "./operations"; +import { PluginRow } from "./plugin-row"; +import { usePluginUpdates } from "./queries"; +import { buildPluginPageRoute } from "./routes"; + +function shortRevision(revision: string | undefined): string | undefined { + return revision && /^[0-9a-f]{40,64}$/.test(revision) ? revision.slice(0, 7) : revision; +} + +function matchesQuery(plugin: PluginListItem, query: string): boolean { + if (!query) return true; + return [plugin.id, plugin.name ?? "", plugin.description ?? ""] + .join("\n") + .toLowerCase() + .includes(query); +} + +/** "author · version" for a listed plugin; where it was installed from otherwise. */ +function installedMeta(plugin: PluginListItem, listing: PluginListing | undefined) { + if (!plugin.installation) return plugin.path; + if (!listing) return formatPluginInstallation(plugin.installation); + const version = shortRevision(plugin.installation.currentRevision); + return version ? `${listingAuthor(listing)} · ${version}` : listingAuthor(listing); +} + +function useUpdate(serverId: string) { + const { t } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + return useCallback( + (previews: PluginUpdatePreview[]) => { + if (!client) return; + void updatePlugins({ + client, + queryClient, + serverId, + proposals: previews.flatMap((preview) => preview.proposal ?? []), + onUpdated: (plugins) => + toast.show( + plugins.length === 1 + ? t("settings.plugins.gallery.update.updated", { + name: pluginDisplayName(plugins[0]!), + }) + : t("settings.plugins.gallery.update.updatedMany", { count: plugins.length }), + { variant: "success" }, + ), + }); + }, + [client, queryClient, serverId, t, toast], + ); +} + +function UpdateRow({ + serverId, + plugin, + preview, + listing, + onUpdate, +}: { + serverId: string; + plugin: PluginListItem; + preview: PluginUpdatePreview; + listing?: PluginListing; + onUpdate(previews: PluginUpdatePreview[]): void; +}) { + const { t } = useTranslation(); + const operation = usePluginOperation(serverId, plugin.id); + const running = operation?.status === "running"; + const name = pluginDisplayName(plugin); + const target = + preview.target?.kind === "npm" ? preview.target.version : preview.target?.commit.slice(0, 7); + const current = shortRevision(preview.current?.currentRevision); + const open = useCallback( + () => router.push(buildPluginPageRoute(serverId, plugin.id)), + [plugin.id, serverId], + ); + const update = useCallback(() => onUpdate([preview]), [onUpdate, preview]); + let label = t("settings.plugins.gallery.actions.update"); + if (running) label = t("settings.plugins.gallery.actions.updating"); + else if (operation?.status === "failed") label = t("settings.plugins.gallery.actions.retry"); + return ( + + + + ); +} + +function InstalledRow({ + serverId, + plugin, + listing, + pending, + onToggle, +}: { + serverId: string; + plugin: PluginListItem; + listing?: PluginListing; + pending: boolean; + onToggle(plugin: PluginListItem, enabled: boolean): void; +}) { + const { t } = useTranslation(); + const name = pluginDisplayName(plugin); + const error = usePluginEvaluationError(serverId, plugin.id) ?? plugin.error; + const failed = error !== undefined || plugin.status === "failed"; + const open = useCallback( + () => router.push(buildPluginPageRoute(serverId, plugin.id)), + [plugin.id, serverId], + ); + const toggle = useCallback((enabled: boolean) => onToggle(plugin, enabled), [onToggle, plugin]); + const badge = useMemo( + () => + failed ? ( + + ) : null, + [failed, t], + ); + return ( + + + + ); +} + +export function InstalledTab({ + serverId, + plugins, + listings, + query, + onBrowse, +}: { + serverId: string; + plugins: readonly PluginListItem[]; + /** Directory listings by ID, for icons and authors. Empty until the directory loads. */ + listings: ReadonlyMap; + query: string; + onBrowse(): void; +}) { + const { t } = useTranslation(); + const actions = usePluginActions(serverId); + const updates = usePluginUpdates(serverId); + const update = useUpdate(serverId); + const normalizedQuery = query.trim().toLowerCase(); + const shown = plugins.filter((plugin) => matchesQuery(plugin, normalizedQuery)); + const byId = new Map(plugins.map((plugin) => [plugin.id, plugin])); + const pendingUpdates = (updates.data ?? []).filter((preview) => byId.has(preview.id)); + const listingOf = (plugin: PluginListItem) => { + const id = installedListingId(plugin); + return id ? listings.get(id) : undefined; + }; + const toggle = useCallback( + (plugin: PluginListItem, enabled: boolean) => + void actions.run(enabled ? "enable" : "disable", plugin), + [actions], + ); + const updateAll = useCallback(() => update(pendingUpdates), [pendingUpdates, update]); + const updatesTrailing = useMemo( + () => + pendingUpdates.length > 1 ? ( + + ) : undefined, + [pendingUpdates.length, t, updateAll], + ); + + return ( + <> + {pendingUpdates.length > 0 && !normalizedQuery ? ( + + + {pendingUpdates.map((preview) => { + const plugin = byId.get(preview.id)!; + return ( + + ); + })} + + + ) : null} + + + {shown.length ? ( + shown.map((plugin) => ( + + )) + ) : ( + + + {normalizedQuery + ? t("settings.plugins.gallery.empty.noMatches") + : t("settings.plugins.states.empty")} + + {normalizedQuery ? null : ( + + )} + + )} + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + empty: { padding: theme.spacing[6], alignItems: "center", gap: theme.spacing[3] }, +})); diff --git a/packages/app/src/plugins/gallery/listing.test.ts b/packages/app/src/plugins/gallery/listing.test.ts new file mode 100644 index 0000000000..51ebd84d7b --- /dev/null +++ b/packages/app/src/plugins/gallery/listing.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vitest"; +import type { PluginListingIndex, PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { + ALL_CATEGORIES, + featuredListings, + filterDirectory, + formatInstallCount, + listingImages, + listingText, +} from "./listing"; + +function listing(id: string, overrides: Partial = {}): PluginListing { + return { + id, + name: id.split("/")[1] ?? id, + description: `${id} description`, + categories: [], + author: { github: id.split("/")[0] ?? id }, + repository: { url: `https://github.com/${id}` }, + artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) }, + media: [], + submittedAt: "2026-01-01T00:00:00Z", + reviewedAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + publishedAt: "2026-01-01T00:00:00Z", + ...overrides, + } as PluginListing; +} + +function directory(plugins: PluginListing[], featured: string[] = []): PluginListingIndex { + return { + schemaVersion: 1, + registry: { name: "Paseo", url: "https://plugins.paseo.sh" }, + categories: [{ slug: "git", label: "Git" }], + plugins, + featured, + generatedAt: "2026-01-01T00:00:00Z", + }; +} + +const ids = (listings: PluginListing[]) => listings.map((entry) => entry.id); + +describe("filterDirectory", () => { + const index = directory([ + listing("acme/zeta", { installs: 5, updatedAt: "2026-03-01T00:00:00Z", categories: ["git"] }), + listing("acme/alpha", { installs: 50, updatedAt: "2026-01-01T00:00:00Z" }), + listing("other/beta", { + updatedAt: "2026-02-01T00:00:00Z", + translations: { fr: { name: "Bêta", description: "Revue de code" } }, + }), + ]); + + it("orders by installs, recency or name", () => { + const all = { query: "", category: ALL_CATEGORIES }; + expect(ids(filterDirectory(index, { ...all, sort: "popular" }, "en"))).toEqual([ + "acme/alpha", + "acme/zeta", + "other/beta", + ]); + expect(ids(filterDirectory(index, { ...all, sort: "recent" }, "en"))).toEqual([ + "acme/zeta", + "other/beta", + "acme/alpha", + ]); + expect(ids(filterDirectory(index, { ...all, sort: "name" }, "en"))).toEqual([ + "acme/alpha", + "other/beta", + "acme/zeta", + ]); + }); + + it("keeps only the chosen category", () => { + expect( + ids(filterDirectory(index, { query: "", category: "git", sort: "popular" }, "en")), + ).toEqual(["acme/zeta"]); + }); + + it("matches the query against the author and the reader's translation", () => { + const search = (query: string, language: string) => + ids(filterDirectory(index, { query, category: ALL_CATEGORIES, sort: "name" }, language)); + expect(search(" ACME ", "en")).toEqual(["acme/alpha", "acme/zeta"]); + expect(search("revue", "fr-CA")).toEqual(["other/beta"]); + expect(search("revue", "en")).toEqual([]); + }); +}); + +describe("listing presentation", () => { + it("falls back from a regional language to its base translation, then English", () => { + const entry = listing("other/beta", { translations: { fr: { name: "Bêta" } } }); + expect(listingText(entry, "fr-CA")).toEqual({ + name: "Bêta", + description: "other/beta description", + }); + expect(listingText(entry, "ja").name).toBe("beta"); + }); + + it("formats install counts compactly", () => { + expect([999, 1000, 1149, 9950, 12_400].map(formatInstallCount)).toEqual([ + "999", + "1k", + "1.1k", + "9.9k", + "12k", + ]); + }); + + it("shows images and leaves videos out", () => { + const entry = listing("acme/alpha", { + media: ["https://cdn.test/a.png", "https://cdn.test/demo.mp4", "https://cdn.test/b.webp"], + }); + expect(listingImages(entry)).toEqual(["https://cdn.test/a.png", "https://cdn.test/b.webp"]); + }); + + it("features listed plugins in the maintainer's order and skips unlisted ones", () => { + const index = directory( + [listing("acme/alpha"), listing("acme/zeta")], + ["acme/zeta", "gone/plugin", "acme/alpha"], + ); + expect(ids(featuredListings(index))).toEqual(["acme/zeta", "acme/alpha"]); + }); +}); diff --git a/packages/app/src/plugins/gallery/listing.ts b/packages/app/src/plugins/gallery/listing.ts new file mode 100644 index 0000000000..184bf78bb6 --- /dev/null +++ b/packages/app/src/plugins/gallery/listing.ts @@ -0,0 +1,115 @@ +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import { + pluginMediaKind, + type PluginListingIndex, + type PluginListing, +} from "@getpaseo/protocol/plugin-registry"; + +export type DirectorySort = "popular" | "recent" | "name"; +export const ALL_CATEGORIES = "all"; + +export interface DirectoryFilter { + query: string; + category: string; + sort: DirectorySort; +} + +/** The listing's name and description in the reader's language, falling back to English. */ +export function listingText(listing: PluginListing, language: string) { + const translation = listing.translations?.[language] ?? listing.translations?.[baseTag(language)]; + return { + name: translation?.name ?? listing.name, + description: translation?.description ?? listing.description, + }; +} + +function baseTag(language: string): string { + return language.split("-")[0] ?? language; +} + +export function listingAuthor(listing: PluginListing): string { + return listing.author.name ?? listing.author.github; +} + +/** The author's GitHub avatar, the same picture the website shows. */ +export function listingAuthorAvatar(listing: PluginListing): string { + return `https://github.com/${encodeURIComponent(listing.author.github)}.png?size=40`; +} + +/** The version a listing pins: the npm version, or the short Git commit. */ +export function listingVersion(listing: PluginListing): string | undefined { + return listing.artifact.version ?? listing.artifact.commit?.slice(0, 7); +} + +/** Where a listing's code comes from: the npm package, or the repository. */ +export function listingSource(listing: PluginListing): string { + return listing.artifact.package ?? listing.repository.url; +} + +/** Image media in display order. Videos are left to the website. */ +export function listingImages(listing: PluginListing): string[] { + return listing.media.filter((url) => pluginMediaKind(url) === "image"); +} + +/** "1.1k" style counts: one decimal below ten thousand, whole thousands above. */ +export function formatInstallCount(count: number): string { + if (count < 1000) return String(count); + if (count < 10_000) return `${(count / 1000).toFixed(1).replace(/\.0$/, "")}k`; + return `${Math.round(count / 1000)}k`; +} + +/** The registry listing an installed plugin came from, if it came from one. */ +export function installedListingId(plugin: PluginListItem): string | undefined { + const identity = plugin.installation?.identity; + if (!identity || identity.kind === "directory") return undefined; + return identity.registry?.id; +} + +/** Installed plugins by the listing they came from. */ +export function installedByListing(plugins: readonly PluginListItem[]) { + const byListing = new Map(); + for (const plugin of plugins) { + const listingId = installedListingId(plugin); + if (listingId) byListing.set(listingId, plugin); + } + return byListing; +} + +function matches(listing: PluginListing, language: string, query: string): boolean { + if (!query) return true; + const { name, description } = listingText(listing, language); + const haystack = [name, description, listing.id, listingAuthor(listing)].join("\n").toLowerCase(); + return haystack.includes(query); +} + +const SORTS: Record number> = { + popular: (left, right) => (right.installs ?? 0) - (left.installs ?? 0), + recent: (left, right) => right.updatedAt.localeCompare(left.updatedAt), + name: (left, right) => left.name.localeCompare(right.name), +}; + +/** The directory's listings that pass the filter, in the chosen order. */ +export function filterDirectory( + index: PluginListingIndex, + filter: DirectoryFilter, + language: string, +): PluginListing[] { + const query = filter.query.trim().toLowerCase(); + return index.plugins + .filter( + (listing) => + (filter.category === ALL_CATEGORIES || listing.categories.includes(filter.category)) && + matches(listing, language, query), + ) + .sort(SORTS[filter.sort]); +} + +/** Featured listings that exist, in the maintainer's order. */ +export function featuredListings(index: PluginListingIndex): PluginListing[] { + const byId = new Map(index.plugins.map((listing) => [listing.id, listing])); + return index.featured.flatMap((id) => byId.get(id) ?? []); +} + +export function categoryLabel(index: PluginListingIndex, slug: string): string { + return index.categories.find((category) => category.slug === slug)?.label ?? slug; +} diff --git a/packages/app/src/plugins/gallery/menus.tsx b/packages/app/src/plugins/gallery/menus.tsx new file mode 100644 index 0000000000..aec3f028ed --- /dev/null +++ b/packages/app/src/plugins/gallery/menus.tsx @@ -0,0 +1,325 @@ +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { + ArrowUpRight, + FileText, + MoreHorizontal, + PackagePlus, + Power, + RotateCw, + Trash2, +} from "lucide-react-native"; +import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages"; +import { + AdaptiveModalSheet, + SheetHeaderIconButton, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + iconButtonChromeHang, + useIconButtonChromeGlyphSize, + useIconButtonChromeStyle, +} from "@/components/ui/icon-button-chrome"; +import { foregroundIconColorMapping, mutedIconColorMapping } from "@/components/ui/icon-color"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-api-context"; +import { useFetchQuery } from "@/data/query"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import type { Theme } from "@/styles/theme"; +import { openExternalUrl } from "@/utils/open-external-url"; +import type { PluginAction } from "./actions"; +import { InstallPluginSheet } from "./install-sheet"; +import { pluginErrorText } from "./error-text"; + +const SUBMIT_PLUGIN_URL = + "https://github.com/getpaseo/plugins/issues/new?template=submit-plugin.yml"; +const ThemedMore = withUnistyles(MoreHorizontal); +const dangerIconMapping = (theme: Theme) => ({ color: theme.colors.statusDanger }); +const ThemedPackagePlus = withUnistyles(PackagePlus); +const ThemedPower = withUnistyles(Power); +const ThemedArrow = withUnistyles(ArrowUpRight); +const ThemedRotate = withUnistyles(RotateCw); +const ThemedLogs = withUnistyles(FileText); +const ThemedTrash = withUnistyles(Trash2); +const installIcon = ; +const powerIcon = ; +const linkIcon = ; +const reloadIcon = ; +const logsIcon = ; +const removeIcon = ; + +type TriggerState = PressableStateCallbackType & { hovered?: boolean; open?: boolean }; +// The trigger hangs by how far its frame reaches past the glyph, so the glyph sits on the trailing +// content rail and the frame does not grow the row. +const TRIGGER_HANG = iconButtonChromeHang("small"); + +function MenuTrigger({ label, testID }: { label: string; testID: string }) { + const compact = useIsCompactFormFactor(); + const style = useIconButtonChromeStyle({ size: "small", compact, style: styles.trigger }); + const glyphSize = useIconButtonChromeGlyphSize("small", compact); + return ( + + {({ hovered, open }: TriggerState) => ( + + )} + + ); +} + +/** The page's occasional actions: install from a source, turn plugins off, submit a plugin. */ +export function PluginGalleryMenu({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const toast = useToast(); + // COMPAT(pluginSourceInstallation): added in v0.8.0; remove gate after 2027-03-16. + const sourceInstallSupported = useHostFeature(serverId, "pluginSourceInstallation"); + const { config, patchConfig } = useDaemonConfig(serverId); + const [installing, setInstalling] = useState(false); + const pluginsOn = config?.pluginsEnabled === true; + const openInstall = useCallback(() => setInstalling(true), []); + const closeInstall = useCallback(() => setInstalling(false), []); + const toggle = useCallback(async () => { + try { + await patchConfig({ pluginsEnabled: !pluginsOn }); + toast.show( + pluginsOn + ? t("settings.plugins.feedback.globalDisabled") + : t("settings.plugins.feedback.globalEnabled"), + { variant: "success" }, + ); + } catch (error) { + toast.error(pluginErrorText(error)); + } + }, [patchConfig, pluginsOn, t, toast]); + const submit = useCallback(() => void openExternalUrl(SUBMIT_PLUGIN_URL), []); + const label = t("settings.plugins.gallery.menu"); + return ( + <> + + + + {sourceInstallSupported ? ( + + {t("settings.plugins.gallery.actions.installFromSource")} + + ) : null} + + {pluginsOn + ? t("settings.plugins.gallery.actions.turnOff") + : t("settings.plugins.gallery.actions.turnOnAll")} + + + {t("settings.plugins.gallery.actions.submit")} + + + + {installing ? ( + + ) : null} + + ); +} +const SOURCE_TARGET = { kind: "source" } as const; + +/** One installed plugin's occasional actions, on its page. */ +export function PluginActionsMenu({ + serverId, + plugin, + repositoryUrl, + pendingAction, + onAction, +}: { + serverId: string; + plugin: PluginListItem; + repositoryUrl?: string; + pendingAction?: PluginAction; + onAction(action: PluginAction): void; +}) { + const { t } = useTranslation(); + // COMPAT(pluginLogs): added in v0.4.0, remove gate after 2027-08-16. + const logsSupported = useHostFeature(serverId, "pluginLogs"); + const [logsOpen, setLogsOpen] = useState(false); + const reload = useCallback(() => onAction("reload"), [onAction]); + const remove = useCallback(() => onAction("remove"), [onAction]); + const openLogs = useCallback(() => setLogsOpen(true), []); + const closeLogs = useCallback(() => setLogsOpen(false), []); + const openRepository = useCallback(() => { + if (repositoryUrl) void openExternalUrl(repositoryUrl); + }, [repositoryUrl]); + const label = t("settings.plugins.actions.menu", { name: pluginDisplayName(plugin) }); + return ( + <> + + + + + {t("settings.plugins.actions.reload")} + + {logsSupported ? ( + + {t("settings.plugins.logs.action")} + + ) : null} + {repositoryUrl ? ( + + {t("settings.plugins.gallery.actions.repository")} + + ) : null} + + {t("settings.plugins.actions.remove")} + + + + {logsOpen ? ( + + ) : null} + + ); +} + +function PluginLogsSheet({ + serverId, + plugin, + onClose, +}: { + serverId: string; + plugin: PluginListItem; + onClose(): void; +}) { + const { t } = useTranslation(); + const client = useHostRuntimeClient(serverId); + const pluginId = plugin.id; + const logs = useFetchQuery({ + queryKey: ["plugin-logs", serverId, pluginId], + queryFn: () => { + if (!client) throw new Error("Plugin host is offline"); + return client.getPluginLogs(pluginId); + }, + enabled: Boolean(client), + dataShape: "list", + staleTimeMs: 0, + }); + const refresh = useCallback(() => { + void logs.refetch(); + }, [logs]); + const header = useMemo( + () => ({ + title: t("settings.plugins.logs.title", { name: pluginDisplayName(plugin) }), + actions: ( + + ), + }), + [logs.isFetching, plugin, refresh, t], + ); + + let content = {t("settings.plugins.logs.loading")}; + if (logs.isError) { + content = ( + + + + ); + } else if (!logs.isLoading) { + content = logs.data?.length ? ( + + {logs.data.map((entry: PluginLogEntry) => ( + + + {entry.timestamp} {entry.stream} + + {entry.message} + + ))} + + ) : ( + {t("settings.plugins.logs.empty")} + ); + } + + return ( + + {content} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + trigger: { marginVertical: TRIGGER_HANG, marginRight: TRIGGER_HANG }, + logsState: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + textAlign: "center", + paddingVertical: theme.spacing[6], + }, + logList: { gap: theme.spacing[2] }, + logEntry: { + padding: theme.spacing[3], + gap: theme.spacing[1], + backgroundColor: theme.colors.surface2, + borderRadius: theme.borderRadius.md, + }, + logStdout: { + color: theme.colors.foregroundMuted, + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.sm, + }, + logStderr: { + color: theme.colors.statusDanger, + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.sm, + }, + logMessage: { + color: theme.colors.foreground, + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/plugins/gallery/operations.ts b/packages/app/src/plugins/gallery/operations.ts new file mode 100644 index 0000000000..edd4964c6a --- /dev/null +++ b/packages/app/src/plugins/gallery/operations.ts @@ -0,0 +1,159 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { useCallback, useSyncExternalStore } from "react"; +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import type { + PluginListItem, + PluginUpdatePreview, + PluginUpdateProposal, +} from "@getpaseo/protocol/messages"; +import { daemonConfigQueryKey } from "@/data/daemon-config"; +import { pluginListQueryKey } from "@/plugins/plugin-list"; +import { pluginErrorText } from "./error-text"; + +/** + * Installs and updates outlive the screen that started them: leaving Plugins and coming back + * mid-run still shows the run on its row. A finished run leaves no entry; the plugin list says + * what changed. + */ +export type PluginOperation = + | { kind: "install" | "update"; status: "running" } + | { kind: "install" | "update"; status: "failed"; error: string }; + +type Listener = () => void; + +const operations = new Map(); +const listeners = new Set(); + +function operationKey(serverId: string, subject: string): string { + return `${serverId}\n${subject}`; +} + +function setOperation(serverId: string, subject: string, operation: PluginOperation | null) { + const key = operationKey(serverId, subject); + if (operation) operations.set(key, operation); + else operations.delete(key); + for (const listener of listeners) listener(); +} + +function subscribe(listener: Listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** The install or update running or failed for a plugin, keyed by listing ID or plugin ID. */ +export function usePluginOperation(serverId: string, subject: string | undefined) { + const read = useCallback( + () => (subject ? operations.get(operationKey(serverId, subject)) : undefined), + [serverId, subject], + ); + return useSyncExternalStore(subscribe, read, read); +} + +/** Forgets a failed run once its error has been read. A running one keeps going. */ +export function dismissFailedOperation(serverId: string, subject: string) { + if (operations.get(operationKey(serverId, subject))?.status === "failed") + setOperation(serverId, subject, null); +} + +export function pluginUpdatesQueryKey(serverId: string) { + return ["plugin-updates", serverId] as const; +} + +function upsertPlugin(queryClient: QueryClient, serverId: string, plugin: PluginListItem) { + queryClient.setQueryData(pluginListQueryKey(serverId), (plugins = []) => { + const others = plugins.filter((candidate) => candidate.id !== plugin.id); + return [...others, plugin].sort((left, right) => left.id.localeCompare(right.id)); + }); +} + +interface HostContext { + client: DaemonClient; + queryClient: QueryClient; + serverId: string; +} + +export interface InstallRequest extends HostContext { + /** A registry ID such as `acme/example`, or any source the CLI accepts. */ + source: string; + /** Where the run shows: the listing ID, or the source for an install from source. */ + subject: string; + /** Plugins are off on the host; the confirmation said installing turns them on. */ + enablePlugins: boolean; + onInstalled(plugin: PluginListItem): void; +} + +export async function installPlugin(request: InstallRequest): Promise { + const { client, queryClient, serverId, subject } = request; + if (operations.get(operationKey(serverId, subject))?.status === "running") return; + setOperation(serverId, subject, { kind: "install", status: "running" }); + try { + if (request.enablePlugins) { + const result = await client.patchDaemonConfig({ pluginsEnabled: true }); + queryClient.setQueryData(daemonConfigQueryKey(serverId), result.config); + } + const plugin = await client.installPluginSource({ source: request.source }); + // Write the result before clearing the run, so the row goes straight to Installed. + upsertPlugin(queryClient, serverId, plugin); + setOperation(serverId, subject, null); + request.onInstalled(plugin); + } catch (error) { + setOperation(serverId, subject, { + kind: "install", + status: "failed", + error: pluginErrorText(error), + }); + } +} + +export interface UpdateRequest extends HostContext { + proposals: PluginUpdateProposal[]; + onUpdated(plugins: PluginListItem[]): void; +} + +export async function updatePlugins(request: UpdateRequest): Promise { + const { client, queryClient, serverId } = request; + const proposals = request.proposals.filter( + (proposal) => operations.get(operationKey(serverId, proposal.id))?.status !== "running", + ); + if (proposals.length === 0) return; + for (const proposal of proposals) + setOperation(serverId, proposal.id, { kind: "update", status: "running" }); + try { + const results = await client.applyPluginUpdates(proposals); + const updated: PluginListItem[] = []; + for (const result of results) { + if (result.outcome === "updated" && result.plugin) { + upsertPlugin(queryClient, serverId, result.plugin); + updated.push(result.plugin); + setOperation(serverId, result.id, null); + } else { + setOperation(serverId, result.id, { + kind: "update", + status: "failed", + error: result.error ?? "Update failed", + }); + } + } + const updatedIds = new Set(updated.map((plugin) => plugin.id)); + queryClient.setQueryData(pluginUpdatesQueryKey(serverId), (previews) => + previews?.filter((preview) => !updatedIds.has(preview.id)), + ); + if (updated.length) request.onUpdated(updated); + if (updated.length < results.length) recheckUpdates(request); + } catch (error) { + for (const proposal of proposals) + setOperation(serverId, proposal.id, { + kind: "update", + status: "failed", + error: pluginErrorText(error), + }); + recheckUpdates(request); + } +} + +// A proposal fails when the plugin changed since it was reviewed; Retry needs a fresh one. +function recheckUpdates({ queryClient, serverId }: HostContext): void { + void queryClient.invalidateQueries({ queryKey: pluginUpdatesQueryKey(serverId) }); +} diff --git a/packages/app/src/plugins/gallery/plugin-page.tsx b/packages/app/src/plugins/gallery/plugin-page.tsx new file mode 100644 index 0000000000..0e83ed5e49 --- /dev/null +++ b/packages/app/src/plugins/gallery/plugin-page.tsx @@ -0,0 +1,581 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { router } from "expo-router"; +import { ArrowLeft } from "lucide-react-native"; +import { useCallback, useMemo, useState, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { Image, ScrollView, Text, View } from "react-native"; +import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem, PluginUpdatePreview } from "@getpaseo/protocol/messages"; +import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference"; +import type { + PluginListingIndex, + PluginListing, + PluginListingDetail, +} from "@getpaseo/protocol/plugin-registry"; +import { MarkdownRenderer } from "@/components/markdown/renderer"; +import { SettingsCard, SettingsRow, SettingsSection } from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { ExternalLink } from "@/components/ui/external-link"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { StatusBadge } from "@/components/ui/status-badge"; +import { Switch } from "@/components/ui/switch"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-api-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { useInstalledPlugin, usePluginEvaluationError } from "@/plugins/registry"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import { PluginSettingsContent } from "@/plugins/settings"; +import { usePluginActions, type PluginAction } from "./actions"; +import { useListingMeta } from "./browse-tab"; +import { ListingInstallControl } from "./install-control"; +import { InstallPluginSheet, type InstallTarget } from "./install-sheet"; +import { + categoryLabel, + installedByListing, + installedListingId, + listingAuthorAvatar, + listingImages, + listingText, + listingSource, + listingVersion, +} from "./listing"; +import { PluginActionsMenu } from "./menus"; +import { updatePlugins, usePluginOperation, type PluginOperation } from "./operations"; +import { PluginMeta, PluginTile } from "./plugin-row"; +import { buildPluginListingRoute } from "./routes"; +import { PluginsOffAlert } from "./plugins-off-alert"; +import { OverviewSkeleton, PluginPageSkeleton } from "./skeletons"; +import { + useLivePluginList, + usePluginDirectory, + usePluginListing, + usePluginUpdates, +} from "./queries"; +import { pluginErrorText } from "./error-text"; + +/** Which plugin the page is for: one installed on the host, or one listed in the directory. */ +export type PluginPageSubject = + | { kind: "installed"; pluginId: string; screenId?: string } + | { kind: "listing"; listingId: string }; + +function useResolvedPlugin(serverId: string, subject: PluginPageSubject) { + const plugins = useLivePluginList(serverId); + const plugin = useMemo(() => { + const list = plugins.data ?? []; + if (subject.kind === "installed") return list.find((item) => item.id === subject.pluginId); + return installedByListing(list).get(subject.listingId); + }, [plugins.data, subject]); + const listingId = + subject.kind === "listing" ? subject.listingId : plugin && installedListingId(plugin); + const detail = usePluginListing(serverId, listingId); + const directory = usePluginDirectory(serverId); + // The directory the user came from already has the listing, so the page shows it at once and + // only the overview waits for the listing's own request. + const listing = + detail.data ?? directory.query.data?.plugins.find((entry) => entry.id === listingId); + const listingLoading = detail.isLoading && !listing; + return { + plugin, + listingId, + listing, + detail, + loading: plugins.isLoading || (subject.kind === "listing" && listingLoading), + }; +} + +function UpdateButton({ serverId, plugin }: { serverId: string; plugin: PluginListItem }) { + const { t } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + const updates = usePluginUpdates(serverId); + const operation = usePluginOperation(serverId, plugin.id); + const preview = updates.data?.find((candidate) => candidate.id === plugin.id); + const update = useCallback(() => { + if (!client || !preview?.proposal) return; + void updatePlugins({ + client, + queryClient, + serverId, + proposals: [preview.proposal], + onUpdated: ([updated]) => + toast.show( + t("settings.plugins.gallery.update.updated", { name: pluginDisplayName(updated!) }), + { variant: "success" }, + ), + }); + }, [client, preview, queryClient, serverId, t, toast]); + if (!preview) return null; + const running = operation?.status === "running"; + let label = t("settings.plugins.gallery.actions.update"); + if (running) label = t("settings.plugins.gallery.actions.updating"); + else if (operation?.status === "failed") label = t("settings.plugins.gallery.actions.retry"); + return ( + + ); +} + +function InstalledControls({ + serverId, + plugin, + repositoryUrl, + onRemoved, +}: { + serverId: string; + plugin: PluginListItem; + repositoryUrl?: string; + onRemoved(): void; +}) { + const { t } = useTranslation(); + const actions = usePluginActions(serverId); + const name = pluginDisplayName(plugin); + const pendingAction = + actions.pending?.pluginId === plugin.id ? actions.pending.action : undefined; + const toggle = useCallback( + (enabled: boolean) => void actions.run(enabled ? "enable" : "disable", plugin), + [actions, plugin], + ); + const act = useCallback( + async (action: PluginAction) => { + if ((await actions.run(action, plugin)) && action === "remove") onRemoved(); + }, + [actions, onRemoved, plugin], + ); + const onAction = useCallback((action: PluginAction) => void act(action), [act]); + return ( + + + + + + ); +} + +function MediaImage({ url, onOpen }: { url: string; onOpen(url: string): void }) { + const { t } = useTranslation(); + const source = useMemo(() => ({ uri: url }), [url]); + const open = useCallback(() => onOpen(url), [onOpen, url]); + return ( + + + + ); +} + +/** The listing's screenshots in a row; one opens full size in the lightbox. */ +function MediaStrip({ urls }: { urls: string[] }) { + const [image, setImage] = useState(null); + const open = useCallback((uri: string) => setImage({ type: "uri", uri }), []); + const close = useCallback(() => setImage(null), []); + if (urls.length === 0) return null; + return ( + <> + + {urls.map((url) => ( + + ))} + + + + ); +} + +function DetailValue({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +function detailSource(plugin: PluginListItem | undefined, listing: PluginListing | undefined) { + if (plugin?.installation) return formatPluginInstallation(plugin.installation); + if (plugin) return plugin.path; + if (!listing) return undefined; + return listingSource(listing); +} + +function Details({ plugin, listing }: { plugin?: PluginListItem; listing?: PluginListing }) { + const { t } = useTranslation(); + const version = plugin?.installation?.currentRevision ?? (listing && listingVersion(listing)); + const source = detailSource(plugin, listing); + const repository = listing?.repository.url; + return ( + + + {version ? ( + + {version} + + ) : null} + {source ? ( + + {source} + + ) : null} + {listing?.license ? ( + + {listing.license} + + ) : null} + {listing ? ( + + {listing.updatedAt.slice(0, 10)} + + ) : null} + {repository ? ( + + + + ) : null} + + + ); +} + +/** What the page shows about the plugin, from whichever of the installed plugin and listing exist. */ +interface PluginPageModel { + name: string; + description?: string; + /** "author · installs · category" for a listing; the ID when the name hides it. */ + metaLine?: string; + /** The listing author's picture, before the meta line. */ + authorAvatar?: string; + /** Why the plugin failed to load, or why its install failed. */ + error?: string; + /** Why the last update failed, while the update is still offered. The installed version keeps running. */ + updateError?: string; + /** The plugin's own settings screen, shown inline. */ + screenId?: string; + overview?: string; +} + +function usePluginPageModel({ + serverId, + subject, + plugin, + listing, + detail, + installOperation, +}: { + serverId: string; + subject: PluginPageSubject; + plugin?: PluginListItem; + listing?: PluginListing; + /** The listing with its overview, once its own request returns. */ + detail?: PluginListingDetail; + installOperation: PluginOperation | undefined; +}): PluginPageModel { + const { i18n } = useTranslation(); + const directory = usePluginDirectory(serverId); + const meta = useListingMeta(); + const pluginId = plugin?.id ?? ""; + const installedPlugin = useInstalledPlugin(serverId, pluginId); + const evaluationError = usePluginEvaluationError(serverId, pluginId); + const pluginOperation = usePluginOperation(serverId, pluginId); + const updates = usePluginUpdates(serverId); + const text = listing ? listingText(listing, i18n.language) : undefined; + const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined; + return { + name: plugin ? pluginDisplayName(plugin) : (text?.name ?? subjectId(subject)), + description: text?.description ?? plugin?.description, + metaLine: listing + ? listingMetaLine(meta(listing), directory.query.data, listing) + : installedMetaLine(plugin), + authorAvatar: listing && listingAuthorAvatar(listing), + error: plugin ? (evaluationError ?? plugin.error) : failedError(installOperation), + updateError: failedUpdateError(pluginOperation, updates.data, pluginId), + screenId: plugin ? (requestedScreen ?? installedPlugin?.settingsScreens[0]?.id) : undefined, + overview: detail && listingOverview(detail, i18n.language), + }; +} + +function subjectId(subject: PluginPageSubject): string { + return subject.kind === "listing" ? subject.listingId : subject.pluginId; +} + +function listingOverview(listing: PluginListingDetail, language: string): string { + return (listing.overviewTranslations?.[language] ?? listing.readme).trim(); +} + +function listingMetaLine( + meta: string, + index: PluginListingIndex | undefined, + listing: PluginListing, +): string { + const category = listing.categories[0]; + return category && index ? `${meta} · ${categoryLabel(index, category)}` : meta; +} + +function installedMetaLine(plugin: PluginListItem | undefined): string | undefined { + return plugin?.name && plugin.name !== plugin.id ? plugin.id : undefined; +} + +function failedError(operation: PluginOperation | undefined): string | undefined { + return operation?.status === "failed" ? operation.error : undefined; +} + +/** Shown with the Update button it belongs to, as on the Installed tab's Updates row. */ +function failedUpdateError( + operation: PluginOperation | undefined, + updates: PluginUpdatePreview[] | undefined, + pluginId: string, +): string | undefined { + if (operation?.kind !== "update" || !updates?.some((preview) => preview.id === pluginId)) + return undefined; + return failedError(operation); +} + +function HeaderControl({ + serverId, + plugin, + listing, + installOperation, + onInstall, + onRemoved, +}: { + serverId: string; + plugin?: PluginListItem; + listing?: PluginListing; + installOperation: PluginOperation | undefined; + onInstall(listing: PluginListing): void; + onRemoved(): void; +}) { + if (plugin) + return ( + + ); + if (!listing) return null; + return ( + + ); +} + +/** + * A plugin's page: what it is, its install or on/off control, its own settings, its overview and + * the facts about where it came from. The same page serves an installed plugin and a listing. + */ +export function PluginPage({ + serverId, + subject, + onBack, +}: { + serverId: string; + subject: PluginPageSubject; + onBack(): void; +}) { + const { t } = useTranslation(); + const compact = useIsCompactFormFactor(); + const { plugin, listingId, listing, detail, loading } = useResolvedPlugin(serverId, subject); + const installOperation = usePluginOperation(serverId, listingId); + const model = usePluginPageModel({ + serverId, + subject, + plugin, + listing, + detail: detail.data, + installOperation, + }); + const [installTarget, setInstallTarget] = useState(null); + const install = useCallback( + (target: PluginListing) => setInstallTarget({ kind: "listing", listing: target }), + [], + ); + const closeInstall = useCallback(() => setInstallTarget(null), []); + // An installed page finds its listing through the plugin, which uninstalling removes. A listed + // plugin's page becomes its listing's page, offering Install again; any other returns to Plugins. + const onRemoved = useCallback(() => { + if (subject.kind !== "installed") return; + if (listingId) router.replace(buildPluginListingRoute(serverId, listingId)); + else onBack(); + }, [listingId, onBack, serverId, subject.kind]); + + const back = compact ? null : ( + + ); + if (loading) + return ( + + {back} + + + ); + if (!plugin && !listing) + return ( + + ); + + return ( + + {back} + + + + + + {model.name} + + {plugin && model.error ? ( + + ) : null} + + {model.metaLine ? ( + + ) : null} + + + + + {installTarget ? ( + + ) : null} + + ); +} + +function PluginPageBody({ + serverId, + plugin, + listing, + overviewLoading, + model, +}: { + serverId: string; + plugin?: PluginListItem; + listing?: PluginListing; + overviewLoading: boolean; + model: PluginPageModel; +}) { + const { t } = useTranslation(); + return ( + <> + {plugin ? : null} + {model.description ? {model.description} : null} + {model.error ? ( + + + + ) : null} + {model.updateError ? ( + + + + ) : null} + {listing ? : null} + {plugin && model.screenId ? ( + // The plugin's settings screen brings its own sections. + + ) : null} + {model.overview || (listing && overviewLoading) ? ( + + {model.overview ? ( + + + + + + ) : ( + + )} + + ) : null} +
+ + ); +} + +const styles = StyleSheet.create((theme) => ({ + back: { alignSelf: "flex-start", paddingHorizontal: 0, marginBottom: theme.spacing[4] }, + header: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[4], + }, + identity: { flex: 1, minWidth: 0, gap: theme.spacing[1] }, + nameRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + name: { flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.xl }, + controls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + description: { + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + marginBottom: theme.spacing[6], + }, + block: { marginBottom: theme.spacing[6] }, + // The settings row's padding, so the overview's text sits where a row's label would. + overview: { padding: theme.spacing[4] }, + mediaStrip: { flexGrow: 0, marginBottom: theme.spacing[6] }, + mediaRow: { gap: theme.spacing[3] }, + media: { + height: 180, + aspectRatio: 16 / 10, + borderRadius: theme.borderRadius.lg, + borderWidth: 1, + borderColor: theme.colors.border, + backgroundColor: theme.colors.surface2, + overflow: "hidden", + }, + mediaImage: { width: "100%", height: "100%" }, + detailValue: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + maxWidth: 320, + }, +})); diff --git a/packages/app/src/plugins/gallery/plugin-row.tsx b/packages/app/src/plugins/gallery/plugin-row.tsx new file mode 100644 index 0000000000..456fda3b37 --- /dev/null +++ b/packages/app/src/plugins/gallery/plugin-row.tsx @@ -0,0 +1,202 @@ +import { ChevronRight } from "lucide-react-native"; +import { useCallback, useMemo, type ReactNode } from "react"; +import { Image, Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { foregroundIconColorMapping, mutedIconColorMapping } from "@/components/ui/icon-color"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { settingsStyles } from "@/styles/settings"; +import { ICON_SIZE } from "@/styles/theme"; + +const ThemedChevron = withUnistyles(ChevronRight); +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +/** A plugin's icon, or its initial on a neutral tile when it has none. */ +export function PluginTile({ + name, + icon, + size = "md", +}: { + name: string; + icon?: string; + size?: "md" | "lg"; +}) { + const tileStyle = useMemo(() => [styles.tile, size === "lg" && styles.tileLarge], [size]); + const source = useMemo(() => (icon ? { uri: icon } : null), [icon]); + if (source) return ; + return ( + + + {name.slice(0, 1).toUpperCase()} + + + ); +} + +/** A listing author's GitHub picture, before their name in a meta line. */ +export function AuthorAvatar({ url }: { url: string }) { + const source = useMemo(() => ({ uri: url }), [url]); + return ; +} + +/** A line of facts, led by the author's picture when the plugin is listed. */ +export function PluginMeta({ + text, + authorAvatar, + testID, +}: { + text: string; + authorAvatar?: string; + testID?: string; +}) { + return ( + + {authorAvatar ? : null} + + {text} + + + ); +} + +export interface PluginRowProps { + name: string; + icon?: string; + /** Beside the name, such as a Failed badge. */ + badge?: ReactNode; + description?: string; + /** Who made it and which version, or how many installs. */ + meta?: string; + /** The listing author's picture, before the meta line. */ + authorAvatar?: string; + /** Replaces the meta line: what went wrong, in the row the user is looking at. */ + error?: string; + /** The row's control: a switch, or the install or update button. The chevron follows it. */ + children?: ReactNode; + onPress(): void; + accessibilityLabel: string; + testID?: string; +} + +/** + * One plugin in a card: icon, name, a line of description and a line of facts. The whole row opens + * the plugin's page; the control in the trailing slot acts without opening it. + */ +export function PluginRow({ + name, + icon, + badge, + description, + meta, + authorAvatar, + error, + children, + onPress, + accessibilityLabel, + testID, +}: PluginRowProps) { + const rowStyle = useCallback( + ({ hovered }: HoverState) => [settingsStyles.row, styles.row, hovered && styles.hovered], + [], + ); + return ( + + {({ hovered }: HoverState) => ( + <> + + + + + {name} + + {badge} + + {description ? ( + + {description} + + ) : null} + {error ? ( + + {error} + + ) : null} + {meta && !error ? ( + + + + ) : null} + + {children} + + + + + )} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + row: { gap: theme.spacing[3] }, + hovered: { backgroundColor: theme.colors.surface2 }, + pressed: { backgroundColor: theme.colors.surface3 }, + tile: { + width: theme.spacing[8], + height: theme.spacing[8], + borderRadius: theme.borderRadius.lg, + borderWidth: 1, + borderColor: theme.colors.border, + backgroundColor: theme.colors.surface2, + alignItems: "center", + justifyContent: "center", + overflow: "hidden", + }, + tileLarge: { + width: theme.spacing[12], + height: theme.spacing[12], + borderRadius: theme.borderRadius.xl, + }, + initial: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.base }, + initialLarge: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.xl }, + text: { flex: 1, minWidth: 0 }, + titleRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + title: { flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.base }, + description: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + marginTop: theme.spacing[0.5], + }, + meta: { marginTop: theme.spacing[0.5] }, + metaRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[1.5] }, + metaText: { + flexShrink: 1, + color: theme.colors.foregroundExtraMuted, + fontSize: theme.fontSize.sm, + }, + avatar: { + width: theme.iconSize.sm, + height: theme.iconSize.sm, + borderRadius: theme.borderRadius.full, + borderWidth: 1, + borderColor: theme.colors.border, + backgroundColor: theme.colors.surface2, + }, + error: { + color: theme.colors.statusDanger, + fontSize: theme.fontSize.sm, + marginTop: theme.spacing[0.5], + }, + // Optical: the chevron's ink sits about 4px inside its box; this puts it on the card's trailing + // rail, the same as SettingsRowHeader. + chevron: { marginRight: -theme.spacing[1] }, +})); diff --git a/packages/app/src/plugins/gallery/plugins-off-alert.tsx b/packages/app/src/plugins/gallery/plugins-off-alert.tsx new file mode 100644 index 0000000000..2e87f9dc55 --- /dev/null +++ b/packages/app/src/plugins/gallery/plugins-off-alert.tsx @@ -0,0 +1,48 @@ +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostLabel } from "./install-sheet"; +import { pluginErrorText } from "./error-text"; + +/** Says that installed plugins are not running on this host, with the switch that runs them. */ +export function PluginsOffAlert({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const toast = useToast(); + const hostLabel = useHostLabel(serverId); + const { config, patchConfig } = useDaemonConfig(serverId); + const [turningOn, setTurningOn] = useState(false); + const turnOn = useCallback(async () => { + setTurningOn(true); + try { + await patchConfig({ pluginsEnabled: true }); + } catch (error) { + toast.error(pluginErrorText(error)); + } finally { + setTurningOn(false); + } + }, [patchConfig, toast]); + if (!config || config.pluginsEnabled === true) return null; + return ( + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + block: { marginBottom: theme.spacing[6] }, +})); diff --git a/packages/app/src/plugins/gallery/queries.ts b/packages/app/src/plugins/gallery/queries.ts new file mode 100644 index 0000000000..8f4451c957 --- /dev/null +++ b/packages/app/src/plugins/gallery/queries.ts @@ -0,0 +1,112 @@ +import { useCallback, useEffect } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { usePluginList } from "@/plugins/plugin-list"; +import { useFetchQuery } from "@/data/query"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { pluginUpdatesQueryKey } from "./operations"; + +// The directory changes when a maintainer publishes, not while someone browses. These queries +// refetch on mount only once stale, so opening a plugin's page does not fetch them again. +const DIRECTORY_STALE_MS = 10 * 60_000; + +function useHostReady(serverId: string) { + const client = useHostRuntimeClient(serverId); + const connected = useHostRuntimeIsConnected(serverId); + return { client, ready: Boolean(client && connected) }; +} + +/** The host's plugin directory. `supported` is false until the host proxies the registry. */ +export function usePluginDirectory(serverId: string) { + const { client, ready } = useHostReady(serverId); + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + const supported = useHostFeature(serverId, "pluginRegistry"); + const query = useFetchQuery({ + queryKey: ["plugin-directory", serverId] as const, + queryFn: () => { + if (!client) throw new Error("Plugin host is offline"); + return client.listPluginRegistry(); + }, + enabled: ready && supported, + dataShape: "value", + staleTimeMs: DIRECTORY_STALE_MS, + refetchOnMount: true, + }); + return { supported, query }; +} + +/** One listing with its overview. */ +export function usePluginListing(serverId: string, listingId: string | undefined) { + const { client, ready } = useHostReady(serverId); + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + const supported = useHostFeature(serverId, "pluginRegistry"); + return useFetchQuery({ + queryKey: ["plugin-listing", serverId, listingId] as const, + queryFn: () => { + if (!client || !listingId) throw new Error("Plugin host is offline"); + return client.getRegistryPlugin(listingId); + }, + enabled: ready && supported && listingId !== undefined, + dataShape: "value", + staleTimeMs: DIRECTORY_STALE_MS, + refetchOnMount: true, + }); +} + +/** Installed plugins with a newer reviewed version, by plugin ID. */ +export function usePluginUpdates(serverId: string) { + const { client, ready } = useHostReady(serverId); + // COMPAT(pluginSourceUpdates): added in v0.8.0, remove gate after 2027-03-16. + const supported = useHostFeature(serverId, "pluginSourceUpdates"); + return useFetchQuery({ + queryKey: pluginUpdatesQueryKey(serverId), + queryFn: () => { + if (!client) throw new Error("Plugin host is offline"); + return client.previewPluginUpdates(); + }, + enabled: ready && supported, + dataShape: "list", + staleTimeMs: DIRECTORY_STALE_MS, + refetchOnMount: true, + select: (previews) => previews.filter((preview) => preview.outcome === "update"), + }); +} + +/** Refetches the plugin list when another client or the CLI changes it. */ +function usePluginCatalogFeed(serverId: string, refetch: () => unknown) { + const client = useHostRuntimeClient(serverId); + const connected = useHostRuntimeIsConnected(serverId); + const supported = useHostFeature(serverId, "pluginManagement"); + useEffect(() => { + if (!client || !connected || !supported) return; + const observation = client.observeEvents(["status.plugin_catalog_changed"]); + observation.subscribe({ + snapshot: () => {}, + update: (message) => { + if (message.type === "status" && message.payload.status === "plugin_catalog_changed") + void refetch(); + }, + }); + return () => { + void observation + .release() + .catch((error) => console.warn("[Plugins] Failed to release settings feed", error)); + }; + }, [client, connected, supported, refetch]); +} + +/** + * The host's plugins, refetched whenever another client or the CLI changes them. A change also + * re-checks updates, whose proposals name the revision each plugin had when checked. + */ +export function useLivePluginList(serverId: string) { + const plugins = usePluginList(serverId); + const queryClient = useQueryClient(); + const { refetch } = plugins; + const refresh = useCallback(() => { + void queryClient.invalidateQueries({ queryKey: pluginUpdatesQueryKey(serverId) }); + return refetch(); + }, [queryClient, refetch, serverId]); + usePluginCatalogFeed(serverId, refresh); + return plugins; +} diff --git a/packages/app/src/plugins/gallery/routes.ts b/packages/app/src/plugins/gallery/routes.ts new file mode 100644 index 0000000000..f8677ceab9 --- /dev/null +++ b/packages/app/src/plugins/gallery/routes.ts @@ -0,0 +1,16 @@ +/** An installed plugin's page. Its settings screens open at `buildPluginSettingsRoute`. */ +export function buildPluginPageRoute(serverId: string, pluginId: string) { + return { + pathname: "/settings/hosts/[serverId]/plugins/[pluginId]" as const, + params: { serverId, pluginId }, + }; +} + +/** A directory listing's page, by its `owner/slug` ID. */ +export function buildPluginListingRoute(serverId: string, listingId: string) { + const [owner = "", slug = ""] = listingId.split("/"); + return { + pathname: "/settings/hosts/[serverId]/plugin-directory/[owner]/[slug]" as const, + params: { serverId, owner, slug }, + }; +} diff --git a/packages/app/src/plugins/gallery/skeletons.tsx b/packages/app/src/plugins/gallery/skeletons.tsx new file mode 100644 index 0000000000..ed7ca61826 --- /dev/null +++ b/packages/app/src/plugins/gallery/skeletons.tsx @@ -0,0 +1,105 @@ +import { useMemo } from "react"; +import { View, type Animated } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { SettingsCard } from "@/components/settings"; +import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton"; +import { settingsStyles } from "@/styles/settings"; + +const ROWS = [0, 1, 2, 3]; +const LINES = [0, 1, 2]; + +function RowSkeleton({ pulse }: { pulse: Animated.Value }) { + const rowStyle = useMemo(() => [settingsStyles.row, styles.row], []); + return ( + + + + + + + + + ); +} + +/** A card of plugin rows while the list or the directory loads. */ +export function PluginRowsSkeleton({ testID }: { testID?: string }) { + const pulse = useSkeletonPulse(); + return ( + + {ROWS.map((row) => ( + + ))} + + ); +} + +/** Lines of text in a card, where the overview will be. */ +export function OverviewSkeleton() { + const pulse = useSkeletonPulse(); + return ( + + + {LINES.map((line) => ( + + ))} + + + ); +} + +/** The plugin page's header and description before anything about the plugin is known. */ +export function PluginPageSkeleton() { + const pulse = useSkeletonPulse(); + return ( + + + + + + + + + + + + + + + ); +} + +// The shapes take the size of what they stand for: a row's tile and text, the page's large tile and +// name, and a button. +const styles = StyleSheet.create((theme) => { + const shape = { backgroundColor: theme.colors.surface2, borderRadius: theme.borderRadius.sm }; + return { + row: { gap: theme.spacing[3] }, + header: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[4], + }, + text: { flex: 1, minWidth: 0, gap: theme.spacing[2] }, + tile: { + ...shape, + width: theme.spacing[8], + height: theme.spacing[8], + borderRadius: theme.borderRadius.lg, + }, + tileLarge: { + ...shape, + width: theme.spacing[12], + height: theme.spacing[12], + borderRadius: theme.borderRadius.xl, + }, + name: { ...shape, width: 180, height: theme.fontSize.xl }, + title: { ...shape, width: 140, height: theme.fontSize.sm }, + line: { ...shape, width: "100%", maxWidth: 420, height: theme.fontSize.sm }, + short: { ...shape, width: "60%", maxWidth: 260, height: theme.fontSize.sm }, + control: { ...shape, width: 72, height: 28, borderRadius: theme.borderRadius.md }, + overview: { padding: theme.spacing[4], gap: theme.spacing[3] }, + description: { gap: theme.spacing[2], marginBottom: theme.spacing[6] }, + }; +}); diff --git a/packages/app/src/plugins/installation-provider.test.tsx b/packages/app/src/plugins/installation-provider.test.tsx index b4f7735e86..0428e3bb2f 100644 --- a/packages/app/src/plugins/installation-provider.test.tsx +++ b/packages/app/src/plugins/installation-provider.test.tsx @@ -1,5 +1,5 @@ import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host"; -import { usePaseo, useRpc } from "@getpaseo/plugin/client"; +import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client"; import { defineRpc } from "@getpaseo/plugin"; import { createPaseoApi, type PaseoApi } from "@getpaseo/client"; import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; @@ -8,7 +8,11 @@ import React from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { expect, it } from "vitest"; import { z } from "zod"; +import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin"; +import type { PluginClientStateSource } from "@getpaseo/plugin/client/host"; +import type { ToastApi } from "@/components/toast-host"; import { PluginInstallationProvider } from "./installation-provider"; +import { PluginEnvironmentProvider } from "./popover"; import type { InstalledPlugin } from "./types"; const status = defineRpc({ @@ -46,6 +50,7 @@ function installation(invoked: string[]): InstalledPlugin { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], @@ -88,3 +93,53 @@ it("gives every surface the installation's client and RPCs on its first frame", plugin.lifetime.abort(); await plugin.paseo.dispose(); }); + +it("lets every surface read state through the plugin state hooks", async () => { + const plugin = installation([]); + function Surface() { + return {useWorkspaces().length} workspaces; + } + + const markup = renderToStaticMarkup( + + + , + ); + + expect(markup).toBe("0 workspaces"); + plugin.lifetime.abort(); + await plugin.paseo.dispose(); +}); + +function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) { + return { installation: plugin, state, toast: {} as ToastApi }; +} + +it("lets a surface read the state source its host passes", async () => { + const plugin = installation([]); + // A sidebar view spans every connected host, so its source is not the installation's host. + const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot; + const state: PluginClientStateSource = { + subscribe: () => () => undefined, + getWorkspace: () => workspace, + getAgent: () => null, + getProject: () => null, + getTerminal: () => null, + getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }), + }; + function Surface() { + return {useWorkspace("ws-on-another-host")?.id}; + } + + const environment = pluginEnvironment(plugin, state); + + const markup = renderToStaticMarkup( + + + , + ); + + expect(markup).toBe("ws-on-another-host"); + plugin.lifetime.abort(); + await plugin.paseo.dispose(); +}); diff --git a/packages/app/src/plugins/installation-provider.tsx b/packages/app/src/plugins/installation-provider.tsx index 19fb3bc8ab..d5faf75b8b 100644 --- a/packages/app/src/plugins/installation-provider.tsx +++ b/packages/app/src/plugins/installation-provider.tsx @@ -2,29 +2,42 @@ import { getPluginClientApi } from "./client-state/api"; import { QueryClientProvider } from "@tanstack/react-query"; import { PaseoApiProvider, + PluginClientStateProvider, PluginComposersProvider, PluginRpcProvider, PluginTranslationProvider, + type PluginClientStateSource, } from "@getpaseo/plugin/client/host"; -import React, { type ReactNode } from "react"; +import React, { useMemo, type ReactNode } from "react"; +import { createPluginClientStateSource } from "./client-state/source"; import { pluginComposersSource } from "./composer-items/source"; import type { InstalledPlugin } from "./types"; -/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */ +/** + * Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs, + * and the state the plugin state hooks read. That state is scoped to the installation's host + * unless the surface passes its own, as a sidebar view does to span every connected host. + */ export function PluginInstallationProvider({ plugin, + state: surfaceState, children, }: { plugin: InstalledPlugin; + state?: PluginClientStateSource; children: ReactNode; }) { + const state = useMemo( + () => surfaceState ?? createPluginClientStateSource(plugin.serverId), + [plugin.serverId, surfaceState], + ); return ( - {children} + {children} diff --git a/packages/app/src/plugins/item-host.tsx b/packages/app/src/plugins/item-host.tsx index 2df4198e7a..3083aa1595 100644 --- a/packages/app/src/plugins/item-host.tsx +++ b/packages/app/src/plugins/item-host.tsx @@ -14,7 +14,7 @@ import type { InstalledPlugin } from "./types"; /** `withUnistyles` mapping that hands a host the plugin theme. */ export const pluginThemeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) }); -function renderNothing() { +export function renderNothing() { return null; } diff --git a/packages/app/src/plugins/plugin-list.ts b/packages/app/src/plugins/plugin-list.ts index 387e0c6b56..40278883b2 100644 --- a/packages/app/src/plugins/plugin-list.ts +++ b/packages/app/src/plugins/plugin-list.ts @@ -3,13 +3,17 @@ import { useFetchQuery } from "@/data/query"; import { useHostFeature } from "@/runtime/host-features"; import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +export function pluginListQueryKey(serverId: string) { + return ["plugins", serverId] as const; +} + /** A host's configured plugins, as listed on Settings → Plugins. One cache entry per host. */ export function usePluginList(serverId: string, options: { enabled?: boolean } = {}) { const client = useHostRuntimeClient(serverId); const connected = useHostRuntimeIsConnected(serverId); const supported = useHostFeature(serverId, "pluginManagement"); return useFetchQuery({ - queryKey: ["plugins", serverId] as const, + queryKey: pluginListQueryKey(serverId), queryFn: async () => { if (!client) throw new Error("Plugin host is offline"); return client.listPlugins(); diff --git a/packages/app/src/plugins/popover.tsx b/packages/app/src/plugins/popover.tsx index f9680ebb29..d56b69f0d5 100644 --- a/packages/app/src/plugins/popover.tsx +++ b/packages/app/src/plugins/popover.tsx @@ -1,4 +1,3 @@ -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import type { ReactNode } from "react"; import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; @@ -30,8 +29,8 @@ export function PluginEnvironmentProvider({ }: PluginEnvironmentProviderProps) { return ( - - {children} + + {children} ); diff --git a/packages/app/src/plugins/react-native/ui.ts b/packages/app/src/plugins/react-native/ui.ts index 8b7d17216d..b5ae3c77b0 100644 --- a/packages/app/src/plugins/react-native/ui.ts +++ b/packages/app/src/plugins/react-native/ui.ts @@ -11,6 +11,7 @@ export { export { ExternalLink } from "@/components/ui/external-link"; export { SidebarRow, SidebarSeparator } from "@/plugins/sidebar-items/kit"; +export { WorkspaceRowBadge } from "@/plugins/workspace-row-badge-items/kit"; export { DocumentFrame } from "@/file-panels/document-frame"; diff --git a/packages/app/src/plugins/registry.ts b/packages/app/src/plugins/registry.ts index 042050ed3a..8319861dc9 100644 --- a/packages/app/src/plugins/registry.ts +++ b/packages/app/src/plugins/registry.ts @@ -125,6 +125,7 @@ export class PluginRegistry { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], @@ -282,6 +283,12 @@ export function usePluginCatalogStatus(serverId: string): PluginCatalogStatus { ); } +/** Why the app could not run the plugin's client bundle, updated when the host's catalog changes. */ +export function usePluginEvaluationError(serverId: string, pluginId: string): string | undefined { + const read = () => pluginRegistry.getEvaluationError(serverId, pluginId); + return useSyncExternalStore(pluginRegistry.subscribe, read, read); +} + export function usePluginInstallations(pluginId: string): InstalledPlugin[] { const installed = useInstalledPlugins(); return useMemo(() => installed.filter((plugin) => plugin.id === pluginId), [installed, pluginId]); diff --git a/packages/app/src/plugins/settings/index.tsx b/packages/app/src/plugins/settings/index.tsx index f2e510872a..122415dace 100644 --- a/packages/app/src/plugins/settings/index.tsx +++ b/packages/app/src/plugins/settings/index.tsx @@ -3,10 +3,8 @@ import { useTranslation } from "react-i18next"; import { Platform, ScrollView, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { router } from "expo-router"; -import { ArrowLeft, Settings } from "lucide-react-native"; import type { PluginHostProps } from "@getpaseo/plugin/client"; import { Button } from "@/components/ui/button"; -import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; import { useIsCompactFormFactor } from "@/constants/layout"; import { useHostFeature } from "@/runtime/host-features"; @@ -18,7 +16,6 @@ import type { InstalledPlugin } from "../types"; import { PluginInstallationProvider } from "../installation-provider"; import { SurfaceErrorBoundary } from "../surface-error-boundary"; import { toPluginTheme } from "../theme"; -import { buildPluginSettingsRoute } from "./routes"; interface SettingsIdentity { serverId: string; @@ -26,32 +23,6 @@ interface SettingsIdentity { screenId: string; } -const ThemedSettingsIcon = withUnistyles(Settings); -const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); - -/** Opens the plugin's settings at its first screen. Renders nothing when it has none. */ -export function PluginSettingsButton({ serverId, pluginId }: Omit) { - const { t } = useTranslation(); - const plugin = useInstalledPlugin(serverId, pluginId); - const supported = useHostFeature(serverId, "pluginSettings"); - const firstScreenId = plugin?.settingsScreens[0]?.id; - const open = useCallback(() => { - if (firstScreenId) router.push(buildPluginSettingsRoute(serverId, pluginId, firstScreenId)); - }, [serverId, pluginId, firstScreenId]); - const compact = useIsCompactFormFactor(); - if (!supported || !firstScreenId) return null; - return ( - - - - ); -} - function renderNoIcon() { return null; } @@ -172,30 +143,12 @@ function SettingsContent({ const ThemedSettingsContent = withUnistyles(SettingsContent); // Settings routes carry no screen params. const themeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) }); -export function PluginSettingsContent({ - onBackToPlugins, - showBackToPlugins, - ...identity -}: SettingsIdentity & { onBackToPlugins: () => void; showBackToPlugins: boolean }) { - const { t } = useTranslation(); - return ( - - {showBackToPlugins ? ( - - ) : null} - - - ); + +/** One of the plugin's settings screens, with tabs to the others. Renders inside its plugin page. */ +export function PluginSettingsContent(identity: SettingsIdentity) { + return ; } const styles = StyleSheet.create((theme) => ({ message: { color: theme.colors.foregroundMuted }, tabs: { flexGrow: 0, marginBottom: theme.spacing[4] }, - backButton: { alignSelf: "flex-start", paddingHorizontal: 0, marginBottom: theme.spacing[4] }, })); diff --git a/packages/app/src/plugins/sidebar-groups.test.ts b/packages/app/src/plugins/sidebar-groups.test.ts index 635f3d8eac..f0a9104e9f 100644 --- a/packages/app/src/plugins/sidebar-groups.test.ts +++ b/packages/app/src/plugins/sidebar-groups.test.ts @@ -37,6 +37,7 @@ function installed( footer: [{ id: "status", title: "Status", Component: () => null }], }, legacySidebarItems, + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/surface-contribution.test.ts b/packages/app/src/plugins/surface-contribution.test.ts index 8af246cf81..9d5a9a4a22 100644 --- a/packages/app/src/plugins/surface-contribution.test.ts +++ b/packages/app/src/plugins/surface-contribution.test.ts @@ -51,6 +51,7 @@ function installation( surfaces: surfaces.map((id) => ({ id, title: id, Component: () => null })), sidebarViews: [], sidebarItems: { header: [], footer: [] }, + workspaceRowBadgeItems: [], legacySidebarItems: sidebarItems.map((item) => ({ ...item, title: item.id, diff --git a/packages/app/src/plugins/theme.test.ts b/packages/app/src/plugins/theme.test.ts index aeb7872a2e..01e0a25041 100644 --- a/packages/app/src/plugins/theme.test.ts +++ b/packages/app/src/plugins/theme.test.ts @@ -3,7 +3,13 @@ import { QueryClient } from "@tanstack/react-query"; import type { PluginThemeContribution } from "@getpaseo/plugin"; import { describe, expect, it } from "vitest"; import { darkTheme, lightTheme } from "@/styles/theme"; -import { collectPluginThemes, rememberPluginThemeHost } from "./themes"; +import { contrastRatio } from "@/utils/color"; +import { + buildPluginTheme, + collectPluginThemes, + parsePluginThemeContribution, + rememberPluginThemeHost, +} from "./themes"; import { toPluginTheme } from "./theme"; import type { InstalledPlugin } from "./types"; @@ -64,6 +70,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], @@ -167,6 +174,146 @@ describe("plugin theme palettes", () => { }); }); +function withColors( + contribution: PluginThemeContribution, + colors: Partial, +): PluginThemeContribution { + return { ...contribution, colors: { ...contribution.colors, ...colors } }; +} + +// A role only drives what it is named for. `ring` once filled the neutral fill, tertiary text and +// the light selected row, and `border` once filled the neutral fill, so a theme tuning either for +// its own purpose repainted unrelated surfaces. +describe("plugin theme roles", () => { + it("derives selected text against an overridden selected surface", () => { + const colors = buildPluginTheme(withColors(MOCHA, { sidebarSelected: "#68687c" })).colors; + expect(colors.surfaceSidebarSelected).toBe("#68687c"); + expect( + contrastRatio(colors.foregroundSidebarSelected, colors.surfaceSidebarSelected), + ).toBeGreaterThanOrEqual(2.5); + }); + + it("uses an explicit tertiary color unchanged on sidebar states", () => { + const colors = buildPluginTheme(withColors(MOCHA, { foregroundExtraMuted: "#123456" })).colors; + expect(colors.foregroundSidebarHover).toBe("#123456"); + expect(colors.foregroundSidebarSelected).toBe("#123456"); + }); + + it("keeps explicit semantic colors independent of ring and border", () => { + const overrides = { + sidebarHover: "#111111", + sidebarSelected: "#222222", + surface3: "#333333", + surface4: "#444444", + foregroundExtraMuted: "#aaaaaa", + }; + const before = buildPluginTheme(withColors(MOCHA, overrides)).colors; + const after = buildPluginTheme( + withColors(MOCHA, { ...overrides, ring: "#ff0000", border: "#00ff00" }), + ).colors; + for (const role of [ + "surfaceSidebarHover", + "surfaceSidebarSelected", + "surface3", + "surface4", + "foregroundExtraMuted", + "foregroundSidebarHover", + "foregroundSidebarSelected", + ] as const) { + expect(after[role]).toBe(before[role]); + } + }); + it.each([ + ["sidebarHover", "surfaceSidebarHover"], + ["sidebarSelected", "surfaceSidebarSelected"], + ["surface3", "surface3"], + ["surface4", "surface4"], + ["foregroundExtraMuted", "foregroundExtraMuted"], + ] as const)("accepts and applies %s independently", (input, output) => { + const contribution = withColors(MOCHA, { [input]: "#123456" }); + const parsed = parsePluginThemeContribution(contribution); + const colors = buildPluginTheme(parsed).colors; + expect(colors[output]).toBe("#123456"); + expect(() => parsePluginThemeContribution(withColors(MOCHA, { [input]: "no" }))).toThrow(); + const baseline = buildPluginTheme(MOCHA).colors; + for (const other of [ + "surfaceSidebarHover", + "surfaceSidebarSelected", + "surface3", + "surface4", + "foregroundExtraMuted", + ] as const) { + if (other !== output) expect(colors[other]).toBe(baseline[other]); + } + }); + it.each([LATTE, MOCHA])("keeps `ring` out of surfaces and text in $name", (contribution) => { + const base = buildPluginTheme(contribution).colors; + const changed = buildPluginTheme(withColors(contribution, { ring: "#ff0000" })).colors; + + expect(changed.ring).toBe("#ff0000"); + expect(changed.terminal.brightBlack).toBe("#ff0000"); + for (const token of [ + "surface3", + "surface4", + "foregroundExtraMuted", + "foregroundSidebarHover", + "foregroundSidebarSelected", + "surfaceSidebar", + "surfaceSidebarHover", + "surfaceSidebarSelected", + ] as const) { + expect(changed[token], token).toBe(base[token]); + } + }); + + it.each([LATTE, MOCHA])("keeps `border` out of the neutral fill in $name", (contribution) => { + const base = buildPluginTheme(contribution).colors; + const changed = buildPluginTheme(withColors(contribution, { border: "#ff0000" })).colors; + + expect(changed.border).toBe("#ff0000"); + expect(changed.surface3).toBe(base.surface3); + expect(changed.surface4).toBe(base.surface4); + }); + + it("builds a theme from colors that carry an alpha channel", () => { + const theme = buildPluginTheme( + withColors(MOCHA, { + background: "#1e1e2eff", + foreground: "#cdd6f4ff", + mutedForeground: "#a6adc8ff", + }), + ); + + expect(theme.colors.surface3).toBe(buildPluginTheme(MOCHA).colors.surface3); + }); + + it("paints the sidebar with `sidebar` when the theme gives one", () => { + const withSidebar = buildPluginTheme(withColors(MOCHA, { sidebar: "#11111b" })).colors; + + expect(withSidebar.surfaceSidebar).toBe("#11111b"); + expect(withSidebar.surfaceSidebarHover).not.toBe("#11111b"); + expect(withSidebar.surfaceSidebarSelected).not.toBe(withSidebar.surfaceSidebarHover); + }); + + it("leaves the sidebar where it was when the theme gives none", () => { + expect(buildPluginTheme(MOCHA).colors.surfaceSidebar).toBe(MOCHA.colors.background); + expect(buildPluginTheme(LATTE).colors.surfaceSidebar).toBe(LATTE.colors.control); + }); + + it("accepts an optional hex `sidebar` and rejects unknown colors", () => { + expect(parsePluginThemeContribution(withColors(MOCHA, { sidebar: "#11111b" }))).toMatchObject({ + colors: { sidebar: "#11111b" }, + }); + expect(() => parsePluginThemeContribution(withColors(MOCHA, { sidebar: "darker" }))).toThrow(); + expect(() => + parsePluginThemeContribution({ + ...MOCHA, + colors: { ...MOCHA.colors, unknownColor: "#000000" }, + }), + ).toThrow(); + }); +}); + const SUPPORTED = new Set(["host-a", "host-b", "host-z"]); describe("collectPluginThemes", () => { diff --git a/packages/app/src/plugins/themes/index.ts b/packages/app/src/plugins/themes/index.ts index fdebdfb52b..735ddda41b 100644 --- a/packages/app/src/plugins/themes/index.ts +++ b/packages/app/src/plugins/themes/index.ts @@ -13,6 +13,12 @@ import { lightTheme, type Theme, } from "@/styles/theme"; +import { + deriveNeutralFills, + deriveTertiaryText, + deriveSurfaceStates, + deriveSidebarStateText, +} from "@/styles/derive-colors"; import { getPreferredPluginContributionHost, rememberPluginContributionHost, @@ -37,6 +43,12 @@ const contributionSchema: z.ZodType = z.strictObject({ accent: hexColorSchema.optional(), mutedForeground: hexColorSchema, ring: hexColorSchema, + sidebar: hexColorSchema.optional(), + sidebarHover: hexColorSchema.optional(), + sidebarSelected: hexColorSchema.optional(), + surface3: hexColorSchema.optional(), + surface4: hexColorSchema.optional(), + foregroundExtraMuted: hexColorSchema.optional(), }), }); @@ -61,18 +73,31 @@ export function parsePluginThemeContribution(value: unknown): PluginThemeContrib function buildDarkPluginTheme(contribution: PluginThemeContribution): Theme { const colors = contribution.colors; const accent = colors.accent ?? colors.foreground; + const fills = deriveNeutralFills(colors.background, colors.foreground, "dark"); + const sidebar = colors.sidebar ?? colors.background; + const states = deriveSurfaceStates(sidebar, colors.foreground, "dark"); + const hover = colors.sidebarHover ?? states.hover; + const selected = colors.sidebarSelected ?? states.selected; + const tertiary = + colors.foregroundExtraMuted ?? deriveTertiaryText(colors.mutedForeground, colors.background); return buildDarkTheme( buildDarkSemanticColors({ surface0: colors.background, surface1: colors.raised, surface2: colors.control, - surface3: colors.border, - surface4: colors.ring, - surfaceDiffEmpty: colors.raised, - surfaceSidebar: colors.background, + surface3: colors.surface3 ?? fills.surface3, + surface4: colors.surface4 ?? fills.surface4, + surfaceSidebar: sidebar, + surfaceSidebarHover: hover, + surfaceSidebarSelected: selected, + foregroundSidebarHover: + colors.foregroundExtraMuted ?? deriveSidebarStateText(tertiary, hover, colors.foreground), + foregroundSidebarSelected: + colors.foregroundExtraMuted ?? + deriveSidebarStateText(tertiary, selected, colors.foreground), foreground: colors.foreground, foregroundMuted: colors.mutedForeground, - foregroundExtraMuted: colors.ring, + foregroundExtraMuted: tertiary, border: colors.border, borderAccent: colors.border, accent, @@ -89,18 +114,31 @@ function buildDarkPluginTheme(contribution: PluginThemeContribution): Theme { function buildLightPluginTheme(contribution: PluginThemeContribution): Theme { const colors = contribution.colors; const accent = colors.accent ?? colors.foreground; + const fills = deriveNeutralFills(colors.background, colors.foreground, "light"); + const sidebar = colors.sidebar ?? colors.control; + const states = deriveSurfaceStates(sidebar, colors.foreground, "light"); + const hover = colors.sidebarHover ?? states.hover; + const selected = colors.sidebarSelected ?? states.selected; + const tertiary = + colors.foregroundExtraMuted ?? deriveTertiaryText(colors.mutedForeground, colors.background); return buildLightTheme( buildLightSemanticColors({ surface0: colors.background, surface1: colors.raised, surface2: colors.control, - surface3: colors.border, - surface4: colors.ring, - surfaceDiffEmpty: colors.raised, - surfaceSidebar: colors.control, + surface3: colors.surface3 ?? fills.surface3, + surface4: colors.surface4 ?? fills.surface4, + surfaceSidebar: sidebar, + surfaceSidebarHover: hover, + surfaceSidebarSelected: selected, + foregroundSidebarHover: + colors.foregroundExtraMuted ?? deriveSidebarStateText(tertiary, hover, colors.foreground), + foregroundSidebarSelected: + colors.foregroundExtraMuted ?? + deriveSidebarStateText(tertiary, selected, colors.foreground), foreground: colors.foreground, foregroundMuted: colors.mutedForeground, - foregroundExtraMuted: colors.ring, + foregroundExtraMuted: tertiary, border: colors.border, borderAccent: colors.border, accent, @@ -116,7 +154,7 @@ function buildLightPluginTheme(contribution: PluginThemeContribution): Theme { ); } -function buildPluginTheme(contribution: PluginThemeContribution): Theme { +export function buildPluginTheme(contribution: PluginThemeContribution): Theme { return contribution.appearance === "light" ? buildLightPluginTheme(contribution) : buildDarkPluginTheme(contribution); diff --git a/packages/app/src/plugins/timeline/model.test.ts b/packages/app/src/plugins/timeline/model.test.ts index 957bd18686..e30e3b40b2 100644 --- a/packages/app/src/plugins/timeline/model.test.ts +++ b/packages/app/src/plugins/timeline/model.test.ts @@ -27,6 +27,7 @@ function plugin(input: { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/timeline/view.test.tsx b/packages/app/src/plugins/timeline/view.test.tsx index 7d96747279..57e371eadc 100644 --- a/packages/app/src/plugins/timeline/view.test.tsx +++ b/packages/app/src/plugins/timeline/view.test.tsx @@ -34,6 +34,7 @@ vi.mock("../client-runtime", () => ({ })); vi.mock("../icons", () => ({ Icon: () => null, + PluginIconView: () => null, pluginIconComponent: () => () => null, })); diff --git a/packages/app/src/plugins/timeline/view.tsx b/packages/app/src/plugins/timeline/view.tsx index 90f6e0e1a2..8a3d522a2b 100644 --- a/packages/app/src/plugins/timeline/view.tsx +++ b/packages/app/src/plugins/timeline/view.tsx @@ -1,4 +1,3 @@ -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import type { PluginTimelineItemProps } from "@getpaseo/plugin/client"; import type { PluginTheme } from "@getpaseo/plugin"; import React, { type ComponentType, useMemo } from "react"; @@ -8,7 +7,6 @@ import { useIsCompactFormFactor } from "@/constants/layout"; import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime"; import type { Theme } from "@/styles/theme"; import type { PluginTimelineStreamItem } from "@/types/stream"; -import { createPluginClientStateSource } from "../client-state/source"; import { useInstalledPlugin } from "../registry"; import { PluginInstallationProvider } from "../installation-provider"; import { SurfaceErrorBoundary } from "../surface-error-boundary"; @@ -59,7 +57,6 @@ function PluginTimelineItemBody({ const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId; const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]); const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]); - const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]); if (!plugin || !renderer || !parsed || !client) { return ; @@ -82,9 +79,7 @@ function PluginTimelineItemBody({ return ( - - - + ); diff --git a/packages/app/src/plugins/types.ts b/packages/app/src/plugins/types.ts index 497df5c59c..2ca1e4cf01 100644 --- a/packages/app/src/plugins/types.ts +++ b/packages/app/src/plugins/types.ts @@ -17,6 +17,7 @@ import type { PluginSidebarContribution as SDKPluginSidebarContribution, PluginSidebarViewContribution, PluginSidebarItemContribution as SDKPluginSidebarItemContribution, + PluginWorkspaceRowBadgeItemContribution as SDKPluginWorkspaceRowBadgeItemContribution, PluginScreenContribution as SDKPluginScreenContribution, PluginSettingsScreenContribution as SDKPluginSettingsScreenContribution, PluginTimelineRendererContribution, @@ -33,6 +34,8 @@ type PluginClientSlashCommandContribution = SDKPluginClientSlashCommandContribut type PluginComposerPillContribution = SDKPluginComposerPillContribution; type PluginSidebarContribution = SDKPluginSidebarContribution; type PluginSidebarItemContribution = SDKPluginSidebarItemContribution; +type PluginWorkspaceRowBadgeItemContribution = + SDKPluginWorkspaceRowBadgeItemContribution; type PluginScreenContribution = SDKPluginScreenContribution; type PluginSettingsScreenContribution = SDKPluginSettingsScreenContribution; type WorkspacePanelInput = SDKPluginWorkspacePanelContribution; @@ -56,6 +59,7 @@ export interface EvaluatedPlugin { // COMPAT(pluginSidebarAliases): added in v0.11.0, remove after 2027-03-29 /** `addSidebarItem` registrations, so `/plugin//sidebar/` routes keep resolving. */ legacySidebarItems: PluginSidebarContribution[]; + workspaceRowBadgeItems: PluginWorkspaceRowBadgeItemContribution[]; filePanels: PluginFilePanelContribution[]; composerItems: PluginComposerItemContribution[]; newWorkspaceItems: PluginNewWorkspaceItemContribution[]; @@ -95,6 +99,7 @@ export type { PluginComposerPillContribution, PluginSidebarContribution, PluginSidebarItemContribution, + PluginWorkspaceRowBadgeItemContribution, PluginScreenContribution, PluginSettingsScreenContribution, PluginThemeContribution, diff --git a/packages/app/src/plugins/workspace-panels/panel.tsx b/packages/app/src/plugins/workspace-panels/panel.tsx index 096400fb66..1500f1cdf1 100644 --- a/packages/app/src/plugins/workspace-panels/panel.tsx +++ b/packages/app/src/plugins/workspace-panels/panel.tsx @@ -5,7 +5,6 @@ import type { PluginTab, } from "@getpaseo/plugin/client"; import type { PluginTheme } from "@getpaseo/plugin"; -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import { CircleAlert } from "lucide-react-native"; import { useMemo, useState } from "react"; import { Text, View } from "react-native"; @@ -20,7 +19,6 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks"; import type { Theme } from "@/styles/theme"; import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity"; import { usePluginHostNavigation } from "../host-navigation"; -import { createPluginClientStateSource } from "../client-state/source"; import { toPluginTheme } from "../theme"; import { pluginIconComponent } from "../icons"; import { useInstalledPlugin } from "../registry"; @@ -67,7 +65,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) { const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId; const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]); const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]); - const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]); const navigation = usePluginHostNavigation(serverId); if (!plugin || !contribution || !workspaceExists) { @@ -123,9 +120,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) { Surface={Surface} key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`} > - - {panel} - + {panel} ); } diff --git a/packages/app/src/plugins/workspace-panels/resolution.test.ts b/packages/app/src/plugins/workspace-panels/resolution.test.ts index 6ceb95f1a1..4a8f7c0112 100644 --- a/packages/app/src/plugins/workspace-panels/resolution.test.ts +++ b/packages/app/src/plugins/workspace-panels/resolution.test.ts @@ -24,6 +24,7 @@ function installed(): InstalledPlugin { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/workspace-row-badge-items/index.tsx b/packages/app/src/plugins/workspace-row-badge-items/index.tsx new file mode 100644 index 0000000000..00f70416c5 --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/index.tsx @@ -0,0 +1,96 @@ +import type { PluginTheme } from "@getpaseo/plugin"; +import type { PluginWorkspaceRowBadgeItemProps } from "@getpaseo/plugin/client"; +import { useMemo } from "react"; +import { withUnistyles } from "react-native-unistyles"; +import { useAppSettings } from "@/hooks/use-settings"; +import { useInstalledPlugins } from "../registry"; +import { pluginThemeMapping, renderNothing, usePluginItemHost } from "../item-host"; +import { PluginEnvironmentProvider } from "../popover"; +import { SurfaceErrorBoundary } from "../surface-error-boundary"; +import type { InstalledPlugin, PluginWorkspaceRowBadgeItemContribution } from "../types"; +import { isWorkspaceRowBadgeItemVisible, workspaceRowBadgeItemKey } from "./model"; + +import { WorkspaceRowBadgeTitleContext } from "./kit"; + +export { WorkspaceRowBadge } from "./kit"; +export { + groupPluginWorkspaceRowBadgeItems, + isWorkspaceRowBadgeItemVisible, + type PluginWorkspaceRowBadgeItemGroup, +} from "./model"; + +interface RowBadgeItemTarget { + plugin: InstalledPlugin; + item: PluginWorkspaceRowBadgeItemContribution; +} + +/** The visible plugin row items installed on this workspace's host. */ +export function usePluginWorkspaceRowBadgeItems(serverId: string | null): RowBadgeItemTarget[] { + const installed = useInstalledPlugins(); + const { + settings: { sidebarPluginRowBadgeItems }, + } = useAppSettings(); + return useMemo( + () => + installed + .filter((plugin) => plugin.serverId === serverId) + .flatMap((plugin) => plugin.workspaceRowBadgeItems.map((item) => ({ plugin, item }))) + .filter(({ plugin, item }) => + isWorkspaceRowBadgeItemVisible( + sidebarPluginRowBadgeItems, + workspaceRowBadgeItemKey(plugin.id, item.id), + ), + ), + [installed, serverId, sidebarPluginRowBadgeItems], + ); +} + +/** + * Plugin items on a workspace's meta line, after the row's own. No wrapper views: an item that + * renders nothing must leave no gap behind it on the line. + */ +export function PluginWorkspaceRowBadgeItems({ + targets, + workspaceId, +}: { + targets: readonly RowBadgeItemTarget[]; + workspaceId: string; +}) { + return targets.map((target) => ( + + )); +} + +function RowBadgeItemHost({ + target: { plugin, item }, + workspaceId, + theme, +}: { + target: RowBadgeItemTarget; + workspaceId: string; + theme: PluginTheme; +}) { + const { environment, props: hostProps } = usePluginItemHost(plugin, theme); + const props = useMemo( + () => ({ ...hostProps, workspaceId }), + [hostProps, workspaceId], + ); + const title = plugin.i18n.resolve(item.title, plugin.locale); + const Item = item.Component; + return ( + + + + + + + + ); +} + +const ThemedRowBadgeItemHost = withUnistyles(RowBadgeItemHost); diff --git a/packages/app/src/plugins/workspace-row-badge-items/kit.tsx b/packages/app/src/plugins/workspace-row-badge-items/kit.tsx new file mode 100644 index 0000000000..eaa3733b5d --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/kit.tsx @@ -0,0 +1,93 @@ +import type { WorkspaceRowBadgeProps, WorkspaceRowBadgeTone } from "@getpaseo/plugin/client/ui"; +import { createContext, useContext, useMemo } from "react"; +import { Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { HOST_BADGE_ICON_SIZE } from "@/hosts/host-badge"; +import type { Theme } from "@/styles/theme"; +import { parsePluginIcon, PluginIconView } from "../icons"; + +/** The item's title, the accessible name of a badge that has neither a label nor its own. */ +export const WorkspaceRowBadgeTitleContext = createContext(undefined); + +const ThemedPluginIconView = withUnistyles(PluginIconView); + +function toneColor(theme: Theme, tone: WorkspaceRowBadgeTone): string { + if (tone === "success") return theme.colors.statusSuccess; + if (tone === "warning") return theme.colors.statusWarning; + if (tone === "danger") return theme.colors.statusDanger; + if (tone === "info") return theme.colors.statusDotRunning; + return theme.colors.foregroundMuted; +} + +const TONE_MAPPINGS: Record { color: string }> = { + muted: (theme) => ({ color: toneColor(theme, "muted") }), + success: (theme) => ({ color: toneColor(theme, "success") }), + warning: (theme) => ({ color: toneColor(theme, "warning") }), + danger: (theme) => ({ color: toneColor(theme, "danger") }), + info: (theme) => ({ color: toneColor(theme, "info") }), +}; + +/** + * A plugin's badge on the line under a workspace title, drawn like the row's own peers: one glyph + * at the line's size and a short word, in the color of the state it reports. The plugin owns the + * slot, so the badge draws no separator. + */ +export function WorkspaceRowBadge({ + icon, + label, + tone = "muted", + accessibilityLabel, +}: WorkspaceRowBadgeProps) { + const itemTitle = useContext(WorkspaceRowBadgeTitleContext); + // Parsed at render, not registration, so an invalid icon throws to the item's boundary. + const parsedIcon = useMemo( + () => (icon === undefined ? null : parsePluginIcon("Workspace row badge", icon)), + [icon], + ); + if (!parsedIcon && !label) return null; + return ( + + {parsedIcon ? ( + + ) : null} + {label ? ( + + {label} + + ) : null} + + ); +} + +// Read inside render, never into a module-scope table — see docs/unistyles.md. +function textToneStyle(tone: WorkspaceRowBadgeTone) { + if (tone === "success") return styles.success; + if (tone === "warning") return styles.warning; + if (tone === "danger") return styles.danger; + if (tone === "info") return styles.info; + return styles.muted; +} + +const styles = StyleSheet.create((theme) => ({ + item: { + flexDirection: "row", + alignItems: "center", + gap: 3, + minWidth: 0, + flexShrink: 1, + }, + text: { + fontSize: theme.fontSize.sm, + lineHeight: 16, + flexShrink: 1, + }, + muted: { color: toneColor(theme, "muted") }, + success: { color: toneColor(theme, "success") }, + warning: { color: toneColor(theme, "warning") }, + danger: { color: toneColor(theme, "danger") }, + info: { color: toneColor(theme, "info") }, +})); diff --git a/packages/app/src/plugins/workspace-row-badge-items/model.test.ts b/packages/app/src/plugins/workspace-row-badge-items/model.test.ts new file mode 100644 index 0000000000..8bcad76426 --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/model.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import type { InstalledPlugin } from "../types"; +import { groupPluginWorkspaceRowBadgeItems, isWorkspaceRowBadgeItemVisible } from "./model"; + +function Item() { + return null; +} + +function installed(id: string, serverId: string, itemIds: string[]): InstalledPlugin { + return { + id, + serverId, + locale: "en", + i18n: { resolve: (text: string) => text }, + workspaceRowBadgeItems: itemIds.map((itemId) => ({ + id: itemId, + title: `${id} ${itemId}`, + icon: "Gauge", + Component: Item, + })), + } as unknown as InstalledPlugin; +} + +describe("groupPluginWorkspaceRowBadgeItems", () => { + it("lists each plugin item once across hosts, in install order", () => { + const groups = groupPluginWorkspaceRowBadgeItems([ + installed("status", "host-a", ["state"]), + installed("asks", "host-a", ["open"]), + installed("status", "host-b", ["state"]), + ]); + expect(groups.map(({ key, title }) => ({ key, title }))).toEqual([ + { key: "status/state", title: "status state" }, + { key: "asks/open", title: "asks open" }, + ]); + }); +}); + +describe("isWorkspaceRowBadgeItemVisible", () => { + it("shows items until they are switched off", () => { + expect(isWorkspaceRowBadgeItemVisible({}, "status/state")).toBe(true); + expect(isWorkspaceRowBadgeItemVisible({ "status/state": true }, "status/state")).toBe(true); + expect(isWorkspaceRowBadgeItemVisible({ "status/state": false }, "status/state")).toBe(false); + }); +}); diff --git a/packages/app/src/plugins/workspace-row-badge-items/model.ts b/packages/app/src/plugins/workspace-row-badge-items/model.ts new file mode 100644 index 0000000000..6f937b3d5d --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/model.ts @@ -0,0 +1,45 @@ +import type { PluginIcon } from "@getpaseo/plugin/client"; +import type { InstalledPlugin } from "../types"; + +/** One workspace row badge item, coalesced across every host that contributes it. */ +export interface PluginWorkspaceRowBadgeItemGroup { + /** `/`: the key its Show toggle is stored under. */ + key: string; + pluginId: string; + itemId: string; + title: string; + icon: PluginIcon; +} + +export function workspaceRowBadgeItemKey(pluginId: string, itemId: string): string { + return `${pluginId}/${itemId}`; +} + +/** An item missing from the stored record has never been toggled, so it shows. */ +export function isWorkspaceRowBadgeItemVisible( + visibility: Readonly>, + key: string, +): boolean { + return visibility[key] !== false; +} + +/** Distinct items in install order, for the Show menu. Each host's copy draws on its own rows. */ +export function groupPluginWorkspaceRowBadgeItems( + plugins: readonly InstalledPlugin[], +): PluginWorkspaceRowBadgeItemGroup[] { + const groups = new Map(); + for (const plugin of plugins) { + for (const item of plugin.workspaceRowBadgeItems) { + const key = workspaceRowBadgeItemKey(plugin.id, item.id); + if (groups.has(key)) continue; + groups.set(key, { + key, + pluginId: plugin.id, + itemId: item.id, + title: plugin.i18n.resolve(item.title, plugin.locale), + icon: item.icon, + }); + } + } + return [...groups.values()]; +} diff --git a/packages/app/src/runtime/daemon-start-service.test.ts b/packages/app/src/runtime/daemon-start-service.test.ts index f1cae10118..8f28caa069 100644 --- a/packages/app/src/runtime/daemon-start-service.test.ts +++ b/packages/app/src/runtime/daemon-start-service.test.ts @@ -64,6 +64,99 @@ function makeRelayOnlyHost(serverId: string): HostProfile { } describe("DaemonStartService", () => { + it("reports a daemon that stops during startup without registering an incomplete host", async () => { + const fake = createFakeStore(); + const service = new DaemonStartService({ + store: fake.store, + startDesktopDaemon: async () => + makeStatus({ status: "starting", serverId: "", listen: null }), + getDesktopDaemonStatus: async () => + makeStatus({ status: "stopped", serverId: "", listen: null, pid: null }), + }); + + expect(await service.start()).toEqual({ + ok: false, + error: "The local daemon stopped before startup completed.", + }); + expect(service.isRunning()).toBe(false); + expect(fake.upserts).toEqual([]); + }); + + it("keeps startup pending until a slow daemon becomes ready without restarting it", async () => { + vi.useFakeTimers(); + try { + const fake = createFakeStore(); + const starting = makeStatus({ status: "starting", serverId: "", listen: null }); + const startDesktopDaemon = vi.fn(async () => starting); + const getDesktopDaemonStatus = vi + .fn() + .mockResolvedValueOnce(starting) + .mockResolvedValueOnce(makeStatus()); + const service = new DaemonStartService({ + store: fake.store, + startDesktopDaemon, + getDesktopDaemonStatus, + }); + const result = service.start(); + await vi.advanceTimersByTimeAsync(1000); + expect(service.isRunning()).toBe(true); + expect(service.getLastError()).toBeNull(); + expect(fake.upserts).toEqual([]); + await vi.advanceTimersByTimeAsync(1000); + expect(await result).toEqual({ ok: true }); + expect(startDesktopDaemon).toHaveBeenCalledTimes(1); + expect(fake.upserts).toEqual([ + { listenAddress: "127.0.0.1:6767", serverId: "srv_desktop", hostname: "desktop" }, + ]); + expect(service.isRunning()).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it("shows the daemon error if it exits while startup is pending", async () => { + vi.useFakeTimers(); + try { + const fake = createFakeStore(); + const service = new DaemonStartService({ + store: fake.store, + startDesktopDaemon: async () => makeStatus({ status: "starting", serverId: "" }), + getDesktopDaemonStatus: async () => + makeStatus({ status: "errored", error: "provider startup failed" }), + }); + const result = service.start(); + await vi.advanceTimersByTimeAsync(1000); + expect(await result).toEqual({ ok: false, error: "provider startup failed" }); + expect(fake.upserts).toEqual([]); + expect(service.isRunning()).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it("bounds the readiness wait and leaves a retryable error", async () => { + vi.useFakeTimers(); + try { + const fake = createFakeStore(); + const starting = makeStatus({ status: "starting", serverId: "" }); + const service = new DaemonStartService({ + store: fake.store, + startDesktopDaemon: async () => starting, + getDesktopDaemonStatus: async () => starting, + }); + const result = service.start(); + await vi.advanceTimersByTimeAsync(120000); + expect(await result).toEqual({ + ok: false, + error: "The local daemon is still starting. Wait a moment and retry.", + }); + expect(fake.upserts).toEqual([]); + expect(service.isRunning()).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + it("upserts the connection on a successful daemon start", async () => { const fake = createFakeStore(); const service = new DaemonStartService({ diff --git a/packages/app/src/runtime/daemon-start-service.ts b/packages/app/src/runtime/daemon-start-service.ts index b00e3a380c..1c07ecf8c4 100644 --- a/packages/app/src/runtime/daemon-start-service.ts +++ b/packages/app/src/runtime/daemon-start-service.ts @@ -1,4 +1,8 @@ -import { startDesktopDaemon, type DesktopDaemonStatus } from "@/desktop/daemon/desktop-daemon"; +import { + getDesktopDaemonStatus, + startDesktopDaemon, + type DesktopDaemonStatus, +} from "@/desktop/daemon/desktop-daemon"; import { connectionFromListen } from "@/types/host-connection"; import type { HostRuntimeStore } from "@/runtime/host-runtime"; @@ -14,6 +18,7 @@ type DaemonConnectionStore = Pick Promise; + getDesktopDaemonStatus?: () => Promise; } export async function upsertDesktopDaemonConnection( @@ -48,6 +53,7 @@ export async function upsertDesktopDaemonConnection( export class DaemonStartService { private readonly store: DaemonConnectionStore; private readonly invokeStartDesktopDaemon: () => Promise; + private readonly invokeGetDesktopDaemonStatus: () => Promise; private readonly listeners = new Set<() => void>(); private lastError: string | null = null; private inFlightCount = 0; @@ -55,6 +61,7 @@ export class DaemonStartService { constructor(deps: DaemonStartServiceDeps) { this.store = deps.store; this.invokeStartDesktopDaemon = deps.startDesktopDaemon ?? startDesktopDaemon; + this.invokeGetDesktopDaemonStatus = deps.getDesktopDaemonStatus ?? getDesktopDaemonStatus; } async start(): Promise { @@ -79,7 +86,21 @@ export class DaemonStartService { return { ok: true }; } - const daemon = await this.invokeStartDesktopDaemon(); + let daemon = await this.invokeStartDesktopDaemon(); + // The desktop start command can return after its readiness deadline while + // the owned process keeps initializing. Keep the startup UI pending until + // that process can supply its host identity; do not launch it again. + const readinessDeadline = Date.now() + 120_000; + while (daemon.status === "starting") { + if (Date.now() >= readinessDeadline) { + return this.fail("The local daemon is still starting. Wait a moment and retry."); + } + await new Promise((resolve) => setTimeout(resolve, 1000)); + daemon = await this.invokeGetDesktopDaemonStatus(); + } + if (daemon.status !== "running") { + return this.fail(daemon.error ?? "The local daemon stopped before startup completed."); + } const result = await upsertDesktopDaemonConnection(this.store, daemon); return result.ok ? result : this.fail(result.error); } catch (error) { diff --git a/packages/app/src/runtime/host-runtime.test.ts b/packages/app/src/runtime/host-runtime.test.ts index c802a945c3..69210defb6 100644 --- a/packages/app/src/runtime/host-runtime.test.ts +++ b/packages/app/src/runtime/host-runtime.test.ts @@ -2149,6 +2149,68 @@ describe("HostRuntimeController", () => { }); }); + it("wakes an active routed client before an unrelated direct probe settles", async () => { + useHostRuntimeClock(); + const route: HostConnection = { + id: "via:srv_parent", + type: "routed", + originServerId: "srv_parent", + }; + const host = makeHost({ connections: [route] }); + const client = makeConnectedProbeClient(5); + const directProbeStarted = createDeferred(); + const directProbe = createDeferred(); + let directProbeCalls = 0; + const controller = new HostRuntimeController({ + host, + deps: { + getClientId: async () => "blocked-direct-probe", + createClient: () => new FakeDaemonClient() as unknown as DaemonClient, + connectToDaemon: async ({ connection }) => { + if (connection.type === "directTcp") { + directProbeCalls += 1; + directProbeStarted.resolve(); + await directProbe.promise; + throw new Error("Direct connection unavailable"); + } + return { + client: client as unknown as DaemonClient, + serverId: host.serverId, + hostname: host.label, + }; + }, + }, + }); + await controller.start({ autoProbe: false }); + client.setConnectionState({ + status: "disconnected", + reason: "origin offline", + nextRetryAt: new Date(Date.now() + 12000).toISOString(), + }); + const probing = controller.updateHost({ + ...host, + connections: [ + route, + { id: "direct:unreachable", type: "directTcp", endpoint: "unreachable:6767" }, + ], + }); + await directProbeStarted.promise; + const recovering = controller.reconnectVia("srv_parent"); + try { + expect(client.ensureConnectedCalls).toBe(1); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + expect(directProbeCalls).toBe(1); + await vi.advanceTimersByTimeAsync(0); + expect(client.ensureConnectedCalls).toBe(1); + expect(directProbeCalls).toBe(1); + } finally { + directProbe.resolve(); + await Promise.all([probing, recovering]); + await controller.stop(); + } + expect(directProbeCalls).toBe(1); + }); + it("keeps active client generation stable during background probe cycles", async () => { useHostRuntimeClock(); const host = makeHost({ @@ -2194,7 +2256,200 @@ describe("HostRuntimeController", () => { }); }); +const REGISTRY_KEY = "@paseo:daemon-registry"; +const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" }; +const directA: HostConnection = { + id: "direct:lan-a:6767", + type: "directTcp", + endpoint: "lan-a:6767", +}; +const directB: HostConnection = { + id: "direct:lan-b:6767", + type: "directTcp", + endpoint: "lan-b:6767", +}; +// What a build with a connection kind this one doesn't know leaves behind: an extra connection +// on a host this build can reach, and a host reached only through it. +const storedWithUnreadableEntries = [ + { + ...makeHost({ serverId: "srv_a", password: "secret-a" }), + connections: [futureConnection, directA], + }, + makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }), + { serverId: "srv_future", label: "future host", connections: [futureConnection] }, +]; + +async function bootWithRegistry(registry: string): Promise<{ + store: HostRuntimeStore; + storage: HostRuntimeStorage; +}> { + const storage = createMemoryHostRuntimeStorage({ + [REGISTRY_KEY]: registry, + "@paseo:e2e": "1", + }); + const store = new HostRuntimeStore({ + storage, + deps: { + createClient: () => new FakeDaemonClient() as unknown as DaemonClient, + connectToDaemon: async ({ host }) => ({ + client: makeConnectedProbeClient(5) as unknown as DaemonClient, + serverId: host.serverId, + hostname: host.label ?? null, + }), + getClientId: async () => "cid_test_runtime", + }, + revokePushNotifications: async () => undefined, + }); + await store.boot(); + return { store, storage }; +} + +async function readRegistry(storage: HostRuntimeStorage): Promise { + const raw = await storage.getItem(REGISTRY_KEY); + return raw === null ? null : JSON.parse(raw); +} + describe("HostRuntimeStore", () => { + function gatewayRecoveryFixture() { + const parent = new FakeDaemonClient(); + parent.connectedHosts = true; + parent.hostDirectory = Promise.resolve({ + self: { serverId: "srv_parent", label: "parent" }, + hosts: ["srv_child", "srv_healthy"].map((serverId) => ({ + registrationId: `reg_${serverId}`, + serverId, + label: serverId, + source: { id: "user", key: serverId }, + metadata: {}, + enabled: true, + status: "online" as const, + targetDescription: "relay", + lastOnlineAt: null, + nextRetryAt: null, + error: null, + })), + }); + const parentReady = createDeferred(); + const child = makeConnectedProbeClient(5); + const healthy = makeConnectedProbeClient(5); + const unrelated = makeConnectedProbeClient(5); + const attempts = new Map(); + const hosts = [ + makeHost({ + serverId: "srv_parent", + connections: [ + { + id: "relay:parent", + type: "relay", + relayEndpoint: "relay.paseo.sh:443", + daemonPublicKeyB64: "pk_parent", + }, + ], + }), + ...["srv_child", "srv_healthy"].map((serverId) => + makeHost({ + serverId, + connections: [ + { + id: "via:srv_parent", + type: "routed" as const, + originServerId: "srv_parent", + }, + ], + }), + ), + makeHost({ + serverId: "srv_unrelated", + connections: [ + { + id: "direct:unrelated:6767", + type: "directTcp", + endpoint: "unrelated:6767", + }, + ], + }), + ]; + const store = new HostRuntimeStore({ + storage: createMemoryHostRuntimeStorage({ + "@paseo:e2e": "1", + "@paseo:daemon-registry": JSON.stringify(hosts), + }), + deps: { + getClientId: async () => "gateway-recovery", + createClient: () => new FakeDaemonClient() as unknown as DaemonClient, + connectToDaemon: async ({ host, connection }) => { + attempts.set(host.serverId, (attempts.get(host.serverId) ?? 0) + 1); + let client: FakeDaemonClient; + if (host.serverId === "srv_parent") { + await parentReady.promise; + parent.setConnectionState({ status: "connected" }); + client = parent; + } else if (connection.type === "routed") { + if (!parent.isConnected) throw new Error("Origin host srv_parent is unavailable"); + client = host.serverId === "srv_child" ? child : healthy; + } else { + client = unrelated; + } + return { + client: client as unknown as DaemonClient, + serverId: host.serverId, + hostname: host.label, + }; + }, + }, + }); + return { store, parent, parentReady, child, healthy, unrelated, attempts }; + } + + it("retries saved child routes immediately when their relay gateway first connects", async () => { + useHostRuntimeClock(); + const { store, parentReady, attempts } = gatewayRecoveryFixture(); + try { + await store.boot(); + await vi.advanceTimersByTimeAsync(100); + expect(attempts.get("srv_child")).toBe(1); + expect(store.getSnapshot("srv_child")?.connectionStatus).not.toBe("online"); + parentReady.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(store.getSnapshot("srv_parent")?.connectionStatus).toBe("online"); + expect(store.getSnapshot("srv_child")?.connectionStatus).toBe("online"); + expect(store.getSnapshot("srv_healthy")?.connectionStatus).toBe("online"); + expect(attempts.get("srv_child")).toBe(2); + expect(attempts.get("srv_healthy")).toBe(2); + expect(attempts.get("srv_unrelated")).toBe(1); + } finally { + store.syncHosts([]); + } + }); + + it("wakes disconnected routed clients on gateway recovery without disturbing healthy hosts", async () => { + useHostRuntimeClock(); + const { store, parent, parentReady, child, healthy, unrelated } = gatewayRecoveryFixture(); + try { + parentReady.resolve(); + await store.boot(); + await vi.advanceTimersByTimeAsync(2000); + expect(store.getSnapshot("srv_child")?.connectionStatus).toBe("online"); + parent.setConnectionState({ status: "disconnected", reason: "relay lost" }); + child.setConnectionState({ + status: "disconnected", + reason: "origin offline", + nextRetryAt: new Date(Date.now() + 12000).toISOString(), + }); + parent.setConnectionState({ status: "connected" }); + await vi.advanceTimersByTimeAsync(0); + expect(child.ensureConnectedCalls).toBe(1); + expect(store.getSnapshot("srv_child")?.connectionStatus).toBe("online"); + expect(healthy.ensureConnectedCalls).toBe(0); + expect(unrelated.ensureConnectedCalls).toBe(0); + parent.setConnectionState({ status: "connected" }); + await vi.advanceTimersByTimeAsync(0); + expect(child.ensureConnectedCalls).toBe(1); + } finally { + store.syncHosts([]); + } + }); + it.each([false, true])( "keeps B and C distinct with routed and direct candidates (B direct first: %s)", async (directFirst) => { @@ -2484,6 +2739,144 @@ describe("HostRuntimeStore", () => { session.clearSession(host.serverId); }); + it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => { + const host = makeHost({ + connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }], + }); + const fakeClient = new FakeDaemonClient(); + fakeClient.setConnectionState({ status: "connected" }); + const store = new HostRuntimeStore({ + storage: createMemoryHostRuntimeStorage({ + [REGISTRY_KEY]: JSON.stringify([host]), + "@paseo:e2e": "1", + }), + deps: { + createClient: () => fakeClient as unknown as DaemonClient, + connectToDaemon: async ({ host: hostProfile }) => ({ + client: fakeClient as unknown as DaemonClient, + serverId: hostProfile.serverId, + hostname: hostProfile.label ?? null, + }), + getClientId: async () => "cid_test_runtime", + }, + }); + + // A component renders on every tick while the registry loads, and acquires directory + // demand for each host it reads, as the sidebar does on its first render. + const registry = { loading: true }; + const boot = store.boot().finally(() => { + registry.loading = false; + }); + let releaseDemand: (() => void) | null = null; + while (registry.loading && !releaseDemand) { + if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) { + releaseDemand = store.acquireDirectoryDemand(host.serverId); + } + await Promise.resolve(); + } + await boot; + expect(releaseDemand).not.toBeNull(); + + await waitForHostOnline(store, host.serverId); + await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1)); + + releaseDemand?.(); + store.syncHosts([]); + useSessionStore.getState().clearSession(host.serverId); + }); + + it("keeps readable hosts when the registry holds entries this build can't read", async () => { + const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries)); + + expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([ + ["srv_a", "secret-a"], + ["srv_b", "secret-b"], + ]); + expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([ + directA.id, + ]); + expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries); + + store.syncHosts([]); + }); + + it("keeps the entries it can't read when it saves the registry", async () => { + const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries)); + + await store.renameHost("srv_b", "renamed"); + + expect(await readRegistry(storage)).toMatchObject([ + { + serverId: "srv_a", + password: "secret-a", + connections: [{ id: directA.id }, futureConnection], + }, + { serverId: "srv_b", password: "secret-b", label: "renamed" }, + storedWithUnreadableEntries[2], + ]); + + store.syncHosts([]); + }); + + it("moves a stored connection password to its host and keeps the connection it can't read", async () => { + const { store, storage } = await bootWithRegistry( + JSON.stringify([ + { + serverId: "srv_legacy", + connections: [ + { type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" }, + futureConnection, + ], + }, + ]), + ); + + expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([ + ["srv_legacy", "old-secret"], + ]); + await vi.waitFor(async () => + expect(await readRegistry(storage)).toMatchObject([ + { serverId: "srv_legacy", password: "old-secret" }, + ]), + ); + expect(await readRegistry(storage)).toMatchObject([ + { connections: [{ ...directA, useTls: false }, futureConnection] }, + ]); + const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>; + expect(written?.connections[0]).not.toHaveProperty("password"); + + store.syncHosts([]); + }); + + it("forgets an entry it can't read once that host is paired again and removed", async () => { + const { store, storage } = await bootWithRegistry( + JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]), + ); + expect(store.getHosts()).toEqual([]); + + await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint }); + await vi.waitFor(async () => + expect(await readRegistry(storage)).toMatchObject([ + { serverId: "srv_future", connections: [{ id: directA.id }] }, + ]), + ); + + await store.removeHost("srv_future"); + expect(await readRegistry(storage)).toEqual([]); + + store.syncHosts([]); + }); + + it("copies a registry that isn't JSON aside instead of deleting it", async () => { + const { store, storage } = await bootWithRegistry("{not json"); + + expect(store.getHosts()).toEqual([]); + expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json"); + expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json"); + + store.syncHosts([]); + }); + it("marks the host registry loaded after boot reads storage", async () => { const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON; process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint"; @@ -2516,7 +2909,8 @@ describe("HostRuntimeStore", () => { await registryLoaded; expect(store.isHostRegistryLoaded()).toBe(true); - expect(hostListNotifications).toBe(2); + // Publishing the restored hosts, the registry turning ready, and the registry loading. + expect(hostListNotifications).toBe(3); } finally { if (previousOverride === undefined) { delete process.env.EXPO_PUBLIC_LOCAL_DAEMON; diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index 15a86b7bb4..4cdee90385 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -17,14 +17,16 @@ import { import { connectionFromListen, createRemoteSshHostConnection, - normalizeStoredHostProfile, + forgetUnreadableHost, pinRelayProtectedSecurityInProfiles, + readHostRegistry, upsertHostConnectionInProfiles, registryHasConnection, relayConnectionFromOffer, - StoredHostRegistrySchema, + writeHostRegistry, type HostConnection, type HostProfile, + type UnreadableHostEntries, } from "@/types/host-connection"; import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance"; import { @@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform"; import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection"; import { getOrCreateClientId } from "@/utils/client-id"; import { z } from "zod"; -import { readValidatedJson, readValidatedString } from "@/storage/validated-storage"; +import { readValidatedString } from "@/storage/validated-storage"; import { selectBestConnection, type ConnectionCandidate, @@ -869,6 +871,22 @@ export class HostRuntimeController { this.activeClient?.ensureConnected(options); } + async reconnectVia(originServerId: string): Promise { + const routes = this.host.connections.filter( + (connection) => + connection.type === "routed" && + connection.originServerId === originServerId && + !this.authRejectedConnectionIds.has(connection.id), + ); + if (routes.length === 0 || !this.started || isHostRuntimeConnected(this.snapshot)) return; + if (routes.some((route) => route.id === this.snapshot.activeConnectionId)) + this.ensureConnected(); + await this.probeCycleInFlight; + if (!this.started || this.snapshot.connectionStatus === "online") return; + for (const route of routes) this.connectionLastProbedAt.delete(route.id); + await this.runProbeCycleNow(); + } + markAgentDirectorySyncLoading(): void { const status = this.snapshot.hasEverLoadedAgentDirectory ? "revalidating" : "initial_loading"; this.updateSnapshot({ @@ -1676,6 +1694,7 @@ export class HostRuntimeStore { private hostListVersion = 0; private hostRegistryLoaded = false; private hosts: HostProfile[] = []; + private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() }; private hostAppearanceMutationTail: Promise = Promise.resolve(); private hostRegistryStatus: HostRegistryStatus = "loading"; private deps: HostRuntimeControllerDeps; @@ -1783,40 +1802,23 @@ export class HostRuntimeStore { let shouldPersistHosts = false; let profiles: HostProfile[] = []; try { - const stored = await readValidatedJson( - this.storage, - REGISTRY_STORAGE_KEY, - StoredHostRegistrySchema, - ); + const stored = await this.readStoredRegistry(); if (stored) { - const normalizedProfiles: HostProfile[] = []; - for (const entry of stored) { - const profile = normalizeStoredHostProfile(entry); - if (!profile) { - await this.storage.removeItem(REGISTRY_STORAGE_KEY); - normalizedProfiles.length = 0; - break; - } - // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration. - if ( - entry.connections.some( - (connection) => connection.type === "directTcp" && connection.password, - ) - ) { - shouldPersistHosts = true; - } - normalizedProfiles.push(profile); + // An entry this build can't read skips only that host or connection, and stays stored. + const registry = readHostRegistry(stored); + this.unreadableHosts = registry.unreadable; + // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration. + if (registry.movedConnectionPassword) { + shouldPersistHosts = true; } - profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId)); - if (profiles.length !== normalizedProfiles.length) { + profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId)); + if (profiles.length !== registry.hosts.length) { shouldPersistHosts = true; } } - this.hosts = profiles; - this.replicaCache.setHosts(profiles.map((profile) => profile.serverId)); projectIconCache.setHosts(profiles.map((profile) => profile.serverId)); await projectIconCache.restore(); - this.syncHosts(profiles); + this.setHostsAndSync(profiles); for (const profile of profiles) { void this.directorySyncByServer .get(profile.serverId) @@ -2304,6 +2306,7 @@ export class HostRuntimeStore { async removeHost(serverId: string): Promise { await this.revokePushNotifications({ client: this.getClient(serverId), serverId }); const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId); + this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId); this.setHostsAndSync(remaining); await this.persistHosts(); } @@ -2392,7 +2395,27 @@ export class HostRuntimeStore { } private async persistHosts(hosts = this.hosts): Promise { - await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts)); + await this.storage.setItem( + REGISTRY_STORAGE_KEY, + JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)), + ); + } + + /** + * Reads the stored registry without removing it. A value that isn't a JSON array is copied to + * `:unreadable` first, because the next save overwrites the key. + */ + private async readStoredRegistry(): Promise { + const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY); + if (raw === null) return null; + try { + const value: unknown = JSON.parse(raw); + if (Array.isArray(value)) return value; + } catch { + // Not JSON: copied aside below. + } + await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw); + return null; } private emitHostList(): void { @@ -2601,6 +2624,7 @@ export class HostRuntimeStore { snapshot.connectionStatus === "online" && previousStatus !== "online"; if (didTransitionOnline) { useSessionStore.getState().bumpHistorySyncGeneration(serverId); + for (const child of this.controllers.values()) void child.reconnectVia(serverId); // Checkout git data is push-driven; pushes emitted while disconnected are gone for // good (the daemon dedupes by snapshot fingerprint). Mark the caches stale so active // queries refetch now and evicted ones on their next mount. diff --git a/packages/app/src/runtime/replica-cache/index.test.ts b/packages/app/src/runtime/replica-cache/index.test.ts index a55bf51e04..f0187e8319 100644 --- a/packages/app/src/runtime/replica-cache/index.test.ts +++ b/packages/app/src/runtime/replica-cache/index.test.ts @@ -354,6 +354,21 @@ describe("ReplicaCache", () => { ); }); + it("preserves where the workspace's forge is on the web across cache reopen", async () => { + const storage = new MemoryStorage(); + const writer = createCache(storage); + const baseline = directory({ workspaces: { generation: "g", afterSeq: 8 } }); + const forgeWeb = { host: "github.com", referenceRepository: "main-owner/repo" }; + const workspace = normalizeWorkspaceDescriptor({ ...workspacePayload(), forgeWeb }); + baseline.workspaces.set(workspace.id, workspace); + commitDirectory(writer, SERVER_ID, baseline); + await writer.flush(); + + const restored = await createCache(storage).readDirectory(SERVER_ID); + + expect(restored.workspaces.get(workspace.id)?.forgeWeb).toEqual(forgeWeb); + }); + it("preserves workspace sorting timestamps across cache reopen", async () => { const storage = new MemoryStorage(); const writer = createCache(storage); diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index e9304513b9..efe2e10639 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { AgentStatusSchema, AgentTimelineItemPayloadSchema, + ForgeWebSchema, WorkspaceGitHubRuntimePayloadSchema, } from "@getpaseo/protocol/messages"; import { AgentProviderSchema } from "@getpaseo/protocol/provider-manifest"; @@ -335,6 +336,7 @@ const StoredWorkspaceSchema = z.strictObject({ gitRuntime: WorkspaceGitRuntimeSchema, githubRuntime: WorkspaceGitHubRuntimePayloadSchema, forge: z.string().optional(), + forgeWeb: ForgeWebSchema.optional(), }); const StoredProjectSchema = z.strictObject({ @@ -768,6 +770,7 @@ function serializeWorkspace(workspace: WorkspaceDescriptor): StoredWorkspace { gitRuntime: workspace.gitRuntime, githubRuntime: workspace.githubRuntime, forge: workspace.forge, + forgeWeb: workspace.forgeWeb, }; } diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index bab4df8f01..96d076224d 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -1,12 +1,9 @@ import { useAddHost } from "@/hosts/add-host"; -import type { - CreateAgentRequestOptions, - CreateWorkspaceRequestOptions, -} from "@getpaseo/client/internal/daemon-client"; +import type { CreateWorkspaceRequestOptions } from "@getpaseo/client/internal/daemon-client"; import type { AgentSnapshotPayload, CreationSnapshot } from "@getpaseo/protocol/messages"; import { encodeImages } from "@/utils/encode-images"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { ReactNode } from "react"; import { useIsFocused } from "expo-router/react-navigation"; import { useTranslation } from "react-i18next"; @@ -124,9 +121,11 @@ import { type ListTerminalsPayload, upsertCreatedTerminalPayload, } from "./workspace/terminals/state"; -import { captureWorkspaceDraftCleanup } from "./new-workspace/background-handoff"; +import { + captureWorkspaceDraftCleanup, + handOffDraftMetadata, +} from "./new-workspace/background-handoff"; import { useNewWorkspaceScreenPresence } from "./new-workspace/screen-presence"; -import { retriedAgentRequest } from "./new-workspace/retry-agent-request"; function useIsNewWorkspaceDraftHandoffActive(input: { draftId: string | undefined; @@ -189,7 +188,10 @@ function noopChangeAttachments() {} function noopClearDraft() {} // Stable reference so the keyboard-action handler doesn't re-register each render. -const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = ["workspace.project.pick"]; +const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [ + "workspace.project.pick", + "workspace.new", +]; interface WorkspaceIsolationState { isolation: "local" | "worktree"; @@ -243,7 +245,6 @@ interface SubmitDraftInput { clearConsumedDraft: () => void; agentCreation?: { result: Promise; - retry: (input: CreateAgentRequestOptions) => Promise; }; serverId: string; draftKey: string; @@ -471,13 +472,13 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise => { + const execute = async (): Promise => { const { agent } = await ensureWorkspace({ cwd, prompt: text, attachments: workspaceNamingAttachments, withInitialAgent: true, - agent: requestedAgent, + agent: initialAgent, onEvent: (snapshot) => { if (!snapshot.workspace || navigated) return; navigated = true; @@ -516,11 +517,8 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise execute()), - retry: (request: CreateAgentRequestOptions) => - execute(retriedAgentRequest(initialAgent, request, cwd)), - }; + // A retry after a failed agent start belongs to the ready workspace's draft, not to this creation. + const agentCreation = { result: Promise.resolve().then(() => execute()) }; await agentCreation.result; if (outcome === "background") clearConsumedDraft(); return outcome; @@ -643,6 +641,7 @@ function submitWorkspaceDraft(input: SubmitDraftInput): SubmitOutcome { allowEmptyText: true, agentCreation: input.agentCreation, }); + handOffDraftMetadata({ serverId, draftId, metadata: composerState.metadata }); clearDraft("sent"); navigateToWorkspace({ serverId, @@ -911,6 +910,7 @@ export function NewWorkspaceScreen({ const isDraftHandoffActive = useIsNewWorkspaceDraftHandoffActive({ draftId, selectedServerId }); const isStillOnCreateScreen = useNewWorkspaceScreenPresence(); const isScreenFocused = useIsFocused(); + const projectPickHandlerId = useId(); // Launch target: what the composer submits to (chat agent, or a terminal // profile). Mirrors useWorkspaceIsolation's pattern below: the derived @@ -1185,19 +1185,18 @@ export function NewWorkspaceScreen({ setProjectPickerOpen(true); }, []); - // Cmd/Ctrl+P opens the project picker with its search focused so the user can - // switch projects from the keyboard. Registered only while this screen is - // mounted, so the shortcut doesn't swallow the browser's native print - // elsewhere; gated on having projects to pick. + // On this screen, both project-pick and new-workspace open the chooser. + // Take precedence over global new-workspace navigation to preserve the draft. const handleProjectPick = useCallback(() => { openProjectPicker(); return true; }, [openProjectPicker]); useKeyboardActionHandler({ - handlerId: "new-workspace-project-pick", + handlerId: `new-workspace-project-pick:${projectPickHandlerId}`, actions: PROJECT_PICK_ACTIONS, - enabled: projectPickerOptions.length > 0, - priority: 0, + enabled: isScreenFocused, + isActive: isStillOnCreateScreen, + priority: 10, handle: handleProjectPick, }); diff --git a/packages/app/src/screens/new-workspace/background-handoff.ts b/packages/app/src/screens/new-workspace/background-handoff.ts index 598772f1a1..68a64b987a 100644 --- a/packages/app/src/screens/new-workspace/background-handoff.ts +++ b/packages/app/src/screens/new-workspace/background-handoff.ts @@ -1,7 +1,29 @@ import { useWorkspaceAttachmentsStore } from "@/attachments/workspace-attachments-store"; +import { buildDraftStoreKey } from "@/stores/draft-keys"; import { useDraftStore } from "@/stores/draft-store"; +import type { JsonValue } from "@getpaseo/protocol/agent-types"; import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store"; +/** + * The ready workspace's draft tab owns the draft once New workspace hands it off, including a + * retry after the first agent start fails. Its metadata moves with it, like its text and setup. + */ +export function handOffDraftMetadata(input: { + serverId: string; + draftId: string; + metadata: Readonly>; +}): void { + if (Object.keys(input.metadata).length === 0) return; + useDraftStore.getState().patchDraftMetadata({ + draftKey: buildDraftStoreKey({ + serverId: input.serverId, + agentId: input.draftId, + draftId: input.draftId, + }), + patch: { ...input.metadata }, + }); +} + interface WorkspaceDraftCleanupInput { draftId?: string; draftKey: string; diff --git a/packages/app/src/screens/new-workspace/form/field-trigger.tsx b/packages/app/src/screens/new-workspace/form/field-trigger.tsx index 8c0be791dc..e4ed92d8ea 100644 --- a/packages/app/src/screens/new-workspace/form/field-trigger.tsx +++ b/packages/app/src/screens/new-workspace/form/field-trigger.tsx @@ -5,6 +5,8 @@ import { ChevronDown } from "lucide-react-native"; import { ComboboxTrigger } from "@/components/ui/combobox-trigger"; import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { Shortcut } from "@/components/ui/shortcut"; +import { useShortcutKeys } from "@/hooks/use-shortcut-keys"; import { ICON_SIZE, type Theme } from "@/styles/theme"; /** @@ -97,15 +99,17 @@ export interface FieldTriggerProps extends FieldTriggerContentProps { disabled?: boolean; /** Desktop hover hint; badges only, since a field shows its label. */ tooltip?: string; + shortcutAction?: string; testID?: string; } /** A field trigger that anchors a Combobox. */ export const FieldTrigger = forwardRef(function FieldTrigger( - { accessibilityLabel, onPress, disabled = false, tooltip, testID, ...content }, + { accessibilityLabel, onPress, disabled = false, tooltip, shortcutAction, testID, ...content }, ref, ): ReactElement { const style = useFieldTriggerStyle(content.variant, disabled); + const shortcutKeys = useShortcutKeys(shortcutAction ?? null); const trigger = ( (function FieldTr {trigger} - {tooltip} + + {tooltip} + {shortcutKeys ? : null} + ); @@ -210,6 +217,11 @@ const styles = StyleSheet.create((theme) => ({ detail: { color: theme.colors.foregroundExtraMuted, }, + tooltipRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, tooltipText: { fontSize: theme.fontSize.base, color: theme.colors.popoverForeground, diff --git a/packages/app/src/screens/new-workspace/form/index.tsx b/packages/app/src/screens/new-workspace/form/index.tsx index 3b2040d389..da9368a6a7 100644 --- a/packages/app/src/screens/new-workspace/form/index.tsx +++ b/packages/app/src/screens/new-workspace/form/index.tsx @@ -209,6 +209,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement label={t("newWorkspace.fields.project")} accessibilityLabel="Workspace project" tooltip={t("newWorkspace.tooltips.project")} + shortcutAction="new-workspace" icon={projectIcon} value={project.triggerLabel} onPress={project.open} diff --git a/packages/app/src/screens/new-workspace/retry-agent-request.test.ts b/packages/app/src/screens/new-workspace/retry-agent-request.test.ts deleted file mode 100644 index 248a044a3c..0000000000 --- a/packages/app/src/screens/new-workspace/retry-agent-request.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { retriedAgentRequest, type WorkspaceAgentRequest } from "./retry-agent-request"; - -const initial: WorkspaceAgentRequest = { - config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, - metadata: { "issues.key": "PAS-1" }, - initialPrompt: "first try", - clientMessageId: "draft_1:initial-message", -}; - -describe("retriedAgentRequest", () => { - it("creates with the metadata the draft resubmitted", () => { - const retried = retriedAgentRequest( - initial, - { - config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, - initialPrompt: "second try", - metadata: { "issues.key": "PAS-2" }, - }, - "/repo", - ); - expect(retried.metadata).toEqual({ "issues.key": "PAS-2" }); - expect(retried.initialPrompt).toBe("second try"); - expect(retried.clientMessageId).toBe("draft_1:initial-message"); - }); - - it("creates with no metadata once the draft cleared it", () => { - const retried = retriedAgentRequest( - initial, - { config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, initialPrompt: "second try" }, - "/repo", - ); - expect("metadata" in retried).toBe(false); - }); - - it("keeps the first attempt's directory over the resubmitted config", () => { - const retried = retriedAgentRequest( - initial, - { - config: { provider: "codex", cwd: "/elsewhere", model: "gpt-6-mini" }, - initialPrompt: "second try", - }, - "/repo", - ); - expect(retried.config).toEqual({ provider: "codex", cwd: "/repo", model: "gpt-6-mini" }); - }); -}); diff --git a/packages/app/src/screens/new-workspace/retry-agent-request.ts b/packages/app/src/screens/new-workspace/retry-agent-request.ts deleted file mode 100644 index 4a7efa02cf..0000000000 --- a/packages/app/src/screens/new-workspace/retry-agent-request.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { - CreateAgentRequestOptions, - CreateWorkspaceRequestOptions, -} from "@getpaseo/client/internal/daemon-client"; - -export type WorkspaceAgentRequest = NonNullable; - -/** - * The agent a retried creation asks for: everything the draft resubmitted (config, prompt, - * images, attachments and metadata, cleared included) on the first attempt's identity, so a - * retry creates what the composer shows now, not what it showed when creation first failed. - */ -export function retriedAgentRequest( - initial: WorkspaceAgentRequest, - request: CreateAgentRequestOptions, - cwd: string, -): WorkspaceAgentRequest { - const { metadata: _replaced, ...identity } = initial; - return { - ...identity, - config: { ...request.config!, cwd }, - initialPrompt: request.initialPrompt ?? "", - clientMessageId: initial.clientMessageId, - images: request.images, - attachments: request.attachments, - ...(request.metadata ? { metadata: request.metadata } : {}), - }; -} diff --git a/packages/app/src/screens/open-project-screen.tsx b/packages/app/src/screens/open-project-screen.tsx index 4fcbb4d2fc..0f55a9eeb3 100644 --- a/packages/app/src/screens/open-project-screen.tsx +++ b/packages/app/src/screens/open-project-screen.tsx @@ -21,8 +21,7 @@ import { import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; import { PairDeviceModal } from "@/desktop/components/pair-device-modal"; import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; - -const WINDOW_CONTENT_DATASET = { "window-content": "" }; +import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region"; export function OpenProjectScreen() { const { t } = useTranslation(); diff --git a/packages/app/src/screens/projects-screen.test.tsx b/packages/app/src/screens/projects-screen.test.tsx index a91043a709..4a2faf1af9 100644 --- a/packages/app/src/screens/projects-screen.test.tsx +++ b/packages/app/src/screens/projects-screen.test.tsx @@ -182,6 +182,7 @@ function workspaceSummary(overrides: Partial = {}): WorkspaceS status: "done", currentBranch: "main", changeRequestNumber: null, + background: false, statusEnteredAt: null, ...overrides, }; diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 9c8b230e4c..7fc6dbe248 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -1,15 +1,10 @@ +import { useSettingsContentPresented } from "@/navigation/settings-presentation"; +import { AppearanceText as Text } from "@/appearance/text"; import { useHardwareKeyboardPresent } from "@/keyboard"; import { useAddHost } from "@/hosts/add-host"; import { useCallback, useMemo, useRef, useState } from "react"; import type { ComponentType, ReactNode } from "react"; -import { - Alert, - Pressable, - ScrollView, - Text, - View, - type PressableStateCallbackType, -} from "react-native"; +import { Alert, Pressable, ScrollView, View, type PressableStateCallbackType } from "react-native"; import { useRouter } from "expo-router"; import { useFocusEffect } from "expo-router/react-navigation"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -113,9 +108,12 @@ import { HostWorkspacesPage, HostTerminalsPage, } from "@/screens/settings/host-page"; -import { PluginSettingsContent } from "@/plugins/settings"; -import { usePluginDisplayName } from "@/plugins/plugin-list"; -import { HostPluginsPage } from "@/screens/settings/plugins-page"; +import { + PluginGalleryMenu, + PluginGalleryPage, + PluginPage, + type PluginPageSubject, +} from "@/plugins/gallery"; import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-page"; import { HostVoicePage } from "@/screens/settings/voice/voice-page"; import ProjectsScreen from "@/screens/projects-screen"; @@ -285,7 +283,7 @@ function renderHostSettingsContent( case "terminals": return ; case "plugins": - return ; + return ; case "host": return ; } @@ -992,7 +990,7 @@ function SettingsSidebar({ let selectedHostSection: HostSectionSlug | null = null; if (view.kind === "host") selectedHostSection = view.section; if (view.kind === "project") selectedHostSection = "projects"; - if (view.kind === "plugin") selectedHostSection = "plugins"; + if (view.kind === "plugin" || view.kind === "pluginListing") selectedHostSection = "plugins"; const sidebarBody = ( <> @@ -1124,6 +1122,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { const appVersion = resolveAppVersion(); const appVersionText = formatVersionWithPrefix(appVersion); const isCompactLayout = useIsCompactFormFactor(); + const onContentLayout = useSettingsContentPresented(); const insets = useSafeAreaInsets(); const insetBottomStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]); const hosts = useHosts(); @@ -1134,7 +1133,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // The host the four sections scope to: the host on the active view, otherwise // the picker choice, otherwise the connected local daemon, otherwise the first host. const activeHostServerId = useMemo(() => { - if (view.kind === "host" || view.kind === "project" || view.kind === "plugin") + if ( + view.kind === "host" || + view.kind === "project" || + view.kind === "plugin" || + view.kind === "pluginListing" + ) return view.serverId; return resolveActiveHostServerId({ selectedServerId: selectedSettingsHostServerId, @@ -1267,10 +1271,20 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { returnFromSettings({ kind: "root" }); }, []); - // The header names the plugin; its tabs name the open settings screen. - const pluginDisplayName = usePluginDisplayName(view.kind === "plugin" ? view : null); + // A plugin's page draws its own header; the compact back header names the plugin. + const pluginPage = useMemo((): { serverId: string; subject: PluginPageSubject } | null => { + if (view.kind === "plugin") + return { + serverId: view.serverId, + subject: { kind: "installed", pluginId: view.pluginId, screenId: view.screenId }, + }; + if (view.kind === "pluginListing") + return { serverId: view.serverId, subject: { kind: "listing", listingId: view.listingId } }; + return null; + }, [view]); const detailTitle = ((): string | undefined => { - if (view.kind === "plugin") return pluginDisplayName; + // The plugin page heads itself with the plugin's name and icon. + if (pluginPage) return undefined; if (view.kind === "host") { const item = HOST_SECTION_ITEMS.find((s) => s.id === view.section); return item ? t(item.labelKey) : undefined; @@ -1285,15 +1299,23 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { return undefined; })(); + const pluginGalleryServerId = + view.kind === "host" && view.section === "plugins" ? view.serverId : null; + const detailActions = useMemo( + () => + pluginGalleryServerId ? : undefined, + [pluginGalleryServerId], + ); + // The gallery and a plugin's page share one width, so opening a plugin keeps the page edges put. + const detailWidth = pluginGalleryServerId || pluginPage ? "wide" : "default"; + const content: ReactNode = (() => { - if (view.kind === "plugin") + if (pluginPage) return ( - ); if (view.kind === "host") { @@ -1347,7 +1369,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { if (settingsLoading) { return ( - + {t("settings.loading")} ); @@ -1356,7 +1378,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // Mobile root: full-screen sidebar-as-list. if (isCompactLayout && view.kind === "root") { return ( - + - + + {content} @@ -1388,7 +1415,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // region + traffic-light padding; detail pane renders whatever header the // selected section provides. return ( - + diff --git a/packages/app/src/screens/settings/appearance/appearance-preview.tsx b/packages/app/src/screens/settings/appearance/appearance-preview.tsx index 01699b6cb0..feb571c62f 100644 --- a/packages/app/src/screens/settings/appearance/appearance-preview.tsx +++ b/packages/app/src/screens/settings/appearance/appearance-preview.tsx @@ -1,6 +1,7 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Text, View, type TextStyle } from "react-native"; +import { View, type TextStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import type { HighlightToken } from "@getpaseo/highlight"; import { isWeb } from "@/constants/platform"; diff --git a/packages/app/src/screens/settings/appearance/appearance-section.tsx b/packages/app/src/screens/settings/appearance/appearance-section.tsx index f42475dc48..9ff6adccad 100644 --- a/packages/app/src/screens/settings/appearance/appearance-section.tsx +++ b/packages/app/src/screens/settings/appearance/appearance-section.tsx @@ -1,8 +1,9 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { TFunction } from "i18next"; import { useTranslation } from "react-i18next"; -import { Text, View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; +import { View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { SYNTAX_THEME_OPTIONS, type SyntaxThemeId, @@ -13,10 +14,7 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; import { SettingsSection } from "@/components/settings/headings/settings-section"; import { ThemePicker } from "@/appearance/theme-picker"; import { Button } from "@/components/ui/button"; -import { - EditingTextInput as TextInput, - type EditingTextInputHandle, -} from "@/components/ui/text-input"; +import { EditingTextInput, type EditingTextInputHandle } from "@/components/ui/text-input"; import { MAX_CODE_FONT_SIZE, MAX_CONTENT_FONT_SIZE, @@ -36,6 +34,12 @@ import { isNative } from "@/constants/platform"; import { settingsStyles } from "@/styles/settings"; import { AppearancePreview } from "./appearance-preview"; +// Subscribe the input leaf to numeric theme changes without resetting its editing state. +const TextInput = withUnistyles(EditingTextInput, (theme) => { + void theme.fontSize; + return {}; +}); + // Platform default stacks can be the bare native tokens ("normal"/"monospace"); // those read as a bug, so show a human label in the placeholder instead. const BARE_DEFAULT_STACKS: ReadonlySet = new Set(["normal", "monospace"]); @@ -124,7 +128,7 @@ interface FontSizeRowProps { draft: string; withBorder?: boolean; onChangeDraft: (value: string) => void; - onCommit: () => void; + onCommit: () => string; } function FontSizeRow({ @@ -136,6 +140,12 @@ function FontSizeRow({ onChangeDraft, onCommit, }: FontSizeRowProps) { + const inputRef = useRef(null); + const handleCommit = useCallback(() => { + const committed = onCommit(); + inputRef.current?.replaceText(committed); + }, [onCommit]); + return ( @@ -144,10 +154,11 @@ function FontSizeRow({ { @@ -402,6 +414,7 @@ export function AppearanceSection() { if (next !== settings.codeFontSize) { void updateSettings({ codeFontSize: next }); } + return String(next); }, [codeSizeDraft, settings.codeFontSize, updateSettings]); const commitContentSize = useCallback(() => { @@ -414,6 +427,7 @@ export function AppearanceSection() { if (next !== settings.contentFontSize) { void updateSettings({ contentFontSize: next }); } + return String(next); }, [contentSizeDraft, settings.contentFontSize, updateSettings]); // Live-while-typing: the in-progress drafts drive the preview without diff --git a/packages/app/src/screens/settings/host-appearance-section.tsx b/packages/app/src/screens/settings/host-appearance-section.tsx index 585be1cfda..d5462f9cb9 100644 --- a/packages/app/src/screens/settings/host-appearance-section.tsx +++ b/packages/app/src/screens/settings/host-appearance-section.tsx @@ -230,6 +230,7 @@ function BadgePreview({ {t("settings.host.appearance.preview.workspaceName")} { - it("keeps the edited source in the submission until explicitly reset", () => { - const model = openPluginInstallForm(); - - model.setSource("owner/review"); - - expect(model.getSubmission()).toEqual({ source: "owner/review" }); - - model.reset(); - expect(model.getState()).toEqual({ - source: "", - canSubmit: false, - resetKey: 1, - }); - }); - - it("trims the submitted source", () => { - const model = openPluginInstallForm(); - model.setSource(" /plugins/review "); - expect(model.getSubmission()).toEqual({ source: "/plugins/review" }); - }); -}); diff --git a/packages/app/src/screens/settings/plugin-install-form-model.ts b/packages/app/src/screens/settings/plugin-install-form-model.ts deleted file mode 100644 index 82fbfa12e2..0000000000 --- a/packages/app/src/screens/settings/plugin-install-form-model.ts +++ /dev/null @@ -1,53 +0,0 @@ -export interface PluginInstallFormState { - source: string; - canSubmit: boolean; - resetKey: number; -} - -export interface PluginInstallSubmission { - source: string; -} - -export interface PluginInstallFormModel { - getState(): PluginInstallFormState; - subscribe(listener: () => void): () => void; - close(): void; - setSource(value: string): void; - getSubmission(): PluginInstallSubmission; - reset(): void; -} - -export function openPluginInstallForm(): PluginInstallFormModel { - const listeners = new Set<() => void>(); - let state: PluginInstallFormState = { - source: "", - canSubmit: false, - resetKey: 0, - }; - - const publish = (next: Pick) => { - state = { ...next, canSubmit: next.source.trim().length > 0 }; - for (const listener of listeners) listener(); - }; - - return { - getState: () => state, - subscribe(listener) { - listeners.add(listener); - return () => listeners.delete(listener); - }, - close() { - listeners.clear(); - }, - setSource(source) { - publish({ ...state, source }); - }, - getSubmission() { - const source = state.source.trim(); - return { source }; - }, - reset() { - publish({ source: "", resetKey: state.resetKey + 1 }); - }, - }; -} diff --git a/packages/app/src/screens/settings/plugins-page-state.test.ts b/packages/app/src/screens/settings/plugins-page-state.test.ts deleted file mode 100644 index 192436029f..0000000000 --- a/packages/app/src/screens/settings/plugins-page-state.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { resolvePluginPageState } from "./plugins-page-state"; - -describe("resolvePluginPageState", () => { - it.each([ - ["offline", false, false, false, false, 0], - ["unsupported", true, false, false, false, 0], - ["loading", true, true, true, false, 0], - ["error", true, true, false, true, 0], - ["empty", true, true, false, false, 0], - ["ready", true, true, false, false, 1], - ] as const)("resolves %s", (expected, connected, supported, loading, error, pluginCount) => { - expect(resolvePluginPageState({ connected, supported, loading, error, pluginCount })).toBe( - expected, - ); - }); -}); diff --git a/packages/app/src/screens/settings/plugins-page-state.ts b/packages/app/src/screens/settings/plugins-page-state.ts deleted file mode 100644 index 0623dca047..0000000000 --- a/packages/app/src/screens/settings/plugins-page-state.ts +++ /dev/null @@ -1,15 +0,0 @@ -export type PluginPageState = "offline" | "unsupported" | "loading" | "error" | "empty" | "ready"; - -export function resolvePluginPageState(input: { - connected: boolean; - supported: boolean; - loading: boolean; - error: boolean; - pluginCount: number; -}): PluginPageState { - if (!input.connected) return "offline"; - if (!input.supported) return "unsupported"; - if (input.loading) return "loading"; - if (input.error) return "error"; - return input.pluginCount === 0 ? "empty" : "ready"; -} diff --git a/packages/app/src/screens/settings/plugins-page.test.tsx b/packages/app/src/screens/settings/plugins-page.test.tsx deleted file mode 100644 index dfb16ccfa7..0000000000 --- a/packages/app/src/screens/settings/plugins-page.test.tsx +++ /dev/null @@ -1,257 +0,0 @@ -import { subscriptionFixture } from "@/runtime/subscription-fixture"; -/** - * @vitest-environment jsdom - */ -import { i18n as testI18n } from "@/i18n/i18next"; -import React, { type ReactElement } from "react"; -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { HostPluginsPage } from "./plugins-page"; - -void testI18n; - -const runtime = vi.hoisted(() => ({ - connected: true, - supported: true, - logsSupported: true, - client: null as DaemonClient | null, -})); - -vi.mock("@/runtime/host-runtime", async (importOriginal) => ({ - ...(await importOriginal()), - useHostRuntimeClient: () => runtime.client, - useHostRuntimeIsConnected: () => runtime.connected, -})); - -vi.mock("@/runtime/host-features", () => ({ - useHostFeature: (_serverId: string, feature: string) => { - if (feature === "pluginLogs") return runtime.logsSupported; - return runtime.supported; - }, -})); - -vi.mock("@/components/adaptive-modal-sheet", async () => { - const ReactModule = await vi.importActual("react"); - const actual = await vi.importActual( - "@/components/adaptive-modal-sheet", - ); - return { - ...actual, - AdaptiveModalSheet: ({ - header, - children, - onClose, - }: { - header: { title: string; actions?: React.ReactNode }; - children: React.ReactNode; - onClose(): void; - }) => - ReactModule.createElement( - "div", - { role: "dialog" }, - ReactModule.createElement("h2", null, header.title), - header.actions, - ReactModule.createElement("button", { type: "button", onClick: onClose }, "Close"), - children, - ), - }; -}); - -vi.mock("react-native-reanimated", () => ({ - default: { View: "div" }, - Keyframe: class { - duration() { - return this; - } - }, - Easing: { ease: "ease", inOut: (value: unknown) => value }, - interpolateColor: (value: number, _input: number[], output: string[]) => - value >= 1 ? output[1] : output[0], - useAnimatedStyle: (factory: () => unknown) => factory(), - useDerivedValue: (factory: () => unknown) => ({ value: factory() }), - withTiming: (value: unknown) => value, -})); - -vi.mock("@gorhom/bottom-sheet", async () => { - const ReactModule = await vi.importActual("react"); - const { ScrollView, TextInput } = - await vi.importActual("react-native"); - return { - BottomSheetBackdrop: () => null, - BottomSheetHandle: () => null, - BottomSheetModal: ReactModule.forwardRef(() => null), - BottomSheetScrollView: ScrollView, - BottomSheetTextInput: TextInput, - useBottomSheetInternal: () => null, - }; -}); - -vi.mock("react-native-safe-area-context", () => ({ - useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }), -})); - -function plugin(enabled = true): PluginListItem { - return { - id: "example", - description: "Reviews changes before merge", - path: "/plugins/example", - enabled, - status: enabled ? "running" : "disabled", - }; -} - -async function selectPluginAction(action: string): Promise { - fireEvent.click(await screen.findByRole("button", { name: "Actions for example" })); - fireEvent.click(await screen.findByRole("menuitem", { name: action })); -} - -function createClient() { - return { - observeEvents: () => - subscriptionFixture( - Promise.resolve({ events: ["status.plugin_catalog_changed"] }), - () => () => {}, - ), - getDaemonConfig: vi.fn(async () => ({ config: { pluginsEnabled: true } })), - patchDaemonConfig: vi.fn(async () => ({ config: { pluginsEnabled: true } })), - listPlugins: vi.fn(async (): Promise => []), - installPluginSource: vi.fn(async () => plugin()), - reloadPlugin: vi.fn(async () => plugin()), - enablePlugin: vi.fn(async () => plugin()), - disablePlugin: vi.fn(async () => plugin(false)), - removePlugin: vi.fn(async () => undefined), - getPluginLogs: vi.fn(async (): Promise => []), - }; -} - -type PluginClient = ReturnType; - -function renderPage(client: PluginClient | null): void { - runtime.client = client as unknown as DaemonClient | null; - const queryClient = new QueryClient({ - defaultOptions: { - queries: { retry: false }, - mutations: { retry: false }, - }, - }); - const element: ReactElement = ( - - - - ); - render(element); -} - -describe("HostPluginsPage", () => { - beforeEach(() => { - vi.stubGlobal("React", React); - runtime.connected = true; - runtime.supported = true; - runtime.logsSupported = true; - runtime.client = null; - vi.stubGlobal( - "confirm", - vi.fn(() => true), - ); - }); - - afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - }); - - it("renders the offline state", () => { - runtime.connected = false; - renderPage(null); - - expect(screen.getByRole("alert").textContent).toContain("Plugin host is offline"); - }); - - it("renders a catalog error and retries through the real query", async () => { - const client = createClient(); - client.listPlugins.mockRejectedValueOnce(new Error("catalog exploded")); - renderPage(client); - - expect(await screen.findByText("Unable to load plugins")).toBeDefined(); - expect(screen.getByText("catalog exploded")).toBeDefined(); - - fireEvent.click(screen.getByRole("button", { name: "Retry" })); - - await waitFor(() => expect(client.listPlugins).toHaveBeenCalledTimes(2)); - expect(await screen.findByText("No plugins configured")).toBeDefined(); - }); - - it.each([ - ["reloadPlugin", "Reload"], - ["removePlugin", "Remove"], - ] as const)("runs %s from the plugin actions menu", async (method, action) => { - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - renderPage(client); - - await selectPluginAction(action); - - await waitFor(() => expect(client[method]).toHaveBeenCalledTimes(1)); - }); - - it("hides the logs action when the host does not advertise support", async () => { - runtime.logsSupported = false; - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - renderPage(client); - - await screen.findByText("example"); - fireEvent.click(screen.getByRole("button", { name: "Actions for example" })); - expect(screen.queryByRole("menuitem", { name: "Logs" })).toBeNull(); - }); - - it("opens readable stdout and stderr logs and refreshes them", async () => { - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - client.getPluginLogs.mockResolvedValue([ - { - sequence: 1, - timestamp: "2026-08-16T12:00:00.000Z", - stream: "stdout", - message: "ready", - }, - { - sequence: 2, - timestamp: "2026-08-16T12:00:01.000Z", - stream: "stderr", - message: "warning", - }, - ]); - renderPage(client); - - await selectPluginAction("Logs"); - - expect(await screen.findByRole("dialog")).toBeDefined(); - expect(screen.getByText("Logs: example")).toBeDefined(); - expect(await screen.findByText("ready")).toBeDefined(); - expect(screen.getByText("warning")).toBeDefined(); - expect(screen.getByText(/stdout/)).toBeDefined(); - expect(screen.getByText(/stderr/)).toBeDefined(); - - fireEvent.click(screen.getByRole("button", { name: "Refresh" })); - await waitFor(() => expect(client.getPluginLogs).toHaveBeenCalledTimes(2)); - }); - - it("shows empty and recoverable error states for plugin logs", async () => { - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - client.getPluginLogs.mockRejectedValueOnce(new Error("logs exploded")); - renderPage(client); - - await selectPluginAction("Logs"); - expect(await screen.findByText("Unable to load plugin logs")).toBeDefined(); - expect(screen.getByText("logs exploded")).toBeDefined(); - - fireEvent.click(screen.getAllByRole("button", { name: "Refresh" }).at(-1)!); - await waitFor(() => expect(client.getPluginLogs).toHaveBeenCalledTimes(2)); - expect(await screen.findByText("No plugin output yet")).toBeDefined(); - }); -}); diff --git a/packages/app/src/screens/settings/plugins-page.tsx b/packages/app/src/screens/settings/plugins-page.tsx deleted file mode 100644 index fdaf260f8d..0000000000 --- a/packages/app/src/screens/settings/plugins-page.tsx +++ /dev/null @@ -1,581 +0,0 @@ -import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference"; -import { PluginSettingsButton } from "@/plugins/settings"; -import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; -import { useTranslation } from "react-i18next"; -import { Text, View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; -import { useMutation } from "@tanstack/react-query"; -import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages"; -import { MoreHorizontal, Trash2 } from "lucide-react-native"; -import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; -import { SettingsCard, SettingsRow } from "@/components/settings"; -import { Alert } from "@/components/ui/alert"; -import { Button } from "@/components/ui/button"; -import { ExternalLink } from "@/components/ui/external-link"; -import { Field, FormTextInput } from "@/components/ui/form-field"; -import { StatusBadge } from "@/components/ui/status-badge"; -import { Switch } from "@/components/ui/switch"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { useFetchQuery } from "@/data/query"; -import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { useHostFeature } from "@/runtime/host-features"; -import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; -import { SettingsSection } from "@/components/settings/headings/settings-section"; -import { resolvePluginPageState } from "@/screens/settings/plugins-page-state"; -import { openPluginInstallForm } from "@/screens/settings/plugin-install-form-model"; -import { pluginRegistry, useInstalledPlugins } from "@/plugins/registry"; -import { pluginDisplayName, usePluginList } from "@/plugins/plugin-list"; -import { settingsStyles } from "@/styles/settings"; -import { confirmDialog } from "@/utils/confirm-dialog"; - -const PLUGIN_SOURCE_DOCS_URL = "https://paseo.sh/docs/plugins/reference#plugin-sources"; -type PluginRowAction = "reload" | "enable" | "disable" | "remove"; - -function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); -} - -function pluginRowAction(action: string | undefined): PluginRowAction | undefined { - if (action === "reload" || action === "enable" || action === "disable" || action === "remove") { - return action; - } - return undefined; -} - -function PluginActionsMenu({ - plugin, - pending, - pendingAction, - onAction, - onOpenLogs, - supportsLogs, -}: { - plugin: PluginListItem; - pending: boolean; - pendingAction?: PluginRowAction; - onAction(action: PluginRowAction, plugin: PluginListItem): void; - onOpenLogs(plugin: PluginListItem): void; - supportsLogs: boolean; -}) { - const { t } = useTranslation(); - const reload = useCallback(() => onAction("reload", plugin), [onAction, plugin]); - const remove = useCallback(() => onAction("remove", plugin), [onAction, plugin]); - const openLogs = useCallback(() => onOpenLogs(plugin), [onOpenLogs, plugin]); - const removeIcon = useMemo(() => , []); - const menuLabel = t("settings.plugins.actions.menu", { name: pluginDisplayName(plugin) }); - - return ( - - - - - - {supportsLogs ? ( - - {t("settings.plugins.logs.action")} - - ) : null} - - {t("settings.plugins.actions.reload")} - - - {t("settings.plugins.actions.remove")} - - - - ); -} - -function PluginRow({ - plugin, - serverId, - clientError, - pending, - pendingAction, - onAction, - onOpenLogs, - supportsLogs, -}: { - plugin: PluginListItem; - serverId: string; - clientError?: string; - pending: boolean; - pendingAction?: PluginRowAction; - onAction(action: PluginRowAction, plugin: PluginListItem): void; - onOpenLogs(plugin: PluginListItem): void; - supportsLogs: boolean; -}) { - const { t } = useTranslation(); - const toggle = useCallback( - (enabled: boolean) => onAction(enabled ? "enable" : "disable", plugin), - [onAction, plugin], - ); - const status = clientError ? "failed" : plugin.status; - let badgeVariant: "success" | "error" | "muted" = "muted"; - if (status === "running") badgeVariant = "success"; - else if (status === "failed") badgeVariant = "error"; - const statusLabel = t(`settings.plugins.status.${status}`); - const statusBadge = useMemo( - () => , - [badgeVariant, statusLabel], - ); - const name = pluginDisplayName(plugin); - // A display name hides the id that the CLI and plugin routes use, so show it beneath. - const shownId = name === plugin.id ? null : plugin.id; - const hint = useMemo( - () => - shownId || plugin.description || plugin.installation ? ( - - {shownId ? {shownId} : null} - {plugin.description ? ( - {plugin.description} - ) : null} - {plugin.installation ? ( - {formatPluginInstallation(plugin.installation)} - ) : null} - - ) : undefined, - [shownId, plugin.description, plugin.installation], - ); - const toggleLabel = `${name}: ${t( - plugin.enabled ? "settings.plugins.actions.disable" : "settings.plugins.actions.enable", - )}`; - return ( - - - - - - - - ); -} - -function PluginLogsSheet({ - client, - plugin, - serverId, - onClose, -}: { - client: NonNullable>; - plugin: PluginListItem; - serverId: string; - onClose(): void; -}) { - const pluginId = plugin.id; - const { t } = useTranslation(); - const logs = useFetchQuery({ - queryKey: ["plugin-logs", serverId, pluginId], - queryFn: () => client.getPluginLogs(pluginId), - dataShape: "list", - staleTimeMs: 0, - }); - const refresh = useCallback(() => { - void logs.refetch(); - }, [logs]); - const header = useMemo( - () => ({ - title: t("settings.plugins.logs.title", { name: pluginDisplayName(plugin) }), - actions: ( - - ), - }), - [logs.isFetching, plugin, refresh, t], - ); - - let content = {t("settings.plugins.logs.loading")}; - if (logs.isError) { - content = ( - - - - ); - } else if (!logs.isLoading) { - content = logs.data?.length ? ( - - {logs.data.map((entry: PluginLogEntry) => ( - - - {entry.timestamp} {entry.stream} - - {entry.message} - - ))} - - ) : ( - {t("settings.plugins.logs.empty")} - ); - } - - return ( - - {content} - - ); -} - -export function HostPluginsPage({ serverId }: { serverId: string }) { - const { t } = useTranslation(); - const client = useHostRuntimeClient(serverId); - const connected = useHostRuntimeIsConnected(serverId); - const supported = useHostFeature(serverId, "pluginManagement"); - // COMPAT(pluginSourceInstallation): added in v0.8.0; remove gate after 2027-03-16 once daemon floor supports source identifiers. - const sourceInstallSupported = useHostFeature(serverId, "pluginSourceInstallation"); - // COMPAT(pluginLogs): added in v0.4.0, remove gate after 2027-08-16. - const logsSupported = useHostFeature(serverId, "pluginLogs"); - const { config, patchConfig } = useDaemonConfig(serverId); - const refreshQueue = useRef(Promise.resolve()); - useInstalledPlugins(); - const [installForm] = useState(openPluginInstallForm); - const installState = useSyncExternalStore( - installForm.subscribe, - installForm.getState, - installForm.getState, - ); - const sourceDocsLink = useMemo( - () => ( - - ), - [t], - ); - const [logsPlugin, setLogsPlugin] = useState(null); - const [feedback, setFeedback] = useState<{ kind: "success" | "error"; message: string } | null>( - null, - ); - const plugins = usePluginList(serverId); - const refetchPlugins = plugins.refetch; - const refresh = useCallback(async () => { - if (!client) return; - const refetch = async () => { - await refetchPlugins(); - }; - refreshQueue.current = refreshQueue.current.then(refetch, refetch); - await refreshQueue.current; - }, [client, refetchPlugins]); - useEffect(() => { - return () => installForm.close(); - }, [installForm]); - useEffect(() => { - if (!client || !connected || !supported) return; - const observation = client.observeEvents(["status.plugin_catalog_changed"]); - observation.subscribe({ - snapshot: () => {}, - update: (message) => { - if (message.type === "status" && message.payload.status === "plugin_catalog_changed") - void refresh(); - }, - }); - return () => { - void observation - .release() - .catch((error) => console.warn("[Plugins] Failed to release settings feed", error)); - }; - }, [client, connected, supported, refresh]); - const mutation = useMutation({ - mutationFn: async (operation: { - action: string; - pluginId?: string; - run: () => Promise; - }) => operation.run(), - onSuccess: async (message) => { - setFeedback({ kind: "success", message }); - await refresh(); - }, - onError: (error) => setFeedback({ kind: "error", message: errorMessage(error) }), - }); - const install = useCallback(() => { - if (!client || !sourceInstallSupported || !installState.canSubmit) return; - const input = installForm.getSubmission(); - setFeedback(null); - mutation.mutate({ - action: "install", - run: async () => { - const installed = await client.installPluginSource(input); - installForm.reset(); - return t("settings.plugins.feedback.installed", { name: pluginDisplayName(installed) }); - }, - }); - }, [client, installForm, installState.canSubmit, mutation, sourceInstallSupported, t]); - const action = useCallback( - (name: PluginRowAction, plugin: PluginListItem) => { - if (!client) return; - const pluginName = pluginDisplayName(plugin); - const run = async () => { - if (name === "remove") { - const confirmed = await confirmDialog({ - title: t("settings.plugins.removeConfirmTitle", { name: pluginName }), - message: t("settings.plugins.removeConfirmMessage"), - confirmLabel: t("settings.plugins.actions.remove"), - destructive: true, - }); - if (!confirmed) return t("settings.plugins.feedback.kept", { name: pluginName }); - await client.removePlugin(plugin.id); - } else { - await client[`${name}Plugin`](plugin.id); - } - return t(`settings.plugins.feedback.${name}`, { name: pluginName }); - }; - setFeedback(null); - mutation.mutate({ action: name, pluginId: plugin.id, run }); - }, - [client, mutation, t], - ); - const toggleGlobal = useCallback( - (enabled: boolean) => { - setFeedback(null); - mutation.mutate({ - action: enabled ? "global-enable" : "global-disable", - run: async () => { - await patchConfig({ pluginsEnabled: enabled }); - return enabled - ? t("settings.plugins.feedback.globalEnabled") - : t("settings.plugins.feedback.globalDisabled"); - }, - }); - }, - [mutation, patchConfig, t], - ); - const pageState = resolvePluginPageState({ - connected, - supported, - loading: plugins.isLoading, - error: plugins.isError, - pluginCount: plugins.data?.length ?? 0, - }); - const retry = useCallback(() => { - void refetchPlugins(); - }, [refetchPlugins]); - const closeLogs = useCallback(() => setLogsPlugin(null), []); - - if (pageState === "offline") { - return ( - - ); - } - if (pageState === "unsupported") { - return ; - } - - let catalogContent = ; - if (pageState === "error") { - catalogContent = ( - - - - ); - } else if (pageState !== "loading") { - catalogContent = ( - - {plugins.data?.length ? ( - plugins.data.map((plugin) => { - const clientError = pluginRegistry.getEvaluationError(serverId, plugin.id); - const pending = mutation.isPending && mutation.variables?.pluginId === plugin.id; - return ( - - ); - }) - ) : ( - - {t("settings.plugins.states.empty")} - - )} - - ); - } - - return ( - - - - - - - {t("settings.plugins.globalTitle")} - {t("settings.plugins.globalHint")} - - - - - {sourceInstallSupported ? ( - - - - - - - ) : ( - - )} - {feedback ? ( - - ) : null} - {catalogContent} - - {client && logsPlugin ? ( - - ) : null} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - pluginDescription: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - marginTop: theme.spacing[1], - }, - pluginSource: { - color: theme.colors.foregroundExtraMuted, - fontSize: theme.fontSize.sm, - marginTop: theme.spacing[1], - }, - install: { padding: theme.spacing[4], gap: theme.spacing[3] }, - pluginControls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, - menuButton: { padding: theme.spacing[1], borderRadius: theme.borderRadius.sm }, - menuIcon: { color: theme.colors.foregroundMuted }, - dangerIcon: { color: theme.colors.statusDanger }, - empty: { padding: theme.spacing[4], alignItems: "center" }, - logsState: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - textAlign: "center", - paddingVertical: theme.spacing[6], - }, - logList: { gap: theme.spacing[2] }, - logEntry: { - padding: theme.spacing[3], - gap: theme.spacing[1], - backgroundColor: theme.colors.surface2, - borderRadius: theme.borderRadius.md, - }, - logStdout: { - color: theme.colors.foregroundMuted, - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.sm, - }, - logStderr: { - color: theme.colors.statusDanger, - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.sm, - }, - logMessage: { - color: theme.colors.foreground, - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.base, - }, -})); diff --git a/packages/app/src/screens/settings/providers-section.test.tsx b/packages/app/src/screens/settings/providers-section.test.tsx index 86c55be4e8..3e55134520 100644 --- a/packages/app/src/screens/settings/providers-section.test.tsx +++ b/packages/app/src/screens/settings/providers-section.test.tsx @@ -8,29 +8,8 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; import { ToastApiProvider } from "@/contexts/toast-api-context"; -const { theme, snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted( +const { snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted( () => ({ - theme: { - spacing: { 1: 4, "1.5": 6, 2: 8, 3: 12, 4: 16, 6: 24 }, - iconSize: { sm: 14, md: 20 }, - fontSize: { xs: 11, sm: 13, base: 15 }, - fontWeight: { normal: "400" }, - borderRadius: { lg: 8 }, - opacity: { 50: 0.5 }, - colors: { - surface1: "#111", - surface2: "#222", - surface3: "#333", - foreground: "#fff", - foregroundMuted: "#aaa", - border: "#555", - accent: "#0a84ff", - statusSuccess: "#00ff00", - statusWarning: "#ff9500", - statusDanger: "#ff0000", - palette: { red: { 300: "#ff6b6b" }, white: "#fff" }, - }, - }, snapshotState: { entries: undefined as ProviderSnapshotEntry[] | undefined, isLoading: false, @@ -44,8 +23,8 @@ const { theme, snapshotState, configState, patchConfigMock, openProviderSettings }), ); -vi.mock("react-native", () => ({ - Platform: { OS: "web" }, +vi.mock("react-native", async (importOriginal) => ({ + ...(await importOriginal()), View: ({ children, testID }: { children?: React.ReactNode; testID?: string }) => React.createElement("div", { "data-testid": testID }, children), Text: ({ children }: { children?: React.ReactNode }) => @@ -87,14 +66,6 @@ vi.mock("react-native", () => ({ ActivityIndicator: () => React.createElement("span", { "data-testid": "activity-indicator" }), })); -vi.mock("react-native-unistyles", () => ({ - StyleSheet: { - create: (factory: unknown) => - typeof factory === "function" ? (factory as (t: typeof theme) => unknown)(theme) : factory, - }, - useUnistyles: () => ({ theme, rt: { breakpoint: "md" } }), -})); - vi.mock("lucide-react-native", () => { const icon = (name: string) => () => React.createElement("span", { "data-icon": name }); return { diff --git a/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx b/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx index 386fcb5578..0884c38e97 100644 --- a/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx +++ b/packages/app/src/screens/settings/voice/speech-provider-sheet.tsx @@ -487,10 +487,7 @@ function LocalModelRow({ } const rowStyle = useCallback( - ({ hovered, pressed }: HoverState) => [ - !selectionLocked && hovered && styles.rowHovered, - !selectionLocked && pressed && styles.rowPressed, - ], + ({ hovered }: HoverState) => [!selectionLocked && hovered && styles.rowHovered], [selectionLocked], ); const accessibilityState = useMemo( diff --git a/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx b/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx index 7b93f84746..9b3fa10c49 100644 --- a/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx +++ b/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx @@ -94,7 +94,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee actions: sheet.policy.openAsTab ? ( diff --git a/packages/app/src/screens/workspace/workspace-pane-state.test.ts b/packages/app/src/screens/workspace/workspace-pane-state.test.ts index 778d8fded2..71a557a67c 100644 --- a/packages/app/src/screens/workspace/workspace-pane-state.test.ts +++ b/packages/app/src/screens/workspace/workspace-pane-state.test.ts @@ -106,6 +106,79 @@ describe("workspace-pane-state", () => { }); }); + it("does not locate a file by an id retained from a previous target", () => { + const layout: WorkspaceLayout = { + root: { + kind: "pane", + pane: { + id: "main", + tabIds: ["file_/repo/a.ts", "agent_agent-a"], + focusedTabId: "agent_agent-a", + }, + }, + focusedPaneId: "main", + }; + const tabs = [ + createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }), + createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }), + ]; + const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" }; + + expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({ + kind: "split-side-pane", + paneId: "main", + }); + expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe( + "agent_agent-a", + ); + }); + + it("matches a retained file instance when only the requested line range differs", () => { + const pane = { + id: "main", + tabIds: ["retained-file", "agent_agent-a"], + focusedTabId: "agent_agent-a", + }; + const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" }; + const tabs = [ + createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }), + createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }), + ]; + const target: WorkspaceTab["target"] = { + kind: "file", + path: "/repo/a.ts", + lineStart: 12, + lineEnd: 20, + }; + + expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({ + kind: "open-in-source", + }); + expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe( + "retained-file", + ); + }); + + it("prefers an exact file navigation target over another instance of the same resource", () => { + const pane = { + id: "main", + tabIds: ["first", "second"], + focusedTabId: "first", + }; + const tabs = [ + createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }), + createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }), + ]; + + expect( + deriveWorkspacePaneState({ + pane, + tabs, + preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 }, + }).activeTabId, + ).toBe("second"); + }); + it("resolves side file opens to an existing file tab", () => { const layout: WorkspaceLayout = { root: { diff --git a/packages/app/src/screens/workspace/workspace-pane-state.ts b/packages/app/src/screens/workspace/workspace-pane-state.ts index b188865eeb..2c782ac132 100644 --- a/packages/app/src/screens/workspace/workspace-pane-state.ts +++ b/packages/app/src/screens/workspace/workspace-pane-state.ts @@ -5,12 +5,9 @@ import { } from "@/stores/workspace-layout-store"; import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model"; import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; -import { - buildDeterministicWorkspaceTabId, - normalizeWorkspaceTabTarget, - workspaceTabTargetsEqual, -} from "@/workspace-tabs/identity"; +import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity"; import { findAdjacentPane } from "@/utils/split-navigation"; +import { panelResourceKey } from "@/panels/panel-manifest"; export interface WorkspaceDerivedTab { descriptor: WorkspaceTabDescriptor; @@ -124,8 +121,10 @@ function getActiveTabId(input: { } const matchingTab = input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ?? - null; - return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget); + input.tabs.find( + (tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget), + ); + return matchingTab?.descriptor.tabId ?? null; })(); if (preferredTabId && input.openTabIds.has(preferredTabId)) { @@ -211,10 +210,8 @@ export function resolveSideFileOpenPlacement(input: { tabs: WorkspaceTab[]; target: WorkspaceTabTarget; }): WorkspaceSideFileOpenPlacement { - const targetTabId = buildDeterministicWorkspaceTabId(input.target); - const existingTab = input.tabs.find( - (tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target), - ); + const targetKey = panelResourceKey(input.target); + const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey); if (existingTab) { return { kind: "open-in-source" }; } diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 185a1dbac3..0c30fb5bfc 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -3919,7 +3919,11 @@ function WorkspaceMarkdownLinks({ }: AssistantFileLinkResolverProviderProps & { workspace: WorkspaceDescriptor | null | undefined }) { return ( - + {children} diff --git a/packages/app/src/stores/download-store.test.ts b/packages/app/src/stores/download-store.test.ts index d3657b4c34..4d176f6505 100644 --- a/packages/app/src/stores/download-store.test.ts +++ b/packages/app/src/stores/download-store.test.ts @@ -90,6 +90,7 @@ interface StartInput { token?: ReturnType; reader?: ReturnType; saver?: ReturnType; + fetchFile?: typeof fetch; } async function startDownload(input: StartInput): Promise { @@ -108,6 +109,7 @@ async function startDownload(input: StartInput): Promise { requestFileDownloadToken: token.request, readFile: reader.read, saveFile: saver.save, + fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)), }); const { activeDownloadId, downloads } = useDownloadStore.getState(); return activeDownloadId ? downloads.get(activeDownloadId) : undefined; @@ -203,6 +205,57 @@ describe("download store transport selection", () => { expect(saver.savedFiles).toEqual([]); }); + it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => { + const requests: Array = []; + const download = await startDownload({ + profile: profileWith([localTcpConnection]), + activeConnectionId: localTcpConnection.id, + fetchFile: async (_url, init) => { + requests.push(init); + return new Response("

401 Authorization Required

", { + status: 401, + headers: { "WWW-Authenticate": 'Basic realm="Paseo"' }, + }); + }, + }); + + expect(download).toMatchObject({ + status: "error", + message: i18n.t("downloads.httpFailed", { status: 401 }), + }); + expect(requests).toEqual([{ credentials: "include", redirect: "error" }]); + }); + + it("fails with a readable message when the download request cannot reach the host", async () => { + const download = await startDownload({ + profile: profileWith([localTcpConnection]), + activeConnectionId: localTcpConnection.id, + fetchFile: async () => { + throw new TypeError("Failed to fetch"); + }, + }); + + expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") }); + }); + + it("fails with a readable message when the connection drops while the file is downloading", async () => { + const saver = createFileSaver(); + const download = await startDownload({ + profile: profileWith([localTcpConnection]), + activeConnectionId: localTcpConnection.id, + fetchFile: async () => + new Response( + new ReadableStream({ + start: (controller) => controller.error(new TypeError("network error")), + }), + ), + saver, + }); + + expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") }); + expect(saver.savedFiles).toEqual([]); + }); + it("fails the download and saves nothing when the session read fails", async () => { const reader = createFileReader(async () => { throw new Error("Connection lost"); diff --git a/packages/app/src/stores/download-store.ts b/packages/app/src/stores/download-store.ts index 790fbd7dee..ae7ac647b4 100644 --- a/packages/app/src/stores/download-store.ts +++ b/packages/app/src/stores/download-store.ts @@ -4,7 +4,6 @@ import * as LegacyFileSystem from "expo-file-system/legacy"; import * as Sharing from "expo-sharing"; import type { HostProfile } from "@/types/host-connection"; import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints"; -import { openExternalUrl } from "@/utils/open-external-url"; import { isWeb } from "@/constants/platform"; import { i18n } from "@/i18n/i18next"; @@ -59,6 +58,7 @@ interface DownloadState { /** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */ readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>; saveFile?: typeof saveDownloadedBytes; + fetchFile?: typeof fetch; }) => Promise; updateProgress: (id: string, progress: DownloadProgress) => void; @@ -86,6 +86,7 @@ export const useDownloadStore = create()((set, get) => ({ requestFileDownloadToken, readFile, saveFile = saveDownloadedBytes, + fetchFile = fetch, }) => { const id = generateDownloadId(); const download: Download = { @@ -144,14 +145,11 @@ export const useDownloadStore = create()((set, get) => ({ throw new Error(i18n.t("downloads.hostUnavailable")); } - const downloadUrl = buildDownloadUrl( - downloadTarget.baseUrl, - tokenResponse.token, - isWeb ? downloadTarget.authCredentials : null, - ); + const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token); if (isWeb) { - triggerBrowserDownload(downloadUrl, resolvedFileName); + const file = await fetchDownload(fetchFile, downloadUrl); + saveBrowserFile(file, resolvedFileName); get().completeDownload(id); return; } @@ -198,11 +196,6 @@ export const useDownloadStore = create()((set, get) => ({ await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName); } catch (error) { const message = error instanceof Error ? error.message : i18n.t("downloads.failed"); - if (isWeb) { - console.warn("[DownloadStore] Download failed:", message); - get().failDownload(id, message); - return; - } get().failDownload(id, message); } }, @@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map): string | nu interface DownloadTarget { baseUrl: string | null; authHeader: string | null; - authCredentials: { username: string; password: string } | null; } /** @@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget( buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }), ); } catch { - return { baseUrl: null, authHeader: null, authCredentials: null }; + return { baseUrl: null, authHeader: null }; } if (parsed.protocol === "ws:") { @@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget( ? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}` : null; - return { baseUrl, authHeader, authCredentials }; + return { baseUrl, authHeader }; } -function buildDownloadUrl( - baseUrl: string, - token: string, - authCredentials: { username: string; password: string } | null, -): string { +function buildDownloadUrl(baseUrl: string, token: string): string { const url = new URL("/api/files/download", baseUrl); url.searchParams.set("token", token); - if (authCredentials) { - url.username = authCredentials.username; - url.password = authCredentials.password; - } return url.toString(); } +/** + * Fetches the file instead of navigating to it. The app runs on another origin than the host + * (paseo://app on desktop), so a link to the download URL navigates the whole window, and any + * response that is not the file (a proxy's 401 page, a 404) replaces the app. + */ +async function fetchDownload(fetchFile: typeof fetch, url: string): Promise { + let response: Response; + try { + // Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the + // host lets the download through. Refuse redirects: a proxy that redirects to a login page + // would otherwise be saved as the file. + response = await fetchFile(url, { credentials: "include", redirect: "error" }); + } catch { + throw new Error(i18n.t("downloads.failed")); + } + if (!response.ok) { + throw new Error(i18n.t("downloads.httpFailed", { status: response.status })); + } + try { + // The body streams after the headers, so the connection can still drop here. + return await response.blob(); + } catch { + throw new Error(i18n.t("downloads.failed")); + } +} + /** * Saves bytes read over the session. Web and Electron hand them to the browser's download * manager and return `null`; native writes the file and returns its URI for the share sheet. @@ -361,12 +371,7 @@ async function saveDownloadedBytes({ if (isWeb) { const buffer = new ArrayBuffer(bytes.byteLength); new Uint8Array(buffer).set(bytes); - const url = URL.createObjectURL( - new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), - ); - triggerBrowserDownload(url, fileName); - // The browser may still be reading the blob while its save prompt is open. - setTimeout(() => URL.revokeObjectURL(url), 60_000); + saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName); return null; } // Resolve and write in one tick so two downloads of the same name cannot pick the same path. @@ -390,14 +395,12 @@ async function shareSavedFile( } } -function triggerBrowserDownload(url: string, fileName: string) { +function saveBrowserFile(file: Blob, fileName: string) { if (typeof document === "undefined") { - if (typeof window !== "undefined") { - void openExternalUrl(url); - } return; } + const url = URL.createObjectURL(file); const link = document.createElement("a"); link.href = url; link.download = fileName; @@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, fileName: string) { document.body.appendChild(link); link.click(); link.remove(); + // The browser may still be reading the blob while its save prompt is open. + setTimeout(() => URL.revokeObjectURL(url), 60_000); } function resolveDownloadTargetFile(fileName: string): FSFile { diff --git a/packages/app/src/stores/keyboard-shortcuts-store.test.ts b/packages/app/src/stores/keyboard-shortcuts-store.test.ts index f35b6ea18a..c532e358c7 100644 --- a/packages/app/src/stores/keyboard-shortcuts-store.test.ts +++ b/packages/app/src/stores/keyboard-shortcuts-store.test.ts @@ -4,7 +4,7 @@ import { useKeyboardShortcutsStore } from "./keyboard-shortcuts-store"; beforeEach(() => { useKeyboardShortcutsStore.setState({ commandCenterOpen: false, - commandCenterScope: null, + commandCenterTab: "all", shortcutsDialogOpen: false, capturingShortcut: false, altDown: false, @@ -20,18 +20,21 @@ describe("keyboard-shortcuts-store", () => { expect(useKeyboardShortcutsStore.getState().commandCenterOpen).toBe(true); }); - it("opens the command center with a scope and clears it when closed", () => { + it("opens the command center on a tab and returns to All when closed", () => { useKeyboardShortcutsStore.getState().setCommandCenterOpen(true, "files"); expect(useKeyboardShortcutsStore.getState()).toMatchObject({ commandCenterOpen: true, - commandCenterScope: "files", + commandCenterTab: "files", }); useKeyboardShortcutsStore.getState().setCommandCenterOpen(false); expect(useKeyboardShortcutsStore.getState()).toMatchObject({ commandCenterOpen: false, - commandCenterScope: null, + commandCenterTab: "all", }); + + useKeyboardShortcutsStore.getState().setCommandCenterOpen(true); + expect(useKeyboardShortcutsStore.getState().commandCenterTab).toBe("all"); }); it("toggles shortcut capture state", () => { diff --git a/packages/app/src/stores/keyboard-shortcuts-store.ts b/packages/app/src/stores/keyboard-shortcuts-store.ts index 0b0e2a516c..58e5e91978 100644 --- a/packages/app/src/stores/keyboard-shortcuts-store.ts +++ b/packages/app/src/stores/keyboard-shortcuts-store.ts @@ -1,13 +1,13 @@ import { create } from "zustand"; +import type { CommandCenterTab } from "@/command-center/tabs"; import type { SidebarShortcutWorkspaceTarget } from "@/utils/sidebar-shortcuts"; const SHORTCUT_BADGE_DELAY_MS = 150; -export type CommandCenterScope = "files" | null; - interface KeyboardShortcutsState { commandCenterOpen: boolean; - commandCenterScope: CommandCenterScope; + /** The tab the open command center shows. Every opening starts on the tab it asks for. */ + commandCenterTab: CommandCenterTab; shortcutsDialogOpen: boolean; capturingShortcut: boolean; altDown: boolean; @@ -16,8 +16,8 @@ interface KeyboardShortcutsState { /** Sidebar-visible workspace targets (up to 9), in top-to-bottom visual order. */ sidebarShortcutWorkspaceTargets: SidebarShortcutWorkspaceTarget[]; - setCommandCenterOpen: (open: boolean, scope?: CommandCenterScope) => void; - setCommandCenterScope: (scope: CommandCenterScope) => void; + setCommandCenterOpen: (open: boolean, tab?: CommandCenterTab) => void; + setCommandCenterTab: (tab: CommandCenterTab) => void; setShortcutsDialogOpen: (open: boolean) => void; setCapturingShortcut: (capturing: boolean) => void; setAltDown: (down: boolean) => void; @@ -51,7 +51,7 @@ function updateBadgeTimer( export const useKeyboardShortcutsStore = create((set, get) => ({ commandCenterOpen: false, - commandCenterScope: null, + commandCenterTab: "all", shortcutsDialogOpen: false, capturingShortcut: false, altDown: false, @@ -59,9 +59,9 @@ export const useKeyboardShortcutsStore = create((set, ge showShortcutBadges: false, sidebarShortcutWorkspaceTargets: [], - setCommandCenterOpen: (open, scope = null) => - set({ commandCenterOpen: open, commandCenterScope: open ? scope : null }), - setCommandCenterScope: (scope) => set({ commandCenterScope: scope }), + setCommandCenterOpen: (open, tab = "all") => + set({ commandCenterOpen: open, commandCenterTab: open ? tab : "all" }), + setCommandCenterTab: (tab) => set({ commandCenterTab: tab }), setShortcutsDialogOpen: (open) => set({ shortcutsDialogOpen: open }), setCapturingShortcut: (capturing) => set({ capturingShortcut: capturing }), setAltDown: (down) => { diff --git a/packages/app/src/stores/navigation-active-workspace-store/index.ts b/packages/app/src/stores/navigation-active-workspace-store/index.ts index 2b6fbff11f..38425924fb 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/index.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/index.ts @@ -37,9 +37,11 @@ const lastWorkspaceSelectionStore = createLastWorkspaceSelectionStore( function navigateDeps(): NavigateToWorkspaceDeps { return { revealTab: revealWorkspaceTab, - revealWorkspace: (workspaceKey) => { + revealWorkspace: (workspaceKey, surface) => { useWorkspaceLayoutStore.getState().focusWorkspace(workspaceKey); - usePanelStore.getState().showMobileAgent(); + const panels = usePanelStore.getState(); + if (surface === "sidebar") panels.showMobileAgentList(); + else panels.showMobileAgent(); }, getSessionWorkspaces: (serverId) => useSessionStore.getState().sessions[serverId]?.workspaces, isWorkspaceLayoutHydrated: () => useWorkspaceLayoutStore.persist.hasHydrated(), diff --git a/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts b/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts index 5dbc292524..db68e05602 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts @@ -77,6 +77,16 @@ describe("workspace navigation", () => { expect(revealed).toEqual([null]); }); + it("returns to the sidebar without revealing workspace content first", () => { + const surfaces: (string | undefined)[] = []; + const { deps, navigations } = createFakeDeps({ + revealWorkspace: (_workspaceKey, surface) => surfaces.push(surface), + }); + navigateToWorkspace({ serverId: "server", workspaceId: "workspace", surface: "sidebar" }, deps); + expect(surfaces).toEqual(["sidebar"]); + expect(navigations).toEqual(["/h/server/workspace/workspace"]); + }); + it("reveals an explicit target after opening instead of forcing center", () => { const workspace = { id: "workspace" } as WorkspaceDescriptor; const { deps, revealed } = createFakeDeps({ diff --git a/packages/app/src/stores/navigation-active-workspace-store/navigation.ts b/packages/app/src/stores/navigation-active-workspace-store/navigation.ts index bbc55701d6..ed73b7ed2d 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/navigation.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/navigation.ts @@ -23,6 +23,7 @@ export interface NavigateToWorkspaceInput { serverId: string; workspaceId: string; target?: WorkspaceTabTarget; + surface?: "sidebar"; pin?: boolean; placement?: WorkspaceTabPlacement; asTab?: boolean; @@ -35,7 +36,7 @@ export interface NavigateToWorkspaceDeps extends PrepareWorkspaceTabDeps { rememberLastWorkspace: (selection: ActiveWorkspaceSelection) => void; navigateToRoute: (route: string) => void; revealTab: (workspaceKey: string, tabId: string | null) => void; - revealWorkspace: (workspaceKey: string) => void; + revealWorkspace: (workspaceKey: string, surface?: "sidebar") => void; } export interface NavigateToLastWorkspaceDeps extends NavigateToWorkspaceDeps { @@ -100,7 +101,10 @@ export function navigateToWorkspace( if (input.target) { prepareWorkspaceTab({ ...input, target: input.target }, { openTab }); } else { - deps.revealWorkspace(`${input.serverId}:${resolvedWorkspaceId ?? input.workspaceId}`); + deps.revealWorkspace( + `${input.serverId}:${resolvedWorkspaceId ?? input.workspaceId}`, + input.surface, + ); } const route = buildHostWorkspaceRoute(input.serverId, input.workspaceId); diff --git a/packages/app/src/stores/panel-store/index.ts b/packages/app/src/stores/panel-store/index.ts index 660f2d1b62..8673030fdc 100644 --- a/packages/app/src/stores/panel-store/index.ts +++ b/packages/app/src/stores/panel-store/index.ts @@ -52,6 +52,7 @@ export type ExpandedPathsUpdate = string[] | ((currentPaths: string[]) => string export interface PanelState { // Mobile: React's durable target plus the generation that owns it. mobilePanel: MobilePanelSelection; + layout: PanelLayout; // Desktop: independent sidebar toggles desktop: DesktopSidebarState; @@ -120,6 +121,7 @@ export const usePanelStore = create()( (set) => ({ // Mobile always starts at agent view mobilePanel: { target: "agent", revision: 0 }, + layout: { isCompact: false, leftSidebar: "hidden" }, // Desktop defaults based on platform desktop: { @@ -215,7 +217,12 @@ export const usePanelStore = create()( applyPanelLayout: (layout) => set((state) => { const mobilePanel = reconcileMobilePanel(state.mobilePanel, layout); - return mobilePanel === state.mobilePanel ? state : { mobilePanel }; + const layoutUnchanged = + state.layout.isCompact === layout.isCompact && + state.layout.leftSidebar === layout.leftSidebar; + return mobilePanel === state.mobilePanel && layoutUnchanged + ? state + : { mobilePanel, layout }; }), setExpandedPathsForWorkspace: (workspaceKey, paths) => diff --git a/packages/app/src/stores/panel-store/state.test.ts b/packages/app/src/stores/panel-store/state.test.ts index 317d4fd9a8..b9613ab020 100644 --- a/packages/app/src/stores/panel-store/state.test.ts +++ b/packages/app/src/stores/panel-store/state.test.ts @@ -171,6 +171,30 @@ describe("panel-store wide navigation overlay", () => { expect(usePanelStore.getState().mobilePanel.target).toBe("agent"); }); + it("retains the sidebar through a suspended layout without publishing motion", () => { + const panels = usePanelStore.getState(); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "overlay" }); + panels.showMobileAgentList(); + const selection = usePanelStore.getState().mobilePanel; + panels.applyPanelLayout({ isCompact: true, leftSidebar: "suspended" }); + expect(usePanelStore.getState().mobilePanel).toBe(selection); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "overlay" }); + expect(usePanelStore.getState().mobilePanel).toBe(selection); + }); + + it("publishes an immediate destination when navigation closes a suspended sidebar", () => { + const panels = usePanelStore.getState(); + panels.showMobileAgentList(); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "suspended" }); + const commands: boolean[] = []; + const unsubscribe = subscribeMobilePanelSelection((_selection, immediate) => + commands.push(immediate), + ); + panels.showMobileAgent(); + unsubscribe(); + expect(commands).toEqual([true, true]); + }); + it("drops the overlay target once the sidebar is no longer presented as an overlay", () => { usePanelStore.getState().showMobileAgentList(); usePanelStore.getState().applyPanelLayout({ isCompact: false, leftSidebar: "overlay" }); diff --git a/packages/app/src/stores/panel-store/state.ts b/packages/app/src/stores/panel-store/state.ts index a9971fa458..5e9cc2119d 100644 --- a/packages/app/src/stores/panel-store/state.ts +++ b/packages/app/src/stores/panel-store/state.ts @@ -26,8 +26,8 @@ export interface PanelLayoutInput { isCompact: boolean; } -/** How app chrome presents the left sidebar: over the workspace, beside it, or not at all. */ -export type LeftSidebarPresentation = "overlay" | "dock" | "hidden"; +/** Sidebar presentation; suspended retains an overlay while Settings covers it. */ +export type LeftSidebarPresentation = "overlay" | "dock" | "hidden" | "suspended"; /** The panels app chrome presents, which decide the mobile panel targets that can stay selected. */ export interface PanelLayout extends PanelLayoutInput { @@ -77,7 +77,7 @@ export function setMobilePanelTarget( } /** - * Only an overlay sidebar shows the `agent-list` target. A docked or hidden sidebar drops it, so + * Only an overlay or suspended sidebar holds `agent-list`. A docked or hidden sidebar drops it, so * a stale target cannot resurface the overlay on the next collapse. Always invalidate in-flight * gestures, even when an opening swipe has not committed `agent-list` yet. */ @@ -98,7 +98,9 @@ export function reconcileMobilePanel( layout: PanelLayout, ): MobilePanelSelection { const sidebarReconciled = - layout.leftSidebar === "overlay" ? selection : dropOverlayAgentList(selection); + layout.leftSidebar === "overlay" || layout.leftSidebar === "suspended" + ? selection + : dropOverlayAgentList(selection); if (!layout.isCompact && sidebarReconciled.target === "file-explorer") { return setMobilePanelTarget(sidebarReconciled, "agent"); } diff --git a/packages/app/src/stores/session-store-hooks/index.ts b/packages/app/src/stores/session-store-hooks/index.ts index d6d4a188c1..e2cc20454f 100644 --- a/packages/app/src/stores/session-store-hooks/index.ts +++ b/packages/app/src/stores/session-store-hooks/index.ts @@ -17,22 +17,16 @@ import { selectWorkspaceExists, selectWorkspaceFields, selectWorkspaceKeys, - selectWorkspaceStatusesForBadges, workspaceEqualityFns, type WorkspaceStructure, } from "./selectors"; import { useSessionStore, type WorkspaceDescriptor } from "../session-store"; -import type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; // These are the ONLY supported ways to read workspaces from the session store. // Do not write raw `useSessionStore` selectors that return the workspaces Map, a session object, // or the sessions dict — it breaks re-render isolation. -export type { - DesktopBadgeWorkspaceStatus, - WorkspaceStructure, - WorkspaceStructureProject, -} from "./selectors"; +export type { WorkspaceStructure, WorkspaceStructureProject } from "./selectors"; export function useWorkspace( serverId: string | null, @@ -163,11 +157,3 @@ export function useHasWorkspaces(serverId: string | null): boolean { workspaceEqualityFns.identity, ); } - -export function useWorkspaceStatusesForBadges(): DesktopBadgeWorkspaceStatus[] { - return useStoreWithEqualityFn( - useSessionStore, - (state) => selectWorkspaceStatusesForBadges(state), - workspaceEqualityFns.deep, - ); -} diff --git a/packages/app/src/stores/session-store-hooks/selectors.test.ts b/packages/app/src/stores/session-store-hooks/selectors.test.ts index 95cc1ba498..68caaf2294 100644 --- a/packages/app/src/stores/session-store-hooks/selectors.test.ts +++ b/packages/app/src/stores/session-store-hooks/selectors.test.ts @@ -14,7 +14,6 @@ import { selectWorkspaceDirectory, selectWorkspaceFields, selectWorkspaceKeys, - selectWorkspaceStatusesForBadges, selectWorkspaceStructureProjects, workspaceEqualityFns, type SidebarOrderSnapshot, @@ -589,36 +588,6 @@ describe("selectHasWorkspaces", () => { }); }); -describe("selectWorkspaceStatusesForBadges", () => { - it("tracks status changes without changing for no-ops or unrelated descriptor updates", () => { - const workspaceA = createWorkspace({ id: "workspace-a", status: "done" }); - const workspaceB = createWorkspace({ id: "workspace-b", status: "attention" }); - initializeWorkspaces([workspaceA, workspaceB]); - - const tracked = trackSelector( - useSessionStore, - (state) => selectWorkspaceStatusesForBadges(state), - workspaceEqualityFns.deep, - ); - const before = tracked.current; - expect(before).toEqual(["done", "attention"]); - - useSessionStore - .getState() - .mergeWorkspaces(SERVER_ID, [{ ...workspaceA, scripts: [...workspaceA.scripts] }]); - expect(tracked.current).toBe(before); - - useSessionStore.getState().mergeWorkspaces(SERVER_ID, [{ ...workspaceB, name: "Renamed" }]); - expect(tracked.current).toBe(before); - - useSessionStore.getState().mergeWorkspaces(SERVER_ID, [{ ...workspaceA, status: "failed" }]); - expect(tracked.current).not.toBe(before); - expect(tracked.current).toEqual(["failed", "attention"]); - - tracked.stop(); - }); -}); - it("a prompt changes only its project's structure and output preserves both project identities", () => { const a = { ...createWorkspace({ id: "a", projectId: "p" }), createdAt: new Date("2026-01-01") }; const b = { ...createWorkspace({ id: "b", projectId: "p" }), createdAt: new Date("2026-02-01") }; diff --git a/packages/app/src/stores/session-store-hooks/selectors.ts b/packages/app/src/stores/session-store-hooks/selectors.ts index 85169b6f4a..832ae54ca2 100644 --- a/packages/app/src/stores/session-store-hooks/selectors.ts +++ b/packages/app/src/stores/session-store-hooks/selectors.ts @@ -5,11 +5,9 @@ import { type WorkspaceStructure, type WorkspaceStructureProject, } from "@/projects/workspace-structure"; -import type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity"; import type { ProjectDescriptor, WorkspaceDescriptor } from "../session-store"; -export type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; export type { WorkspaceStructure, WorkspaceStructureProject } from "@/projects/workspace-structure"; export interface SessionsSnapshot { @@ -321,15 +319,3 @@ export function selectHasWorkspaces(state: SessionsSnapshot, serverId: string | } return (state.sessions[serverId]?.workspaces?.size ?? 0) > 0; } - -export function selectWorkspaceStatusesForBadges( - state: SessionsSnapshot, -): DesktopBadgeWorkspaceStatus[] { - const statuses: DesktopBadgeWorkspaceStatus[] = []; - for (const session of Object.values(state.sessions)) { - for (const workspace of session.workspaces.values()) { - statuses.push(workspace.status); - } - } - return statuses; -} diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index 625c3d8c2f..72ed4af90e 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -140,6 +140,7 @@ export interface WorkspaceDescriptor { gitRuntime?: WorkspaceDescriptorPayload["gitRuntime"]; githubRuntime?: WorkspaceDescriptorPayload["githubRuntime"]; forge?: WorkspaceDescriptorPayload["forge"]; + forgeWeb?: WorkspaceDescriptorPayload["forgeWeb"]; project?: ProjectPlacementPayload; } @@ -185,6 +186,7 @@ export function normalizeWorkspaceDescriptor( gitRuntime: payload.gitRuntime, githubRuntime: payload.githubRuntime, forge: payload.forge, + forgeWeb: payload.forgeWeb, project: payload.project, }; } diff --git a/packages/app/src/stores/workspace-draft-submission-store.test.ts b/packages/app/src/stores/workspace-draft-submission-store.test.ts index 73e1a40899..317b605767 100644 --- a/packages/app/src/stores/workspace-draft-submission-store.test.ts +++ b/packages/app/src/stores/workspace-draft-submission-store.test.ts @@ -45,27 +45,3 @@ test("the production app consumes a draft once and leaves other drafts pending", expect(store.getState().consumePending(submission)).toBeNull(); expect(Object.keys(store.getState().pendingByDraftId)).toEqual(["draft-2"]); }); - -test("consuming draft presentation retains its running creation through remount and retry", () => { - const store = loadProductionStore(); - const result = new Promise(() => {}); - const creation = { result, retry: () => result }; - const submission = { - serverId: "server", - workspaceId: "workspace", - draftId: "draft-one", - text: "hello", - attachments: [], - cwd: "/repo", - provider: "codex", - clientMessageId: "message", - timestamp: 1, - agentCreation: creation, - }; - store.getState().setPending(submission); - store.getState().consumePending(submission); - expect(store.getState().pendingByDraftId[submission.draftId]).toBeUndefined(); - expect(store.getState().creationByDraftId[submission.draftId]).toBe(creation); - store.getState().clearDraftSetup({ draftId: submission.draftId }); - expect(store.getState().creationByDraftId[submission.draftId]).toBeUndefined(); -}); diff --git a/packages/app/src/stores/workspace-draft-submission-store.ts b/packages/app/src/stores/workspace-draft-submission-store.ts index 4a7d3ceaf3..b3eb086d46 100644 --- a/packages/app/src/stores/workspace-draft-submission-store.ts +++ b/packages/app/src/stores/workspace-draft-submission-store.ts @@ -1,4 +1,3 @@ -import type { CreateAgentRequestOptions } from "@getpaseo/client/internal/daemon-client"; import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; import { create } from "zustand"; import type { ComposerAttachment } from "@/attachments/types"; @@ -9,7 +8,6 @@ export interface PendingWorkspaceDraftSubmission { /** Already-running creation. Mounting the draft only observes its result. */ agentCreation?: { result: Promise; - retry: (input: CreateAgentRequestOptions) => Promise; }; serverId: string; workspaceId: string; @@ -35,7 +33,6 @@ export interface PendingWorkspaceDraftSetup { interface WorkspaceDraftSubmissionState { pendingByDraftId: Record; setupByDraftId: Record; - creationByDraftId: Record>; setPending: (submission: PendingWorkspaceDraftSubmission) => void; setDraftSetup: (input: { draftId: string; @@ -69,12 +66,8 @@ export const useWorkspaceDraftSubmissionStore = create ({ pendingByDraftId: {}, setupByDraftId: {}, - creationByDraftId: {}, setPending: (submission) => set((state) => ({ - creationByDraftId: submission.agentCreation - ? { ...state.creationByDraftId, [submission.draftId]: submission.agentCreation } - : state.creationByDraftId, pendingByDraftId: { ...state.pendingByDraftId, [submission.draftId]: submission, @@ -94,10 +87,8 @@ export const useWorkspaceDraftSubmissionStore = create { - const creationByDraftId = { ...state.creationByDraftId }; - delete creationByDraftId[normalizedDraftId]; const { [normalizedDraftId]: _removed, ...setupByDraftId } = state.setupByDraftId; - return { setupByDraftId, creationByDraftId }; + return { setupByDraftId }; }); }, consumePending: (input) => { diff --git a/packages/app/src/stores/workspace-layout-actions.ts b/packages/app/src/stores/workspace-layout-actions.ts index cd727a6915..384aa725b2 100644 --- a/packages/app/src/stores/workspace-layout-actions.ts +++ b/packages/app/src/stores/workspace-layout-actions.ts @@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model"; import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants"; import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest"; -import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids"; +import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids"; import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids"; import { buildDeterministicWorkspaceTabId, @@ -137,6 +137,8 @@ interface OpenTabInLayoutInput { placement: WorkspaceTabPlacement; /** Required so a new caller cannot silently opt out of Explorer placement rules. */ explorerSidebarPaneId: string | null; + /** Live sheets share the workspace's panel-instance namespace with its tabs. */ + reservedTabIds?: ReadonlySet; } interface CreateTabInLayoutInput extends OpenTabInLayoutInput { @@ -261,6 +263,7 @@ interface ReorderPaneTabsInLayoutInput { export interface WorkspaceTabReconcileState { layout: WorkspaceLayout; + reservedTabIds?: ReadonlySet; pinnedAgentIds?: ReadonlySet | null; hiddenAgentIds?: ReadonlySet | null; explorerSidebarPaneId: string | null; @@ -398,15 +401,11 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] { if (!Array.isArray(input)) { return []; } + // Preserve colliding entries until the whole layout can assign each an identity. const next: WorkspaceTab[] = []; - const seen = new Set(); for (const value of input) { const tab = normalizeWorkspaceTab(value); - if (!tab || seen.has(tab.tabId)) { - continue; - } - seen.add(tab.tabId); - next.push(tab); + if (tab) next.push(tab); } return next; } @@ -1022,13 +1021,65 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern }; } +function repairDuplicateTabIds(root: SplitNodeInternal): { + root: SplitNodeInternal; + ambiguousIds: ReadonlySet; +} { + const keepers = new Map(); + const ambiguousIds = new Set(); + for (const tab of collectAllTabs(root)) { + const keeper = keepers.get(tab.tabId); + if (!keeper) { + keepers.set(tab.tabId, tab); + continue; + } + ambiguousIds.add(tab.tabId); + if ( + buildDeterministicWorkspaceTabId(tab.target) === tab.tabId && + buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId + ) { + keepers.set(tab.tabId, tab); + } + } + if (ambiguousIds.size === 0) return { root, ambiguousIds }; + + // Reserve every original id before assigning replacements, including hidden panes. + const occupiedIds = new Set(keepers.keys()); + function repair(node: SplitNodeInternal): SplitNodeInternal { + if (node.kind === "group") { + return { ...node, group: { ...node.group, children: node.group.children.map(repair) } }; + } + const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId); + const focusedTab = + focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0]; + let focusedTabId = node.pane.focusedTabId; + const tabs = node.pane.tabs.map((tab) => { + if (keepers.get(tab.tabId) === tab) return tab; + const tabId = allocateWorkspaceTabId( + buildDeterministicWorkspaceTabId(tab.target), + occupiedIds, + ); + occupiedIds.add(tabId); + if (tab === focusedTab) focusedTabId = tabId; + return { ...tab, tabId }; + }); + return { + ...node, + pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId }, + }; + } + return { root: repair(root), ambiguousIds }; +} + export function normalizeLayout(layout: unknown): WorkspaceLayout { if (!layout || typeof layout !== "object") { return createDefaultLayout(); } const rawLayout = layout as WorkspaceLayout; - const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root); + const { root, ambiguousIds } = repairDuplicateTabIds( + normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root), + ); const focusedPaneId = rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId); const resolvedFocusedPaneId = @@ -1047,7 +1098,16 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout { openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)), }); - return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout; + if (parentTabIdByTabId) { + // A duplicated id cannot identify either end of a parent relationship unambiguously. + for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) { + if (ambiguousIds.has(childId) || ambiguousIds.has(parentId)) + delete parentTabIdByTabId[childId]; + } + if (Object.keys(parentTabIdByTabId).length > 0) + return { ...normalizedLayout, parentTabIdByTabId }; + } + return normalizedLayout; } export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null { @@ -1364,7 +1424,9 @@ function insertNewTabIntoPane( return null; } - const tabId = input.createTabId(); + const occupiedIds = new Set(input.reservedTabIds); + for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId); + const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds); const nextTab: WorkspaceTab = { tabId, target: input.target, @@ -2284,6 +2346,7 @@ function openEntityTabWithoutFocusing(input: { layout: WorkspaceLayout; target: WorkspaceTabTarget; explorerSidebarPaneId: string | null; + reservedTabIds: ReadonlySet | undefined; }): WorkspaceLayout { return ( insertNewTabIntoPane({ @@ -2292,6 +2355,7 @@ function openEntityTabWithoutFocusing(input: { now: Date.now(), placement: AMBIENT_PLACEMENT, explorerSidebarPaneId: input.explorerSidebarPaneId, + reservedTabIds: input.reservedTabIds, createTabId: () => buildDeterministicWorkspaceTabId(input.target), focus: false, })?.layout ?? input.layout @@ -2382,6 +2446,7 @@ function addMissingEntityTabs(input: { hasActivePendingTerminalCreate: boolean; hasActivePendingDraftCreate: boolean; explorerSidebarPaneId: string | null; + reservedTabIds: ReadonlySet | undefined; }): WorkspaceLayout { const { autoOpenAgentIds, @@ -2412,6 +2477,7 @@ function addMissingEntityTabs(input: { layout: nextLayout, target: { kind: "agent", agentId }, explorerSidebarPaneId, + reservedTabIds: input.reservedTabIds, }); currentAgentIds.add(agentId); } @@ -2426,6 +2492,7 @@ function addMissingEntityTabs(input: { layout: nextLayout, target: { kind: "terminal", terminalId }, explorerSidebarPaneId, + reservedTabIds: input.reservedTabIds, }); currentTerminalIds.add(terminalId); } @@ -2525,6 +2592,7 @@ export function reconcileWorkspaceTabs( hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false, hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false, explorerSidebarPaneId: state.explorerSidebarPaneId, + reservedTabIds: state.reservedTabIds, }); if (reconciledFocusedTabId) { diff --git a/packages/app/src/stores/workspace-layout-ids.ts b/packages/app/src/stores/workspace-layout-ids.ts index ce4009a2be..f325481af8 100644 --- a/packages/app/src/stores/workspace-layout-ids.ts +++ b/packages/app/src/stores/workspace-layout-ids.ts @@ -11,6 +11,22 @@ function createRandomIdValue(): string { : `${Date.now()}-${Math.random().toString(16).slice(2)}`; } +export function createWorkspaceTabInstanceId(): string { + return `tab_${createRandomIdValue()}`; +} + +/** A resource-derived id may still belong to a preview slot showing another target. */ +export function allocateWorkspaceTabId( + preferredId: string, + occupiedIds: ReadonlySet, +): string { + let tabId = preferredId; + for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) { + tabId = `${preferredId}:${suffix}`; + } + return tabId; +} + export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = { createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`, createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`, diff --git a/packages/app/src/stores/workspace-layout-persistence.test.ts b/packages/app/src/stores/workspace-layout-persistence.test.ts index 47c4ab81da..1c472400ac 100644 --- a/packages/app/src/stores/workspace-layout-persistence.test.ts +++ b/packages/app/src/stores/workspace-layout-persistence.test.ts @@ -59,6 +59,84 @@ it("skips unchanged reconciliations and immediately saves real layout changes", ); }); +it("hydrates a saved preview collision and persists the repaired identities", async () => { + const workspaceKey = "server:workspace"; + const duplicateId = "file_a.ts"; + const values = new Map([ + [ + "workspace-layout-state", + JSON.stringify({ + version: 2, + state: { + layoutByWorkspace: { + [workspaceKey]: { + root: { + kind: "group", + group: { + id: "split", + direction: "horizontal", + sizes: [0.5, 0.5], + children: [ + { id: "main", path: "b.ts" }, + { id: "right", path: "a.ts" }, + ].map(({ id, path }) => ({ + kind: "pane", + pane: { + id, + tabIds: [duplicateId], + focusedTabId: duplicateId, + tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }], + }, + })), + }, + }, + focusedPaneId: "right", + }, + }, + }, + }), + ], + ]); + const storage: StateStorage = { + getItem: (name) => values.get(name) ?? null, + setItem: (name, value) => { + values.set(name, value); + }, + removeItem: (name) => { + values.delete(name); + }, + }; + const store = createWorkspaceLayoutStore(undefined, storage); + await store.persist.rehydrate(); + const layout = store.getState().layoutByWorkspace[workspaceKey]; + const tabs = collectAllTabs(layout.root); + + expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([ + "file_b.ts", + "file_a.ts", + ]); + expect( + deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target, + ).toEqual({ + kind: "file", + path: "b.ts", + }); + expect( + deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target, + ).toEqual({ + kind: "file", + path: "a.ts", + }); + store.getState().focusTab(workspaceKey, "file_b.ts"); + expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main"); + + const reloaded = createWorkspaceLayoutStore(undefined, storage); + await reloaded.persist.rehydrate(); + expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual( + store.getState().layoutByWorkspace[workspaceKey], + ); +}); + it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => { const values = new Map(); const storage: StateStorage = { diff --git a/packages/app/src/stores/workspace-layout-store.test.ts b/packages/app/src/stores/workspace-layout-store.test.ts index 6bb930334a..678f9f5ab6 100644 --- a/packages/app/src/stores/workspace-layout-store.test.ts +++ b/packages/app/src/stores/workspace-layout-store.test.ts @@ -906,6 +906,91 @@ describe("workspace-layout-store actions", () => { ).toEqual(override); }); + it("keeps reused file tabs unique and focuses the matching split pane", () => { + const workspaceKey = createWorkspaceKey(); + const store = workspaceLayoutStore.getState(); + const firstTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + })!; + store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" }); + const rightPaneId = store.splitPaneEmpty(workspaceKey, { + targetPaneId: "main", + position: "right", + }); + if (!rightPaneId) throw new Error("Expected a right split pane"); + const rightTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + placement: { mode: "pane", paneId: rightPaneId }, + })!; + + store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/b.ts" }, + intent: "reveal", + }); + store.focusTab(workspaceKey, rightTabId); + + const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey]; + const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file"); + expect({ + fileTabCount: fileTabs.length, + uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size, + fileTargets: fileTabs.map((tab) => tab.target), + focusedPaneId: layout.focusedPaneId, + }).toEqual({ + fileTabCount: 2, + uniqueFileTabCount: 2, + fileTargets: [ + { kind: "file", path: "src/b.ts" }, + { kind: "file", path: "src/a.ts" }, + ], + focusedPaneId: rightPaneId, + }); + }); + + it("allocates distinct ids across retained tabs, sheets, and background opens", () => { + const workspaceKey = createWorkspaceKey(); + const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds); + const store = layoutStore.getState(); + const fileTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + })!; + store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" }); + layoutStore.setState({ layoutMode: "compact" }); + const sheetTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + })!; + const selectedSheet = selectSheetTab(layoutStore.getState(), { + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + }); + expect(selectedSheet?.tab.tabId).toBe(sheetTabId); + const backgroundTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "background", + })!; + + expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3); + expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1); + expect( + collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root) + .filter((tab) => tab.target.kind === "file") + .map((tab) => tab.target), + ).toEqual([ + { kind: "file", path: "src/b.ts" }, + { kind: "file", path: "src/a.ts" }, + ]); + }); + it("keeps the tab instance when a panel receives a same-kind replacement", () => { const workspaceKey = createWorkspaceKey(); const store = workspaceLayoutStore.getState(); @@ -3200,6 +3285,75 @@ describe("workspace-layout-store actions", () => { ]); }); + it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => { + const file = (tabId: string, path: string) => ({ + tabId, + target: { kind: "file", path }, + createdAt: 1, + state: { treeVisible: true, treeWidth: 280 }, + }); + const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")]; + const rightTabs = [ + file("file_a.ts", "a.ts"), + file("file_b.ts", "b.ts"), + file("file_b.ts:2", "b.ts"), + file("child", "child.ts"), + file("parent", "parent.ts"), + ]; + const layout = normalizeLayout({ + root: { + kind: "group", + group: { + id: "root", + direction: "horizontal", + sizes: [0.4, 0.6], + children: [ + { + kind: "pane", + pane: { + id: "main", + tabs: leftTabs, + tabIds: leftTabs.map((tab) => tab.tabId), + focusedTabId: "file_a.ts", + }, + }, + { + kind: "pane", + pane: { + id: "right", + tabs: rightTabs, + tabIds: rightTabs.map((tab) => tab.tabId), + focusedTabId: "file_a.ts", + hidden: true, + }, + }, + ], + }, + }, + focusedPaneId: "main", + parentTabIdByTabId: { + "file_a.ts": "parent", + "file_b.ts": "file_a.ts", + child: "parent", + }, + }); + const tabs = collectAllTabs(layout.root); + + expect(tabs).toHaveLength(7); + expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7); + expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" }); + expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" }); + expect(tabs.slice(2)).toEqual(rightTabs); + expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]); + expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3"); + expect(findPaneById(layout.root, "right")).toMatchObject({ + hidden: true, + focusedTabId: "file_a.ts", + }); + expect(layout.parentTabIdByTabId).toEqual({ child: "parent" }); + expect(normalizeLayout(layout)).toEqual(layout); + }); + it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => { const tabs = [ { @@ -5110,6 +5264,50 @@ describe("compact workspace sheet", () => { expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]); }); + it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => { + seedAgents([ + { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" }, + { id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" }, + ]); + const store = createCompactStore(); + store.getState().openTab({ + workspaceKey, + target: { kind: "agent", agentId: "child-a" }, + intent: "reveal", + }); + const sheetId = requireTopSheet(store).tab.tabId; + store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" }); + seedAgents([ + { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" }, + ]); + + store.getState().reconcileTabs(workspaceKey, { + agentsHydrated: true, + terminalsHydrated: true, + activeAgentIds: ["root", "child-a", "child-b"], + autoOpenAgentIds: ["child-a"], + knownTerminalIds: ["term-1"], + standaloneTerminalIds: ["term-1"], + }); + const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find( + (candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a", + ); + if (!tab) throw new Error("Expected the root agent's tab"); + expect(tab.tabId).not.toBe(sheetId); + + store.getState().closeTab(workspaceKey, tab.tabId); + expect(requireTopSheet(store).tab).toMatchObject({ + tabId: sheetId, + target: { kind: "agent", agentId: "child-b" }, + }); + expect( + collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root), + ).not.toContainEqual(tab); + }); + it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => { seedAgents([ { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, diff --git a/packages/app/src/stores/workspace-layout-store.ts b/packages/app/src/stores/workspace-layout-store.ts index 3e0d14ba6b..f0f6cc308b 100644 --- a/packages/app/src/stores/workspace-layout-store.ts +++ b/packages/app/src/stores/workspace-layout-store.ts @@ -7,6 +7,8 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage" import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model"; import { + allocateWorkspaceTabId, + createWorkspaceTabInstanceId, defaultWorkspaceLayoutIds, type WorkspaceLayoutIdSource, } from "@/stores/workspace-layout-ids"; @@ -431,14 +433,6 @@ function trimNonEmpty(value: string | null | undefined): string | null { return trimmed.length > 0 ? trimmed : null; } -function createWorkspaceTabInstanceId(): string { - const value = - typeof globalThis.crypto?.randomUUID === "function" - ? globalThis.crypto.randomUUID() - : `${Date.now()}-${Math.random().toString(16).slice(2)}`; - return `tab_${value}`; -} - function addAgentIdToWorkspaceSet( state: Record>, workspaceKey: string, @@ -531,7 +525,10 @@ export function selectExplorerSidebarPaneId( */ export function selectSheetTab( state: Pick, - input: Pick, + input: Pick & { + /** A host outside the sheet stack owns its instance identity. */ + preferredTabId?: string; + }, ): SheetTab | null { const workspaceKey = trimNonEmpty(input.workspaceKey); const target = normalizeWorkspaceTabTarget(input.target); @@ -539,9 +536,14 @@ export function selectSheetTab( const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal"); if (!policy) return null; return placeTargetInSheet({ - kept: undefined, + occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey), + kept: input.preferredTabId + ? undefined + : getSheets(state, workspaceKey).find( + (sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target), + ), target, - intent: "reveal", + createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target), policy, parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId), state: undefined, @@ -638,6 +640,7 @@ function getOpenTabPlacement( layout: WorkspaceLayout; placement: WorkspaceTabPlacement; explorerSidebarPaneId: string | null; + reservedTabIds: Set; } { const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey); const explorerSidebarPaneId = resolveExplorerSidebarPaneId( @@ -670,6 +673,7 @@ function getOpenTabPlacement( layout, placement: resolvedPlacement, explorerSidebarPaneId, + reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)), }; } @@ -815,11 +819,23 @@ function resolveOpenParentTabId( return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId; } +function collectWorkspaceTabIds( + state: Pick, + workspaceKey: string, +): Set { + const layout = state.layoutByWorkspace[workspaceKey]; + return new Set([ + ...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []), + ...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId), + ]); +} + function placeTargetInSheet(input: { + occupiedTabIds: ReadonlySet; /** The sheet whose tab the target keeps, if any. */ kept: SheetTab | undefined; target: WorkspaceTabTarget; - intent: WorkspaceTabOpenIntent; + createTabId: () => string; policy: CompactSheetPolicy; parentTabId: string | null; state: JsonValue | undefined; @@ -829,10 +845,7 @@ function placeTargetInSheet(input: { } return { tab: { - tabId: - input.intent === "reveal" - ? buildDeterministicWorkspaceTabId(input.target) - : createWorkspaceTabInstanceId(), + tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds), target: input.target, createdAt: Date.now(), ...(input.state !== undefined ? { state: input.state } : {}), @@ -853,6 +866,7 @@ function promoteSheetToTab( ): { tabId: string; patch: Partial } | null { const { tab } = sheet; const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT); + placement.reservedTabIds.delete(tab.tabId); const input = { ...placement, target: tab.target, @@ -1122,9 +1136,13 @@ export function createWorkspaceLayoutStore( const sheets = getSheets(get(), normalizedWorkspaceKey); const { keptIndex } = sheetPlacement; const sheet = placeTargetInSheet({ + occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey), kept: keptIndex === null ? undefined : sheets[keptIndex], target: normalizedTarget, - intent: input.intent, + createTabId: () => + input.intent === "reveal" + ? buildDeterministicWorkspaceTabId(normalizedTarget) + : createWorkspaceTabInstanceId(), policy: sheetPlacement.policy, parentTabId, state: input.state, @@ -1706,9 +1724,14 @@ export function createWorkspaceLayoutStore( explorerSidebarPaneId, rawLayout.focusedPaneId, ); + const sheets = getSheets(state, normalizedWorkspaceKey); + const fittingSheets = sheets.filter( + (sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot), + ); const nextState = reconcileWorkspaceTabs( { layout: currentLayout, + reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)), pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null, hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null, explorerSidebarPaneId, @@ -1730,10 +1753,6 @@ export function createWorkspaceLayoutStore( ); } } - const sheets = getSheets(state, normalizedWorkspaceKey); - const fittingSheets = sheets.filter( - (sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot), - ); const sheetAgentGone = fittingSheets.length !== sheets.length; if ( state.layoutByWorkspace[normalizedWorkspaceKey] && diff --git a/packages/app/src/styles/derive-colors.ts b/packages/app/src/styles/derive-colors.ts new file mode 100644 index 0000000000..bc2661b92c --- /dev/null +++ b/packages/app/src/styles/derive-colors.ts @@ -0,0 +1,90 @@ +/** + * The relationships between theme colors, stated once. + * + * A theme supplies places (a background, a sidebar) and identity (foreground, accent). What sits + * on top of a place — its hover, its selected state, the neutral fill of a chip, the text one + * notch quieter than muted — is a relationship, and is derived here so that no theme has to pick + * it by eye and no plugin has to borrow another role's color to fill it. + * + * Every step is a WCAG contrast ratio from the color it starts at, moving toward the foreground. + * A ratio keeps the step equally visible on every base; a lightness delta disappears near black. + * The numbers come from the default themes: Paseo dark and Light. + */ +import { contrastRatio, mixHexColors, stepContrast } from "@/utils/color"; + +export type ColorScheme = "light" | "dark"; + +const SURFACE_STATE_STEPS = { + dark: { hover: 1.11, selected: 1.245 }, + light: { hover: 1.15, selected: 1.35 }, +} as const; + +// Fills for chips, bubbles, tracks and secondary buttons, as `surface3` and `surface4`. +const NEUTRAL_FILL_STEPS = { + dark: { surface3: 1.8, surface4: 2.5 }, + light: { surface3: 1.27, surface4: 1.48 }, +} as const; + +// `surface3` carries text (message bubbles, secondary buttons, badges), so its step is bounded by +// the contrast the theme gives its own text: foreground stays at least this readable on it. The +// margin over 3:1 absorbs the rounding of the fill to 8-bit channels. +const NEUTRAL_FILL_TEXT_FLOOR = 3.05; +// The fill never steps less than this, so it stays visible against the page. A theme whose body +// text is under about 3.8:1 (3.05 x 1.25) cannot have both: the fill keeps this step and text on +// it falls under 3:1. +const NEUTRAL_FILL_MIN_STEP = 1.25; + +// Tertiary text: muted text, that fraction of the way toward the background, but never quieter +// than this contrast against it (or than the muted text itself, when that is already quieter). The +// margin over 2.5:1 absorbs the rounding to 8-bit channels. +const TERTIARY_TEXT_FADE = 0.35; +const TERTIARY_TEXT_FLOOR = 2.55; + +/** Hover and selected fills for a row that sits on `surface`. */ +export function deriveSurfaceStates( + surface: string, + foreground: string, + scheme: ColorScheme, +): { hover: string; selected: string } { + const steps = SURFACE_STATE_STEPS[scheme]; + return { + hover: stepContrast(surface, foreground, steps.hover), + selected: stepContrast(surface, foreground, steps.selected), + }; +} + +/** The neutral fills that sit on the page background. */ +export function deriveNeutralFills( + background: string, + foreground: string, + scheme: ColorScheme, +): { surface3: string; surface4: string } { + const steps = NEUTRAL_FILL_STEPS[scheme]; + // Foreground on the fill is about (foreground on background) / step. + const textBound = contrastRatio(background, foreground) / NEUTRAL_FILL_TEXT_FLOOR; + return { + surface3: stepContrast( + background, + foreground, + Math.max(NEUTRAL_FILL_MIN_STEP, Math.min(steps.surface3, textBound)), + ), + surface4: stepContrast(background, foreground, steps.surface4), + }; +} + +export function deriveTertiaryText(mutedForeground: string, background: string): string { + const faded = mixHexColors(mutedForeground, background, TERTIARY_TEXT_FADE); + const floor = Math.min(TERTIARY_TEXT_FLOOR, contrastRatio(background, mutedForeground)); + if (contrastRatio(background, faded) >= floor) return faded; + return stepContrast(background, mutedForeground, floor); +} + +/** Keep page tertiary text where it is readable; otherwise derive it against the row state. */ +export function deriveSidebarStateText( + tertiary: string, + surface: string, + foreground: string, +): string { + if (contrastRatio(tertiary, surface) >= TERTIARY_TEXT_FLOOR) return tertiary; + return stepContrast(surface, foreground, TERTIARY_TEXT_FLOOR); +} diff --git a/packages/app/src/styles/theme-contrast.test.ts b/packages/app/src/styles/theme-contrast.test.ts new file mode 100644 index 0000000000..e32964704e --- /dev/null +++ b/packages/app/src/styles/theme-contrast.test.ts @@ -0,0 +1,219 @@ +import { describe, expect, it } from "vitest"; +import type { PluginThemeContribution } from "@getpaseo/plugin"; +import { buildPluginTheme } from "@/plugins/themes"; +import { contrastRatio } from "@/utils/color"; +import { THEME_OPTIONS, type Theme } from "./theme"; + +// Palettes of the plugin themes users run into: Catppuccin (the e2e fixture) and +// @mousebomb/paseo-solarized 0.1.1, the palette behind issue #7471. +const LATTE: PluginThemeContribution = { + id: "latte", + name: "Catppuccin Latte", + appearance: "light", + colors: { + background: "#eff1f5", + foreground: "#4c4f69", + raised: "#e6e9ef", + control: "#dce0e8", + border: "#ccd0da", + accent: "#8839ef", + mutedForeground: "#6c6f85", + ring: "#9ca0b0", + }, +}; + +const MOCHA: PluginThemeContribution = { + id: "mocha", + name: "Catppuccin Mocha", + appearance: "dark", + colors: { + background: "#1e1e2e", + foreground: "#cdd6f4", + raised: "#313244", + control: "#45475a", + border: "#45475a", + accent: "#cba6f7", + mutedForeground: "#a6adc8", + ring: "#6c7086", + }, +}; + +const SOLARIZED_LIGHT: PluginThemeContribution = { + id: "solarized-light", + name: "Solarized Light", + appearance: "light", + colors: { + background: "#fdf6e3", + foreground: "#657b83", + raised: "#eee8d5", + control: "#eee8d5", + border: "#e6e0cd", + accent: "#cb4b16", + mutedForeground: "#839496", + ring: "#586e75", + }, +}; + +const SOLARIZED_DARK: PluginThemeContribution = { + id: "solarized-dark", + name: "Solarized Dark", + appearance: "dark", + colors: { + background: "#002b36", + foreground: "#839496", + raised: "#073642", + control: "#073642", + border: "#073642", + accent: "#268bd2", + mutedForeground: "#586e75", + ring: "#93a1a1", + }, +}; + +const themes: Array<{ name: string; theme: Theme }> = [ + ...THEME_OPTIONS.flatMap((option) => + "theme" in option ? [{ name: option.name, theme: option.theme as Theme }] : [], + ), + ...[LATTE, MOCHA, SOLARIZED_LIGHT, SOLARIZED_DARK].map((contribution) => ({ + name: `plugin ${contribution.name}`, + theme: buildPluginTheme(contribution), + })), +]; + +// Contrast floors. A state is a fixed step from the surface it sits on; the built-in Paseo dark +// and Light themes sit at about 1.11/1.25 and 1.15/1.35. +const HOVER_STEP = 1.08; +const SELECTED_STEP = 1.2; +const SELECTED_OVER_HOVER_STEP = 1.04; +// Text on a selected row may cost at most 40% of the legibility the theme gives its own text, and +// never drops below the floor for large UI text. +const SELECTED_TEXT_KEEPS = 0.6; +const SELECTED_TEXT_FLOOR = 2.5; +const NEUTRAL_FILL_STEP = 1.2; +const NEUTRAL_FILL_TEXT_FLOOR = 3; +const TERTIARY_TEXT_FLOOR = 2.5; +// The bright hues are dim on a cream or white background by design; the floor only has to catch a +// color that disappears. +const TERMINAL_COLOR_FLOOR = 1.5; + +it("keeps Solarized Dark's selected workspace timestamp readable", () => { + const { colors } = buildPluginTheme(SOLARIZED_DARK); + expect( + contrastRatio(colors.foregroundSidebarSelected, colors.surfaceSidebarSelected), + ).toBeGreaterThanOrEqual(2.5); +}); + +describe.each(themes)("$name", ({ theme }) => { + const colors = theme.colors; + + it("separates a hovered and a selected sidebar row from the sidebar", () => { + expect(contrastRatio(colors.surfaceSidebar, colors.surfaceSidebarHover)).toBeGreaterThanOrEqual( + HOVER_STEP, + ); + expect( + contrastRatio(colors.surfaceSidebar, colors.surfaceSidebarSelected), + ).toBeGreaterThanOrEqual(SELECTED_STEP); + expect( + contrastRatio(colors.surfaceSidebarHover, colors.surfaceSidebarSelected), + ).toBeGreaterThanOrEqual(SELECTED_OVER_HOVER_STEP); + }); + + it("keeps the selected row's title readable", () => { + const onSidebar = contrastRatio(colors.foreground, colors.surfaceSidebar); + const onSelected = contrastRatio(colors.foreground, colors.surfaceSidebarSelected); + expect(onSelected).toBeGreaterThanOrEqual(SELECTED_TEXT_FLOOR); + expect(onSelected).toBeGreaterThanOrEqual(onSidebar * SELECTED_TEXT_KEEPS); + }); + + it("keeps the neutral fill apart from the page and readable under text", () => { + expect(contrastRatio(colors.surface0, colors.surface3)).toBeGreaterThanOrEqual( + NEUTRAL_FILL_STEP, + ); + expect(contrastRatio(colors.foreground, colors.surface3)).toBeGreaterThanOrEqual( + NEUTRAL_FILL_TEXT_FLOOR, + ); + }); + + it("keeps terminal text readable on the terminal background", () => { + const terminal = colors.terminal; + const { background, ...palette } = terminal; + // The whites and black are fills as often as text, so only the hues are held to a floor. + for (const key of [ + "red", + "green", + "yellow", + "blue", + "magenta", + "cyan", + "brightRed", + "brightGreen", + "brightYellow", + "brightBlue", + "brightMagenta", + "brightCyan", + ] as const) { + expect(contrastRatio(background, palette[key]), key).toBeGreaterThanOrEqual( + TERMINAL_COLOR_FLOOR, + ); + } + }); +}); + +describe.each(themes.filter(({ name }) => name.startsWith("plugin ")))( + "$name derived text", + ({ theme }) => { + it("keeps tertiary text readable on the page", () => { + expect( + contrastRatio(theme.colors.surface0, theme.colors.foregroundExtraMuted), + ).toBeGreaterThanOrEqual(TERTIARY_TEXT_FLOOR); + }); + it("keeps passive text readable on hovered and selected sidebar rows", () => { + expect( + contrastRatio(theme.colors.foregroundSidebarHover, theme.colors.surfaceSidebarHover), + ).toBeGreaterThanOrEqual(TERTIARY_TEXT_FLOOR); + expect( + contrastRatio(theme.colors.foregroundSidebarSelected, theme.colors.surfaceSidebarSelected), + ).toBeGreaterThanOrEqual(TERTIARY_TEXT_FLOOR); + expect(contrastRatio(theme.colors.surface0, theme.colors.foregroundExtraMuted)).toBeLessThan( + contrastRatio(theme.colors.surface0, theme.colors.foreground), + ); + }); + }, +); + +describe("a plugin theme whose own text is quiet", () => { + it("still separates the neutral fill from the page", () => { + const { colors } = buildPluginTheme({ + ...MOCHA, + colors: { ...MOCHA.colors, background: "#202020", foreground: "#6a6a6a" }, + }); + expect(contrastRatio(colors.surface0, colors.surface3)).toBeGreaterThanOrEqual( + NEUTRAL_FILL_STEP, + ); + }); +}); + +describe("a plugin theme with body text between 3:1 and 3.8:1", () => { + it("keeps the fill visible and lets text on it fall under 3:1", () => { + const { colors } = buildPluginTheme({ + ...MOCHA, + colors: { ...MOCHA.colors, background: "#202020", foreground: "#757575" }, + }); + expect(contrastRatio(colors.surface0, colors.foreground)).toBeLessThan(3.8); + expect(contrastRatio(colors.surface0, colors.surface3)).toBeGreaterThanOrEqual( + NEUTRAL_FILL_STEP, + ); + expect(contrastRatio(colors.foreground, colors.surface3)).toBeLessThan(NEUTRAL_FILL_TEXT_FLOOR); + }); +}); + +describe("built-in themes", () => { + it.each(themes.filter(({ name }) => !name.startsWith("plugin ")))( + "$name keeps a control hover visible on the workspace surface", + ({ theme }) => { + expect( + contrastRatio(theme.colors.surfaceWorkspace, theme.colors.surface2), + ).toBeGreaterThanOrEqual(1.09); + }, + ); +}); diff --git a/packages/app/src/styles/theme.test.ts b/packages/app/src/styles/theme.test.ts index 461d980ecd..7ccb92cadd 100644 --- a/packages/app/src/styles/theme.test.ts +++ b/packages/app/src/styles/theme.test.ts @@ -53,12 +53,10 @@ describe("Pure black theme", () => { expect(darkPureBlackTheme.colors.accentBright).toBe("#7ccba0"); }); - it("derives sidebar interaction surfaces from the surface scale", () => { + it("steps its sidebar hover and selection off the black sidebar", () => { expect(darkPureBlackTheme.colors.surfaceSidebar).toBe("#000000"); - expect(darkPureBlackTheme.colors.surfaceSidebarHover).toBe(darkPureBlackTheme.colors.surface1); - expect(darkPureBlackTheme.colors.surfaceSidebarSelected).toBe( - darkPureBlackTheme.colors.surface2, - ); + expect(darkPureBlackTheme.colors.surfaceSidebarHover).toBe("#111111"); + expect(darkPureBlackTheme.colors.surfaceSidebarSelected).toBe("#1d1d1d"); }); it("keeps ANSI black output readable on its zero-luminance terminal background", () => { @@ -67,16 +65,26 @@ describe("Pure black theme", () => { }); }); +// Hover and selected are derived from the sidebar color. The values the default themes had when +// they were picked by eye are the reference: derivation lands within a few RGB units of them. describe("Sidebar interaction surfaces", () => { - it("keeps Light hover and selection darker than the sidebar surface", () => { - expect(lightTheme.colors.surfaceSidebarHover).toBe(lightTheme.colors.surface3); - expect(lightTheme.colors.surfaceSidebarSelected).toBe(lightTheme.colors.surface4); - expect(lightTheme.colors.surfaceSidebarSelected).not.toBe(lightTheme.colors.surfaceSidebar); + function expectWithin(actual: string, expected: string, units: number) { + const channels = (hex: string) => + [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16)); + const expectedChannels = channels(expected); + channels(actual).forEach((channel, index) => { + expect(Math.abs(channel - expectedChannels[index])).toBeLessThanOrEqual(units); + }); + } + + it("keeps Light hover and selection where they were", () => { + expectWithin(lightTheme.colors.surfaceSidebarHover, "#e4e4e7", 3); + expectWithin(lightTheme.colors.surfaceSidebarSelected, "#d4d4d8", 3); }); - it("derives Dark hover and selection from the first two raised surfaces", () => { - expect(darkTheme.colors.surfaceSidebarHover).toBe(darkTheme.colors.surface1); - expect(darkTheme.colors.surfaceSidebarSelected).toBe(darkTheme.colors.surface2); + it("keeps Dark hover and selection where they were", () => { + expectWithin(darkTheme.colors.surfaceSidebarHover, "#1e2120", 2); + expectWithin(darkTheme.colors.surfaceSidebarSelected, "#272a29", 2); }); }); @@ -86,7 +94,6 @@ describe("Built-in light theme", () => { primary: "#18181b", primaryForeground: "#fafafa", destructiveForeground: "#ffffff", - successForeground: "#ffffff", terminal: { black: "#1a1a1e", brightBlack: "#3f3f46", diff --git a/packages/app/src/styles/theme.ts b/packages/app/src/styles/theme.ts index 9b941543fe..f90594fa55 100644 --- a/packages/app/src/styles/theme.ts +++ b/packages/app/src/styles/theme.ts @@ -1,5 +1,6 @@ import { Platform } from "react-native"; import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight"; +import { deriveSurfaceStates } from "./derive-colors"; export const baseColors = { // Base colors @@ -223,8 +224,11 @@ export interface LightThemeConfig { surface2: string; surface3: string; surface4: string; - surfaceDiffEmpty: string; surfaceSidebar: string; + surfaceSidebarHover?: string; + surfaceSidebarSelected?: string; + foregroundSidebarHover?: string; + foregroundSidebarSelected?: string; foreground: string; foregroundMuted: string; foregroundExtraMuted: string; @@ -238,7 +242,7 @@ export interface LightThemeConfig { destructive: string; terminalBlack: string; terminalBrightBlack: string; - ring: string; + ring?: string; } const lightTerminalAnsi = { @@ -259,16 +263,18 @@ const lightTerminalAnsi = { } as const; export function buildLightSemanticColors(tint: LightThemeConfig) { + const sidebarStates = deriveSurfaceStates(tint.surfaceSidebar, tint.foreground, "light"); return { surface0: tint.surface0, surface1: tint.surface1, surface2: tint.surface2, surface3: tint.surface3, surface4: tint.surface4, - surfaceDiffEmpty: tint.surfaceDiffEmpty, surfaceSidebar: tint.surfaceSidebar, - surfaceSidebarHover: tint.surface3, - surfaceSidebarSelected: tint.surface4, + surfaceSidebarHover: tint.surfaceSidebarHover ?? sidebarStates.hover, + surfaceSidebarSelected: tint.surfaceSidebarSelected ?? sidebarStates.selected, + foregroundSidebarHover: tint.foregroundSidebarHover ?? tint.foregroundExtraMuted, + foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted, surfaceWorkspace: tint.surface0, interactionHighlight: "rgba(0, 0, 0, 0.06)", @@ -286,20 +292,14 @@ export function buildLightSemanticColors(tint: LightThemeConfig) { destructive: tint.destructive, destructiveForeground: tint.surface0, success: tint.accent, - successForeground: tint.surface0, background: tint.surface0, popover: tint.surface0, popoverForeground: tint.foreground, primary: tint.primary, primaryForeground: tint.primaryForeground, - secondary: tint.surface2, - secondaryForeground: tint.foreground, - muted: tint.surface2, mutedForeground: tint.foregroundMuted, - accentBorder: tint.borderAccent, - input: tint.surface2, - ring: tint.ring, + ring: tint.ring ?? tint.accent, ...lightDiffColors, ...lightStatusColors, @@ -326,7 +326,6 @@ const lightSemanticColors = buildLightSemanticColors({ surface2: "#f4f4f5", surface3: "#e4e4e7", surface4: "#d4d4d8", - surfaceDiffEmpty: "#f6f6f6", surfaceSidebar: "#f4f4f5", foreground: "#1a1a1e", foregroundMuted: "#71717a", @@ -341,7 +340,6 @@ const lightSemanticColors = buildLightSemanticColors({ destructive: "#b04138", terminalBlack: "#1a1a1e", terminalBrightBlack: "#3f3f46", - ring: "#18181b", }); // --------------------------------------------------------------------------- @@ -354,8 +352,11 @@ export interface DarkThemeConfig { surface2: string; surface3: string; surface4: string; - surfaceDiffEmpty: string; surfaceSidebar: string; + surfaceSidebarHover?: string; + surfaceSidebarSelected?: string; + foregroundSidebarHover?: string; + foregroundSidebarSelected?: string; foregroundMuted: string; foregroundExtraMuted: string; border: string; @@ -389,17 +390,19 @@ const darkTerminalAnsi = { export function buildDarkSemanticColors(tint: DarkThemeConfig) { const foreground = tint.foreground ?? "#fafafa"; - const ring = tint.ring ?? "#d4d4d8"; + const ring = tint.ring ?? tint.accent; + const sidebarStates = deriveSurfaceStates(tint.surfaceSidebar, foreground, "dark"); return { surface0: tint.surface0, surface1: tint.surface1, surface2: tint.surface2, surface3: tint.surface3, surface4: tint.surface4, - surfaceDiffEmpty: tint.surfaceDiffEmpty, surfaceSidebar: tint.surfaceSidebar, - surfaceSidebarHover: tint.surface1, - surfaceSidebarSelected: tint.surface2, + surfaceSidebarHover: tint.surfaceSidebarHover ?? sidebarStates.hover, + surfaceSidebarSelected: tint.surfaceSidebarSelected ?? sidebarStates.selected, + foregroundSidebarHover: tint.foregroundSidebarHover ?? tint.foregroundExtraMuted, + foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted, surfaceWorkspace: tint.surface1, interactionHighlight: "rgba(255, 255, 255, 0.08)", @@ -417,7 +420,6 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) { destructive: tint.destructive, destructiveForeground: "#ffffff", success: tint.accent, - successForeground: "#ffffff", // Legacy aliases (for gradual migration) background: tint.surface0, @@ -425,12 +427,7 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) { popoverForeground: foreground, primary: foreground, primaryForeground: tint.surface0, - secondary: tint.surface2, - secondaryForeground: foreground, - muted: tint.surface2, mutedForeground: tint.foregroundMuted, - accentBorder: tint.borderAccent, - input: tint.surface2, ring, ...darkDiffColors, @@ -463,7 +460,6 @@ const paseoDarkColors = buildDarkSemanticColors({ surface2: "#272A29", surface3: "#434645", surface4: "#595B5B", - surfaceDiffEmpty: "#252827", surfaceSidebar: "#141716", foregroundMuted: "#A1A5A4", foregroundExtraMuted: "#717574", @@ -483,7 +479,6 @@ const zincDarkColors = buildDarkSemanticColors({ surface2: "#27272a", surface3: "#3f3f46", surface4: "#52525b", - surfaceDiffEmpty: "#242427", surfaceSidebar: "#131316", foregroundMuted: "#a1a1aa", foregroundExtraMuted: "#71717a", @@ -504,7 +499,6 @@ const midnightDarkColors = buildDarkSemanticColors({ surface2: "#252731", surface3: "#3c3e4c", surface4: "#535564", - surfaceDiffEmpty: "#222430", surfaceSidebar: "#121420", foregroundMuted: "#9a9db0", foregroundExtraMuted: "#6b6e82", @@ -524,7 +518,6 @@ const claudeDarkColors = buildDarkSemanticColors({ surface2: "#2f2d2b", surface3: "#4a4745", surface4: "#605d5b", - surfaceDiffEmpty: "#2a2826", surfaceSidebar: "#1a1918", foregroundMuted: "#ada9a5", foregroundExtraMuted: "#78746f", @@ -544,7 +537,6 @@ const ghosttyDarkColors = buildDarkSemanticColors({ surface2: "#383c48", surface3: "#4a4f5e", surface4: "#5b6175", - surfaceDiffEmpty: "#323643", surfaceSidebar: "#21252d", foregroundMuted: "#c8ccd8", foregroundExtraMuted: "#a0a4b2", @@ -719,14 +711,15 @@ export const darkMidnightTheme = buildDarkTheme(midnightDarkColors); export const darkClaudeTheme = buildDarkTheme(claudeDarkColors); export const darkGhosttyTheme = buildDarkTheme(ghosttyDarkColors); -// Pure black — zero-luminance background with high-contrast surfaces. +// Pure black — zero-luminance background with high-contrast surfaces. A control over the +// workspace surface (`surface2` on `surface1`) steps by a contrast ratio of 1.12, the step Paseo +// dark has there; the old `#111111` gave half of it. const pureBlackDarkColors = buildDarkSemanticColors({ surface0: "#000000", surface1: "#0a0a0a", - surface2: "#111111", + surface2: "#181818", surface3: "#202020", surface4: "#2d2d2d", - surfaceDiffEmpty: "#0c0c0c", surfaceSidebar: "#000000", foregroundMuted: "#a1a1aa", foregroundExtraMuted: "#71717a", diff --git a/packages/app/src/subagents/open-tab-labels.test.ts b/packages/app/src/subagents/open-tab-labels.test.ts index 61874cd058..9cab01f11b 100644 --- a/packages/app/src/subagents/open-tab-labels.test.ts +++ b/packages/app/src/subagents/open-tab-labels.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from "vitest"; import type { Agent } from "@/stores/session-store"; import type { WorkspaceTab } from "@/workspace-tabs/model"; -import { getAgentTabsNeedingOpenLabel } from "./open-tab-labels"; +import { shallow } from "zustand/shallow"; +import { getAgentTabsNeedingOpenLabel, selectOpenTabAgents } from "./open-tab-labels"; const label = "paseo.open-agent-tab.client-1"; @@ -51,3 +52,54 @@ describe("getAgentTabsNeedingOpenLabel", () => { ).toEqual([]); }); }); + +describe("selectOpenTabAgents", () => { + function stateWith(agents: Agent[]) { + return { + sessions: { + srv: { agents: new Map(agents.map((entry) => [entry.id, entry])), agentDetails: new Map() }, + }, + }; + } + + it("stays equal when only an agent without an open tab changes", () => { + const open = agent({ id: "open" }); + const before = selectOpenTabAgents(stateWith([open, agent({ id: "elsewhere" })]), { + serverId: "srv", + agentIds: ["open"], + }); + const after = selectOpenTabAgents(stateWith([open, agent({ id: "elsewhere" })]), { + serverId: "srv", + agentIds: ["open"], + }); + + expect(shallow(before, after)).toBe(true); + }); + + it("changes when an agent with an open tab changes", () => { + const elsewhere = agent({ id: "elsewhere" }); + const before = selectOpenTabAgents(stateWith([agent({ id: "open" }), elsewhere]), { + serverId: "srv", + agentIds: ["open"], + }); + const after = selectOpenTabAgents(stateWith([agent({ id: "open" }), elsewhere]), { + serverId: "srv", + agentIds: ["open"], + }); + + expect(shallow(before, after)).toBe(false); + }); + + it("falls back to agent details and returns null for unknown agents", () => { + const detail = agent({ id: "detail" }); + const state = { + sessions: { + srv: { agents: new Map(), agentDetails: new Map([["detail", detail]]) }, + }, + }; + + expect( + selectOpenTabAgents(state, { serverId: "srv", agentIds: ["detail", "missing"] }), + ).toEqual([detail, null]); + }); +}); diff --git a/packages/app/src/subagents/open-tab-labels.ts b/packages/app/src/subagents/open-tab-labels.ts index ca7d8e63dc..df855a6df5 100644 --- a/packages/app/src/subagents/open-tab-labels.ts +++ b/packages/app/src/subagents/open-tab-labels.ts @@ -23,3 +23,24 @@ export function getAgentTabsNeedingOpenLabel(input: { } return [...agentIds]; } + +interface OpenTabAgentSource { + sessions: Record< + string, + { agents: ReadonlyMap; agentDetails: ReadonlyMap } | undefined + >; +} + +/** + * The agents behind the given open tabs, in tab order. Compared element by element, this changes + * only when one of those agents changes, not on updates to other agents on the host. + */ +export function selectOpenTabAgents( + state: OpenTabAgentSource, + input: { serverId: string; agentIds: readonly string[] }, +): (Agent | null)[] { + const session = state.sessions[input.serverId]; + return input.agentIds.map( + (agentId) => session?.agents.get(agentId) ?? session?.agentDetails.get(agentId) ?? null, + ); +} diff --git a/packages/app/src/subagents/sheet-tab.test.tsx b/packages/app/src/subagents/sheet-tab.test.tsx index c8e0ab7f13..ab57ab9082 100644 --- a/packages/app/src/subagents/sheet-tab.test.tsx +++ b/packages/app/src/subagents/sheet-tab.test.tsx @@ -138,6 +138,88 @@ describe("useSubagentSheetTab", () => { expect(result.current?.tab.tabId).toBe(tabId); }); + it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => { + const row = seedParentWithChild(); + const store = useWorkspaceLayoutStore.getState(); + const reusedId = store.openTab({ + workspaceKey, + target: { kind: "agent", agentId: "child" }, + intent: "reveal", + asTab: true, + }); + if (!reusedId) throw new Error("Expected a child tab"); + store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" }); + store.setLayoutMode("compact"); + const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row)); + const sheetId = result.current?.tab.tabId; + expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" }); + expect(sheetId).not.toBe(reusedId); + + act(() => { + store.reconcileTabs(workspaceKey, { + agentsHydrated: true, + terminalsHydrated: true, + activeAgentIds: ["parent", "child"], + autoOpenAgentIds: [], + knownTerminalIds: [], + standaloneTerminalIds: [], + }); + }); + expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId); + expect(result.current?.tab.tabId).toBe(sheetId); + expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" }); + }); + + it("promotes a menu sheet to the subagent's own tab", () => { + const row = seedParentWithChild(); + const store = useWorkspaceLayoutStore.getState(); + store.setLayoutMode("compact"); + const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row)); + const sheet = result.current; + if (!sheet) throw new Error("Expected a menu sheet"); + + let promotedId: string | null = null; + act(() => { + promotedId = store.openTabInFront(workspaceKey, sheet); + }); + expect(promotedId).toBe("agent_child"); + expect( + store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"), + ).toEqual([ + expect.objectContaining({ + tabId: "agent_child", + target: { kind: "agent", agentId: "child" }, + }), + ]); + }); + + it("does not reuse a menu id retained by a promoted tab showing another target", () => { + const row = seedParentWithChild(); + const store = useWorkspaceLayoutStore.getState(); + store.setLayoutMode("compact"); + const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row)); + const sheet = result.current; + if (!sheet) throw new Error("Expected a menu sheet"); + act(() => { + store.openTabInFront(workspaceKey, sheet); + }); + expect(result.current).toBeNull(); + + act(() => { + store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" }); + }); + expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" }); + expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId); + expect( + store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"), + ).toEqual([ + expect.objectContaining({ + tabId: sheet.tab.tabId, + target: { kind: "agent", agentId: "other" }, + }), + ]); + }); + it("hands a re-rendered row the same sheet", () => { const row = seedParentWithChild(); useWorkspaceLayoutStore.getState().setLayoutMode("compact"); diff --git a/packages/app/src/subagents/sheet-tab.ts b/packages/app/src/subagents/sheet-tab.ts index c81be94ced..783d81bc5d 100644 --- a/packages/app/src/subagents/sheet-tab.ts +++ b/packages/app/src/subagents/sheet-tab.ts @@ -4,6 +4,7 @@ import { useWorkspaceLayoutStore, type SheetTab, } from "@/stores/workspace-layout-store"; +import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity"; import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; import type { SubagentRow } from "./select"; @@ -32,6 +33,9 @@ export function useSubagentSheetTab( const sheets = useWorkspaceLayoutStore((state) => workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined, ); + // Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening + // it as a tab lands on that id, and keeps the id it was given across layout updates. + const tabIds = useMemo(() => new Map(), []); return useMemo(() => { // One answer per row until the state it reads changes, so a re-render of the list hands an // open sheet the same tab rather than a fresh one. @@ -43,16 +47,19 @@ export function useSubagentSheetTab( layoutByWorkspace: layout ? { [workspaceKey]: layout } : {}, sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {}, }; - const key = `${row.kind}:${row.id}`; + const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]); const known = answers.get(key); if (known !== undefined) return known; + const target = subagentRowTarget(row); const sheet = selectSheetTab(state, { workspaceKey, - target: subagentRowTarget(row), + target, parentTabId, + preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target), }); + if (sheet) tabIds.set(key, sheet.tab.tabId); answers.set(key, sheet); return sheet; }; - }, [layout, layoutMode, parentTabId, sheets, workspaceKey]); + }, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]); } diff --git a/packages/app/src/subagents/use-open-agent-tab-labels.ts b/packages/app/src/subagents/use-open-agent-tab-labels.ts index ea02fd1b16..7570d65465 100644 --- a/packages/app/src/subagents/use-open-agent-tab-labels.ts +++ b/packages/app/src/subagents/use-open-agent-tab-labels.ts @@ -1,10 +1,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { getOpenAgentTabLabel } from "@getpaseo/protocol/agent-labels"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { useShallow } from "zustand/shallow"; import { useSessionStore } from "@/stores/session-store"; import { getOrCreateClientId } from "@/utils/client-id"; import type { WorkspaceTab } from "@/workspace-tabs/model"; -import { getAgentTabsNeedingOpenLabel } from "./open-tab-labels"; +import { getAgentTabsNeedingOpenLabel, selectOpenTabAgents } from "./open-tab-labels"; function increment(value: number): number { return value + 1; @@ -16,9 +17,16 @@ export function useOpenAgentTabLabels(input: { tabs: WorkspaceTab[]; enabled: boolean; }): void { - const agents = useSessionStore((state) => state.sessions[input.serverId]?.agents ?? null); - const agentDetails = useSessionStore( - (state) => state.sessions[input.serverId]?.agentDetails ?? null, + const openAgentIds = useMemo( + () => input.tabs.flatMap((tab) => (tab.target.kind === "agent" ? [tab.target.agentId] : [])), + [input.tabs], + ); + // Only the agents with open tabs can need a label. Subscribing to the whole agent map would + // re-render the workspace screen on every update to any agent on the host. + const openAgents = useSessionStore( + useShallow((state) => + selectOpenTabAgents(state, { serverId: input.serverId, agentIds: openAgentIds }), + ), ); const pendingAgentIdsRef = useRef(new Set()); const retryTimerRef = useRef | null>(null); @@ -39,15 +47,13 @@ export function useOpenAgentTabLabels(input: { return; } - const openAgentIds = new Set( - input.tabs.flatMap((tab) => (tab.target.kind === "agent" ? [tab.target.agentId] : [])), - ); + const agentsById = new Map(openAgentIds.map((agentId, index) => [agentId, openAgents[index]])); for (const agentId of pendingAgentIdsRef.current) { - if (!openAgentIds.has(agentId)) { + if (!agentsById.has(agentId)) { pendingAgentIdsRef.current.delete(agentId); } } - if (openAgentIds.size === 0) { + if (agentsById.size === 0) { return; } @@ -57,7 +63,7 @@ export function useOpenAgentTabLabels(input: { const label = getOpenAgentTabLabel(clientId); const agentIds = getAgentTabsNeedingOpenLabel({ tabs: input.tabs, - getAgent: (agentId) => agents?.get(agentId) ?? agentDetails?.get(agentId), + getAgent: (agentId) => agentsById.get(agentId), label, pendingAgentIds: pendingAgentIdsRef.current, }); @@ -82,5 +88,5 @@ export function useOpenAgentTabLabels(input: { console.warn("[OpenAgentTabLabels] Failed to resolve client ID", { error }); } })(); - }, [agentDetails, agents, input.client, input.enabled, input.tabs, retryVersion]); + }, [input.client, input.enabled, input.tabs, openAgentIds, openAgents, retryVersion]); } diff --git a/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts b/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts index 01d3e398d5..1b92045fdb 100644 --- a/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts @@ -6,7 +6,7 @@ import { TERMINAL_INPUT_CONTEXT_MENU_HIDDEN, TERMINAL_INPUT_HITBOX_SIZE, } from "./terminal-input.native"; -import { forwardNativeTerminalKey, type NativeTerminalKeyEvent } from "./terminal-key-events"; +import { createNativeTerminalKeyEvent, resolveHardwareTerminalKey } from "./terminal-key-events"; describe("native terminal typed input", () => { function inputData(change: { data: string; shouldClear: boolean }): string { @@ -149,25 +149,18 @@ describe("native terminal typed input", () => { }); }); - it("forwards native arrow key events to the terminal key path", () => { - const events: NativeTerminalKeyEvent[] = []; - - forwardNativeTerminalKey({ - key: "ArrowUp", - onTerminalKey: (event) => { - events.push(event); - }, + it("identifies hardware arrows by code and keeps their modifiers", () => { + // UIKit leaves `key` as a sentinel for Left/Right, so the code leads. + expect(resolveHardwareTerminalKey({ key: "\uF702", code: "ArrowLeft" })).toBe("ArrowLeft"); + expect(resolveHardwareTerminalKey({ key: "ArrowUp", code: "" })).toBe("ArrowUp"); + expect(resolveHardwareTerminalKey({ key: "a", code: "KeyA" })).toBeNull(); + expect(createNativeTerminalKeyEvent("ArrowDown", { shift: true, alt: true })).toEqual({ + key: "ArrowDown", + ctrl: false, + shift: true, + alt: true, + meta: false, }); - - expect(events).toEqual([ - { - key: "ArrowUp", - ctrl: false, - shift: false, - alt: false, - meta: false, - }, - ]); }); it("keeps the hidden input from owning terminal long-press selection", () => { diff --git a/packages/app/src/terminal/native-renderer/terminal-input.native.tsx b/packages/app/src/terminal/native-renderer/terminal-input.native.tsx index 4eea8a1da3..7ca7020cb0 100644 --- a/packages/app/src/terminal/native-renderer/terminal-input.native.tsx +++ b/packages/app/src/terminal/native-renderer/terminal-input.native.tsx @@ -1,5 +1,6 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"; import { + Platform, StyleSheet, type NativeSyntheticEvent, type StyleProp, @@ -10,10 +11,19 @@ import { EditingTextInput as TextInput, type EditingTextInputHandle, } from "@/components/ui/text-input"; -import { resolveNativeTerminalKey, type NativeTerminalKey } from "./terminal-key-events"; +import { hasActiveOverlay, subscribeHardwareKeyboard } from "@/keyboard"; +import { + createNativeTerminalKeyEvent, + resolveHardwareTerminalKey, + resolveNativeTerminalKey, + type NativeTerminalKey, + type NativeTerminalKeyEvent, +} from "./terminal-key-events"; export const TERMINAL_INPUT_CONTEXT_MENU_HIDDEN = true; export const TERMINAL_INPUT_HITBOX_SIZE = 1; +/** Matched by the Android hardware keyboard module to claim arrow keys for this input. */ +export const TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"; export interface TerminalTextInputChange { data: string; @@ -39,7 +49,7 @@ interface TerminalInputProps { isKeyboardVisible: boolean; onFocus?: () => void; onInput?: (data: string) => void; - onTerminalKey?: (key: NativeTerminalKey) => void; + onTerminalKey?: (event: NativeTerminalKeyEvent) => void; style?: StyleProp; } @@ -187,6 +197,8 @@ export const TerminalInput = forwardRef const inputRef = useRef(null); const isFocusedRef = useRef(false); const pendingFocusFrameRef = useRef(null); + const onTerminalKeyRef = useRef(onTerminalKey); + onTerminalKeyRef.current = onTerminalKey; const inputState = useMemo(() => createTerminalTextInputState(), []); const inputStyle = useMemo(() => [styles.input, style], [style]); @@ -250,6 +262,27 @@ export const TerminalInput = forwardRef useEffect(() => clearPendingFocus, [clearPendingFocus]); + useEffect(() => { + // Physical arrows arrive through the native key stream, never through + // TextInput.onKeyPress (RN builds that event from the IME connection). + // The native module claims them for this input so the hidden buffer + // cannot move its caret, then re-emits them here for the PTY. + if (Platform.OS !== "android") return; + return subscribeHardwareKeyboard((event) => { + if (!isFocusedRef.current || event.phase !== "down" || event.isComposing) return; + if (hasActiveOverlay()) return; + const key = resolveHardwareTerminalKey(event); + if (!key) return; + onTerminalKeyRef.current?.({ + key, + ctrl: event.ctrlKey, + shift: event.shiftKey, + alt: event.altKey, + meta: event.metaKey, + }); + }); + }, []); + useImperativeHandle( ref, () => ({ @@ -293,7 +326,7 @@ export const TerminalInput = forwardRef (event: NativeSyntheticEvent) => { const change = inputState.receiveKeyPress(event.nativeEvent.key); if (change.key) { - onTerminalKey?.(change.key); + onTerminalKey?.(createNativeTerminalKeyEvent(change.key)); } if (change.data.length > 0) { onInput?.(change.data); @@ -321,6 +354,7 @@ export const TerminalInput = forwardRef blurOnSubmit={false} importantForAutofill="no" multiline={true} + nativeID={TERMINAL_INPUT_NATIVE_ID} onChangeText={handleChangeText} onBlur={handleBlur} onFocus={handleFocus} diff --git a/packages/app/src/terminal/native-renderer/terminal-key-events.ts b/packages/app/src/terminal/native-renderer/terminal-key-events.ts index 35b0a54f72..8d6aa8d44b 100644 --- a/packages/app/src/terminal/native-renderer/terminal-key-events.ts +++ b/packages/app/src/terminal/native-renderer/terminal-key-events.ts @@ -22,19 +22,26 @@ export function resolveNativeTerminalKey(key: string): NativeTerminalKey | null } } -export function createNativeTerminalKeyEvent(key: NativeTerminalKey): NativeTerminalKeyEvent { - return { - key, - ctrl: false, - shift: false, - alt: false, - meta: false, - }; +/** + * Physical keyboards report the DOM `code`. UIKit leaves `key` as a sentinel + * for Left/Right, so the code is the only reliable identifier there. + */ +export function resolveHardwareTerminalKey(input: { + key?: string; + code?: string; +}): NativeTerminalKey | null { + return resolveNativeTerminalKey(input.code ?? "") ?? resolveNativeTerminalKey(input.key ?? ""); } -export function forwardNativeTerminalKey(input: { - key: NativeTerminalKey; - onTerminalKey?: NativeTerminalKeyHandler; -}): void { - input.onTerminalKey?.(createNativeTerminalKeyEvent(input.key)); +export function createNativeTerminalKeyEvent( + key: NativeTerminalKey, + modifiers: { ctrl?: boolean; shift?: boolean; alt?: boolean; meta?: boolean } = {}, +): NativeTerminalKeyEvent { + return { + key, + ctrl: modifiers.ctrl ?? false, + shift: modifiers.shift ?? false, + alt: modifiers.alt ?? false, + meta: modifiers.meta ?? false, + }; } diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts index bf044237b0..a875ae5a3a 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts @@ -115,6 +115,26 @@ interface CreateTerminalHostInput { isMac?: boolean; } +/** Text typed into xterm's textarea, as the browser reports a typed character. */ +function typeText(mounted: MountedTerminal, text: string): void { + mounted.host + .querySelector(".xterm-helper-textarea") + ?.dispatchEvent( + new InputEvent("input", { data: text, inputType: "insertText", bubbles: true }), + ); +} + +/** A native paste of plain text into xterm's textarea. */ +function pasteText(mounted: MountedTerminal, text: string): void { + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", text); + mounted.host + .querySelector(".xterm-helper-textarea") + ?.dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); +} + function createTerminalHost(input: CreateTerminalHostInput): MountedTerminal { const root = document.createElement("div"); root.style.width = `${input.width}px`; @@ -824,6 +844,23 @@ describe("incremental replay lifecycle", () => { expect(mounted.inputs[0]?.startsWith("\x1b]4;1;rgb:")).toBe(true); }); + it("keeps what the user types, but not pastes, while a replay is still parsing", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + await waitFor({ predicate: () => mounted.sizes.length > 0 }); + mounted.runtime.replay({ type: "begin" }); + mounted.runtime.replay({ type: "data", data: terminalOutput("\x1b]4;1;?\x07restored") }); + mounted.runtime.replay({ type: "end" }); + + typeText(mounted, "a"); + pasteText(mounted, "echo one\necho two\n"); + typeText(mounted, "f"); + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("live"), onCommitted: resolve }), + ); + + expect(mounted.inputs).toEqual(["a", "f"]); + }); + it("measures emoji clusters with the daemon's grapheme widths and copies them intact", async () => { const mounted = createTerminalHost({ width: 720, height: 360 }); const text = "A😀B❤️C👋🏽D👨‍👩‍👧E"; diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index ae74a4945f..3aaf1e1393 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -124,6 +124,7 @@ interface TerminalEmulatorRuntimeDisposables { clearFitTimeouts: () => void; removeFontListeners: () => void; removeFilePasteListener: () => void; + removeUserInputListeners: () => void; restoreDocumentStyles: () => void; restoreViewportStyles: () => void; disposeFitAddon: () => void; @@ -157,6 +158,10 @@ const isAppleHandheld = const FIT_TIMEOUT_DELAYS_MS = [0, 16, 48, 120, 250, 500, 1_000, 2_000]; const OUTPUT_OPERATION_TIMEOUT_MS = 5_000; const EMPTY_TERMINAL_OUTPUT = new Uint8Array(0); +// DOM events xterm turns into typed data on its textarea. Pastes stay suppressed during a +// replay: until the snapshot restores bracketed paste mode, a multi-line paste would run +// line by line in the shell. +const USER_INPUT_EVENT_TYPES = ["keydown", "keypress", "input"] as const; const RESET_TERMINAL_OUTPUT = new Uint8Array([0x1b, 0x63]); const terminalOutputEncoder = new TextEncoder(); @@ -313,6 +318,8 @@ export class TerminalEmulatorRuntime { private hasUngatedWrites = false; private readonly inputModeDecoder = new TextDecoder(); private suppressInput = false; + // The latest user input event the host saw; its eventPhase is NONE once dispatch ends. + private userInputEvent: Event | null = null; private readonly inputModeTracker = new TerminalInputModeTracker(); private lastInputModeState: TerminalInputModeState = this.inputModeTracker.getState(); private themeBackgroundElements: HTMLElement[] = []; @@ -739,8 +746,17 @@ export class TerminalEmulatorRuntime { fitAndEmitResize({ forceRefresh: true, shouldClaim: false }); + // xterm reports what the user types and the replies it generates while parsing + // through the same onData. Replies only come out of parsing a write, never while a + // user input event is dispatching, so typing survives a replay that suppresses them. + const recordUserInputEvent = (event: Event): void => { + this.userInputEvent = event; + }; + for (const type of USER_INPUT_EVENT_TYPES) { + input.host.addEventListener(type, recordUserInputEvent, true); + } const inputDisposable = terminal.onData((data) => { - if (this.suppressInput) { + if (this.suppressInput && !this.isDispatchingUserInput()) { return; } this.callbacks.onInput?.(data); @@ -844,6 +860,12 @@ export class TerminalEmulatorRuntime { removeFilePasteListener: () => { input.host.removeEventListener("paste", filePasteHandler, true); }, + removeUserInputListeners: () => { + for (const type of USER_INPUT_EVENT_TYPES) { + input.host.removeEventListener(type, recordUserInputEvent, true); + } + this.userInputEvent = null; + }, restoreDocumentStyles, restoreViewportStyles, disposeFitAddon: () => { @@ -873,6 +895,7 @@ export class TerminalEmulatorRuntime { disposables.clearFitTimeouts(); disposables.removeFontListeners(); disposables.removeFilePasteListener(); + disposables.removeUserInputListeners(); disposables.disposeFitAddon(); disposables.disposeWebglAddon(); disposables.disposeTerminal(); @@ -913,6 +936,10 @@ export class TerminalEmulatorRuntime { this.terminal?.paste(text); } + private isDispatchingUserInput(): boolean { + return (this.userInputEvent?.eventPhase ?? Event.NONE) !== Event.NONE; + } + private pasteClipboard(terminal: Pick): void { const text = this.clipboard.readText().catch(() => ""); const onFilePaste = this.callbacks.onFilePaste; diff --git a/packages/app/src/timeline/replica.test.ts b/packages/app/src/timeline/replica.test.ts index 13046701ee..2254aacf5d 100644 --- a/packages/app/src/timeline/replica.test.ts +++ b/packages/app/src/timeline/replica.test.ts @@ -6,6 +6,7 @@ import { type SqliteValue, } from "@/runtime/replica-cache/row-store-sqlite"; import { afterEach, describe, expect, it } from "vitest"; +import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages"; import type { CachedTimeline } from "@/runtime/replica-cache"; import { @@ -17,6 +18,8 @@ import { } from "@/stores/session-store"; import { useCreateFlowStore, type PendingCreateAttempt } from "@/stores/create-flow-store"; import type { StreamItem } from "@/types/stream"; +import type { AgentStreamReducerEvent } from "./session-stream-reducers"; +import type { ProjectedTimelineForwardFetchPlan } from "./timeline-sync-plan"; import { reduceTurnLiveness, type TurnLivenessTransition } from "./turn-liveness"; import { createTimelineReplica, @@ -1379,6 +1382,318 @@ describe("create handoff lifetime", () => { }); }); +describe("a chat that was empty when it went offline", () => { + const EPOCH = "epoch-1"; + const PROMPT = "stream through a reconnect"; + const THOUGHT = "Thinking before the reply."; + const TURN_ID = "turn-1"; + const TIMESTAMP = "2026-10-31T10:00:00.000Z"; + + /** The daemon's timeline: one row per flushed chunk, read back as projected pages. */ + class DaemonTimeline { + private readonly rows: Array<{ seq: number; item: AgentTimelineItem }> = []; + + record(timelineItem: AgentTimelineItem): AgentStreamReducerEvent { + const seq = this.rows.length + 1; + this.rows.push({ seq, item: timelineItem }); + return { + event: { type: "timeline", provider: "mock", turnId: TURN_ID, item: timelineItem }, + seq, + epoch: EPOCH, + timestamp: new Date(TIMESTAMP), + }; + } + + page(request: ProjectedTimelineForwardFetchPlan): TimelineResponsePayload { + const maxSeq = this.rows.at(-1)?.seq ?? 0; + const after = request.direction === "after" ? request.cursor.seq : 0; + const entries = this.projected().filter((entry) => entry.seqEnd > after); + const first = entries[0]; + const startSeq = request.direction === "after" ? after + 1 : first?.seqStart; + return { + requestId: `${request.direction}-${after}`, + agentId: AGENT_ID, + agent: null, + direction: request.direction, + projection: "projected", + reset: false, + epoch: EPOCH, + window: { minSeq: this.rows[0]?.seq ?? 0, maxSeq, nextSeq: maxSeq + 1 }, + startCursor: first && startSeq !== undefined ? { epoch: EPOCH, seq: startSeq } : null, + endCursor: first ? { epoch: EPOCH, seq: maxSeq } : null, + entries, + error: null, + hasNewer: false, + hasOlder: after > 0, + staleCursor: false, + gap: false, + }; + } + + /** Contiguous reply and thought chunks read back as one row, like the daemon's projection. */ + private projected(): TimelineResponsePayload["entries"] { + const entries: TimelineResponsePayload["entries"] = []; + for (const { seq, item: row } of this.rows) { + const previous = entries.at(-1); + const continues = + previous !== undefined && + ((row.type === "assistant_message" && + previous.item.type === "assistant_message" && + previous.item.messageId === row.messageId) || + (row.type === "reasoning" && previous.item.type === "reasoning")); + if ( + continues && + (previous.item.type === "assistant_message" || previous.item.type === "reasoning") && + (row.type === "assistant_message" || row.type === "reasoning") + ) { + previous.item = { ...previous.item, text: `${previous.item.text}${row.text}` }; + previous.seqEnd = seq; + previous.sourceSeqRanges = [{ startSeq: previous.seqStart, endSeq: seq }]; + previous.collapsed = [ + row.type === "assistant_message" ? "assistant_merge" : "reasoning_merge", + ]; + continue; + } + entries.push({ + provider: "mock", + item: row, + timestamp: TIMESTAMP, + seqStart: seq, + seqEnd: seq, + sourceSeqRanges: [{ startSeq: seq, endSeq: seq }], + collapsed: [], + turnId: TURN_ID, + }); + } + return entries; + } + } + + interface PendingFetch { + request: ProjectedTimelineForwardFetchPlan; + /** Delivers a page the way the host runtime does: queued live chunks first, then the page. */ + deliver(page: TimelineResponsePayload): void; + } + + function openChat(storage: TimelineReplicaStorage) { + const fetches: PendingFetch[] = []; + const errors: unknown[] = []; + const fetch = (request: ProjectedTimelineForwardFetchPlan) => + new Promise<{ hasNewer: boolean; endCursor: { epoch: string; seq: number } | null }>( + (resolve) => { + fetches.push({ + request, + deliver: (page) => { + owner.flushStreamAgent(AGENT_ID); + owner.applyTimelineResponse(page); + resolve({ hasNewer: page.hasNewer, endCursor: page.endCursor }); + }, + }); + }, + ); + const replica = createTimelineReplica({ + serverId: SERVER_ID, + storage, + prepareAgent: async () => undefined, + }); + const owner = createViewedTimelineOwner({ + serverId: SERVER_ID, + replica, + replaceDemandedAgentIds: () => undefined, + drainQueuedAgentMessage: () => undefined, + applyTurnLiveness: () => undefined, + ports: { + canCheckFreshness: () => true, + observe: () => ({ ready: Promise.resolve(), release: async () => undefined }), + readCursor: (agentId) => { + const timeline = selectAgentTimelineState( + useSessionStore.getState().sessions[SERVER_ID], + agentId, + ); + return timeline.status === "synced" && timeline.range + ? { epoch: timeline.range.epoch, endSeq: timeline.range.endSeq } + : undefined; + }, + fetchPage: (_agentId, request) => fetch(request), + fetchLatestTail: () => + fetch({ direction: "tail", limit: 40, projection: "projected", wholeTurns: true }), + reportError: (error) => errors.push(error), + }, + }); + owner.setConnected(true); + owner.replaceVisibleAgentIds("test", [AGENT_ID]); + return { + owner, + async nextFetch(): Promise { + await expect.poll(() => fetches.length).toBeGreaterThan(0); + return fetches.shift()!; + }, + live(event: AgentStreamReducerEvent): void { + owner.applyStreamEvent(AGENT_ID, event); + owner.flushStreamAgent(AGENT_ID); + }, + /** Answers every catch-up the chat still asks for until it reports itself current. */ + async settle(daemon: DaemonTimeline): Promise { + for (let turn = 0; turn < 20; turn += 1) { + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(errors).toEqual([]); + const next = fetches.shift(); + if (next) next.deliver(daemon.page(next.request)); + else if (owner.getAgentTimelineStatus(AGENT_ID) === "ready") return; + } + throw new Error("The chat never caught up"); + }, + }; + } + + function rows(): Array<{ kind: StreamItem["kind"]; text: string }> { + const session = useSessionStore.getState().sessions[SERVER_ID]; + return [ + ...(session?.agentStreamTail.get(AGENT_ID) ?? []), + ...(session?.agentStreamHead.get(AGENT_ID) ?? []), + ].map((entry) => ({ + kind: entry.kind, + text: "text" in entry && typeof entry.text === "string" ? entry.text : "", + })); + } + + const reply = (words: number) => + Array.from({ length: words }, (_unused, index) => `word${index}`).join(" "); + const chunk = (index: number) => `${index === 0 ? "" : " "}word${index}`; + const replyChunk = (index: number): AgentTimelineItem => ({ + type: "assistant_message", + text: chunk(index), + messageId: "reply-1", + }); + + /** + * Opens the chat while its timeline is empty, then drops the connection while the prompt, + * an optional thought and the first three reply chunks are recorded. + */ + async function goOfflineWhileTheReplyStarts(input: { + reasoning: boolean; + storage: TimelineReplicaStorage; + }) { + useSessionStore.getState().initializeSession(SERVER_ID, null); + const daemon = new DaemonTimeline(); + const chat = openChat(input.storage); + const opened = await chat.nextFetch(); + opened.deliver(daemon.page(opened.request)); + expect( + selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID), + ).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" }); + + chat.owner.setConnected(false); + daemon.record({ type: "user_message", text: PROMPT, messageId: "prompt-1" }); + if (input.reasoning) daemon.record({ type: "reasoning", text: THOUGHT }); + for (const index of [0, 1, 2]) daemon.record(replyChunk(index)); + chat.owner.setConnected(true); + const catchUp = await chat.nextFetch(); + return { daemon, chat, catchUp }; + } + + function expectedRows(reasoning: boolean, words: number) { + return [ + { kind: "user_message", text: PROMPT }, + ...(reasoning ? [{ kind: "thought", text: THOUGHT }] : []), + { kind: "assistant_message", text: reply(words) }, + ]; + } + + /** A saved range that starts after the prompt claims history the chat never received. */ + function expectCoverageFromTheFirstRow(commits: CachedTimeline[]): void { + expect(commits.map((commit) => commit.range?.startSeq ?? 1)).toEqual(commits.map(() => 1)); + } + + it.each([true, false])( + "keeps the prompt and the whole reply when live chunks arrive before a page that holds them (reasoning=%s)", + async (reasoning) => { + const commits: CachedTimeline[] = []; + const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({ + reasoning, + storage: { + readTimeline: async () => undefined, + commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline), + }, + }); + try { + chat.live(daemon.record(replyChunk(3))); + chat.live(daemon.record(replyChunk(4))); + catchUp.deliver(daemon.page(catchUp.request)); + chat.live(daemon.record(replyChunk(5))); + await chat.settle(daemon); + + expect(rows()).toEqual(expectedRows(reasoning, 6)); + expectCoverageFromTheFirstRow(commits); + } finally { + chat.owner.dispose(); + } + + // The saved chat paints the same rows after a reload. + const saved = commits.at(-1); + useSessionStore.getState().clearSession(SERVER_ID); + useSessionStore.getState().initializeSession(SERVER_ID, null); + const reopened = createOwner({ + readTimeline: async () => saved, + commitTimeline: () => undefined, + }); + try { + reopened.replaceVisibleAgentIds("test", [AGENT_ID]); + await expect.poll(rows).toEqual(expectedRows(reasoning, 6)); + } finally { + reopened.dispose(); + } + }, + ); + + it("keeps the prompt when the page already holds a chunk the chat has not seen live", async () => { + const commits: CachedTimeline[] = []; + const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({ + reasoning: true, + storage: { + readTimeline: async () => undefined, + commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline), + }, + }); + try { + chat.live(daemon.record(replyChunk(3))); + const notYetLive = daemon.record(replyChunk(4)); + catchUp.deliver(daemon.page(catchUp.request)); + chat.live(notYetLive); + chat.live(daemon.record(replyChunk(5))); + await chat.settle(daemon); + + expect(rows()).toEqual(expectedRows(true, 6)); + expectCoverageFromTheFirstRow(commits); + } finally { + chat.owner.dispose(); + } + }); + + it("finishes the reply when its last chunks arrive while an older page is in flight", async () => { + const commits: CachedTimeline[] = []; + const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({ + reasoning: true, + storage: { + readTimeline: async () => undefined, + commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline), + }, + }); + try { + const olderPage = daemon.page(catchUp.request); + chat.live(daemon.record(replyChunk(3))); + chat.live(daemon.record(replyChunk(4))); + catchUp.deliver(olderPage); + await chat.settle(daemon); + + expect(rows()).toEqual(expectedRows(true, 5)); + expectCoverageFromTheFirstRow(commits); + } finally { + chat.owner.dispose(); + } + }); +}); + function createSqliteCache() { const database = new DatabaseSync(":memory:"); let beforeRead = async () => {}; diff --git a/packages/app/src/timeline/session-stream-reducers.test.ts b/packages/app/src/timeline/session-stream-reducers.test.ts index 0e401ad7a0..45b4e293dd 100644 --- a/packages/app/src/timeline/session-stream-reducers.test.ts +++ b/packages/app/src/timeline/session-stream-reducers.test.ts @@ -53,6 +53,7 @@ it.each([false, true])( (hasAuthoritativeBaseline) => { let head: StreamItem[] = []; let tail: StreamItem[] = []; + let cursor: TimelineCursor | undefined; for (const [index, turnId] of ["turn-1", "turn-2"].entries()) { const result = processAgentStreamEvent({ event: { @@ -65,12 +66,13 @@ it.each([false, true])( epoch: "epoch-1", currentTail: tail, currentHead: head, - currentCursor: undefined, + currentCursor: cursor, timestamp: new Date(1000), hasAuthoritativeBaseline, }); head = result.head; tail = result.tail; + cursor = result.cursor ?? cursor; } expect([...tail, ...head]).toMatchObject([ { kind: "thought", text: "turn-1", turnId: "turn-1" }, @@ -2848,7 +2850,7 @@ describe("processTimelineResponse", () => { ], currentTail: [], currentHead: [], - currentCursor: undefined, + currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 }, }); expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([ "First paragraph.\n\nSecond paragraph.", @@ -3677,6 +3679,7 @@ describe("processAgentStreamEvent", () => { event: makeAssistantTimelineEvent("[System Error] failed"), epoch: "timeline-1", seq: 42, + currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 }, }); expect(result.head).toEqual([ @@ -3897,6 +3900,24 @@ describe("processAgentStreamEvent", () => { }); }); + it("catches up from the first row when a chat that was empty receives a later row", () => { + const result = processAgentStreamEvent({ + ...baseStreamInput, + event: makeTimelineEvent("word3"), + seq: 6, + epoch: "epoch-1", + currentCursor: undefined, + }); + + expect(result).toMatchObject({ + head: [], + changedHead: false, + cursor: null, + cursorChanged: false, + sideEffects: [{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 0 } }], + }); + }); + it("renders a live row over painted items without creating an authoritative cursor", () => { const result = processAgentStreamEvent({ ...baseStreamInput, @@ -4087,7 +4108,7 @@ describe("processAgentStreamEvents", () => { ], currentTail: [], currentHead: [], - currentCursor: undefined, + currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 }, }); expect(result.changedTail).toBe(false); @@ -4261,6 +4282,7 @@ describe("processAgentStreamEvents", () => { currentTail: [], currentHead: [], currentCursor: undefined, + hasAuthoritativeBaseline: false, timestamp: new Date("2026-05-02T10:00:00.186Z"), }); @@ -4462,7 +4484,7 @@ describe("createAgentStreamReducerQueue", () => { const scheduler = createManualScheduler(); let currentTail: StreamItem[] = []; let currentHead: StreamItem[] = []; - let currentCursor: TimelineCursor | undefined; + let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 }; const queue = createAgentStreamReducerQueue({ getSnapshot: () => ({ @@ -4505,7 +4527,7 @@ describe("createAgentStreamReducerQueue", () => { expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]); expect(currentCursor).toEqual({ epoch: "epoch-1", - startSeq: 2, + startSeq: 1, endSeq: 4, }); }); diff --git a/packages/app/src/timeline/session-stream-reducers.ts b/packages/app/src/timeline/session-stream-reducers.ts index a46ec8188f..1eec63ed9a 100644 --- a/packages/app/src/timeline/session-stream-reducers.ts +++ b/packages/app/src/timeline/session-stream-reducers.ts @@ -289,7 +289,10 @@ function classifySessionTimelineSeq({ seq: number; }): SessionTimelineSeqDecision { if (!cursor) { - return "init"; + // A synced chat without coverage was empty when it last caught up. Only an epoch's + // first row can start coverage; a later row means rows before it were missed, for + // example while offline, and a cursor started there would hide them from catch-up. + return seq === 1 ? "init" : "gap"; } if (cursor.epoch !== epoch) { return "drop_epoch"; @@ -1543,14 +1546,14 @@ function processTimelineSequencingGate(input: { return { ...base, shouldApplyStreamEvent: false, - sideEffects: currentCursor - ? [ - { - type: "catch_up", - cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }, - }, - ] - : [], + sideEffects: [ + { + type: "catch_up", + cursor: currentCursor + ? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } + : { epoch, endSeq: 0 }, + }, + ], }; } if (decision === "drop_epoch" && seq === 1) { diff --git a/packages/app/src/timeline/timeline-sync-plan.ts b/packages/app/src/timeline/timeline-sync-plan.ts index b66de16941..8aa2dc5a35 100644 --- a/packages/app/src/timeline/timeline-sync-plan.ts +++ b/packages/app/src/timeline/timeline-sync-plan.ts @@ -64,6 +64,21 @@ export function planTimelineResumeFetch( : planTimelineTailFetch(); } +/** + * A catch-up that waited behind another starts after the rows applied meanwhile. A forward + * page is applied row by row, so asking again for rows the chat already holds repeats them. + */ +export function planTimelineCatchUpPastApplied( + request: ProjectedTimelineForwardFetchPlan, + applied: { epoch: string; endSeq: number } | undefined, +): ProjectedTimelineForwardFetchPlan { + if (request.direction !== "after" || !applied) return request; + if (applied.epoch !== request.cursor.epoch || applied.endSeq <= request.cursor.seq) { + return request; + } + return planTimelineCatchUpAfter({ epoch: applied.epoch, seq: applied.endSeq }); +} + export function planTimelineOlderFetch(cursor: TimelineSyncCursor) { return { direction: "before", diff --git a/packages/app/src/timeline/viewed-timeline-sync.test.ts b/packages/app/src/timeline/viewed-timeline-sync.test.ts index d61581cc73..6550350829 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.test.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.test.ts @@ -441,6 +441,96 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); }); +test("a gap parked behind a running tail resumes after the rows that tail applied", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + const tail = await world.nextFetch("agent-a"); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 }); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 7 }); + tail.respond({ hasNewer: false, seq: 7 }); + + const recovery = await world.nextFetch("agent-a"); + expect(recovery.request).toEqual({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 7 }, + limit: 40, + projection: "projected", + wholeTurns: true, + }); + recovery.respond({ hasNewer: false, seq: 7 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + +test("a chat without coverage that recovers a gap loads the latest tail when history overflows a page", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + const tail = await world.nextFetch("agent-a"); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 }); + tail.respond({ hasNewer: false, seq: 0 }); + + const recovery = await world.nextFetch("agent-a"); + expect(recovery.request).toEqual({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 0 }, + limit: 40, + projection: "projected", + wholeTurns: true, + }); + recovery.respond({ hasNewer: true, seq: 40 }); + + const fallback = await world.nextFetch("agent-a"); + expect(fallback.request).toEqual({ + direction: "tail", + limit: 40, + projection: "projected", + wholeTurns: true, + }); + fallback.respond({ hasNewer: false, seq: 90 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + +test("a recovery's follow-up page starts after rows another fetch applied meanwhile", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-a")).respond({ hasNewer: false, seq: 0 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 }); + const firstPage = await world.nextFetch("agent-a"); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 40 }); + firstPage.respond({ hasNewer: true, seq: 40 }); + const latestTail = await world.nextFetch("agent-a"); + expect(latestTail.request.direction).toBe("tail"); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 40 }); + const recovery = await world.nextFetch("agent-a"); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 300 }); + latestTail.respond({ hasNewer: false, seq: 300 }); + recovery.respond({ hasNewer: true, seq: 80 }); + + const followUp = await world.nextFetch("agent-a"); + expect(followUp.request).toEqual({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 300 }, + limit: 40, + projection: "projected", + wholeTurns: true, + }); + followUp.respond({ hasNewer: false, seq: 300 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + test("reports a chat current only once its parked follow-up page completes", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); @@ -885,7 +975,8 @@ test("gap recovery supersedes completed catch-up and pages through the current t const membership = await world.nextMembership(); membership.succeed(); const initial = await world.nextFetch("agent-a"); - initial.respond({ hasNewer: false }); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 }); + initial.respond({ hasNewer: false, seq: 10 }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 }); diff --git a/packages/app/src/timeline/viewed-timeline-sync.ts b/packages/app/src/timeline/viewed-timeline-sync.ts index 06c3fff0d4..b6423de9c3 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.ts @@ -1,5 +1,6 @@ import { planTimelineCatchUpAfter, + planTimelineCatchUpPastApplied, planTimelineResumeFetch, type ProjectedTimelineForwardFetchPlan, } from "./timeline-sync-plan"; @@ -690,7 +691,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed // The delay measures the daemon's answer, so it starts when the question is sent. On a cold // start the cache read that precedes the question can outlast it on its own. Only opening a - // chat escalates. A reconnect already shows Reconnecting to host until the answer. A resume + // chat escalates. A reconnect already shows Reconnecting until the answer. A resume // kept its socket subscribed, so a slow answer is no reason to doubt the chat; a socket that // died quietly is caught by the foreground liveness probe and becomes a reconnect. const startFreshnessCheckDelay = (agentId: string) => { @@ -741,7 +742,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed await fetchUntilCurrent( agentId, generation, - planTimelineCatchUpAfter(page.endCursor), + planTimelineCatchUpPastApplied( + planTimelineCatchUpAfter(page.endCursor), + ports.readCursor(agentId), + ), false, ); return; @@ -819,7 +823,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed ensureCacheLoaded(agentId); return; } - const nextRequest = request ?? planTimelineResumeFetch(ports.readCursor(agentId)); + const applied = ports.readCursor(agentId); + const nextRequest = request + ? planTimelineCatchUpPastApplied(request, applied) + : planTimelineResumeFetch(applied); const current = catchUps.get(agentId); const decision = decideCatchUp({ current, request: nextRequest, supersede }); if (decision === "keep-and-park") { @@ -833,11 +840,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed catchUpGenerations.set(agentId, generation); catchUps.set(agentId, { generation, status: "running", request: nextRequest }); pendingCatchUps.delete(agentId); + // A gap recovery pages forward to keep the coverage it extends. Without coverage there is + // nothing to keep, so an overflowing page falls back to the latest tail, as a resume does. void fetchUntilCurrent( agentId, generation, nextRequest, - request === undefined && nextRequest.direction === "after", + nextRequest.direction === "after" && (request === undefined || applied === undefined), ); }; diff --git a/packages/app/src/tool-calls/detail-level/overview/sheet.tsx b/packages/app/src/tool-calls/detail-level/overview/sheet.tsx index 2888f1f424..c42b7de513 100644 --- a/packages/app/src/tool-calls/detail-level/overview/sheet.tsx +++ b/packages/app/src/tool-calls/detail-level/overview/sheet.tsx @@ -1,16 +1,16 @@ -import { useCallback, useEffect, useRef, type ReactNode } from "react"; -import { Pressable, Text, View } from "react-native"; +import { useCallback, useEffect, useMemo, useRef, type ReactNode } from "react"; +import { View } from "react-native"; import { BottomSheetScrollView, type BottomSheetScrollViewMethods } from "@gorhom/bottom-sheet"; -import { Wrench, X } from "lucide-react-native"; +import { Wrench } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { useTranslation } from "react-i18next"; import { type ContextBridge, useIsolatedBottomSheetVisibility, } from "@/components/ui/isolated-bottom-sheet-modal"; +import { SheetHeaderView, type SheetHeader } from "@/components/adaptive-modal-sheet"; import { ToolCallSheetModal, useToolCallSheetContextBridge } from "@/components/tool-call-sheet"; import { useToolCallExpansionContextBridge } from "@/tool-calls/expansion-context"; -import type { Theme } from "@/styles/theme"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; interface OverviewToolCallGroupSheetProps { visible: boolean; @@ -21,9 +21,8 @@ interface OverviewToolCallGroupSheetProps { const SNAP_POINTS = ["60%", "95%"]; const ThemedWrench = withUnistyles(Wrench); -const ThemedX = withUnistyles(X); const foregroundMapping = (theme: Theme) => ({ color: theme.colors.foreground }); -const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const headerIcon = ; export function OverviewToolCallGroupSheet({ visible, @@ -31,7 +30,6 @@ export function OverviewToolCallGroupSheet({ children, onClose, }: OverviewToolCallGroupSheetProps) { - const { t } = useTranslation(); const scrollRef = useRef(null); const sheetContextBridge = useToolCallSheetContextBridge(); const expansionContextBridge = useToolCallExpansionContextBridge(); @@ -39,6 +37,10 @@ export function OverviewToolCallGroupSheet({ (content) => sheetContextBridge(expansionContextBridge(content)), [expansionContextBridge, sheetContextBridge], ); + const header = useMemo( + () => ({ title: summary, titleTestID: "tool-call-group-sheet-summary", leading: headerIcon }), + [summary], + ); const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({ visible, onClose, @@ -68,27 +70,11 @@ export function OverviewToolCallGroupSheet({ enablePanDownToClose > - - - - - {summary} - - - - - - + {children} @@ -102,30 +88,6 @@ const styles = StyleSheet.create((theme) => ({ flex: 1, backgroundColor: theme.colors.surface2, }, - header: { - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[3], - borderBottomWidth: theme.borderWidth[1], - borderBottomColor: theme.colors.border, - }, - headerLeft: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - flex: 1, - }, - headerTitle: { - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - color: theme.colors.foreground, - flex: 1, - }, - closeButton: { - padding: theme.spacing[2], - }, content: { flex: 1, minHeight: 0, diff --git a/packages/app/src/tool-calls/detail-level/overview/view.tsx b/packages/app/src/tool-calls/detail-level/overview/view.tsx index b05fbe1edd..825a4ba9aa 100644 --- a/packages/app/src/tool-calls/detail-level/overview/view.tsx +++ b/packages/app/src/tool-calls/detail-level/overview/view.tsx @@ -27,12 +27,8 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView onExpandedChange, children, }: OverviewGroupProps) { - const scrollRef = useRef(null); const isCompact = useIsCompactFormFactor(); const aggregateSummary = useOverviewSummaryLabel(group.summary); - const scrollToLatest = useCallback(() => { - scrollRef.current?.scrollToEnd({ animated: false }); - }, []); const hold = useDisclosureHold(); const toggle = useCallback(() => { const apply = () => onExpandedChange(group.run.id, !expanded); @@ -44,19 +40,8 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView onExpandedChange(group.run.id, false); }, [group.run.id, onExpandedChange]); const renderDetails = useCallback( - () => ( - - {children} - - ), - [children, scrollToLatest], + () => {children}, + [children, group.run.latest.id], ); if (isCompact) { @@ -93,6 +78,35 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView ); }); +function InlineGroupDetails({ + latestCallId, + children, +}: { + latestCallId: string; + children: ReactNode; +}) { + const scrollRef = useRef(null); + const lastRevealedCall = useRef(null); + const revealLatestCall = useCallback(() => { + // A disclosure changes height without appending a call. Keep the reader's place then. + if (lastRevealedCall.current === latestCallId) return; + lastRevealedCall.current = latestCallId; + scrollRef.current?.scrollToEnd({ animated: false }); + }, [latestCallId]); + return ( + + {children} + + ); +} + const styles = StyleSheet.create((theme) => ({ scroll: { maxHeight: TOOL_CALL_GROUP_MAX_HEIGHT, diff --git a/packages/app/src/types/host-connection.test.ts b/packages/app/src/types/host-connection.test.ts index 8d7fb87b35..36c652ccab 100644 --- a/packages/app/src/types/host-connection.test.ts +++ b/packages/app/src/types/host-connection.test.ts @@ -5,9 +5,11 @@ import { normalizeStoredHostProfile, orderHostsLocalFirst, pinRelayProtectedSecurityInProfiles, + readHostRegistry, relayConnectionFromOffer, resolveActiveHostServerId, upsertHostConnectionInProfiles, + writeHostRegistry, type HostConnection, type HostProfile, } from "./host-connection"; @@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => { expect(profile?.connections[0]).not.toHaveProperty("password"); }); + it("drops a connection kind this build doesn't know and keeps the host", () => { + const profile = normalizeStoredHostProfile({ + serverId: "srv_mixed", + password: "secret", + connections: [ + { id: "future:1", type: "futureKind", address: "future.example.com" }, + { id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true }, + { id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" }, + ], + preferredConnectionId: "direct:remote:6767", + }); + + expect(profile?.password).toBe("secret"); + expect(profile?.connections).toEqual([ + { id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false }, + ]); + expect(profile?.preferredConnectionId).toBe("direct:remote:6767"); + }); + it("preserves legacy relay ids when TLS is absent", () => { const profile = normalizeStoredHostProfile({ serverId: "srv_relay", @@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => { }); }); +describe("readHostRegistry and writeHostRegistry", () => { + const direct: HostConnection = { + id: "direct:lan:6767", + type: "directTcp", + endpoint: "lan:6767", + useTls: false, + }; + const future = { id: "future:1", type: "futureKind", address: "future.example.com" }; + + it("writes back every entry it could not read", () => { + const unreadableHost = { serverId: "srv_future", connections: [future] }; + const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 }; + const stored = [ + { ...makeHost("srv_a"), connections: [direct, future] }, + unreadableHost, + hostWithFutureField, + "not a host", + ]; + + const { hosts, unreadable } = readHostRegistry(stored); + expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]); + expect(hosts[0]?.connections).toEqual([direct]); + + expect(writeHostRegistry(hosts, unreadable)).toEqual([ + { ...hosts[0], connections: [direct, future] }, + unreadableHost, + hostWithFutureField, + "not a host", + ]); + }); + + it("writes a host saved again by this build in place of the entry it could not read", () => { + const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]); + expect(hosts).toEqual([]); + + const saved = { ...makeHost("srv_a"), connections: [direct] }; + expect(writeHostRegistry([saved], unreadable)).toEqual([saved]); + }); + + it("moves a stored direct TCP password to its host next to a connection it can't read", () => { + const registry = readHostRegistry([ + { + serverId: "srv_legacy", + connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }], + }, + ]); + + expect(registry.movedConnectionPassword).toBe(true); + expect(registry.hosts[0]?.password).toBe("old-secret"); + expect(registry.hosts[0]?.connections).toEqual([direct]); + }); +}); + describe("createRemoteSshHostConnection", () => { it("keeps optional SSH settings absent", () => { expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({ diff --git a/packages/app/src/types/host-connection.ts b/packages/app/src/types/host-connection.ts index e7449b9a67..d830955118 100644 --- a/packages/app/src/types/host-connection.ts +++ b/packages/app/src/types/host-connection.ts @@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({ label: z.string().optional(), appearance: HostAppearanceSchema.optional(), lifecycle: z.strictObject({}).optional(), - connections: z.array(StoredHostConnectionSchema).min(1), + // Read one by one, so a connection kind another build wrote skips only that connection. + connections: z.array(z.unknown()).min(1), preferredConnectionId: z.string().nullable().optional(), createdAt: z.string().datetime({ offset: true }).optional(), updatedAt: z.string().datetime({ offset: true }).optional(), }); -export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema); type StoredHostConnection = z.infer; function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null { @@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec } export function normalizeStoredHostProfile(entry: unknown): HostProfile | null { + return readStoredHost(entry)?.profile ?? null; +} + +interface StoredHostRead { + profile: HostProfile; + unreadableConnections: unknown[]; + movedConnectionPassword: boolean; +} + +function readStoredHost(entry: unknown): StoredHostRead | null { const result = StoredHostProfileSchema.safeParse(entry); if (!result.success) { return null; } const record = result.data; const serverId = record.serverId; + const storedConnections: StoredHostConnection[] = []; + const unreadableConnections: unknown[] = []; + for (const stored of record.connections) { + const parsed = StoredHostConnectionSchema.safeParse(stored); + if (parsed.success) storedConnections.push(parsed.data); + else unreadableConnections.push(stored); + } // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated. - const legacyPassword = record.connections.find( + const legacyPassword = storedConnections.find( (connection) => connection.type === "directTcp" && connection.password, ); const password = record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined); - const connections = record.connections + const connections = storedConnections .map((connection) => normalizeStoredConnection(connection)) .filter((connection): connection is HostConnection => connection !== null); if (connections.length === 0) { @@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null { : (connections[0]?.id ?? null); return { - serverId, - ...(password ? { password } : {}), - label, - appearance: record.appearance ?? defaultHostAppearance(), - lifecycle: defaultLifecycle(), - connections, - preferredConnectionId, - createdAt: record.createdAt ?? now, - updatedAt: record.updatedAt ?? now, + profile: { + serverId, + ...(password ? { password } : {}), + label, + appearance: record.appearance ?? defaultHostAppearance(), + lifecycle: defaultLifecycle(), + connections, + preferredConnectionId, + createdAt: record.createdAt ?? now, + updatedAt: record.updatedAt ?? now, + }, + unreadableConnections, + movedConnectionPassword: legacyPassword !== undefined, }; } +/** + * Stored registry entries this build can't read, such as a connection kind added by a newer + * build. `writeHostRegistry` writes them back so that build still finds them. + */ +export interface UnreadableHostEntries { + hosts: unknown[]; + connectionsByServerId: Map; +} + +export function readHostRegistry(stored: unknown[]): { + hosts: HostProfile[]; + unreadable: UnreadableHostEntries; + // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration. + movedConnectionPassword: boolean; +} { + const hosts: HostProfile[] = []; + const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() }; + let movedConnectionPassword = false; + for (const entry of stored) { + const read = readStoredHost(entry); + if (!read) { + unreadable.hosts.push(entry); + continue; + } + hosts.push(read.profile); + if (read.unreadableConnections.length > 0) { + unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections); + } + movedConnectionPassword ||= read.movedConnectionPassword; + } + return { hosts, unreadable, movedConnectionPassword }; +} + +export function writeHostRegistry( + hosts: HostProfile[], + unreadable: UnreadableHostEntries, +): unknown[] { + const savedServerIds = new Set(hosts.map((host) => host.serverId)); + const written: unknown[] = hosts.map((host) => { + const kept = unreadable.connectionsByServerId.get(host.serverId); + return kept ? { ...host, connections: [...host.connections, ...kept] } : host; + }); + for (const entry of unreadable.hosts) { + // A host this build saved again replaces the entry it couldn't read. + const serverId = readStoredServerId(entry); + if (serverId === null || !savedServerIds.has(serverId)) written.push(entry); + } + return written; +} + +/** Drops the entries this build couldn't read for a host you removed. */ +export function forgetUnreadableHost( + unreadable: UnreadableHostEntries, + serverId: string, +): UnreadableHostEntries { + const connectionsByServerId = new Map(unreadable.connectionsByServerId); + connectionsByServerId.delete(serverId); + return { + hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId), + connectionsByServerId, + }; +} + +function readStoredServerId(entry: unknown): string | null { + if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null; + return typeof entry.serverId === "string" ? entry.serverId.trim() : null; +} + export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean { return host.connections.some((existing) => hostConnectionEquals(existing, connection)); } diff --git a/packages/app/src/usage/agent-usage.tsx b/packages/app/src/usage/agent-usage.tsx index bf10054db6..98f1c9bf82 100644 --- a/packages/app/src/usage/agent-usage.tsx +++ b/packages/app/src/usage/agent-usage.tsx @@ -1,3 +1,4 @@ +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; @@ -8,7 +9,7 @@ import type { UsageReportEntry } from "./types"; /** * The usage of the account an agent runs under, for its context window details: one card per - * report as it streams in, without pins. Nothing on hosts that cannot report usage, or for an + * report in the user's card order, without pins. Nothing on hosts that cannot report usage, or for an * agent with no account to report. */ export function AgentUsage({ @@ -55,7 +56,8 @@ function AgentUsageCards({ refreshable: boolean; }) { const { display } = useUsageDisplay(reports); - return reports.map((entry) => ( + const arranged = useMemo(() => display.arrange(reports), [display, reports]); + return arranged.map((entry) => ( void; + /** The handle is always there; it shows while the card is hovered or where there is no hover. */ + handleVisible: boolean; +} const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); export function UsageCard({ @@ -41,6 +53,7 @@ export function UsageCard({ display, pinnable, refreshable, + arrangement, compact = false, }: { serverId: string; @@ -51,6 +64,8 @@ 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. */ + arrangement?: UsageCardArrangement; compact?: boolean; }) { const { t } = useTranslation(); @@ -60,9 +75,9 @@ export function UsageCard({ const showsFreshnessInline = isNative || isCompact || !refreshable; const usage = entry.report; const status = statusText(usage, t); - const footer = entry.account.label ?? null; - const { windows, balances, details, planLabel, successfulAt, retained, messages } = - resolveUsageReport(entry, t); + const collapsed = arrangement?.on === false; + const report = resolveUsageReport(entry, t); + const { planLabel, successfulAt, retained } = report; const containerStyle = useMemo( () => [styles.container, compact ? styles.containerCompact : styles.containerPadded], @@ -79,20 +94,34 @@ export function UsageCard({ return ( - + + {arrangement ? ( + + ) : null} {entry.sourceLabel} - {planLabel ? : null} + {collapsed && entry.account.label ? ( + // The body that names the account is gone, and two off cards of one source must differ. + + {entry.account.label} + + ) : null} + {planLabel && !collapsed ? ( + + ) : null} - {status ? ( + {status && !collapsed ? ( {status} ) : null} - {refreshable ? ( + {refreshable && !collapsed ? ( ) : null} + {arrangement ? ( + + + + ) : null} + {collapsed ? null : ( + + )} + + ); +} + +function UsageCardBody({ + entry, + display, + pinnable, + report, + showsFreshnessInline, + refreshState, +}: { + entry: UsageReportEntry; + display: UsageDisplay; + pinnable: boolean; + report: ReturnType; + showsFreshnessInline: boolean; + refreshState: UsageRefresh; +}) { + const { t } = useTranslation(); + const { windows, balances, details, retained, successfulAt, messages } = report; + const footer = entry.account.label ?? null; + return ( + <> {messages.length > 0 ? ( {messages.join("\n")} @@ -164,7 +240,24 @@ export function UsageCard({ {t("providerUsage.refreshFailed")} ) : null} - + + ); +} + +/** + * Drags the card. It hangs in the card's left padding, so the logo, name and body share one rail + * and revealing it on hover moves nothing. + */ +function UsageCardDragHandle({ name, visible }: { name: string; visible: boolean }) { + const { t } = useTranslation(); + return ( + + + ); } @@ -279,6 +372,21 @@ function UsageFreshness({ ); } +const DRAG_GRIP_SIZE = 14; + +// The handle fills the card's left padding beside the header. +function dragHandleSlot(spacing: { 4: number }) { + return { + position: "absolute", + left: 0, + width: spacing[4], + top: 0, + bottom: 0, + alignItems: "center", + justifyContent: "center", + } as const; +} + // The Refresh glyph lands on the card's right rail and the header keeps its text height; // the button's larger hitbox overhangs both instead of pushing them. function iconHitboxOverhang(compact: boolean) { @@ -305,11 +413,28 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", gap: theme.spacing[2], }, + // The row reaches into the card's left padding and above and below its text, so the handle + // there is inside it: Android delivers no touches to a child where it overflows its parent. + headerWithHandle: { + position: "relative", + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + marginLeft: -theme.spacing[4], + paddingLeft: theme.spacing[4], + marginVertical: -theme.spacing[2], + paddingVertical: theme.spacing[2], + }, name: { flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.base, }, + collapsedAccount: { + flexShrink: 1, + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, headerSpacer: { flex: 1, }, @@ -379,6 +504,12 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm, }, + 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), })); diff --git a/packages/app/src/usage/cards.test.ts b/packages/app/src/usage/cards.test.ts new file mode 100644 index 0000000000..86e62b3d21 --- /dev/null +++ b/packages/app/src/usage/cards.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from "vitest"; +import { + arrangeUsageCards, + arrangeUsageReports, + DEFAULT_USAGE_PREFERENCES, + setUsageCardOn, + UsagePreferencesSchema, + usageReportsOn, + type UsagePreferences, +} from "./preferences"; +import { resolvePinnedUsage } from "./pinned"; +import type { UsageReportEntry } from "./types"; + +function report(sourceId: string, sourceLabel: string, account?: string): UsageReportEntry { + return { + id: `${sourceId}:${account ?? "default"}`, + sourceId, + sourceLabel, + account: account ? { label: account } : {}, + fetchedAt: "2026-01-01T00:00:00.000Z", + report: { + status: "available", + windows: [{ id: "weekly", label: "Weekly", summary: true, usedPct: 40 }], + }, + }; +} + +const codex = report("codex", "Codex"); +const claudeWork = report("claude", "Claude", "work"); +const claudePersonal = report("claude", "Claude", "personal"); +const copilot = report("copilot", "Copilot"); +const gemini = report("gemini", "Gemini"); + +function ids(reports: readonly UsageReportEntry[]): string[] { + return reports.map((entry) => entry.id); +} + +function arranged(cardOrder: string[]): UsagePreferences { + return { ...DEFAULT_USAGE_PREFERENCES, cardOrder }; +} + +describe("usage card order", () => { + it("shows cards by provider, then account, whatever order they arrive in", () => { + const expected = ["claude:personal", "claude:work", "codex:default", "copilot:default"]; + for (const arrival of [ + [codex, claudeWork, copilot, claudePersonal], + [copilot, claudePersonal, codex, claudeWork], + ]) { + expect(ids(arrangeUsageReports(arrival, DEFAULT_USAGE_PREFERENCES))).toEqual(expected); + } + }); + + it("puts the cards the user arranged first, in their order", () => { + const preferences = arranged(["copilot:default", "claude:work"]); + + expect( + ids(arrangeUsageReports([claudeWork, codex, claudePersonal, copilot], preferences)), + ).toEqual(["copilot:default", "claude:work", "claude:personal", "codex:default"]); + }); + + it("lands a report from a new login in its default slot after the arranged cards", () => { + const preferences = arrangeUsageCards(DEFAULT_USAGE_PREFERENCES, { + moved: "codex:default", + after: ["codex:default", "claude:work"], + }); + const newLogin = report("claude", "Claude", "agent"); + + expect(ids(arrangeUsageReports([newLogin, claudeWork, codex], preferences))).toEqual([ + "codex:default", + "claude:work", + "claude:agent", + ]); + }); + + it("keeps another host's arrangement when a drop on this host moves a card both show", () => { + // Host A shows Codex, Claude and Gemini; host B shows Copilot and the same Claude account. + const hostA = [codex, claudeWork, gemini]; + const hostB = [claudeWork, copilot]; + const arrangedOnA = arrangeUsageCards(DEFAULT_USAGE_PREFERENCES, { + moved: "codex:default", + after: ["codex:default", "claude:work", "gemini:default"], + }); + + const after = ["copilot:default", "claude:work"]; + const arrangedOnB = arrangeUsageCards(arrangedOnA, { moved: "copilot:default", after }); + + expect(ids(arrangeUsageReports(hostA, arrangedOnB))).toEqual([ + "codex:default", + "claude:work", + "gemini:default", + ]); + expect(ids(arrangeUsageReports(hostB, arrangedOnB))).toEqual(after); + }); + + it("moves only the dragged card when it swaps with its neighbour", () => { + // Gemini sits between Codex and Copilot, but only another host shows it. + const preferences = arranged(["codex:default", "gemini:default", "copilot:default"]); + const swapped = arrangeUsageCards(preferences, { + moved: "codex:default", + after: ["copilot:default", "codex:default"], + }); + + expect(ids(arrangeUsageReports([codex, copilot], swapped))).toEqual([ + "copilot:default", + "codex:default", + ]); + expect(ids(arrangeUsageReports([gemini, copilot], swapped))).toEqual([ + "gemini:default", + "copilot:default", + ]); + }); +}); + +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([]); + }); + + it("leaves off cards out of the sidebar summary", () => { + const preferences = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, "codex:default", false); + + expect(ids(usageReportsOn([codex, claudeWork], preferences))).toEqual(["claude:work"]); + expect( + resolvePinnedUsage([codex, claudeWork], preferences).map((source) => source.key), + ).toEqual(["claude:work"]); + }); + + it("orders the sidebar summary like the cards", () => { + const preferences = arranged(["codex:default"]); + + expect( + resolvePinnedUsage([claudeWork, codex], preferences).map((source) => source.key), + ).toEqual(["codex:default", "claude:work"]); + }); +}); + +describe("stored card preferences", () => { + it("reads settings saved before cards could be arranged as no arrangement", () => { + expect(UsagePreferencesSchema.parse({ displayAs: "used", serverId: null })).toEqual( + DEFAULT_USAGE_PREFERENCES, + ); + }); + + 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] }), + ).toEqual(DEFAULT_USAGE_PREFERENCES); + }); +}); diff --git a/packages/app/src/usage/controls.tsx b/packages/app/src/usage/controls.tsx index f0a8c73f5e..b4637778c7 100644 --- a/packages/app/src/usage/controls.tsx +++ b/packages/app/src/usage/controls.tsx @@ -1,23 +1,16 @@ import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; -import { HostFilter } from "@/components/hosts/host-filter"; import { useMemo, type ReactElement } from "react"; import { UsageRefreshButton } from "./refresh-button"; import { UsageOptions } from "./options"; -import type { UsageHost } from "./model"; +import { hasHostChoice, type UsageHostSelection } from "./hosts"; import { useHostUsage } from "./queries"; import type { UsageView } from "./types"; -/** The hosts to choose between, and which one is shown. */ -export interface UsageHostSelection { - hosts: UsageHost[]; - serverId: string; - onSelect: (serverId: string) => void; -} - /** - * The controls on the right of every usage title row: the host filter when there is more than one - * host, Refresh all, and the Settings cog. A host that cannot report usage keeps only the host filter. + * The controls on the right of every usage title row: Refresh all and the Settings cog. A host + * that cannot report usage has none, unless there is another host to switch to: the host choice + * lives in the cog, so the cog stays. */ export function UsageControls({ view, @@ -31,36 +24,19 @@ export function UsageControls({ hostSelection?: UsageHostSelection; }) { const busy = view.kind === "loading" || (view.kind === "ready" && view.isRefreshing); + if (!hasUsageControls(view, hostSelection)) return null; return ( - {hasHostChoice(hostSelection) ? ( - - ) : null} - {view.kind === "unavailable" ? null : ( - <> - {view.kind === "off" ? null : } - - + {view.kind === "off" || view.kind === "unavailable" ? null : ( + )} + ); } -function hasHostChoice( - hostSelection: UsageHostSelection | undefined, -): hostSelection is UsageHostSelection { - return hostSelection !== undefined && hostSelection.hosts.length > 1; -} - -function usageHostOptionTestID(serverId: string): string { - return `usage-host-filter-item-${serverId}`; +function hasUsageControls(view: UsageView, hostSelection: UsageHostSelection | undefined): boolean { + return view.kind !== "unavailable" || hasHostChoice(hostSelection); } const styles = StyleSheet.create((theme) => ({ @@ -73,8 +49,8 @@ const styles = StyleSheet.create((theme) => ({ })); /** - * One host’s usage and title-row controls for the Usage modal. - * Returns null when there is nothing to control, so headers leave no empty island. + * One host’s usage for the Usage modal, and its title-row controls: null when there is nothing to + * control, so the header leaves no empty island. */ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { view: UsageView; @@ -82,18 +58,20 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { controls: ReactElement | null; } { const { view, refresh } = useHostUsage(hostSelection.serverId); - const hasControls = hasHostChoice(hostSelection) || view.kind !== "unavailable"; const controls = useMemo( () => - hasControls ? ( + hasUsageControls(view, hostSelection) ? ( + // Keyed by host, so state one host's controls hold, such as a failed setting change, + // never shows on another's. ) : null, - [hasControls, hostSelection, refresh, view], + [hostSelection, refresh, view], ); return { view, refresh, controls }; } diff --git a/packages/app/src/usage/display.ts b/packages/app/src/usage/display.ts index c62ed78fd7..f54c168834 100644 --- a/packages/app/src/usage/display.ts +++ b/packages/app/src/usage/display.ts @@ -1,21 +1,32 @@ import { useCallback, useMemo } from "react"; import { useAppSettings } from "@/hooks/use-settings"; import { + arrangeUsageCards, + arrangeUsageReports, + isUsageCardOff, isUsagePinned, + setUsageCardOn, setUsageDisplayAs, toggleUsagePin, + type UsageCardDrop, type UsageDisplayAs, type UsagePin, type UsagePreferences, } from "./preferences"; import type { UsageReportEntry } from "./types"; -/** What usage views need from the preferences: how to read percents, and the pins. */ +/** What usage views need from the preferences: how to read percents, the pins, and the cards. */ export interface UsageDisplay { displayAs: UsageDisplayAs; setDisplayAs: (displayAs: UsageDisplayAs) => void; isPinned: (pin: UsagePin) => boolean; togglePin: (pin: UsagePin) => void; + /** Reports in the order their cards show. */ + 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; + setCardOn: (reportId: string, on: boolean) => void; } interface UsagePreferencesState { @@ -41,14 +52,30 @@ export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePref }, [updateSettings, reports], ); + const arrangeCards = useCallback( + (drop: UsageCardDrop) => { + void updateSettings((current) => ({ usage: arrangeUsageCards(current.usage, drop) })); + }, + [updateSettings], + ); + const setCardOn = useCallback( + (reportId: string, on: boolean) => { + void updateSettings((current) => ({ usage: setUsageCardOn(current.usage, reportId, on) })); + }, + [updateSettings], + ); const display = useMemo( () => ({ displayAs: preferences.displayAs, setDisplayAs, isPinned: (pin) => isUsagePinned(preferences, pin, reports), togglePin, + arrange: (shown) => arrangeUsageReports(shown, preferences), + arrangeCards, + isCardOn: (reportId) => !isUsageCardOff(preferences, reportId), + setCardOn, }), - [preferences, reports, setDisplayAs, togglePin], + [arrangeCards, preferences, reports, setCardOn, setDisplayAs, togglePin], ); return { preferences, display }; } diff --git a/packages/app/src/usage/format.ts b/packages/app/src/usage/format.ts index 867976a586..16386810fa 100644 --- a/packages/app/src/usage/format.ts +++ b/packages/app/src/usage/format.ts @@ -2,7 +2,7 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; import { formatTimeOfDay } from "@/utils/time"; import type { UsageDisplayAs } from "./preferences"; -import type { UsageBalanceUnit } from "./types"; +import type { UsageBalanceUnit, UsageReportEntry } from "./types"; const providerUsageLabels = { session: { label: "Session", key: "providerUsage.labels.session" }, @@ -13,6 +13,11 @@ const providerUsageLabels = { monthly_credits: { label: "Monthly credits", key: "providerUsage.labels.monthlyCredits" }, } as const; +/** The source, with the account when the report names one: "Claude (work)". */ +export function formatUsageAccountName(entry: UsageReportEntry): string { + return entry.account.label ? `${entry.sourceLabel} (${entry.account.label})` : entry.sourceLabel; +} + export function formatProviderUsageLabel(id: string, label: string, t: TFunction = i18n.t): string { const reviewPrefix = "Code review · "; if (id.startsWith("code_review:") && label.startsWith(reviewPrefix)) { diff --git a/packages/app/src/usage/hosts.ts b/packages/app/src/usage/hosts.ts index dba21dc316..f07c6d7dcd 100644 --- a/packages/app/src/usage/hosts.ts +++ b/packages/app/src/usage/hosts.ts @@ -57,3 +57,17 @@ export function useUsageHostSelection(): { ); return { serverId: resolveUsageModalHostId(choice), connectedHosts, select }; } + +/** The hosts to choose between, and which one is shown. */ +export interface UsageHostSelection { + hosts: UsageHost[]; + serverId: string; + onSelect: (serverId: string) => void; +} + +/** Whether there is more than one host to show usage for. */ +export function hasHostChoice( + hostSelection: UsageHostSelection | undefined, +): hostSelection is UsageHostSelection { + return (hostSelection?.hosts.length ?? 0) > 1; +} diff --git a/packages/app/src/usage/list.tsx b/packages/app/src/usage/list.tsx index 10e76ba57f..e9218ae326 100644 --- a/packages/app/src/usage/list.tsx +++ b/packages/app/src/usage/list.tsx @@ -1,12 +1,24 @@ +import { useCallback, useMemo, useState } from "react"; import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; +import { DraggableList } from "@/components/draggable-list"; +import type { DraggableRenderItemInfo } from "@/components/draggable-list.types"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { isNative } from "@/constants/platform"; import { settingsStyles } from "@/styles/settings"; import { UsageCard } from "./card"; import type { UsageDisplay } from "./display"; import { useUsageInSidebar } from "./in-sidebar"; import type { UsageReportEntry } from "./types"; -/** One card per report (source + account). Window rows pin while the sidebar summary is on. */ +function reportKey(entry: UsageReportEntry): string { + return entry.id; +} + +/** + * 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. + */ export function UsageList({ serverId, reports, @@ -17,25 +29,113 @@ export function UsageList({ display: UsageDisplay; }) { const { inSidebar } = useUsageInSidebar(); + const { arrange, arrangeCards } = display; + const arranged = useMemo(() => arrange(reports), [arrange, reports]); + const handleDragEnd = useCallback( + (next: UsageReportEntry[], moved: string) => + arrangeCards({ moved, after: next.map(reportKey) }), + [arrangeCards], + ); + const renderItem = useCallback( + ({ item, isActive }: DraggableRenderItemInfo) => ( + + + + ), + [display, inSidebar, serverId], + ); return ( - - {reports.map((entry) => ( - - - - ))} + + ); +} + +/** + * The card inside its hover target: the drag handle shows while the pointer is over the card or + * keyboard focus is inside it, and always where there is no hover. + */ +function UsageListCard({ + serverId, + entry, + display, + pinnable, + dragging, +}: { + serverId: string; + entry: UsageReportEntry; + display: UsageDisplay; + pinnable: boolean; + dragging: boolean; +}) { + const isCompact = useIsCompactFormFactor(); + const [isHovered, setIsHovered] = useState(false); + const handlePointerEnter = useCallback(() => setIsHovered(true), []); + const handlePointerLeave = useCallback(() => setIsHovered(false), []); + // Focus events bubble from the card's controls, so tabbing onto the handle reveals it. + 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], + ); + return ( + + + + ); } const styles = StyleSheet.create((theme) => ({ + // Each card carries the gap below it, so a native drag moves it with its slot; the list + // takes the last one back. list: { - gap: theme.spacing[3], + marginBottom: -theme.spacing[3], + }, + item: { + paddingBottom: theme.spacing[3], + }, + hoverTarget: { + position: "relative", }, })); diff --git a/packages/app/src/usage/model.ts b/packages/app/src/usage/model.ts index bbe183dcd0..ac2cf62db2 100644 --- a/packages/app/src/usage/model.ts +++ b/packages/app/src/usage/model.ts @@ -2,7 +2,13 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; import { usageCopy } from "./copy"; import type { UsageDisplayAs } from "./preferences"; -import type { UsageReport, UsageReportEntry, UsageView, UsageWindow } from "./types"; +import type { + AvailableUsageReport, + UsageReport, + UsageReportEntry, + UsageView, + UsageWindow, +} from "./types"; export function usedPercent(window: UsageWindow): number | null { if (window.usedPct != null) return window.usedPct; @@ -205,13 +211,34 @@ export function resolveUsageModalHostId(choice: UsageHostChoice): string | null return picked?.serverId ?? resolveUsageHostId(choice) ?? connected[0]?.serverId ?? null; } +export interface UsageSnapshot { + report: AvailableUsageReport; + successfulAt: string; + retained: boolean; +} + +/** The latest successful values and their freshness, independent of the latest attempt's outcome. */ +export function resolveUsageSnapshot(entry: UsageReportEntry): UsageSnapshot | null { + if (entry.report.status === "available") { + // COMPAT(usageSuccessfulAt): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. + // Old daemons expose only attempt time for available reports, never for failures. + return { + report: entry.report, + successfulAt: entry.successfulAt ?? entry.fetchedAt, + retained: false, + }; + } + // COMPAT(usageLastSuccessful): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. + // Older daemons cannot provide history; a failed attempt is never a successful update. + const retained = entry.lastSuccessful; + if (!retained) return null; + return { report: retained.report, successfulAt: retained.fetchedAt, retained: true }; +} + /** Current outcome owns messages; only a successful poll owns values and freshness. */ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) { const available = entry.report.status === "available"; - // COMPAT(usageLastSuccessful): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. - // Older daemons cannot provide history; a failed attempt is never a successful update. - const snapshot = available ? null : (entry.lastSuccessful ?? null); - const content = entry.report.status === "available" ? entry.report : (snapshot?.report ?? null); + const snapshot = resolveUsageSnapshot(entry); const messages: string[] = []; if (!available) { if (entry.loginErrors) @@ -224,16 +251,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) { else messages.push(usageProblemText(entry.report, t)); } return { - windows: content?.windows ?? [], - balances: content?.balances ?? [], - details: content?.details ?? [], - planLabel: content?.planLabel ?? null, - // COMPAT(usageSuccessfulAt): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. - // Old daemons expose only attempt time for available reports, never for failures. - successfulAt: available - ? (entry.successfulAt ?? entry.fetchedAt) - : (snapshot?.fetchedAt ?? null), - retained: snapshot !== null, + windows: snapshot?.report.windows ?? [], + balances: snapshot?.report.balances ?? [], + details: snapshot?.report.details ?? [], + planLabel: snapshot?.report.planLabel ?? null, + successfulAt: snapshot?.successfulAt ?? null, + retained: snapshot?.retained ?? false, messages, }; } diff --git a/packages/app/src/usage/options.tsx b/packages/app/src/usage/options.tsx index cc674cb90f..53277eb20a 100644 --- a/packages/app/src/usage/options.tsx +++ b/packages/app/src/usage/options.tsx @@ -2,11 +2,22 @@ import { useTranslation } from "react-i18next"; import { View } from "react-native"; import { Settings } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; -import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu"; -import { extraMutedIconColorMapping } from "@/components/ui/icon-button-chrome"; -import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { useMemo } from "react"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuSubTrigger, + type MenuPageDefinition, +} from "@/components/ui/dropdown-menu"; +import { HostMenuItem } from "@/components/hosts/host-menu-item"; +import { getHostPickerLabel } from "@/components/hosts/host-picker"; +import { + mutedIconColorMapping, + useIconButtonChromeGlyphSize, +} from "@/components/ui/icon-button-chrome"; +import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; import { useIsCompactFormFactor } from "@/constants/layout"; -import { SettingsRow, SettingsSwitch } from "@/components/settings"; +import { MenuSettingsRows, SettingsRow, SettingsSwitch } from "@/components/settings"; import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; import { Alert } from "@/components/ui/alert"; import { useHosts } from "@/runtime/host-runtime"; @@ -14,12 +25,25 @@ import { settingsStyles } from "@/styles/settings"; import { useUsageSetting } from "./setting"; import { useUsageDisplay } from "./display"; import { useUsageInSidebar } from "./in-sidebar"; +import { hasHostChoice, type UsageHostSelection } from "./hosts"; import type { UsageDisplayAs } from "./preferences"; const ThemedSettings = withUnistyles(Settings); -/** The shared usage preferences, opened from a cog as a popover or compact sheet. */ -export function UsageOptions({ serverId }: { serverId: string | null }) { +const HOST_PAGE = "host"; + +/** + * 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. + */ +export function UsageOptions({ + serverId, + hostSelection, +}: { + serverId: string | null; + hostSelection?: UsageHostSelection; +}) { const setting = useUsageSetting(serverId); const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId; const { t } = useTranslation(); @@ -32,8 +56,23 @@ export function UsageOptions({ serverId }: { serverId: string | null }) { }, ]; const compact = useIsCompactFormFactor(); + const glyphSize = useIconButtonChromeGlyphSize("small", compact); const { display } = useUsageDisplay([]); const { inSidebar, setInSidebar } = useUsageInSidebar(); + const hostChoice = hasHostChoice(hostSelection) ? hostSelection : null; + const pages = useMemo( + () => + hostChoice + ? [ + { + id: HOST_PAGE, + title: t("providerUsage.host"), + content: , + }, + ] + : undefined, + [hostChoice, t], + ); return ( - + - - {setting.error ? : null} - {setting.supported ? ( - - ) : null} - - - - - - + {t("providerUsage.host")} + + ) : null} + + + {setting.error ? : null} + {setting.supported ? ( + - - + ) : null} + + + + + + + + + ); } + +function UsageHostPage({ hostSelection }: { hostSelection: UsageHostSelection }) { + return ( + <> + {hostSelection.hosts.map((host) => ( + + ))} + + ); +} diff --git a/packages/app/src/usage/pinned.test.ts b/packages/app/src/usage/pinned.test.ts index 410b81575f..b780659043 100644 --- a/packages/app/src/usage/pinned.test.ts +++ b/packages/app/src/usage/pinned.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { UsagePreferences } from "./preferences"; +import { DEFAULT_USAGE_PREFERENCES, type UsagePreferences } from "./preferences"; import { choosePinnedUsageLayout, resolvePinnedUsage, @@ -49,7 +49,7 @@ function preferences( pinned: UsagePreferences["pins"], displayAs: UsagePreferences["displayAs"] = "used", ): UsagePreferences { - return { displayAs, pins: pinned, serverId: null }; + return { ...DEFAULT_USAGE_PREFERENCES, displayAs, pins: pinned }; } describe("choosePinnedUsageLayout", () => { @@ -114,7 +114,7 @@ describe("resolvePinnedUsage", () => { ]); }); - it("groups pinned windows by source in report order, not pin order", () => { + it("lists pinned windows in card order, not pin order", () => { const work = report({ sourceId: "claude", sourceLabel: "Claude", @@ -139,6 +139,7 @@ describe("resolvePinnedUsage", () => { expect(sources[0]).toEqual({ key: "claude:default", icon: "", + hasError: false, windows: [ { key: "claude:default/five-hour", @@ -160,6 +161,28 @@ describe("resolvePinnedUsage", () => { }); }); + it("follows the arranged card order, even when it separates a source's accounts", () => { + const work = report({ + sourceId: "claude", + sourceLabel: "Claude", + account: "work", + windows: [{ id: "weekly", label: "Weekly", usedPct: 90 }], + }); + const sources = resolvePinnedUsage([claude, codex, work], { + ...preferences([ + { sourceId: "claude", windowId: "weekly" }, + { sourceId: "codex", windowId: "weekly" }, + ]), + cardOrder: ["claude:default", "codex:default", "claude:work"], + }); + + expect(sources.map((source) => source.key)).toEqual([ + "claude:default", + "codex:default", + "claude:work", + ]); + }); + it("names a window by its label when the source gives no short label", () => { const items = windows([codex], preferences([{ sourceId: "codex", windowId: "weekly" }])); @@ -257,7 +280,7 @@ describe("resolvePinnedUsage", () => { }); }); -it("keeps unavailable and error reports out of the sidebar summary even with retained data", () => { +it("shows retained windows and marks errored sources in the sidebar summary", () => { if (claude.report.status !== "available" || codex.report.status !== "available") throw new Error("fixtures must be available"); const expired: UsageReportEntry = { @@ -273,7 +296,30 @@ it("keeps unavailable and error reports out of the sidebar summary even with ret lastSuccessful: { fetchedAt: codex.fetchedAt, report: codex.report }, report: { status: "error", error: "Store deleted" }, }; - expect(resolvePinnedUsage([expired, failed], preferences(null))).toEqual([]); + const expected = [ + { key: "claude:default", hasError: false, windows: ["31%"] }, + { key: "codex:default", hasError: true, windows: ["12%"] }, + ]; + const summarize = (pins: UsagePreferences["pins"]) => + resolvePinnedUsage([expired, failed], preferences(pins)).map((source) => ({ + key: source.key, + hasError: source.hasError, + windows: source.windows.map((window) => window.percentText), + })); + + expect(summarize(null)).toEqual(expected); + expect( + summarize([ + { sourceId: "claude", windowId: "five-hour" }, + { sourceId: "codex", windowId: "weekly" }, + ]), + ).toEqual(expected); + expect( + resolvePinnedUsage( + [{ ...failed, lastSuccessful: undefined }], + preferences([{ sourceId: "codex", windowId: "weekly" }]), + ), + ).toEqual([]); }); it("localizes pinned labels and meanings while preserving custom window names", async () => { diff --git a/packages/app/src/usage/pinned.ts b/packages/app/src/usage/pinned.ts index 21fd4cf06c..b725c3e086 100644 --- a/packages/app/src/usage/pinned.ts +++ b/packages/app/src/usage/pinned.ts @@ -1,8 +1,13 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; -import { formatPct, formatDisplayPct, formatProviderUsageLabel } from "./format"; -import { displayPercent } from "./model"; -import { effectiveUsagePins, type UsagePreferences } from "./preferences"; +import { + formatPct, + formatDisplayPct, + formatProviderUsageLabel, + formatUsageAccountName, +} from "./format"; +import { displayPercent, resolveUsageSnapshot } from "./model"; +import { effectiveUsagePins, usageReportsOn, type UsagePreferences } from "./preferences"; import { windowTone } from "./tone"; import type { UsageReportEntry, UsageTone } from "./types"; @@ -23,6 +28,8 @@ export interface PinnedUsageWindow { export interface PinnedUsageSource { key: string; icon: string | null; + /** The displayed values are retained from before a failed refresh. */ + hasError: boolean; windows: PinnedUsageWindow[]; } @@ -53,19 +60,12 @@ export function choosePinnedUsageLayout(input: { } function describe(entry: UsageReportEntry, windowLabel: string): string { - const account = entry.account.label ? ` (${entry.account.label})` : ""; - return `${entry.sourceLabel}${account} ${windowLabel}`; -} - -/** Reports with every account of a source together, sources in the order they first appear. */ -function groupBySource(reports: readonly UsageReportEntry[]): UsageReportEntry[] { - const sourceIds = [...new Set(reports.map((entry) => entry.sourceId))]; - return sourceIds.flatMap((sourceId) => reports.filter((entry) => entry.sourceId === sourceId)); + return `${formatUsageAccountName(entry)} ${windowLabel}`; } /** - * The sidebar Usage item's summary: one group per account, grouped by source, each with its - * windows in its report's order. Accounts with nothing to show are left out. + * The sidebar Usage item's summary: one group per account in card order, each with its windows in + * its report's order. Accounts turned off or with nothing to show are left out. */ export function resolvePinnedUsage( reports: readonly UsageReportEntry[], @@ -73,9 +73,10 @@ export function resolvePinnedUsage( t: TFunction = i18n.t, ): PinnedUsageSource[] { const pins = effectiveUsagePins(preferences, reports); - return groupBySource(reports).flatMap((entry) => { - if (entry.report.status !== "available") return []; - const windows = entry.report.windows + return usageReportsOn(reports, preferences).flatMap((entry) => { + const snapshot = resolveUsageSnapshot(entry); + if (!snapshot) return []; + const windows = snapshot.report.windows .filter( (window) => displayPercent(window, preferences.displayAs) !== null && @@ -94,6 +95,13 @@ export function resolvePinnedUsage( }; }); if (windows.length === 0) return []; - return [{ key: entry.id, icon: entry.icon ?? null, windows }]; + return [ + { + key: entry.id, + icon: entry.icon ?? null, + hasError: entry.report.status === "error", + windows, + }, + ]; }); } diff --git a/packages/app/src/usage/preferences.test.ts b/packages/app/src/usage/preferences.test.ts index 43dccc466d..064920fb5e 100644 --- a/packages/app/src/usage/preferences.test.ts +++ b/packages/app/src/usage/preferences.test.ts @@ -31,7 +31,7 @@ describe("usage preferences", () => { it("unpins a pinned window and keeps the others in order", () => { const three = [codexWeekly, claudeFiveHour, { sourceId: "claude", windowId: "weekly" }]; const unpinned = toggleUsagePin({ - preferences: { displayAs: "used", pins: three, serverId: null }, + preferences: { ...DEFAULT_USAGE_PREFERENCES, pins: three }, pin: claudeFiveHour, reports: [], }); @@ -40,18 +40,18 @@ describe("usage preferences", () => { }); it("switches between used and remaining without touching pins", () => { - const preferences = { displayAs: "used" as const, pins: [codexWeekly], serverId: null }; + const preferences = { ...DEFAULT_USAGE_PREFERENCES, pins: [codexWeekly] }; expect(setUsageDisplayAs(preferences, "remaining")).toEqual({ + ...DEFAULT_USAGE_PREFERENCES, displayAs: "remaining", pins: [codexWeekly], - serverId: null, }); }); it("remembers the picked host without touching pins", () => { expect(setUsageHost({ ...DEFAULT_USAGE_PREFERENCES, pins: [codexWeekly] }, "server")).toEqual({ - displayAs: "used", + ...DEFAULT_USAGE_PREFERENCES, pins: [codexWeekly], serverId: "server", }); @@ -59,7 +59,7 @@ describe("usage preferences", () => { it("reads preferences saved before hosts could be picked as no pick", () => { expect(UsagePreferencesSchema.parse({ displayAs: "remaining", pinned: [codexWeekly] })).toEqual( - { displayAs: "remaining", pins: [codexWeekly], serverId: null }, + { ...DEFAULT_USAGE_PREFERENCES, displayAs: "remaining", pins: [codexWeekly] }, ); }); }); @@ -125,6 +125,6 @@ it("reads old selections without losing display or host and preserves an explici ] as const) { expect( UsagePreferencesSchema.parse({ displayAs: "remaining", serverId: "host", ...input }), - ).toEqual({ displayAs: "remaining", serverId: "host", pins }); + ).toEqual({ ...DEFAULT_USAGE_PREFERENCES, displayAs: "remaining", serverId: "host", pins }); } }); diff --git a/packages/app/src/usage/preferences.ts b/packages/app/src/usage/preferences.ts index e082870af6..7ad7d5a3e8 100644 --- a/packages/app/src/usage/preferences.ts +++ b/packages/app/src/usage/preferences.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { displayPercent } from "./model"; +import { displayPercent, resolveUsageSnapshot } from "./model"; import type { UsageReportEntry } from "./types"; /** Whether percentages read as the share used or the share left. */ @@ -18,15 +18,22 @@ export interface UsagePreferences { pins: UsagePin[] | null; /** The host the user picked to show usage for; null until they pick one. */ 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[]; } export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = { displayAs: "used", pins: null, serverId: null, + cardOrder: [], + cardsOff: [], }; const pinsSchema = z.array(z.object({ sourceId: z.string(), windowId: z.string() })); +const reportIdsSchema = z.array(z.string()).optional().catch(undefined); export const UsagePreferencesSchema = z .object({ @@ -36,10 +43,18 @@ export const UsagePreferencesSchema = z // Old [] meant defaults. Read it only when the new selection is absent. pinned: pinsSchema.optional().catch([]), serverId: z.string().nullable().catch(null), + cardOrder: reportIdsSchema, + cardsOff: reportIdsSchema, }) - .transform(({ displayAs, pins, pinned, serverId }): UsagePreferences => { + .transform(({ displayAs, pins, pinned, serverId, cardOrder, cardsOff }): UsagePreferences => { const legacyPins = pinned && pinned.length > 0 ? pinned : null; - return { displayAs, pins: pins === undefined ? legacyPins : pins, serverId }; + return { + displayAs, + pins: pins === undefined ? legacyPins : pins, + serverId, + cardOrder: cardOrder ?? [], + cardsOff: cardsOff ?? [], + }; }) .catch(DEFAULT_USAGE_PREFERENCES); @@ -55,8 +70,9 @@ export function effectiveUsagePins( if (preferences.pins !== null) return preferences.pins; const pins: UsagePin[] = []; for (const entry of reports) { - if (entry.report.status !== "available") continue; - const withPercent = entry.report.windows.filter( + const snapshot = resolveUsageSnapshot(entry); + if (!snapshot) continue; + const withPercent = snapshot.report.windows.filter( (window) => displayPercent(window, preferences.displayAs) !== null, ); const marked = withPercent.filter((window) => window.summary); @@ -103,3 +119,84 @@ export function setUsageDisplayAs( export function setUsageHost(preferences: UsagePreferences, serverId: string): UsagePreferences { return { ...preferences, serverId }; } + +/** Reports the user has not arranged: by provider, then account, then ID. */ +function compareByDefaultOrder(a: UsageReportEntry, b: UsageReportEntry): number { + return ( + a.sourceLabel.localeCompare(b.sourceLabel) || + (a.account.label ?? "").localeCompare(b.account.label ?? "") || + a.id.localeCompare(b.id) + ); +} + +/** + * Reports in the order their cards show: the ones the user arranged first, in their order, then + * the rest in the default order. Arrival order never matters, so a report that streams in late or + * appears for a new login lands in its own slot. + */ +export function arrangeUsageReports( + reports: readonly UsageReportEntry[], + preferences: UsagePreferences, +): UsageReportEntry[] { + const rank = new Map(preferences.cardOrder.map((id, index) => [id, index])); + return [...reports].sort((a, b) => { + const rankA = rank.get(a.id); + const rankB = rank.get(b.id); + if (rankA !== undefined && rankB !== undefined) return rankA - rankB; + if (rankA !== undefined) return -1; + if (rankB !== undefined) return 1; + return compareByDefaultOrder(a, b); + }); +} + +/** Reports whose cards are on, in card order: what the sidebar summary reads. */ +export function usageReportsOn( + reports: readonly UsageReportEntry[], + preferences: UsagePreferences, +): UsageReportEntry[] { + return arrangeUsageReports(reports, preferences).filter( + (entry) => !isUsageCardOff(preferences, entry.id), + ); +} + +/** A drop as the list reports it: the card the user moved and the shown cards' order after it. */ +export interface UsageCardDrop { + moved: string; + after: readonly string[]; +} + +/** + * The order after the user drops a card. Only the moved card changes place: it goes just before + * its new successor among the shown cards, or just after its new predecessor when it lands last. + * Shown cards not yet arranged are added at the end, in their shown order. Other arranged cards + * keep their places relative to each other. The order is shared by every host, so a drop that + * arranges a card another host also shows ranks it ahead of that host's unarranged cards. + */ +export function arrangeUsageCards( + preferences: UsagePreferences, + { moved, after }: UsageCardDrop, +): UsagePreferences { + const arranged = new Set([...preferences.cardOrder, moved]); + const rest = [ + ...preferences.cardOrder.filter((id) => id !== moved), + ...after.filter((id) => !arranged.has(id)), + ]; + const index = after.indexOf(moved); + const successor = after[index + 1]; + const at = successor === undefined ? rest.indexOf(after[index - 1]) + 1 : rest.indexOf(successor); + rest.splice(at, 0, moved); + return { ...preferences, cardOrder: rest }; +} + +export function isUsageCardOff(preferences: UsagePreferences, reportId: string): boolean { + return preferences.cardsOff.includes(reportId); +} + +export function setUsageCardOn( + preferences: UsagePreferences, + reportId: string, + on: boolean, +): UsagePreferences { + const others = preferences.cardsOff.filter((id) => id !== reportId); + return { ...preferences, cardsOff: on ? others : [...others, reportId] }; +} diff --git a/packages/app/src/usage/queries.ts b/packages/app/src/usage/queries.ts index 26a7fa62ea..702f115253 100644 --- a/packages/app/src/usage/queries.ts +++ b/packages/app/src/usage/queries.ts @@ -43,6 +43,11 @@ function hostUsageQueryKey(serverId: string) { return ["usage", serverId] as const; } +/** + * A host's own reports. The key differs only by host, so it is read with `dataShape: "value"`: + * a list shape keeps the previous key's data while the next one loads, which would show one host's + * reports as another's. + */ function usageReportsQueryKey(serverId: string) { return [...hostUsageQueryKey(serverId), "reports"] as const; } @@ -150,7 +155,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () = queryKey: usageReportsQueryKey(serverId), queryFn: () => listReports(queryClient, serverId), enabled: isConnected && isSupported && setting.enabled, - dataShape: "list", + dataShape: "value", staleTimeMs: REPORTS_STALE_TIME_MS, }); const refresh = useCallback(() => { @@ -189,7 +194,7 @@ export function useUsageHostReports({ enabled: setting.enabled, queryKey: usageReportsQueryKey(serverId ?? ""), queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken, - dataShape: "list", + dataShape: "value", staleTimeMs: REPORTS_STALE_TIME_MS, refetchInterval: shouldPoll ? REPORTS_REFETCH_INTERVAL_MS : false, }); diff --git a/packages/app/src/usage/refresh-button.tsx b/packages/app/src/usage/refresh-button.tsx index 473e4442cc..80a31389e4 100644 --- a/packages/app/src/usage/refresh-button.tsx +++ b/packages/app/src/usage/refresh-button.tsx @@ -1,9 +1,12 @@ import { useTranslation } from "react-i18next"; import { RotateCw } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; -import { extraMutedIconColorMapping } from "@/components/ui/icon-button-chrome"; +import { + mutedIconColorMapping, + useIconButtonChromeGlyphSize, +} from "@/components/ui/icon-button-chrome"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; import { useIsCompactFormFactor } from "@/constants/layout"; const ThemedRotateCw = withUnistyles(RotateCw); @@ -16,7 +19,7 @@ const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); export function UsageRefreshButton({ busy, onRefresh }: { busy: boolean; onRefresh: () => void }) { const { t } = useTranslation(); const compact = useIsCompactFormFactor(); - const iconSize = paneContentToolbarIconSize(compact); + const iconSize = useIconButtonChromeGlyphSize("small", compact); return ( {busy ? ( - + ) : ( - + )} ); diff --git a/packages/app/src/usage/sidebar-item.tsx b/packages/app/src/usage/sidebar-item.tsx index bd4dfeb65e..32136b0639 100644 --- a/packages/app/src/usage/sidebar-item.tsx +++ b/packages/app/src/usage/sidebar-item.tsx @@ -8,14 +8,11 @@ import { type ReactNode, } from "react"; import { useTranslation } from "react-i18next"; -import { - Pressable, - Text, - View, - type LayoutChangeEvent, - type PressableStateCallbackType, -} from "react-native"; -import { StyleSheet } from "react-native-unistyles"; +import { TriangleAlert } from "lucide-react-native"; +import { Text, View, type LayoutChangeEvent, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import type { Theme } from "@/styles/theme"; import { useRetainedPanelActive } from "@/components/retained-panel"; import { useAppVisible } from "@/hooks/use-app-visible"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; @@ -35,6 +32,9 @@ import { } from "./pinned"; import { UsageModal } from "./usage-modal"; +const ThemedTriangleAlert = withUnistyles(TriangleAlert); +const errorIconColor = (theme: Theme) => ({ color: theme.colors.statusDanger }); + /** Each summary window with data on the usage host, under its source; empty while none has. */ export function useUsageSummary(): readonly PinnedUsageSource[] { const { t } = useTranslation(); @@ -60,7 +60,14 @@ export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSou const label = t(builtinSidebarNavLabelKey("usage")); const openUsage = useOpenSidebarUsage(); if (sources.length === 0) return null; - return ; + return ( + + ); } const OpenSidebarUsageContext = createContext<(() => void) | null>(null); @@ -95,13 +102,19 @@ export function useOpenSidebarUsage(): () => void { return openUsage; } -function pinnedUsageLabel(label: string, sources: readonly PinnedUsageSource[]): string { +function pinnedUsageLabel( + label: string, + sources: readonly PinnedUsageSource[], + errorLabel: string, +): string { const windows = sources.flatMap((source) => source.windows); - return `${label}: ${windows.map((window) => window.label).join(", ")}`; + const summary = windows.map((window) => window.label).join(", "); + const error = sources.some((source) => source.hasError) ? `, ${errorLabel}` : ""; + return `${label}: ${summary}${error}`; } function triggerStyle({ hovered }: PressableStateCallbackType & { hovered?: boolean }) { - return hovered ? [styles.trigger, styles.triggerHovered] : styles.trigger; + return [styles.trigger, hovered && styles.triggerHovered]; } function layoutWidth(event: LayoutChangeEvent): number { @@ -116,10 +129,12 @@ function layoutWidth(event: LayoutChangeEvent): number { function PinnedUsageTrigger({ label, sources, + errorLabel, onPress, }: { label: string; sources: readonly PinnedUsageSource[]; + errorLabel: string; onPress: () => void; }) { const [available, setAvailable] = useState(null); @@ -141,11 +156,12 @@ function PinnedUsageTrigger({ windowCount: sources.reduce((count, source) => count + source.windows.length, 0), }); return ( - @@ -165,7 +181,7 @@ function PinnedUsageTrigger({ - + ); } @@ -185,10 +201,17 @@ function PinnedUsageLine({ return sources.map((source, sourceIndex) => ( + {source.hasError ? ( + + ) : null} {source.windows.map((window, windowIndex) => { const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap; @@ -231,6 +254,9 @@ const styles = StyleSheet.create((theme) => ({ triggerHovered: { backgroundColor: theme.colors.surfaceSidebarHover, }, + triggerPressed: { + backgroundColor: theme.colors.surface2, + }, line: { flex: 1, minWidth: 0, @@ -251,6 +277,11 @@ const styles = StyleSheet.create((theme) => ({ flexDirection: "row", alignItems: "center", }, + source: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1], + }, sourceGap: { marginLeft: theme.spacing[3], }, diff --git a/packages/app/src/usage/usage-modal.tsx b/packages/app/src/usage/usage-modal.tsx index 4e049c0b58..d93bea8b1b 100644 --- a/packages/app/src/usage/usage-modal.tsx +++ b/packages/app/src/usage/usage-modal.tsx @@ -1,11 +1,12 @@ import { useMemo, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { View } from "react-native"; -import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet"; +import { AdaptiveModalSheet, SheetHeaderSubtitle } from "@/components/adaptive-modal-sheet"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; import { useHostUsageWithControls } from "./controls"; import { useUsageDisplay } from "./display"; -import { useUsageHostSelection } from "./hosts"; +import { getHostPickerLabel } from "@/components/hosts/host-picker"; +import { hasHostChoice, useUsageHostSelection } from "./hosts"; import type { UsageHost } from "./model"; import { UsageBody, UsageMessage } from "./usage-section"; @@ -17,8 +18,8 @@ interface UsageModalProps { /** * Usage over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. It - * shows the usage host's reports with pins, and the host filter, Refresh all, and Settings in its - * title row. + * shows the usage host's reports with pins, and Refresh all and Settings in its title row. With more + * than one host, the host shown is the title's subtitle, and Settings is where it is picked. */ export function UsageModal(props: UsageModalProps) { const { t } = useTranslation(); @@ -30,15 +31,8 @@ export function UsageModal(props: UsageModalProps) { ); } - // Keyed by host so a refresh in flight on one host never shows on another's cards. return ( - + ); } @@ -58,9 +52,15 @@ function HostUsageModal({ ); const { view, refresh, controls } = useHostUsageWithControls(hostSelection); const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); + const hostLabel = hasHostChoice(hostSelection) + ? getHostPickerLabel(hostSelection.hosts, hostSelection.serverId) + : undefined; return ( - - + + {/* Keyed by host so state the cards hold, such as a refresh in flight, never shows on another + host's cards. The frame is not keyed: remounting it would dismiss a compact sheet, and Usage + with it. */} + @@ -72,11 +72,22 @@ function UsageModalFrame({ onClose, onDismiss, actions, + subtitle, children, -}: UsageModalProps & { actions?: ReactNode; children: ReactNode }) { +}: UsageModalProps & { actions?: ReactNode; subtitle?: string; children: ReactNode }) { const { t } = useTranslation(); const title = t(builtinSidebarNavLabelKey("usage")); - const header = useMemo(() => ({ title, actions }), [actions, title]); + const header = useMemo( + () => ({ + title, + titleTestID: "usage-modal-title", + subtitle: subtitle ? ( + + ) : undefined, + actions, + }), + [actions, subtitle, title], + ); return ( { it("parses six-digit hex", () => { @@ -71,3 +78,43 @@ describe("desaturateHexColor", () => { expect(desaturateHexColor("currentColor", 0.5)).toBe("currentColor"); }); }); + +describe("contrastRatio", () => { + it("is 21 between black and white and 1 for the same color", () => { + expect(contrastRatio("#000000", "#ffffff")).toBeCloseTo(21, 5); + expect(contrastRatio("#3e704a", "#3e704a")).toBe(1); + }); +}); + +describe("stepContrast", () => { + it("steps off pure black by a visible contrast, where a lightness delta would not", () => { + const stepped = stepContrast("#000000", "#fafafa", 1.11); + expect(stepped).not.toBe("#000000"); + expect(contrastRatio("#000000", stepped)).toBeCloseTo(1.11, 1); + }); + + it("moves toward the target, lighter or darker", () => { + expect(stepContrast("#f4f4f5", "#1a1a1e", 1.35) < "#f4f4f5").toBe(true); + expect(stepContrast("#181b1a", "#fafafa", 1.245) > "#181b1a").toBe(true); + }); + + it("stops at the target when the ratio is out of reach", () => { + expect(stepContrast("#808080", "#909090", 21)).toBe("#909090"); + }); +}); + +describe("colours with an alpha channel", () => { + it("are compared and stepped as the opaque colour", () => { + expect(contrastRatio("#1e1e2eff", "#ffffff")).toBe(contrastRatio("#1e1e2e", "#ffffff")); + expect(contrastRatio("#fffe", "#000")).toBeCloseTo(21, 5); + expect(stepContrast("#1e1e2e80", "#cdd6f4", 1.8)).toBe(stepContrast("#1e1e2e", "#cdd6f4", 1.8)); + }); +}); + +describe("mixHexColors", () => { + it("blends by the given fraction", () => { + expect(mixHexColors("#000000", "#ffffff", 0)).toBe("#000000"); + expect(mixHexColors("#000000", "#ffffff", 1)).toBe("#ffffff"); + expect(mixHexColors("#000000", "#ffffff", 0.5)).toBe("#808080"); + }); +}); diff --git a/packages/app/src/utils/color.ts b/packages/app/src/utils/color.ts index 64bc75533e..195ce06047 100644 --- a/packages/app/src/utils/color.ts +++ b/packages/app/src/utils/color.ts @@ -104,3 +104,67 @@ export function desaturateHexColor(hex: string, amount: number): string { return `#${toHexChannel(linearToSrgb(linearR))}${toHexChannel(linearToSrgb(linearG))}${toHexChannel(linearToSrgb(linearB))}`; } + +function relativeLuminance([r, g, b]: [number, number, number]): number { + return 0.2126 * srgbToLinear(r) + 0.7152 * srgbToLinear(g) + 0.0722 * srgbToLinear(b); +} + +// Derivation compares opaque colors. `#rgba` and `#rrggbbaa` are valid theme input, so their alpha +// channel is dropped here and the colour is read as the opaque one it sits on. +function withoutAlpha(hex: string): string { + if (/^#[0-9a-fA-F]{4}$/.test(hex)) return hex.slice(0, 4); + if (/^#[0-9a-fA-F]{8}$/.test(hex)) return hex.slice(0, 7); + return hex; +} + +function requireRgb(hex: string): [number, number, number] { + const rgb = parseHexColor(withoutAlpha(hex)); + if (!rgb) throw new TypeError(`Expected a hex color, received ${hex}`); + return rgb; +} + +/** WCAG contrast ratio between two hex colours, from 1 (identical) to 21. */ +export function contrastRatio(a: string, b: string): number { + const first = relativeLuminance(requireRgb(a)); + const second = relativeLuminance(requireRgb(b)); + const [lighter, darker] = first >= second ? [first, second] : [second, first]; + return (lighter + 0.05) / (darker + 0.05); +} + +/** + * Moves `hex` toward `toward` until it sits at `ratio` WCAG contrast from where it started. + * + * A step is expressed as a contrast ratio rather than a lightness delta because a lightness step + * vanishes near black: the same OKLab delta that is obvious on mid grey changes nothing visible + * on `#000000`, while a contrast step stays equally visible on every base. The move is a blend in + * linear light, so hue stays with the base. A ratio the target cannot reach stops at the target. + */ +export function stepContrast(hex: string, toward: string, ratio: number): string { + const from = requireRgb(hex); + const goal = requireRgb(toward); + const fromLuminance = relativeLuminance(from); + const goalLuminance = relativeLuminance(goal); + if (goalLuminance === fromLuminance) return hex; + const lighter = goalLuminance > fromLuminance; + const targetLuminance = lighter + ? ratio * (fromLuminance + 0.05) - 0.05 + : (fromLuminance + 0.05) / ratio - 0.05; + const reach = (targetLuminance - fromLuminance) / (goalLuminance - fromLuminance); + const amount = Math.min(1, Math.max(0, reach)); + const channels = from.map((channel, index) => { + const start = srgbToLinear(channel); + const end = srgbToLinear(goal[index]); + return toHexChannel(linearToSrgb(start + (end - start) * amount)); + }); + return `#${channels.join("")}`; +} + +/** Blends `hex` toward `toward` by `amount` (0 keeps `hex`, 1 is `toward`) in sRGB. */ +export function mixHexColors(hex: string, toward: string, amount: number): string { + const from = requireRgb(hex); + const goal = requireRgb(toward); + const channels = from.map((channel, index) => + toHexChannel(channel + (goal[index] - channel) * amount), + ); + return `#${channels.join("")}`; +} diff --git a/packages/app/src/utils/desktop-badge-state.test.ts b/packages/app/src/utils/desktop-badge-state.test.ts index 9bcdd39bc4..c02a667249 100644 --- a/packages/app/src/utils/desktop-badge-state.test.ts +++ b/packages/app/src/utils/desktop-badge-state.test.ts @@ -1,9 +1,39 @@ import { describe, expect, it } from "vitest"; +import type { WorkspaceDescriptor } from "@/stores/session-store"; import { - deriveMacDockBadgeCountFromWorkspaceStatuses, + createMacDockBadgeCountSelector, isWorkspaceActionableForDesktopBadge, + selectMacDockBadgeCount, } from "./desktop-badge-state"; +function workspace(id: string, status: WorkspaceDescriptor["status"]): WorkspaceDescriptor { + return { + createdAt: null, + lastUserMessageAt: null, + id, + projectId: "project-1", + projectDisplayName: "Project 1", + projectRootPath: "/repo", + workspaceDirectory: "/repo", + projectKind: "git", + workspaceKind: "local_checkout", + name: id, + status, + archivingAt: null, + statusEnteredAt: null, + diffStat: null, + scripts: [], + }; +} + +function stateWith(...workspaces: WorkspaceDescriptor[]) { + return { + sessions: { + srv_a: { workspaces: new Map(workspaces.map((entry) => [entry.id, entry])) }, + }, + }; +} + describe("desktop-badge-state", () => { it("treats attention-requiring workspace statuses as actionable", () => { expect(isWorkspaceActionableForDesktopBadge("attention")).toBe(true); @@ -17,18 +47,52 @@ describe("desktop-badge-state", () => { }); it("returns undefined when no visible workspaces need attention", () => { - expect(deriveMacDockBadgeCountFromWorkspaceStatuses(["done", "running"])).toBeUndefined(); + expect( + selectMacDockBadgeCount(stateWith(workspace("a", "done"), workspace("b", "running"))), + ).toBeUndefined(); }); - it("counts only actionable visible workspaces", () => { - expect( - deriveMacDockBadgeCountFromWorkspaceStatuses([ - "done", - "attention", - "running", - "needs_input", - "failed", - ]), - ).toBe(3); + it("counts only actionable visible workspaces across every host", () => { + const state = { + sessions: { + srv_a: { + workspaces: new Map([ + ["a", workspace("a", "done")], + ["b", workspace("b", "attention")], + ]), + }, + srv_b: { + workspaces: new Map([ + ["c", workspace("c", "running")], + ["d", workspace("d", "needs_input")], + ["e", workspace("e", "failed")], + ]), + }, + }, + }; + expect(selectMacDockBadgeCount(state)).toBe(3); + }); + + it("leaves out background workspaces, which the sidebar hides", () => { + const hidden = { ...workspace("a", "attention"), background: true }; + expect(selectMacDockBadgeCount(stateWith(hidden))).toBeUndefined(); + expect(selectMacDockBadgeCount(stateWith(hidden, workspace("b", "failed")))).toBe(1); + }); + + it("counts background workspaces while Show background puts them in the sidebar", () => { + const hidden = { ...workspace("a", "attention"), background: true }; + expect(selectMacDockBadgeCount(stateWith(hidden), { showBackground: true })).toBe(1); + expect(createMacDockBadgeCountSelector({ showBackground: true })(stateWith(hidden))).toBe(1); + }); + + it("recounts only when a workspace map is replaced", () => { + const select = createMacDockBadgeCountSelector(); + const state = stateWith(workspace("a", "attention")); + expect(select(state)).toBe(1); + + state.sessions.srv_a.workspaces.set("b", workspace("b", "failed")); + expect(select({ sessions: { ...state.sessions } })).toBe(1); + + expect(select(stateWith(workspace("a", "attention"), workspace("b", "failed")))).toBe(2); }); }); diff --git a/packages/app/src/utils/desktop-badge-state.ts b/packages/app/src/utils/desktop-badge-state.ts index 00a2a78328..1888cb9534 100644 --- a/packages/app/src/utils/desktop-badge-state.ts +++ b/packages/app/src/utils/desktop-badge-state.ts @@ -1,14 +1,51 @@ import type { WorkspaceDescriptor } from "@/stores/session-store"; +import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; export type DesktopBadgeWorkspaceStatus = WorkspaceDescriptor["status"]; +interface WorkspaceStatusSession { + workspaces: ReadonlyMap; +} + +interface WorkspaceStatusSource { + sessions: Record; +} + export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspaceStatus): boolean { return status === "attention" || status === "needs_input" || status === "failed"; } -export function deriveMacDockBadgeCountFromWorkspaceStatuses( - statuses: readonly DesktopBadgeWorkspaceStatus[], +/** + * The macOS dock badge only needs a count, so count here instead of materialising every + * workspace status and comparing the whole list on every store write. + */ +export interface DockBadgeOptions { + /** Count background workspaces too, as the sidebar shows them while Show background is on. */ + showBackground?: boolean; +} + +export function selectMacDockBadgeCount( + state: WorkspaceStatusSource, + options: DockBadgeOptions = {}, ): number | undefined { - const actionableCount = statuses.filter(isWorkspaceActionableForDesktopBadge).length; + let actionableCount = 0; + for (const session of Object.values(state.sessions)) { + if (!session) continue; + for (const workspace of session.workspaces.values()) { + // A hidden background workspace would leave the badge pointing at nothing in the sidebar. + if (workspace.background && !options.showBackground) continue; + if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1; + } + } return actionableCount > 0 ? actionableCount : undefined; } + +/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */ +export function createMacDockBadgeCountSelector( + options: DockBadgeOptions = {}, +): (state: WorkspaceStatusSource) => number | undefined { + return memoizeOnSessionMaps( + (session) => [session.workspaces], + (state) => selectMacDockBadgeCount(state, options), + ); +} diff --git a/packages/app/src/utils/favicon-status.test.ts b/packages/app/src/utils/favicon-status.test.ts new file mode 100644 index 0000000000..a2e26e2ac1 --- /dev/null +++ b/packages/app/src/utils/favicon-status.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import type { Agent, WorkspaceDescriptor } from "@/stores/session-store"; +import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status"; + +function agent(input: Partial & { id: string }): Agent { + return { + status: "idle", + background: false, + archivedAt: null, + requiresAttention: false, + pendingPermissions: [], + ...input, + } as Agent; +} + +function stateWith(...agents: Agent[]) { + return stateWithWorkspaces([], ...agents); +} + +function stateWithWorkspaces( + workspaces: Array>, + ...agents: Agent[] +) { + return { + sessions: { + srv: { + agents: new Map(agents.map((entry) => [entry.id, entry])), + workspaces: new Map(workspaces.map((entry) => [entry.id, entry])), + }, + }, + }; +} + +describe("deriveFaviconStatus", () => { + it("is running when any visible agent runs", () => { + expect( + deriveFaviconStatus( + stateWith( + agent({ id: "a", requiresAttention: true }), + agent({ id: "b", status: "running" }), + ), + ), + ).toBe("running"); + }); + + it("needs attention for attention or pending permissions", () => { + expect(deriveFaviconStatus(stateWith(agent({ id: "a", requiresAttention: true })))).toBe( + "attention", + ); + expect( + deriveFaviconStatus( + stateWith(agent({ id: "a", pendingPermissions: [{}] as Agent["pendingPermissions"] })), + ), + ).toBe("attention"); + }); + + it("ignores background and archived agents", () => { + expect( + deriveFaviconStatus( + stateWith( + agent({ id: "a", status: "running", background: true }), + agent({ id: "b", requiresAttention: true, archivedAt: new Date() }), + ), + ), + ).toBe("none"); + }); + + it("ignores agents in background workspaces, which the sidebar hides", () => { + const hidden = { id: "ws-hidden", background: true }; + expect( + deriveFaviconStatus( + stateWithWorkspaces( + [hidden], + agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }), + agent({ id: "b", workspaceId: "ws-hidden", status: "running" }), + ), + ), + ).toBe("none"); + expect( + deriveFaviconStatus( + stateWithWorkspaces( + [hidden, { id: "ws-shown", background: false }], + agent({ id: "a", workspaceId: "ws-hidden", status: "running" }), + agent({ id: "b", workspaceId: "ws-shown", requiresAttention: true }), + ), + ), + ).toBe("attention"); + }); + + it("counts agents in background workspaces while Show background puts them in the sidebar", () => { + const state = stateWithWorkspaces( + [{ id: "ws-hidden", background: true }], + agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }), + ); + expect(deriveFaviconStatus(state, { showBackground: true })).toBe("attention"); + expect(createFaviconStatusSelector({ showBackground: true })(state)).toBe("attention"); + }); +}); + +describe("createFaviconStatusSelector", () => { + it("reuses its result while the agent maps are unchanged", () => { + const select = createFaviconStatusSelector(); + const state = stateWith(agent({ id: "a", status: "running" })); + expect(select(state)).toBe("running"); + + // Same agent map, mutated behind the store's back: the selector must not rescan. + state.sessions.srv.agents.set("a", agent({ id: "a" })); + expect(select({ sessions: { ...state.sessions } })).toBe("running"); + }); + + it("rescans when a workspace map is replaced", () => { + const select = createFaviconStatusSelector(); + const state = stateWithWorkspaces( + [], + agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }), + ); + expect(select(state)).toBe("attention"); + // The agent synced before its workspace; only the workspace map changes. + const workspaces = new Map([["ws-hidden", { id: "ws-hidden", background: true }]]); + expect(select({ sessions: { srv: { ...state.sessions.srv, workspaces } } })).toBe("none"); + }); + + it("rescans when an agent map is replaced", () => { + const select = createFaviconStatusSelector(); + expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running"); + expect(select(stateWith(agent({ id: "a" })))).toBe("none"); + }); +}); diff --git a/packages/app/src/utils/favicon-status.ts b/packages/app/src/utils/favicon-status.ts new file mode 100644 index 0000000000..cea80b7f83 --- /dev/null +++ b/packages/app/src/utils/favicon-status.ts @@ -0,0 +1,56 @@ +import type { Agent, WorkspaceDescriptor } from "@/stores/session-store"; +import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; + +export type FaviconStatus = "none" | "running" | "attention"; + +interface FaviconAgentSession { + agents: ReadonlyMap; + workspaces: ReadonlyMap>; +} + +interface FaviconAgentSource { + sessions: Record; +} + +/** + * The favicon is the only always-mounted consumer of the whole agent directory, so derive its + * three states here instead of building the aggregated agent list: the list allocates a + * projection per agent, deep-compares it and sorts every agent on the host on each update. + */ +export interface FaviconStatusOptions { + /** Count agents in background workspaces too, as the sidebar shows them while Show background is on. */ + showBackground?: boolean; +} + +export function deriveFaviconStatus( + state: FaviconAgentSource, + options: FaviconStatusOptions = {}, +): FaviconStatus { + let hasAttention = false; + let hasNeedsInput = false; + for (const session of Object.values(state.sessions)) { + if (!session) continue; + for (const agent of session.agents.values()) { + if (agent.background || agent.archivedAt) continue; + if (!options.showBackground && isInBackgroundWorkspace(agent, session)) continue; + if (agent.status === "running") return "running"; + if (agent.requiresAttention) hasAttention = true; + if (agent.pendingPermissions.length > 0) hasNeedsInput = true; + } + } + return hasAttention || hasNeedsInput ? "attention" : "none"; +} + +function isInBackgroundWorkspace(agent: Agent, session: FaviconAgentSession): boolean { + return agent.workspaceId ? session.workspaces.get(agent.workspaceId)?.background === true : false; +} + +/** A session-store selector for the favicon status that rescans only when an agent or workspace map changes. */ +export function createFaviconStatusSelector( + options: FaviconStatusOptions = {}, +): (state: FaviconAgentSource) => FaviconStatus { + return memoizeOnSessionMaps( + (session) => [session.agents, session.workspaces], + (state) => deriveFaviconStatus(state, options), + ); +} diff --git a/packages/app/src/utils/memoize-on-session-maps.ts b/packages/app/src/utils/memoize-on-session-maps.ts new file mode 100644 index 0000000000..5daeb58674 --- /dev/null +++ b/packages/app/src/utils/memoize-on-session-maps.ts @@ -0,0 +1,31 @@ +interface SessionsSource { + sessions: Record; +} + +/** + * Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has + * changed. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost + * a reference check per host instead of a walk over every entry. + */ +export function memoizeOnSessionMaps, TResult>( + pickMaps: (session: TSession) => readonly unknown[], + derive: (state: TState) => TResult, +): (state: TState) => TResult { + let previousMaps: unknown[] | null = null; + let previousResult: TResult; + return (state) => { + const maps = Object.values(state.sessions).flatMap((session) => + session ? pickMaps(session) : [undefined], + ); + if ( + previousMaps && + previousMaps.length === maps.length && + previousMaps.every((map, index) => map === maps[index]) + ) { + return previousResult; + } + previousMaps = maps; + previousResult = derive(state); + return previousResult; + }; +} diff --git a/packages/app/src/utils/projects.ts b/packages/app/src/utils/projects.ts index 647561c56f..3136476b74 100644 --- a/packages/app/src/utils/projects.ts +++ b/packages/app/src/utils/projects.ts @@ -8,6 +8,8 @@ export interface WorkspaceSummary { name: string; title?: string; workspaceKind: WorkspaceDescriptor["workspaceKind"]; + /** Started by automation rather than the user. The sidebar hides it unless asked. */ + background: boolean; status: WorkspaceDescriptor["status"]; currentBranch: string | null; archivingAt?: string; @@ -158,6 +160,7 @@ function toWorkspaceSummary(workspace: WorkspaceDescriptor): WorkspaceSummary { name: workspace.name, ...(workspace.title ? { title: workspace.title } : {}), workspaceKind: workspace.workspaceKind, + background: workspace.background ?? false, status: workspace.status, currentBranch: currentBranch && currentBranch !== "HEAD" ? currentBranch : null, ...(workspace.archivingAt ? { archivingAt: workspace.archivingAt } : {}), diff --git a/packages/app/src/window-layout/context.ts b/packages/app/src/window-layout/context.ts index b1da8c58f8..1fe1a9dc98 100644 --- a/packages/app/src/window-layout/context.ts +++ b/packages/app/src/window-layout/context.ts @@ -1,5 +1,6 @@ import { createContext, useContext } from "react"; import { useWindowDimensions } from "react-native"; +import type { EdgeInsets } from "react-native-safe-area-context"; import type { TopBand, WindowLayout } from "./model"; export const WindowLayoutContext = createContext(null); @@ -7,6 +8,12 @@ export const WindowLayoutContext = createContext(null); /** Published by `WindowLayoutProvider` beside the safe-area insets it derives from it. */ export const TopBandContext = createContext(null); +/** + * The insets of the whole window, published by `WindowLayoutProvider` before any surface (a + * sheet tab, for one) narrows the insets its content reads. + */ +export const WindowInsetsContext = createContext(null); + export function useWindowLayout(): WindowLayout | null { const layout = useContext(WindowLayoutContext); const { width, height } = useWindowDimensions(); diff --git a/packages/app/src/window-layout/index.ios.tsx b/packages/app/src/window-layout/index.ios.tsx index 47c985dace..e698fb72fd 100644 --- a/packages/app/src/window-layout/index.ios.tsx +++ b/packages/app/src/window-layout/index.ios.tsx @@ -2,13 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react"; import { StyleSheet, View, type NativeSyntheticEvent, type ViewProps } from "react-native"; import { requireNativeViewManager } from "expo-modules-core"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; -import { TopBandContext, WindowLayoutContext, useWindowLayout } from "./context"; +import { + TopBandContext, + WindowInsetsContext, + WindowLayoutContext, + useWindowLayout, +} from "./context"; import { resolveSafeAreaInsets, resolveTopBand, type WindowLayout } from "./model"; export { useWindowLayout } from "./context"; export { WindowLayoutActions, WindowLayoutActionsHost } from "./actions"; export { WindowLayoutSurface, WindowLayoutDivisionGap } from "./surface"; export { useTopBand } from "./context"; +export { WindowSafeArea } from "./window-safe-area"; export { resolveDesktopDivisionLayout, resolveWorkspaceActionPlacement, @@ -56,7 +62,9 @@ function WindowSafeAreaInsets({ children }: { children: ReactNode }) { ); return ( - {children} + + {children} + ); } diff --git a/packages/app/src/window-layout/index.tsx b/packages/app/src/window-layout/index.tsx index 13a7c4c128..0b71f1f0cd 100644 --- a/packages/app/src/window-layout/index.tsx +++ b/packages/app/src/window-layout/index.tsx @@ -1,9 +1,12 @@ import type { ReactNode } from "react"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { WindowInsetsContext } from "./context"; export { useWindowLayout } from "./context"; export { WindowLayoutActions, WindowLayoutActionsHost } from "./actions"; export { WindowLayoutSurface, WindowLayoutDivisionGap } from "./surface"; export { useTopBand } from "./context"; +export { WindowSafeArea } from "./window-safe-area"; export { resolveDesktopDivisionLayout, resolveWorkspaceActionPlacement, @@ -12,5 +15,6 @@ export { export type { DesktopDivisionLayout, TopBand, WindowLayout, WindowLayoutRect } from "./model"; export function WindowLayoutProvider({ children }: { children: ReactNode }) { - return children; + const insets = useSafeAreaInsets(); + return {children}; } diff --git a/packages/app/src/window-layout/window-safe-area.browser.test.tsx b/packages/app/src/window-layout/window-safe-area.browser.test.tsx new file mode 100644 index 0000000000..62af88ca06 --- /dev/null +++ b/packages/app/src/window-layout/window-safe-area.browser.test.tsx @@ -0,0 +1,43 @@ +import React, { act } from "react"; +import { createRoot } from "react-dom/client"; +import { Text } from "react-native"; +import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; +import { afterEach, expect, it, vi } from "vitest"; +import { WindowLayoutProvider, WindowSafeArea } from "@/window-layout"; + +vi.stubGlobal("React", React); +const windowInsets = { top: 52, right: 0, bottom: 24, left: 0 }; +const sheetTabInsets = { ...windowInsets, bottom: 0 }; +const container = document.createElement("div"); +document.body.appendChild(container); +const root = createRoot(container); +afterEach(() => { + act(() => root.render(null)); +}); + +function InsetsProbe({ testID }: { testID: string }) { + const insets = useSafeAreaInsets(); + return {JSON.stringify(insets)}; +} + +it("gives an overlay opened inside a sheet tab the window's insets", () => { + act(() => + root.render( + + + + + + + + + + , + ), + ); + + const insetsOf = (testID: string) => + JSON.parse(container.querySelector(`[data-testid="${testID}"]`)?.textContent ?? "null"); + expect(insetsOf("sheet-tab")).toEqual(sheetTabInsets); + expect(insetsOf("overlay")).toEqual(windowInsets); +}); diff --git a/packages/app/src/window-layout/window-safe-area.tsx b/packages/app/src/window-layout/window-safe-area.tsx new file mode 100644 index 0000000000..908e4a26f2 --- /dev/null +++ b/packages/app/src/window-layout/window-safe-area.tsx @@ -0,0 +1,15 @@ +import { useContext, type ReactNode } from "react"; +import { SafeAreaInsetsContext } from "react-native-safe-area-context"; +import { WindowInsetsContext } from "./context"; + +/** + * Gives an overlay that draws over the whole window, such as an RN `Modal`, the window's insets + * instead of the ones its call site was given. Read them below it with `useSafeAreaInsets()`. + */ +export function WindowSafeArea({ children }: { children: ReactNode }) { + const insets = useContext(WindowInsetsContext); + if (!insets) { + throw new Error("WindowSafeArea must render inside WindowLayoutProvider"); + } + return {children}; +} diff --git a/packages/app/src/workspace-labels/manager-modal.tsx b/packages/app/src/workspace-labels/manager-modal.tsx index 8b0905dd16..5ef3252e5c 100644 --- a/packages/app/src/workspace-labels/manager-modal.tsx +++ b/packages/app/src/workspace-labels/manager-modal.tsx @@ -191,6 +191,7 @@ export function WorkspaceLabelManagerModal({ selectedHost={state.serverId} onSelectHost={selectHost} includeAllHost={false} + hang triggerTestID="workspace-label-manager-host" hostOptionTestID={managerHostOptionTestID} /> diff --git a/packages/app/src/workspace/open-in-editor/planner.test.ts b/packages/app/src/workspace/open-in-editor/planner.test.ts index d97e54c22c..694816593c 100644 --- a/packages/app/src/workspace/open-in-editor/planner.test.ts +++ b/packages/app/src/workspace/open-in-editor/planner.test.ts @@ -184,6 +184,55 @@ describe("planWorkspaceOpenTargets", () => { ]); }); + it("opens the branch and the active file on the web host the daemon resolved for an SSH alias", () => { + const aliasStatus = { + isGit: true, + remoteUrl: "git@github.com-work:acme/repo.git", + currentBranch: "feature/x", + forgeWeb: { host: "github.com" }, + }; + const open = (activeFile?: { path: string }) => + planWorkspaceOpenTargets({ + workspaceDirectory: "/repo", + activeFile, + desktopTargets: [], + canUseDesktopBridge: false, + isLocalExecution: false, + checkoutStatus: aliasStatus, + forge: "github", + }).map((target) => (target.source === "forge" ? target.url : null)); + + expect(open()).toEqual(["https://github.com/acme/repo/tree/feature/x"]); + expect(open({ path: "src/app.ts" })).toEqual([ + "https://github.com/acme/repo/blob/feature/x/src/app.ts", + ]); + }); + + it("keeps the branch and file on the origin repository of a fork", () => { + const forkStatus = { + isGit: true, + remoteUrl: "git@github.com:fork-owner/repo.git", + currentBranch: "feature/only-on-fork", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }; + const forgeUrls = (activeFile: { path: string } | undefined) => + planWorkspaceOpenTargets({ + workspaceDirectory: "/repo", + activeFile, + desktopTargets: [], + canUseDesktopBridge: false, + isLocalExecution: false, + checkoutStatus: forkStatus, + forge: "github", + }).flatMap((target) => (target.source === "forge" ? [target.url] : [])); + const urls = [...forgeUrls(undefined), ...forgeUrls({ path: "src/app.ts" })]; + + expect(urls).toEqual([ + "https://github.com/fork-owner/repo/tree/feature/only-on-fork", + "https://github.com/fork-owner/repo/blob/feature/only-on-fork/src/app.ts", + ]); + }); + it("infers the forge from the remote URL when the forge input is null", () => { const targets = planWorkspaceOpenTargets({ workspaceDirectory: "/repo", diff --git a/packages/app/src/workspace/open-in-editor/planner.ts b/packages/app/src/workspace/open-in-editor/planner.ts index 08cd23ffef..d4b98a1697 100644 --- a/packages/app/src/workspace/open-in-editor/planner.ts +++ b/packages/app/src/workspace/open-in-editor/planner.ts @@ -1,3 +1,4 @@ +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import { type Forge, forgeFromRemoteUrl, getForgePresentation } from "@/git/forge"; import type { DesktopOpenTarget, OpenDesktopTargetInput } from "@/workspace/desktop-open-targets"; import { @@ -9,6 +10,7 @@ import { interface CheckoutStatusForOpenTarget { isGit: boolean; remoteUrl?: string | null; + forgeWeb?: ForgeWeb | null; currentBranch?: string | null; } @@ -118,6 +120,7 @@ function buildForgeWebUrl( forge: Forge, input: { remoteUrl: string | null | undefined; + forgeWeb: ForgeWeb | null | undefined; branch: string | null | undefined; path: string | null; lineStart?: number; @@ -129,6 +132,7 @@ function buildForgeWebUrl( return ( presentation.buildBlobUrl?.({ remoteUrl: input.remoteUrl, + forgeWeb: input.forgeWeb, branch: input.branch, path: input.path, lineStart: input.lineStart, @@ -139,6 +143,7 @@ function buildForgeWebUrl( return ( presentation.buildBranchTreeUrl?.({ remoteUrl: input.remoteUrl, + forgeWeb: input.forgeWeb, branch: input.branch, }) ?? null ); @@ -159,6 +164,7 @@ function planForgeOpenTarget(input: { } const url = buildForgeWebUrl(forge, { remoteUrl: input.checkoutStatus.remoteUrl, + forgeWeb: input.checkoutStatus.forgeWeb, branch: input.checkoutStatus.currentBranch, path: input.resolvedFile?.relativePath ?? null, lineStart: input.activeFile?.lineStart, diff --git a/packages/app/src/workspace/use-workspace-archive.ts b/packages/app/src/workspace/use-workspace-archive.ts index 9608cef0cd..82255f6e91 100644 --- a/packages/app/src/workspace/use-workspace-archive.ts +++ b/packages/app/src/workspace/use-workspace-archive.ts @@ -1,17 +1,21 @@ -import { useCallback } from "react"; +import { useCallback, useRef } from "react"; import { useTranslation } from "react-i18next"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { useToast } from "@/contexts/toast-context"; import { confirmRiskyWorktreeArchive, DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS, + readWorktreeArchiveRisk, type WorktreeArchiveWarningLabels, } from "@/git/worktree-archive-warning"; import type { WorkspaceDescriptor } from "@/stores/session-store"; import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo"; -import { archiveWorkspaceOptimistically } from "@/workspace/workspace-archive"; +import { + archiveWorkspaceOptimistically, + type WorkspaceArchiveTarget, +} from "@/workspace/workspace-archive"; function purgeArchivedWorkspaceState(input: { serverId: string; workspaceId: string }): void { const workspaceKey = buildWorkspaceTabPersistenceKey(input); @@ -24,12 +28,13 @@ export interface ArchiveWorkspaceInput { serverId: string; workspaceId: string; workspaceKind: WorkspaceDescriptor["workspaceKind"]; + workspaceDirectory: string; name: string; - isDirty?: boolean | null; - aheadOfOrigin?: number | null; + /** Labels the warning's line counts. Whether to warn comes from the host's git state. */ diffStat?: { additions: number; deletions: number } | null; warningLabels?: WorktreeArchiveWarningLabels; - onArchiveStarted: () => void; + /** Runs once the archive starts, with the workspace being archived. */ + onArchiveStarted: (workspace: WorkspaceArchiveTarget) => void; onSetHiding?: (hiding: boolean) => void; } @@ -42,9 +47,8 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch serverId, workspaceId, workspaceKind, + workspaceDirectory, name, - isDirty, - aheadOfOrigin, diffStat, warningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS, onArchiveStarted, @@ -52,6 +56,11 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch } = input; const { t } = useTranslation(); const toast = useToast(); + const confirmingRef = useRef(false); + // The archive starts after the host answers and you confirm. By then you may have opened another + // workspace, so the redirect reads the selection from the latest render. + const onArchiveStartedRef = useRef(onArchiveStarted); + onArchiveStartedRef.current = onArchiveStarted; const archiveWorkspaceRecord = useCallback(async () => { const client = getHostRuntimeStore().getClient(serverId); @@ -62,7 +71,7 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch const workspace = { serverId, workspaceId }; onSetHiding?.(true); try { - onArchiveStarted(); + onArchiveStartedRef.current(workspace); if (supportsWorkspaceArchiveUndo(serverId)) { await archiveWorkspaceWithUndo({ client, @@ -82,35 +91,54 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch } finally { onSetHiding?.(false); } - }, [onArchiveStarted, onSetHiding, serverId, t, toast, workspaceId]); + }, [onSetHiding, serverId, t, toast, workspaceId]); + + // The host removes a worktree it archives, uncommitted work included. Ask it what that would + // lose: the sidebar row's git status is empty until the row receives it. + const confirmWorktreeArchive = useCallback(async (): Promise => { + const client = getHostRuntimeStore().getClient(serverId); + if (!client) { + toast.error(t("sidebar.workspace.toasts.hostDisconnected")); + return false; + } + const risk = await readWorktreeArchiveRisk(client, workspaceDirectory).catch( + (error: unknown) => { + toast.error( + error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"), + ); + return null; + }, + ); + if (!risk) { + return false; + } + return await confirmRiskyWorktreeArchive( + { workspaceName: name, diffStat, ...risk }, + warningLabels, + ); + }, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]); const archive = useCallback(() => { + // A second press while the host answers or the warning is open would ask twice. + if (confirmingRef.current) { + return; + } void (async () => { if (workspaceKind === "worktree") { - const confirmed = await confirmRiskyWorktreeArchive( - { - workspaceName: name, - isDirty, - aheadOfOrigin, - diffStat, - }, - warningLabels, - ); + confirmingRef.current = true; + let confirmed: boolean; + try { + confirmed = await confirmWorktreeArchive(); + } finally { + confirmingRef.current = false; + } if (!confirmed) { return; } } await archiveWorkspaceRecord(); })(); - }, [ - aheadOfOrigin, - archiveWorkspaceRecord, - diffStat, - isDirty, - name, - warningLabels, - workspaceKind, - ]); + }, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]); return { archive, diff --git a/packages/app/src/workspace/workspace-archive.test.ts b/packages/app/src/workspace/workspace-archive.test.ts index e519bcffb3..9b703800d8 100644 --- a/packages/app/src/workspace/workspace-archive.test.ts +++ b/packages/app/src/workspace/workspace-archive.test.ts @@ -7,6 +7,8 @@ import { isWorkspaceArchivePending, isWorkspaceArchiveUndoPending, } from "@/contexts/session-workspace-upserts"; +import { queryClient } from "@/data/query-client"; +import { allAgentHistoryQueryKey } from "@/hooks/agent-history-query-key"; import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store"; import { archiveWorkspaceOptimistically, @@ -133,6 +135,17 @@ describe("archiveWorkspaceOptimistically", () => { expect(storedWorkspace(archived.id)).toBeUndefined(); }); + it("marks cached agent history stale once the host has archived the workspace", async () => { + const historyKey = [...allAgentHistoryQueryKey([SERVER_ID]), "workspace-1"]; + queryClient.setQueryData(historyKey, { pages: [], pageParams: [] }); + const client = createClient(vi.fn(async () => archivePayload({ workspaceId: "workspace-1" }))); + + await archiveWorkspaceOptimistically({ client, workspace: target() }); + + expect(queryClient.getQueryState(historyKey)?.isInvalidated).toBe(true); + queryClient.removeQueries({ queryKey: historyKey }); + }); + it("restores the workspace and clears pending state when the daemon rejects the archive", async () => { const archived = workspace(); getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]); diff --git a/packages/app/src/workspace/workspace-archive.ts b/packages/app/src/workspace/workspace-archive.ts index fd757934ef..9569455706 100644 --- a/packages/app/src/workspace/workspace-archive.ts +++ b/packages/app/src/workspace/workspace-archive.ts @@ -1,3 +1,5 @@ +import { queryClient } from "@/data/query-client"; +import { agentHistoryQueryKey, allAgentHistoryQueryRootKey } from "@/hooks/agent-history-query-key"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { isWorkspaceArchiveIntentCurrent, @@ -96,6 +98,12 @@ function restoreOptimisticallyHiddenWorkspace(input: { } } +/** History fetched before the archive still lists the workspace's agents as active. */ +function invalidateAgentHistory(serverId: string): void { + void queryClient.invalidateQueries({ queryKey: agentHistoryQueryKey(serverId) }); + void queryClient.invalidateQueries({ queryKey: allAgentHistoryQueryRootKey() }); +} + async function archiveWorkspaceOrThrow(input: { client: WorkspaceArchiveClient; workspaceId: string; @@ -127,6 +135,8 @@ export function beginOptimisticWorkspaceArchive(input: { }); if (outcome === "canceled") { restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot }); + } else { + invalidateAgentHistory(input.workspace.serverId); } return outcome; } catch (error) { diff --git a/packages/app/test-stubs/lucide-react-native.ts b/packages/app/test-stubs/lucide-react-native.ts index 1cff249d47..fac72b444c 100644 --- a/packages/app/test-stubs/lucide-react-native.ts +++ b/packages/app/test-stubs/lucide-react-native.ts @@ -83,6 +83,7 @@ export const PinOff = StubIcon; export const Play = StubIcon; export const Plug = StubIcon; export const Plus = StubIcon; +export const Puzzle = StubIcon; export const QrCode = StubIcon; export const RefreshCcw = StubIcon; export const RefreshCw = StubIcon; @@ -100,6 +101,7 @@ export const Smartphone = StubIcon; export const Split = StubIcon; export const Square = StubIcon; export const SquarePen = StubIcon; +export const SquareSlash = StubIcon; export const SquareTerminal = StubIcon; export const Star = StubIcon; export const Sun = StubIcon; diff --git a/packages/app/test-stubs/react-native-unistyles.ts b/packages/app/test-stubs/react-native-unistyles.ts index 04f61bc77e..e33f3347c2 100644 --- a/packages/app/test-stubs/react-native-unistyles.ts +++ b/packages/app/test-stubs/react-native-unistyles.ts @@ -1,7 +1,8 @@ +import { createElement, type ElementType } from "react"; import { lightHighlightColors } from "@getpaseo/highlight"; import { lightTheme } from "../src/styles/theme"; -const testTheme = { +const pinnedTheme = { colorScheme: "light", colors: { syntax: lightHighlightColors, @@ -86,6 +87,14 @@ const testTheme = { }, }; +// Tokens a test does not pin come from the real light theme, so a style or `uniProps` mapping +// that reads one (the markdown renderer reads `colors.terminal`) gets a value instead of crashing. +const testTheme = { + ...lightTheme, + ...pinnedTheme, + colors: { ...lightTheme.colors, ...pinnedTheme.colors }, +}; + type StyleFactory = (theme: typeof testTheme) => T; function isStyleFactory(styles: T | StyleFactory): styles is StyleFactory { @@ -142,7 +151,19 @@ export const StyleSheet = { resolveStyles(isStyleFactory(styles) ? styles(testTheme) : styles), }; -export const withUnistyles = (Component: T): T => Component; +type UniPropsMapping = (theme: typeof testTheme, runtime: object) => Record; + +/** Applies `uniProps` with the test theme, the way Unistyles maps theme values onto props. */ +export const withUnistyles = (Component: T): T => { + function ThemedComponent({ uniProps, ...props }: { uniProps?: UniPropsMapping }) { + // Explicit props win over mapped ones, as in Unistyles' `deepMergeObjects(mappings, uniProps, props)`. + return createElement(Component as ElementType, { + ...(uniProps ? uniProps(testTheme, {}) : {}), + ...props, + }); + } + return ThemedComponent as T; +}; export const useUnistyles = () => ({ theme: testTheme, diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts index c13780d6b6..2a138c7383 100644 --- a/packages/app/vitest.config.ts +++ b/packages/app/vitest.config.ts @@ -35,6 +35,26 @@ export default defineConfig({ }; }, }, + { + name: "reanimated-web-style-helpers", + transform(_source, id) { + // Reanimated writes animated styles to the DOM through react-native-web helpers it loads + // with `require` inside try/catch. Vite serves ESM, so the require throws, the helpers stay + // undefined, and the first animated style update after mount crashes the component. + if ( + !id.split("?")[0].endsWith("/lib/module/ReanimatedModule/js-reanimated/webUtils.web.js") + ) { + return; + } + return { + code: [ + 'export { default as createReactDOMStyle } from "react-native-web/dist/exports/StyleSheet/compiler/createReactDOMStyle";', + 'export { createTransformValue, createTextShadowValue } from "react-native-web/dist/exports/StyleSheet/preprocess";', + ].join("\n"), + map: null, + }; + }, + }, { name: "compile-react-components", enforce: "pre", @@ -187,6 +207,9 @@ export default defineConfig({ "react/jsx-dev-runtime", "react-native-gesture-handler > hoist-non-react-statics", "react-native-gesture-handler > invariant", + // Loaded by the reanimated-web-style-helpers plugin, which the dependency scan does not see. + "react-native-web/dist/exports/StyleSheet/compiler/createReactDOMStyle", + "react-native-web/dist/exports/StyleSheet/preprocess", ], exclude: [ "react-native-enriched-markdown", diff --git a/packages/cli/package.json b/packages/cli/package.json index 572d8aab98..06853cc2b3 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Paseo CLI - control your AI coding agents from the command line", "license": "Apache-2.0", "bin": { @@ -29,9 +29,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/server": "0.16.0-beta.1", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/server": "0.16.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/cli/src/commands/agent/archive.test.ts b/packages/cli/src/commands/agent/archive.test.ts new file mode 100644 index 0000000000..de9f6fe68d --- /dev/null +++ b/packages/cli/src/commands/agent/archive.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; +import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; +import { archiveAgent, type AgentArchiveClient } from "./archive.js"; +import { reloadAgent, type AgentReloadClient } from "./reload.js"; +import { detachAgent, type AgentDetachClient } from "./detach.js"; + +function makeAgent( + id: string, + overrides: Partial = {}, +): AgentSnapshotPayload { + return { + id, + title: null, + status: "closed", + archivedAt: null, + ...overrides, + } as AgentSnapshotPayload; +} + +class FakeAgentClient implements AgentArchiveClient, AgentReloadClient, AgentDetachClient { + readonly archived: string[] = []; + readonly refreshed: string[] = []; + readonly detached: string[] = []; + readonly fetchAgentCalls: string[] = []; + fetchAgentError: Error | null = null; + closed = false; + + constructor( + private readonly listed: AgentSnapshotPayload[], + private readonly stored: AgentSnapshotPayload[] = listed, + ) {} + + async fetchAgents() { + return { entries: this.listed.map((agent) => ({ agent })), pageInfo: { nextCursor: null } }; + } + + async fetchAgent({ agentId }: { agentId: string }) { + this.fetchAgentCalls.push(agentId); + if (this.fetchAgentError) throw this.fetchAgentError; + const found = + this.stored.find((e) => e.id === agentId) ?? + this.stored.find((e) => e.id.startsWith(agentId)) ?? + this.stored.find((e) => e.title === agentId); + return found ? { agent: found } : null; + } + + async archiveAgent(agentId: string) { + this.archived.push(agentId); + return { archivedAt: "2026-11-15T00:00:00.000Z" }; + } + + async refreshAgent(agentId: string) { + this.refreshed.push(agentId); + return { agentId, timelineSize: 3 }; + } + + async detachAgent(agentId: string) { + this.detached.push(agentId); + } + + async close() { + this.closed = true; + } +} + +describe("unlisted agent resolution", () => { + const unlistedId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const otherId = "c9a97e5d-4a92-4646-a016-53032146d0a1"; + + it("archives an unlisted agent via fetchAgent without title collision", async () => { + const unlisted = makeAgent(unlistedId, { title: "orphaned agent" }); + const other = makeAgent(otherId, { title: `worker ${unlistedId}` }); + const client = new FakeAgentClient([other], [other, unlisted]); + const result = await archiveAgent(unlistedId.toUpperCase(), {}, async () => client); + expect(result.data).toEqual({ + agentId: unlistedId, + status: "archived", + archivedAt: "2026-11-15T00:00:00.000Z", + }); + expect(client.fetchAgentCalls).toEqual([unlistedId]); + expect(client.archived).toEqual([unlistedId]); + expect(client.closed).toBe(true); + }); + + it("enforces archived and running checks on fetched unlisted agents", async () => { + const archivedClient = new FakeAgentClient( + [], + [makeAgent(unlistedId, { archivedAt: "2026-11-14T10:00:00.000Z" })], + ); + await expect(archiveAgent(unlistedId, {}, async () => archivedClient)).rejects.toMatchObject({ + code: "AGENT_ALREADY_ARCHIVED", + }); + const runningClient = new FakeAgentClient([], [makeAgent(unlistedId, { status: "running" })]); + await expect(archiveAgent(unlistedId, {}, async () => runningClient)).rejects.toMatchObject({ + code: "AGENT_RUNNING", + }); + }); + + it("reloads and detaches unlisted agents via fetchAgent fallback", async () => { + const unlisted = makeAgent(unlistedId, { title: "orphaned agent" }); + const reloadClient = new FakeAgentClient([], [unlisted]); + const detachClient = new FakeAgentClient([], [unlisted]); + expect((await reloadAgent(unlistedId, {}, async () => reloadClient)).data).toEqual({ + agentId: unlistedId, + status: "reloaded", + timelineSize: 3, + }); + expect((await detachAgent(unlistedId, {}, async () => detachClient)).data).toEqual({ + agentId: unlistedId, + status: "detached", + }); + }); + + it("does not accept another agent the daemon matched by title for a missing full id", async () => { + const titled = makeAgent(otherId, { title: unlistedId }); + const client = new FakeAgentClient([], [titled]); + await expect(archiveAgent(unlistedId, {}, async () => client)).rejects.toMatchObject({ + code: "AGENT_NOT_FOUND", + }); + expect(client.archived).toEqual([]); + }); + + it("throws AGENT_NOT_FOUND when missing and propagates lookup errors", async () => { + await expect( + archiveAgent(unlistedId, {}, async () => new FakeAgentClient([], [])), + ).rejects.toMatchObject({ + code: "AGENT_NOT_FOUND", + }); + const failingClient = new FakeAgentClient([], []); + failingClient.fetchAgentError = new Error('Agent identifier "9eac" is ambiguous'); + await expect(archiveAgent("9eac", {}, async () => failingClient)).rejects.toMatchObject({ + code: "ARCHIVE_FAILED", + }); + await expect(detachAgent("9eac", {}, async () => failingClient)).rejects.toMatchObject({ + code: "DETACH_FAILED", + message: 'Failed to detach agent: Agent identifier "9eac" is ambiguous', + }); + }); +}); diff --git a/packages/cli/src/commands/agent/archive.ts b/packages/cli/src/commands/agent/archive.ts index 382cd193ce..c8e60f5033 100644 --- a/packages/cli/src/commands/agent/archive.ts +++ b/packages/cli/src/commands/agent/archive.ts @@ -1,6 +1,6 @@ import { Command } from "commander"; -import { connectToDaemon, resolveAgentId } from "../../utils/client.js"; -import { fetchAllAgents } from "../../utils/agent-directory.js"; +import { connectToDaemon } from "../../utils/client.js"; +import { resolveAgentEntry, type AgentLookupClient } from "../../utils/agent-directory.js"; import type { CommandOptions, SingleResult, @@ -39,10 +39,25 @@ export interface AgentArchiveOptions extends CommandOptions { export type AgentArchiveCommandResult = SingleResult; +export interface AgentArchiveClient extends AgentLookupClient { + archiveAgent(agentId: string): Promise<{ archivedAt: string }>; + close(): Promise; +} + export async function runArchiveCommand( agentIdArg: string, options: AgentArchiveOptions, _command: Command, +): Promise { + return archiveAgent(agentIdArg, options); +} + +export async function archiveAgent( + agentIdArg: string, + options: AgentArchiveOptions, + connect: ( + options: Parameters[0], + ) => Promise = connectToDaemon, ): Promise { // Validate arguments if (!agentIdArg || agentIdArg.trim().length === 0) { @@ -54,12 +69,11 @@ export async function runArchiveCommand( throw error; } - const client = await connectToDaemon({ target: options.daemonTarget }); + const client = await connect({ target: options.daemonTarget }); try { - const agents = await fetchAllAgents(client, { filter: { includeArchived: true } }); - const agentId = resolveAgentId(agentIdArg, agents); - if (!agentId) { + const agent = await resolveAgentEntry(client, agentIdArg); + if (!agent) { const error: CommandError = { code: "AGENT_NOT_FOUND", message: `Agent not found: ${agentIdArg}`, @@ -67,10 +81,7 @@ export async function runArchiveCommand( }; throw error; } - const agent = agents.find((entry) => entry.id === agentId); - if (!agent) { - throw new Error(`Resolved agent missing from fetched agents: ${agentId}`); - } + const agentId = agent.id; // Check if agent is already archived if (agent.archivedAt) { diff --git a/packages/cli/src/commands/agent/detach.ts b/packages/cli/src/commands/agent/detach.ts index 9de223dffb..8bf41efd09 100644 --- a/packages/cli/src/commands/agent/detach.ts +++ b/packages/cli/src/commands/agent/detach.ts @@ -1,5 +1,6 @@ import type { Command } from "commander"; -import { connectToDaemon, resolveAgentId } from "../../utils/client.js"; +import { connectToDaemon } from "../../utils/client.js"; +import { resolveAgentEntry, type AgentLookupClient } from "../../utils/agent-directory.js"; import type { CommandError, CommandOptions, @@ -20,27 +21,51 @@ const detachSchema: OutputSchema = { ], }; +export interface AgentDetachClient extends AgentLookupClient { + detachAgent(agentId: string): Promise; + close(): Promise; +} + export async function runDetachCommand( agentIdArg: string, options: CommandOptions, _command: Command, ): Promise> { - const client = await connectToDaemon({ target: options.daemonTarget }); + return detachAgent(agentIdArg, options); +} + +export async function detachAgent( + agentIdArg: string, + options: CommandOptions, + connect: ( + options: Parameters[0], + ) => Promise = connectToDaemon, +): Promise> { + const client = await connect({ target: options.daemonTarget }); try { - const payload = await client.fetchAgents({ filter: { includeArchived: true } }); - const agentId = resolveAgentId( - agentIdArg, - payload.entries.map((entry) => entry.agent), - ); - if (!agentId) { + const agent = await resolveAgentEntry(client, agentIdArg); + if (!agent) { throw { code: "AGENT_NOT_FOUND", message: `Agent not found: ${agentIdArg}`, } satisfies CommandError; } - await client.detachAgent(agentId); - return { type: "single", data: { agentId, status: "detached" }, schema: detachSchema }; + await client.detachAgent(agent.id); + return { + type: "single", + data: { agentId: agent.id, status: "detached" }, + schema: detachSchema, + }; + } catch (err) { + if (err && typeof err === "object" && "code" in err) { + throw err; + } + const message = err instanceof Error ? err.message : String(err); + throw { + code: "DETACH_FAILED", + message: `Failed to detach agent: ${message}`, + } satisfies CommandError; } finally { await client.close().catch(() => undefined); } diff --git a/packages/cli/src/commands/agent/ls.test.ts b/packages/cli/src/commands/agent/ls.test.ts index 82d6c09a61..f2a09d2902 100644 --- a/packages/cli/src/commands/agent/ls.test.ts +++ b/packages/cli/src/commands/agent/ls.test.ts @@ -15,7 +15,8 @@ function createPagingClient() { cwd: "/tmp/project", createdAt: `2026-10-0${n}T00:00:00.000Z`, updatedAt: `2026-10-0${n}T00:00:00.000Z`, - labels: {}, + labels: n === 3 ? { bot: "worker", issue: "42" } : {}, + workspaceId: n === 3 ? "workspace-3" : undefined, model: null, lastUserMessageAt: null, currentModeId: null, @@ -124,6 +125,19 @@ describe("buildAgentLsFetchOptions", () => { }); describe("runLsCommand", () => { + it("includes labels and workspace IDs in JSON listings", async () => { + const result = await listAgents({ daemonTarget, global: true }, async () => + createPagingClient(), + ); + const rows = JSON.parse(render(result, { format: "json" })); + + expect(rows).toMatchObject([ + { name: "agent 3", labels: { bot: "worker", issue: "42" }, workspaceId: "workspace-3" }, + { name: "agent 2", labels: {}, workspaceId: null }, + { name: "agent 1", labels: {}, workspaceId: null }, + ]); + }); + it("lists agents on every page, including one updated during the listing", async () => { const result = await listAgents({ daemonTarget, all: true, global: true }, async () => createPagingClient(), diff --git a/packages/cli/src/commands/agent/ls.ts b/packages/cli/src/commands/agent/ls.ts index d60ad0ce97..2e6bf68330 100644 --- a/packages/cli/src/commands/agent/ls.ts +++ b/packages/cli/src/commands/agent/ls.ts @@ -36,6 +36,8 @@ export interface AgentListItem { cwd: string; created: string; background: boolean; + labels: Record; + workspaceId: string | null; } /** Helper to get relative time string */ @@ -112,6 +114,8 @@ function toListItem(agent: AgentSnapshotPayload): AgentListItem { cwd: shortenPath(agent.cwd), created: relativeTime(agent.createdAt), background: agent.background === true, + labels: agent.labels, + workspaceId: agent.workspaceId ?? null, }; } diff --git a/packages/cli/src/commands/agent/reload.ts b/packages/cli/src/commands/agent/reload.ts index f6cda480e2..73b5947a69 100644 --- a/packages/cli/src/commands/agent/reload.ts +++ b/packages/cli/src/commands/agent/reload.ts @@ -1,5 +1,6 @@ import { Command } from "commander"; -import { connectToDaemon, resolveAgentId } from "../../utils/client.js"; +import { connectToDaemon } from "../../utils/client.js"; +import { resolveAgentEntry, type AgentLookupClient } from "../../utils/agent-directory.js"; import type { CommandOptions, SingleResult, @@ -34,10 +35,25 @@ export interface AgentReloadOptions extends CommandOptions { export type AgentReloadCommandResult = SingleResult; +export interface AgentReloadClient extends AgentLookupClient { + refreshAgent(agentId: string): Promise<{ agentId: string; timelineSize?: number }>; + close(): Promise; +} + export async function runReloadCommand( agentIdArg: string, options: AgentReloadOptions, _command: Command, +): Promise { + return reloadAgent(agentIdArg, options); +} + +export async function reloadAgent( + agentIdArg: string, + options: AgentReloadOptions, + connect: ( + options: Parameters[0], + ) => Promise = connectToDaemon, ): Promise { if (!agentIdArg || agentIdArg.trim().length === 0) { const error: CommandError = { @@ -48,13 +64,11 @@ export async function runReloadCommand( throw error; } - const client = await connectToDaemon({ target: options.daemonTarget }); + const client = await connect({ target: options.daemonTarget }); try { - const agentsPayload = await client.fetchAgents({ filter: { includeArchived: true } }); - const agents = agentsPayload.entries.map((entry) => entry.agent); - const agentId = resolveAgentId(agentIdArg, agents); - if (!agentId) { + const agent = await resolveAgentEntry(client, agentIdArg); + if (!agent) { const error: CommandError = { code: "AGENT_NOT_FOUND", message: `Agent not found: ${agentIdArg}`, @@ -63,7 +77,7 @@ export async function runReloadCommand( throw error; } - const result = await client.refreshAgent(agentId); + const result = await client.refreshAgent(agent.id); await client.close(); diff --git a/packages/cli/src/commands/agent/send.ts b/packages/cli/src/commands/agent/send.ts index acdea38507..9a0bc465b7 100644 --- a/packages/cli/src/commands/agent/send.ts +++ b/packages/cli/src/commands/agent/send.ts @@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command { .addOption( new Option( "--behavior ", - "Active-turn behavior (agent default: steer; otherwise: interrupt)", + "Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)", ).choices(["interrupt", "steer"]), ) .option("--no-wait", "Return immediately without waiting for completion"); @@ -218,7 +218,7 @@ export async function runSendCommand( status: receipt.deliveryStatus ?? "sent", message: receipt.deliveryStatus === "queued" - ? "Message queued for delivery after two quiet seconds" + ? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested" : "Message sent, not waiting for completion", }, schema: agentSendSchema, diff --git a/packages/cli/src/commands/agent/wait.test.ts b/packages/cli/src/commands/agent/wait.test.ts new file mode 100644 index 0000000000..4cb0b7b7e4 --- /dev/null +++ b/packages/cli/src/commands/agent/wait.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; +import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; +import { buildWaitResult } from "./wait.js"; + +const agentId = "11111111-1111-4111-8111-111111111111"; + +describe("buildWaitResult", () => { + it("reports an identifier the daemon could not resolve as a missing agent", () => { + expect(() => + buildWaitResult({ + state: { + status: "error", + final: null, + error: "Agent not found: does-not-exist", + lastMessage: null, + }, + resolvedAgentId: "does-not-exist", + recentActivity: null, + timeoutLabel: null, + }), + ).toThrow( + expect.objectContaining({ + code: "AGENT_NOT_FOUND", + message: "Agent not found: does-not-exist", + details: "Use `paseo ls` to list available agents", + }), + ); + }); + + it("still reports an agent that finished in error as a result", () => { + const result = buildWaitResult({ + state: { + status: "error", + final: { id: agentId, lastError: "The provider returned 500" } as AgentSnapshotPayload, + error: "The provider returned 500", + lastMessage: null, + }, + resolvedAgentId: agentId, + recentActivity: null, + timeoutLabel: null, + }); + + expect(result).toEqual({ + agentId, + status: "error", + message: "The provider returned 500", + }); + }); +}); diff --git a/packages/cli/src/commands/agent/wait.ts b/packages/cli/src/commands/agent/wait.ts index 3e5e5b533a..1fc91f6772 100644 --- a/packages/cli/src/commands/agent/wait.ts +++ b/packages/cli/src/commands/agent/wait.ts @@ -86,7 +86,12 @@ type WaitFinishState = Awaited< ReturnType>["waitForFinish"]> >; -function buildWaitResult(args: { +/** + * Turn the daemon's wait reply into the command result. Throws AGENT_NOT_FOUND when the + * daemon resolved no agent: it answers an unknown identifier with an error and no agent + * payload, while an agent that finished in error always comes with its payload. + */ +export function buildWaitResult(args: { state: WaitFinishState; resolvedAgentId: string; recentActivity: string | null; @@ -117,6 +122,13 @@ function buildWaitResult(args: { } if (state.status === "error") { + if (state.final === null) { + throw { + code: "AGENT_NOT_FOUND", + message: state.error ?? `Agent not found: ${resolvedAgentId}`, + details: "Use `paseo ls` to list available agents", + } satisfies CommandError; + } return { agentId: resolvedAgentId, status: "error", @@ -155,6 +167,7 @@ export async function runWaitCommand( const client = await connectToDaemon({ target: options.daemonTarget }); + let reply: Omit[0], "timeoutLabel">; try { try { const state = await client.waitForFinish(agentIdArg, timeoutMs); @@ -166,11 +179,7 @@ export async function runWaitCommand( await client.close(); - return { - type: "single", - data: buildWaitResult({ state, resolvedAgentId, recentActivity, timeoutLabel }), - schema: agentWaitSchema, - }; + reply = { state, resolvedAgentId, recentActivity }; } catch (waitErr) { await client.close().catch(() => {}); @@ -198,4 +207,10 @@ export async function runWaitCommand( }; throw error; } + + return { + type: "single", + data: buildWaitResult({ ...reply, timeoutLabel }), + schema: agentWaitSchema, + }; } diff --git a/packages/cli/src/commands/workspace/create.test.ts b/packages/cli/src/commands/workspace/create.test.ts index 62bfcdc6f1..a0c03b5e0d 100644 --- a/packages/cli/src/commands/workspace/create.test.ts +++ b/packages/cli/src/commands/workspace/create.test.ts @@ -1,3 +1,4 @@ +import path from "node:path"; import { describe, expect, it } from "vitest"; import { buildWorkspaceSource } from "./create.js"; @@ -8,6 +9,49 @@ describe("workspace create source", () => { ).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" }); }); + it("resolves a relative path against the directory the command runs in", () => { + const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" }; + expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({ + kind: "directory", + path: process.cwd(), + }); + expect( + buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }), + ).toEqual({ + kind: "worktree", + cwd: path.resolve(process.cwd(), "../sibling"), + action: "branch-off", + }); + }); + + it("sends a relative path to an explicit daemon endpoint as written", () => { + const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" }; + expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({ + kind: "directory", + path: "repo", + }); + }); + + it("passes an absolute path from another operating system through unchanged", () => { + expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({ + kind: "directory", + path: "C:\\repos\\project", + }); + }); + + it("leaves a home-relative path for the daemon to expand", () => { + const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" }; + expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({ + kind: "directory", + path: "~/repo", + }); + expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({ + kind: "worktree", + cwd: "~", + action: "branch-off", + }); + }); + it("keeps branch names separate from managed worktree slugs", () => { expect( buildWorkspaceSource({ diff --git a/packages/cli/src/commands/workspace/create.ts b/packages/cli/src/commands/workspace/create.ts index 04d9e10ef0..63417587cb 100644 --- a/packages/cli/src/commands/workspace/create.ts +++ b/packages/cli/src/commands/workspace/create.ts @@ -1,6 +1,10 @@ +import { isAbsolute as isPosixAbsolute } from "node:path/posix"; +import { isAbsolute as isWindowsAbsolute } from "node:path/win32"; +import { resolve } from "node:path"; import type { Command } from "commander"; import { connectToDaemon, getDaemonHost } from "../../utils/client.js"; import { resolveCallerAgentId } from "../../utils/caller-agent.js"; +import type { DaemonTarget } from "../../utils/daemon-target.js"; import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js"; import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js"; @@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str } } +// A relative --path names a directory relative to where the command runs, so +// it is made absolute here for a local daemon, which would otherwise resolve +// it against its own working directory. For an explicit endpoint the path is +// sent as written, the same rule as resolveRepositoryDirectory. An absolute +// path can target a daemon on a different operating system, and the daemon +// expands a leading ~ to its own home directory. +function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string { + const isHomeRelative = input === "~" || input.startsWith("~/"); + if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input; + return daemonTarget.kind === "instance" ? resolve(input) : input; +} + export function buildWorkspaceSource(options: WorkspaceCreateOptions) { + const callerPath = + options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget); if (options.isolation === "local") { - return buildLocalWorkspaceSource(options, options.path ?? process.cwd()); + return buildLocalWorkspaceSource(options, callerPath ?? process.cwd()); } if (options.isolation === "worktree") { - const sourcePath = options.path ?? (options.project ? undefined : process.cwd()); + const sourcePath = callerPath ?? (options.project ? undefined : process.cwd()); return buildWorktreeWorkspaceSource(options, sourcePath); } throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`); diff --git a/packages/cli/src/utils/agent-directory.ts b/packages/cli/src/utils/agent-directory.ts index 5531213203..d2031adbde 100644 --- a/packages/cli/src/utils/agent-directory.ts +++ b/packages/cli/src/utils/agent-directory.ts @@ -1,17 +1,24 @@ import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; -import type { connectToDaemon } from "./client.js"; +import { resolveAgentId, type connectToDaemon } from "./client.js"; -type FetchAgentsOptions = NonNullable< - Parameters>["fetchAgents"]>[0] ->; +type DaemonClient = Awaited>; +type FetchAgentsOptions = NonNullable[0]>; -interface AgentDirectoryClient { +export interface AgentDirectoryClient { fetchAgents(options?: FetchAgentsOptions): Promise<{ entries: { agent: AgentSnapshotPayload }[]; pageInfo: { nextCursor: string | null }; }>; } +export interface AgentLookupClient extends AgentDirectoryClient { + fetchAgent(options: { agentId: string }): Promise<{ + agent: AgentSnapshotPayload; + } | null>; +} + +const FULL_AGENT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i; + /** Read the complete directory without agents moving between pages as they update. */ export async function fetchAllAgents( client: AgentDirectoryClient, @@ -31,3 +38,38 @@ export async function fetchAllAgents( } while (cursor); return agents; } + +/** + * Resolve an agent by ID, prefix, or name from the directory, falling back to + * `fetch_agent` for agents omitted from `fetch_agents` (for example after their + * workspace or project was deleted). + */ +export async function resolveAgentEntry( + client: AgentLookupClient, + agentIdArg: string, +): Promise { + const trimmed = agentIdArg.trim(); + if (!trimmed) { + return null; + } + + const agents = await fetchAllAgents(client, { filter: { includeArchived: true } }); + const listedId = resolveAgentId(agentIdArg, agents); + if (listedId) { + const match = agents.find((entry) => entry.id === listedId); + if (match) { + return match; + } + } + + // COMPAT(fullAgentIdExact): daemons before v0.16.0 resolve a full agent ID + // that matches no agent to an agent titled with it, so archive, detach and + // reload accept their answer only when it is that ID. Remove after 2027-05-15. + if (FULL_AGENT_UUID_PATTERN.test(trimmed)) { + const agentId = trimmed.toLowerCase(); + const fetchResult = await client.fetchAgent({ agentId }); + return fetchResult?.agent.id === agentId ? fetchResult.agent : null; + } + const fetchResult = await client.fetchAgent({ agentId: trimmed }); + return fetchResult?.agent ?? null; +} diff --git a/packages/cli/src/utils/client.ts b/packages/cli/src/utils/client.ts index 27d1a4dbcb..2a594753fe 100644 --- a/packages/cli/src/utils/client.ts +++ b/packages/cli/src/utils/client.ts @@ -236,6 +236,8 @@ interface AgentLike { title?: string | null; } +const FULL_AGENT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i; + /** * Resolve an agent ID from a partial ID or name. * Supports: @@ -252,6 +254,11 @@ export function resolveAgentId(idOrName: string, agents: AgentLike[]): string | const query = idOrName.toLowerCase(); + // A complete agent UUID is an exact identity, never a name search fallback. + if (FULL_AGENT_UUID_PATTERN.test(idOrName)) { + return agents.find((a) => a.id.toLowerCase() === query)?.id ?? null; + } + // Try exact ID match first const exactMatch = agents.find((a) => a.id === idOrName); if (exactMatch) { diff --git a/packages/cli/tests/11-agent-archive.test.ts b/packages/cli/tests/11-agent-archive.test.ts index 50df5c326d..998ac8ec87 100644 --- a/packages/cli/tests/11-agent-archive.test.ts +++ b/packages/cli/tests/11-agent-archive.test.ts @@ -197,6 +197,16 @@ try { "the agent should be listed before it is archived", ); + const detached = await runPaseoCli(daemon, [ + "agent", + "detach", + TARGET_AGENT_ID, + "--json", + "--host", + host, + ]); + assert.strictEqual(detached.exitCode, 0, detached.stdout + detached.stderr); + const archived = await runPaseoCli(daemon, [ "agent", "archive", @@ -283,6 +293,191 @@ try { await daemon.stop(); } } + // Test 10: archives an agent whose workspace no longer exists (omitted from agent ls) + { + console.log("Test 10: archives an agent whose workspace was deleted"); + const orphanId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${orphanId}.json`), + JSON.stringify( + { + id: orphanId, + provider: "codex", + cwd: dirs.workDir, + workspaceId: "deleted-workspace-id", + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: "orphaned agent", + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + const listed = await runPaseoCli(daemon, ["agent", "ls", "-ag", "--json", "--host", host]); + assert.strictEqual(listed.exitCode, 0, listed.stderr); + assert.deepStrictEqual(JSON.parse(listed.stdout), []); + + const inspected = await runPaseoCli(daemon, [ + "agent", + "inspect", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(inspected.exitCode, 0, inspected.stderr); + assert.strictEqual((JSON.parse(inspected.stdout) as { Archived: boolean }).Archived, false); + + const detached = await runPaseoCli(daemon, [ + "agent", + "detach", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(detached.exitCode, 0, detached.stdout + detached.stderr); + assert.deepStrictEqual(JSON.parse(detached.stdout), { + agentId: orphanId, + status: "detached", + }); + + const reloaded = await runPaseoCli(daemon, [ + "agent", + "reload", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(reloaded.exitCode, 1); + assert.strictEqual( + (parseJsonError(reloaded.stderr) as { error: { code: string } }).error.code, + "agent_refresh_failed", + ); + + const archived = await runPaseoCli(daemon, [ + "agent", + "archive", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(archived.exitCode, 0, archived.stdout + archived.stderr); + const result = JSON.parse(archived.stdout) as { agentId: string; status: string }; + assert.strictEqual(result.agentId, orphanId); + assert.strictEqual(result.status, "archived"); + } finally { + await daemon.stop(); + } + console.log("✓ archives an agent whose workspace was deleted\n"); + } + // Test 11: archives an agent whose provider is not available + { + console.log("Test 11: archives an agent whose provider is not available"); + const agentId = "22222222-2222-4333-8444-555555555555"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${agentId}.json`), + JSON.stringify( + { + id: agentId, + provider: "not-a-registered-provider", + cwd: dirs.workDir, + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: "provider gone", + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + const archived = await runPaseoCli(daemon, [ + "agent", + "archive", + agentId, + "--json", + "--host", + host, + ]); + assert.strictEqual(archived.exitCode, 0, archived.stdout + archived.stderr); + assert.strictEqual((JSON.parse(archived.stdout) as { agentId: string }).agentId, agentId); + } finally { + await daemon.stop(); + } + console.log("✓ archives an agent whose provider is not available\n"); + } + // Test 12: a missing full ID never resolves to an unlisted agent titled with it + { + console.log("Test 12: a missing full ID does not archive an agent titled with it"); + const missingId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const titledId = "c9a97e5d-4a92-4646-a016-53032146d0a1"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${titledId}.json`), + JSON.stringify( + { + id: titledId, + provider: "codex", + cwd: dirs.workDir, + workspaceId: "deleted-workspace-id", + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: missingId, + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + for (const command of ["archive", "detach", "reload"]) { + const result = await runPaseoCli(daemon, [ + "agent", + command, + missingId, + "--json", + "--host", + host, + ]); + assert.strictEqual(result.exitCode, 1, `${command}: ${result.stdout}`); + assert.strictEqual( + (parseJsonError(result.stderr) as { error: { code: string } }).error.code, + "AGENT_NOT_FOUND", + `${command}: ${result.stderr}`, + ); + } + + const titled = await runPaseoCli(daemon, [ + "agent", + "inspect", + titledId, + "--json", + "--host", + host, + ]); + assert.strictEqual(titled.exitCode, 0, titled.stderr); + assert.strictEqual((JSON.parse(titled.stdout) as { Archived: boolean }).Archived, false); + } finally { + await daemon.stop(); + } + console.log("✓ a missing full ID does not archive an agent titled with it\n"); + } } finally { // Clean up temp directory await rm(paseoHome, { recursive: true, force: true }); diff --git a/packages/cli/tests/11-agent-wait.test.ts b/packages/cli/tests/11-agent-wait.test.ts index 198fa08910..5b179b1c3e 100644 --- a/packages/cli/tests/11-agent-wait.test.ts +++ b/packages/cli/tests/11-agent-wait.test.ts @@ -20,6 +20,7 @@ import assert from "node:assert"; import { getAvailablePort } from "./helpers/network.ts"; +import { runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts"; import { $ } from "zx"; import { mkdtemp, rm } from "fs/promises"; import { tmpdir } from "os"; @@ -177,6 +178,28 @@ try { ); console.log("timeout option documents no default limit\n"); } + + // Test 13: wait reports AGENT_NOT_FOUND for an unknown ID + { + console.log("Test 13: wait reports AGENT_NOT_FOUND for an unknown ID"); + const daemon = await startTestDaemon(); + try { + const result = await runPaseoCli(daemon, [ + "wait", + "does-not-exist", + "--host", + `127.0.0.1:${daemon.port}`, + "--json", + ]); + assert.notStrictEqual(result.exitCode, 0, "wait should fail for an unknown ID"); + const { error } = JSON.parse(result.stderr); + assert.strictEqual(error.code, "AGENT_NOT_FOUND", result.stderr); + assert.match(error.details, /paseo ls/); + } finally { + await daemon.stop(); + } + console.log("✓ wait reports AGENT_NOT_FOUND for an unknown ID\n"); + } } finally { // Clean up temp directory await rm(paseoHome, { recursive: true, force: true }); diff --git a/packages/cli/tests/27-agent-delete.test.ts b/packages/cli/tests/27-agent-delete.test.ts index 349125109b..77bc0301dd 100644 --- a/packages/cli/tests/27-agent-delete.test.ts +++ b/packages/cli/tests/27-agent-delete.test.ts @@ -13,8 +13,8 @@ import assert from "node:assert"; import { runLocalPaseo } from "./helpers/local-cli.ts"; import { getAvailablePort } from "./helpers/network.ts"; -import { runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts"; -import { mkdtemp, rm } from "fs/promises"; +import { createTempDirs, runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts"; +import { mkdtemp, rm, writeFile } from "fs/promises"; import { tmpdir } from "os"; import { join } from "path"; @@ -135,6 +135,64 @@ try { } console.log("✓ delete reports AGENT_NOT_FOUND for an unknown ID\n"); } + + { + console.log("Test 10: a missing full ID does not delete an agent titled with it"); + const missingId = "11111111-2222-4333-8444-555555555555"; + const titledId = "c9a97e5d-4a92-4646-a016-53032146d0a1"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${titledId}.json`), + JSON.stringify( + { + id: titledId, + provider: "codex", + cwd: dirs.workDir, + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: missingId, + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + for (const command of ["inspect", "delete"]) { + const result = await runPaseoCli(daemon, [ + "agent", + command, + missingId, + "--json", + "--host", + host, + ]); + assert.strictEqual(result.exitCode, 1, `${command}: ${result.stdout}`); + assert.strictEqual( + JSON.parse(result.stderr).error.code, + "AGENT_NOT_FOUND", + `${command}: ${result.stderr}`, + ); + } + + const titled = await runPaseoCli(daemon, [ + "agent", + "inspect", + titledId, + "--json", + "--host", + host, + ]); + assert.strictEqual(titled.exitCode, 0, titled.stderr); + assert.strictEqual(JSON.parse(titled.stdout).Id, titledId); + } finally { + await daemon.stop(); + } + console.log("✓ a missing full ID does not delete an agent titled with it\n"); + } } finally { await rm(paseoHome, { recursive: true, force: true }); } diff --git a/packages/cli/tests/29-agent-id-resolution.test.ts b/packages/cli/tests/29-agent-id-resolution.test.ts index 721e307aea..bb59a35a34 100644 --- a/packages/cli/tests/29-agent-id-resolution.test.ts +++ b/packages/cli/tests/29-agent-id-resolution.test.ts @@ -18,25 +18,52 @@ const agents = [ } { - console.log("Test 2: ID prefix resolves"); + console.log("Test 2: full UUID resolves exactly, case-insensitively"); + const exactId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const agentsWithNameCollision = [ + { id: exactId, title: "target agent" }, + { + id: "c9a97e5d-4a92-4646-a016-53032146d0a1", + title: `worker ${exactId}`, + }, + ]; + assert.strictEqual(resolveAgentId(exactId.toUpperCase(), agentsWithNameCollision), exactId); + console.log("✓ full UUID resolves exactly, case-insensitively\n"); +} + +{ + console.log("Test 3: missing full UUID does not match another agent name"); + const missingId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const nameCollision = [ + { + id: "c9a97e5d-4a92-4646-a016-53032146d0a1", + title: `worker ${missingId}`, + }, + ]; + assert.strictEqual(resolveAgentId(missingId, nameCollision), null); + console.log("✓ missing full UUID does not match another agent name\n"); +} + +{ + console.log("Test 4: ID prefix resolves"); assert.strictEqual(resolveAgentId("def5678", agents), "def5678-other-agent-id"); console.log("✓ ID prefix resolves\n"); } { - console.log("Test 3: exact name match resolves case-insensitively"); + console.log("Test 5: exact name match resolves case-insensitively"); assert.strictEqual(resolveAgentId("fix archive flow", agents), "def5678-other-agent-id"); console.log("✓ exact name match resolves case-insensitively\n"); } { - console.log("Test 4: partial name match resolves when unique"); + console.log("Test 6: partial name match resolves when unique"); assert.strictEqual(resolveAgentId("review", agents), "987zyxw-third-agent-id"); console.log("✓ partial name match resolves when unique\n"); } { - console.log("Test 5: missing agent returns null"); + console.log("Test 7: missing agent returns null"); assert.strictEqual(resolveAgentId("does not exist", agents), null); console.log("✓ missing agent returns null\n"); } diff --git a/packages/client/package.json b/packages/client/package.json index c244deb6db..9c418743e4 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Paseo client SDK package", "license": "Apache-2.0", "files": [ @@ -49,8 +49,8 @@ "measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts" }, "dependencies": { - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/relay": "0.16.0-beta.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/relay": "0.16.1", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/client/src/connection.test.ts b/packages/client/src/connection.test.ts index ef326bf516..50622779e8 100644 --- a/packages/client/src/connection.test.ts +++ b/packages/client/src/connection.test.ts @@ -449,7 +449,7 @@ test("a timed-out subscription rejects and cannot replay on reconnect", async () h.open(); await connecting; const observation = h.client.observeAgents({ timeout: 10 }); - await expect(observation.ready).rejects.toThrow(/timed out|timeout/i); + await expect(observation.ready).rejects.toMatchObject({ code: "DAEMON_REQUEST_TIMEOUT" }); await observation.release(); const reconnecting = h.client.connect(); h.open(); diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 2ddef8cc61..af1f2edd1f 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -12,6 +12,7 @@ import { type PluginClientBundle, type PluginClientBundleStore, } from "./daemon-client"; +import { createHostChannelTransport } from "./hosts/index.js"; import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities"; import { ChunkedTransport } from "@getpaseo/protocol/chunked-transport"; import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas"; @@ -1491,7 +1492,7 @@ test("keeps the transport connected when a session RPC ping times out", async () await connectPromise; expect(client.getConnectionState().status).toBe("connected"); - await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("Timeout waiting for message"); + await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("No response to ping after"); expect(client.getConnectionState().status).toBe("connected"); }); @@ -1540,7 +1541,9 @@ test("bounds the wait for push token revocation", async () => { await connectPromise; const revocation = client.unregisterPushToken("ExponentPushToken[test-device]"); - const rejection = expect(revocation).rejects.toThrow("Timeout waiting for message (2000ms)"); + const rejection = expect(revocation).rejects.toThrow( + "No response to push.unregister.request after 2000ms", + ); await vi.advanceTimersByTimeAsync(1_999); expect(client.getConnectionState().status).toBe("connected"); @@ -1549,6 +1552,30 @@ test("bounds the wait for push token revocation", async () => { expect(client.getConnectionState().status).toBe("connected"); }); +test("identifies the request when marking an agent as read times out", async () => { + useHeartbeatClock(); + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_attention_timeout", + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + const connected = client.connect(); + transport.triggerOpen(); + await connected; + + const outcome = client.clearAgentAttention("agent-1").catch((error: unknown) => error); + await vi.advanceTimersByTimeAsync(60_000); + expect(await outcome).toMatchObject({ + name: "DaemonConnectionError", + code: "DAEMON_REQUEST_TIMEOUT", + message: "No response to clear_agent_attention after 60000ms", + }); + expect(client.isConnected).toBe(true); +}); + test("defaults session RPC waiters to sixty seconds", async () => { useHeartbeatClock(); const logger = createMockLogger(); @@ -1593,7 +1620,7 @@ test("defaults session RPC waiters to sixty seconds", async () => { expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (60000ms)"); + await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms"); }); test("honors explicit fetchAgent timeout below the session RPC default", async () => { @@ -1641,7 +1668,7 @@ test("honors explicit fetchAgent timeout below the session RPC default", async ( expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (5000ms)"); + await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 5000ms"); }); test("preserves legacy fetchAgent id overload", async () => { @@ -1805,7 +1832,9 @@ test("honors explicit fetchAgentTimeline timeout below the session RPC default", expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (2000ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to fetch_agent_timeline_request after 2000ms", + ); }); test("lists the full agent prompt index", async () => { @@ -1898,7 +1927,7 @@ test("honors explicit fetchAgents timeout below the session RPC default", async expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1200ms)"); + await expect(responsePromise).rejects.toThrow("No response to fetch_agents_request after 1200ms"); }); test("honors explicit shutdownServer timeout below the session RPC default", async () => { @@ -1944,7 +1973,9 @@ test("honors explicit shutdownServer timeout below the session RPC default", asy expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to shutdown_server_request after 1500ms", + ); }); test("honors explicit getDaemonStatus timeout below the session RPC default", async () => { @@ -1990,7 +2021,9 @@ test("honors explicit getDaemonStatus timeout below the session RPC default", as expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to daemon.get_status.request after 1500ms", + ); }); test("honors explicit getDaemonPairingOffer timeout below the session RPC default", async () => { @@ -2036,7 +2069,9 @@ test("honors explicit getDaemonPairingOffer timeout below the session RPC defaul expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to daemon.get_pairing_offer.request after 1500ms", + ); }); test("gates config reload on the daemon capability", async () => { @@ -2442,7 +2477,9 @@ test("keeps enable and disable inside the session RPC deadline", async () => { expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(pending).rejects.toThrow("Timeout waiting for message (60000ms)"); + await expect(pending).rejects.toThrow( + `No response to plugin.${action}.request after 60000ms`, + ); } } finally { vi.useRealTimers(); @@ -8618,7 +8655,9 @@ test("usage request timeout detaches its update listener", async () => { const result = client.listUsageReports({ requestId: "timeout-usage" }, (report) => updates.push(report), ); - const rejected = expect(result).rejects.toThrow("Timeout waiting for message (60000ms)"); + const rejected = expect(result).rejects.toThrow( + "No response to usage.list_reports.request after 60000ms", + ); await vi.advanceTimersByTimeAsync(60_001); await rejected; mock.triggerMessage( @@ -9402,7 +9441,7 @@ test("RPC deadlines remain active while a preceding frame waits for drain", asyn blocked = true; const first = client.sendHostFrame("route", new Uint8Array([1])); try { - await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("Timeout waiting for message"); + await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("No response to ping after"); expect(client.isConnected).toBe(true); } finally { drain(); @@ -9562,7 +9601,6 @@ test.each(["latency", "dictation start", "dictation finish"])( ); test("routed channels inherit an origin without drain support", async () => { - const { createHostChannelTransport } = await import("./hosts/index.js"); const mock = createMockTransport(); mock.transport.supportsDrain = false; const client = new DaemonClient({ @@ -10133,3 +10171,69 @@ describe("provider options across daemon versions", () => { }); }); }); + +test.each([ + { name: "route", initialRouteId: null, link: false }, + { name: "link", initialRouteId: null, link: true }, + { name: "initial route", initialRouteId: "route", link: false }, +])( + "$name fails promptly when its origin is offline during initialization", + async ({ initialRouteId, link }) => { + vi.useFakeTimers(); + const origin = new DaemonClient({ + url: "ws://origin", + clientId: "offline-origin", + transportFactory: () => createMockTransport().transport, + reconnect: { enabled: false }, + logger: createMockLogger(), + }); + clients.push(origin); + const unsubscribe = vi.fn(); + const subscribe = origin.subscribeConnectionStatus.bind(origin); + vi.spyOn(origin, "subscribeConnectionStatus").mockImplementation((listener) => { + const release = subscribe(listener); + return () => { + release(); + unsubscribe(); + }; + }); + const child = new DaemonClient({ + url: "ws://routed-host/ws", + clientId: "offline-origin-child", + transportFactory: createHostChannelTransport(origin, "child", "scope", initialRouteId, link), + reconnect: { enabled: false }, + logger: createMockLogger(), + }); + clients.push(child); + const rejected = expect(child.connect()).rejects.toThrow(); + await vi.advanceTimersByTimeAsync(0); + expect(child.getConnectionState().status).toBe("disconnected"); + await rejected; + expect(unsubscribe).toHaveBeenCalledTimes(1); + }, +); + +test("disposing a route before its deferred close does not reopen it on origin recovery", async () => { + vi.useFakeTimers(); + const mock = createMockTransport(); + const origin = new DaemonClient({ + url: "ws://origin", + clientId: "disposed-route-origin", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + logger: createMockLogger(), + }); + clients.push(origin); + const route = createHostChannelTransport(origin, "child", "scope", null)({ url: "ws://route" }); + const opened = vi.fn(); + const closed = vi.fn(); + route.onOpen(opened); + route.onClose(closed); + route.close(); + const connecting = origin.connect(); + mock.triggerOpen({ features: { ownedSubscriptions: true, connectedHosts: true } }); + await connecting; + await vi.advanceTimersByTimeAsync(0); + expect(opened).not.toHaveBeenCalled(); + expect(closed).toHaveBeenCalledTimes(1); +}); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index a401de273f..e677fbe3b0 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -16,6 +16,7 @@ import { } from "@getpaseo/protocol/binary-frames/index"; import { messageTooLargeError } from "./daemon-client-transport-utils.js"; import type { HostAdd, HostUpdate, HostDirectory } from "@getpaseo/protocol/hosts"; +import type { PluginListingDetail, PluginListingIndex } from "@getpaseo/protocol/plugin-registry"; import { legacyUsageIcon } from "./legacy-usage-icons.js"; import { subscribeTimeline, type TimelineMessage } from "./timeline-subscription/index.js"; import { ProviderSnapshotUpdates } from "./provider-snapshots/index.js"; @@ -482,7 +483,7 @@ export interface SendMessageOptions { sourceAgentServerId?: string; sessionMode?: string; messageId?: string; - /** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */ + /** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */ activeTurnBehavior?: ActiveTurnBehavior; images?: Array<{ data: string; mimeType: string }>; attachments?: SendAgentMessageRequest["attachments"]; @@ -1022,6 +1023,7 @@ interface WaitHandle { interface WaitOptions { skipQueue?: boolean; requestId?: string; + requestType?: SessionInboundMessage["type"]; } interface CorrelatedResponseIdentity { @@ -2358,7 +2360,7 @@ export class DaemonClient { return { kind: "ok", value }; }, timeout, - { ...params.options, requestId: params.requestId }, + { ...params.options, requestId: params.requestId, requestType: params.message.type }, ); // The response deadline still applies while the transport waits for drain. @@ -6575,6 +6577,38 @@ export class DaemonClient { return payload.plugins; } + private requirePluginRegistry(): void { + // COMPAT(pluginRegistry): added in v0.16.0; remove after 2027-05-15 once daemon floor proxies the registry. + if (this.getLastServerInfoMessage()?.features?.pluginRegistry !== true) + throw new Error("Update the host to browse plugins."); + } + + /** The host's default plugin registry directory. */ + async listPluginRegistry(): Promise { + this.requirePluginRegistry(); + const requestId = this.createRequestId(); + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "plugin.registry.list.request", requestId }, + responseType: "plugin.registry.list.response", + timeout: 60_000, + }); + return payload.index; + } + + /** One registry listing with its overview. */ + async getRegistryPlugin(id: string): Promise { + this.requirePluginRegistry(); + const requestId = this.createRequestId(); + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "plugin.registry.get.request", requestId, id }, + responseType: "plugin.registry.get.response", + timeout: 60_000, + }); + return payload.plugin; + } + private requirePluginUpdates(): void { // COMPAT(pluginSourceUpdates): added in v0.8.0; remove after 2027-03-16 once daemon floor supports reviewed updates. if (this.getLastServerInfoMessage()?.features?.pluginSourceUpdates !== true) @@ -8074,7 +8108,9 @@ export class DaemonClient { ): WaitHandle { // Capture stack trace at call site, not inside setTimeout const timeoutError = new DaemonConnectionError( - `Timeout waiting for message (${timeout}ms)`, + options?.requestType + ? `No response to ${options.requestType} after ${timeout}ms` + : `Timeout waiting for message (${timeout}ms)`, "DAEMON_REQUEST_TIMEOUT", ); diff --git a/packages/client/src/hosts/index.ts b/packages/client/src/hosts/index.ts index 150cf48071..47504f0ebe 100644 --- a/packages/client/src/hosts/index.ts +++ b/packages/client/src/hosts/index.ts @@ -86,7 +86,8 @@ export function createHostChannelTransport( ); cleanups.push( origin.subscribeConnectionStatus((connectionState) => { - if (connectionState.status !== "connected") close(); + // The initial status arrives before the client installs transport handlers. + if (connectionState.status !== "connected") queueMicrotask(close); }), ); let opening: Promise; diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 7f1c5fd14f..1a056de459 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -306,6 +306,11 @@ export interface PaseoAgentTimelineRefetchOptions { cursor?: FetchAgentTimelineCursor; limit?: number; projection?: FetchAgentTimelineProjection; + /** + * Extends a `tail` or `before` page back to the start of the oldest turn it touches, so + * `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. + */ + wholeTurns?: boolean; requestId?: string; } diff --git a/packages/desktop/bin/paseo.cmd b/packages/desktop/bin/paseo.cmd index 1e767523bb..2dac445381 100644 --- a/packages/desktop/bin/paseo.cmd +++ b/packages/desktop/bin/paseo.cmd @@ -11,9 +11,6 @@ if not exist "%APP_EXECUTABLE%" ( set "ELECTRON_RUN_AS_NODE=1" set "PASEO_NODE_ENV=production" -rem PASEO_DESKTOP_MANAGED marks daemons started through this bundled CLI as -rem desktop-managed, so the desktop app restarts them when it upgrades. -set "PASEO_DESKTOP_MANAGED=1" set "PASEO_CLI=%~f0" "%APP_EXECUTABLE%" --disable-warning=DEP0040 "%RESOURCES_DIR%\app.asar.unpacked\dist\daemon\node-entrypoint-runner.js" node-script "%RESOURCES_DIR%\app.asar\node_modules\@getpaseo\cli\dist\index.js" %* exit /b %errorlevel% diff --git a/packages/desktop/e2e/daemon-lifecycle.e2e.mjs b/packages/desktop/e2e/daemon-lifecycle.e2e.mjs index 870e0f7db5..f0cbb74553 100644 --- a/packages/desktop/e2e/daemon-lifecycle.e2e.mjs +++ b/packages/desktop/e2e/daemon-lifecycle.e2e.mjs @@ -41,16 +41,24 @@ savePersistedConfig(home, { }, }); const main = path.join(root, "main.cjs"); +const updatedMain = path.join(root, "updated-main.cjs"); const managerPath = path.join(repo, "packages/desktop/dist/daemon/daemon-manager.js"); +const desktopMain = (setup) => + `const { app } = require("electron"); ${setup} app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`; +await writeFile(main, desktopMain("")); +// An unpackaged Desktop reads its version from packages/desktop/package.json. This entry +// reports a newer version, standing in for the Desktop an update installs. await writeFile( - main, - `const { app } = require("electron"); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`, + updatedMain, + desktopMain( + `const fs = require("node:fs"); const path = require("node:path"); const readFileSync = fs.readFileSync; fs.readFileSync = (file, ...rest) => typeof file === "string" && path.relative(${JSON.stringify(path.join(repo, "packages/desktop"))}, file) === "package.json" ? JSON.stringify({ version: "999.0.0" }) : readFileSync(file, ...rest);`, + ), ); let desktop; let captured; -async function openDesktop() { +async function openDesktop(entry = main) { desktop = await electron.launch({ - args: ["--no-sandbox", "--ozone-platform=headless", main], + args: ["--no-sandbox", "--ozone-platform=headless", entry], env: { ...env, PASEO_LISTEN: "127.0.0.1:1", @@ -78,27 +86,31 @@ async function command(name, args) { ); } try { - // Simulate a legacy independent launch that carries the old Desktop flag. + // A daemon the user started through the CLI, which Desktop must never stop on its own. + // Older bundled CLIs exported PASEO_DESKTOP_MANAGED, and the CLI launch must not record it. const launch = await startDaemonInstance({ home, command: process.execPath, args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")], - env, + env: { ...env, PASEO_DESKTOP_MANAGED: "1" }, mode: "deployment", - desktopManaged: true, timeoutMs: 30_000, }); captured = launch.instance; await openDesktop(); const attached = await command("start_desktop_daemon"); assert.equal(attached.pid, captured.pid); - assert.equal(attached.desktopManaged, true); + assert.equal(attached.desktopManaged, false); assert.equal(attached.ownedByDesktop, false); for (const reason of ["quit", "settings", "app_update", "host_remove", "version_mismatch"]) { const status = await command("stop_desktop_daemon", { reason }); assert.equal(status.pid, captured.pid, `${reason} stopped an attached daemon`); process.kill(captured.pid, 0); } + await closeDesktop(); + await openDesktop(updatedMain); + const afterUpdate = await command("start_desktop_daemon"); + assert.equal(afterUpdate.pid, captured.pid, "a newer Desktop replaced a daemon the user started"); const restarted = await command("restart_desktop_daemon"); assert.equal(restarted.pid, captured.pid); await assert.rejects( @@ -134,18 +146,37 @@ try { desktop = null; process.kill(captured.pid, 0); await openDesktop(); - assert.equal((await command("start_desktop_daemon")).ownedByDesktop, false); - await command("stop_desktop_daemon", { reason: "quit" }); + // The next session attaches to the daemon Desktop launched before it quit. + const survivor = await command("start_desktop_daemon"); + assert.equal(survivor.pid, captured.pid); + assert.equal(survivor.desktopManaged, true); + assert.equal(survivor.ownedByDesktop, false); + for (const reason of ["quit", "settings", "host_remove"]) { + await command("stop_desktop_daemon", { reason }); + process.kill(captured.pid, 0); + } + // With management off, Desktop leaves the daemon running through an update. + await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: false } }); + await command("stop_desktop_daemon", { reason: "app_update" }); process.kill(captured.pid, 0); - await command("stop_desktop_daemon", { - reason: "manual_ipc", - pid: captured.pid, - startedAt: captured.startedAt, - }); + await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: true } }); + // Installing an update stops it, so the updated Desktop starts its own daemon. + const beforeInstall = await command("stop_desktop_daemon", { reason: "app_update" }); + assert.equal(beforeInstall.status, "stopped", "app_update left Desktop's daemon running"); captured = null; const next = await command("start_desktop_daemon"); captured = await readDaemonInstance(home); assert.equal(next.ownedByDesktop, true); + await closeDesktop(); + process.kill(captured.pid, 0); + // A newer Desktop replaces the daemon an older Desktop launched and kept running. + const outdated = captured; + await openDesktop(updatedMain); + const replaced = await command("start_desktop_daemon"); + captured = await readDaemonInstance(home); + assert.notEqual(replaced.pid, outdated.pid, "a newer Desktop kept the outdated daemon"); + assert.equal(replaced.ownedByDesktop, true); + assert.throws(() => process.kill(outdated.pid, 0), "the outdated daemon is still running"); await command("stop_desktop_daemon", { reason: "quit" }); assert.equal(await readDaemonInstance(home), null); captured = null; @@ -195,7 +226,7 @@ try { ); } console.log( - "PASS: attached legacy daemon survives automatic actions; explicit captured stop, owned launch, managed settings, worker restart, and next-session attachment.", + "PASS: a user-started daemon survives automatic actions and updates; explicit captured stop, owned launch, managed settings, worker restart, next-session attachment, and update replacement of an earlier session's daemon.", ); } finally { await closeDesktop(); diff --git a/packages/desktop/e2e/sidebar-nav-drag-region.spec.ts b/packages/desktop/e2e/sidebar-nav-drag-region.spec.ts new file mode 100644 index 0000000000..18e1e7c91b --- /dev/null +++ b/packages/desktop/e2e/sidebar-nav-drag-region.spec.ts @@ -0,0 +1,64 @@ +import type { Page } from "@playwright/test"; +import { test, expect } from "../../app/e2e/support/fixtures"; +import { gotoAppShell } from "../../app/e2e/support/helpers/app"; + +// Windows and Linux draw their window controls top-right, so the desktop sidebar has no +// chrome row of its own. Its window-drag surface is the strip above the navigation rows. +const CUSTOM_CHROME_HOSTS = [ + { platform: "linux", windowChromeMode: "custom-linux" }, + { platform: "win32", windowChromeMode: "custom-windows" }, +] as const; + +async function installDesktopHost( + page: Page, + host: (typeof CUSTOM_CHROME_HOSTS)[number], +): Promise { + await page.addInitScript((desktopHost) => { + window.paseoDesktop = { + ...desktopHost, + events: { on: () => () => {} }, + invoke: async (command: string) => { + if (command === "get_desktop_settings") { + return { + releaseChannel: "stable", + daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true }, + }; + } + return null; + }, + }; + }, host); +} + +async function sidebarDragGeometry(page: Page) { + const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first(); + await expect(navScroll).toBeVisible(); + return navScroll.evaluate((node) => { + const nav = node.getBoundingClientRect(); + const dragRegions = []; + for (const element of document.querySelectorAll("*")) { + if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue; + const rect = element.getBoundingClientRect(); + const overSidebar = rect.left < nav.right && rect.right > nav.left; + if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom }); + } + return { navTop: nav.top, navBottom: nav.bottom, dragRegions }; + }); +} + +for (const host of CUSTOM_CHROME_HOSTS) { + test.describe(`Desktop sidebar on ${host.platform}`, () => { + test.use({ viewport: { width: 1280, height: 480 } }); + + test("keeps a window drag strip above the scrolling navigation", async ({ page }) => { + await installDesktopHost(page, host); + await gotoAppShell(page); + + const geometry = await sidebarDragGeometry(page); + expect(geometry.dragRegions).not.toEqual([]); + for (const region of geometry.dragRegions) { + expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1); + } + }); + }); +} diff --git a/packages/desktop/e2e/window-startup.e2e.mjs b/packages/desktop/e2e/window-startup.e2e.mjs index e6654c09c2..974cc0f30c 100644 --- a/packages/desktop/e2e/window-startup.e2e.mjs +++ b/packages/desktop/e2e/window-startup.e2e.mjs @@ -5,18 +5,25 @@ import { fileURLToPath } from "node:url"; import { _electron as electron, expect } from "playwright/test"; const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-")); -const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url)); +const showWhenReadyPath = fileURLToPath( + new URL("../dist/window/show-when-ready.js", import.meta.url), +); +const rendererRecoveryPath = fileURLToPath( + new URL("../dist/window/renderer-recovery.js", import.meta.url), +); -async function launchWindowWithoutHiddenFrames() { +async function launchDesktopWindow() { const main = path.join(root, "main.cjs"); await writeFile( main, `const { app, BrowserWindow } = require("electron"); - const { showWindowWhenReady } = require(${JSON.stringify(modulePath)}); + const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)}); + const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)}); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(async () => { const win = global.mainWindow = new BrowserWindow({ show: false, paintWhenInitiallyHidden: false }); showWindowWhenReady(win, { showOnLoad: true }); + reloadWhenRendererExits(win); await win.loadURL("data:text/html,

Desktop ready

"); global.visibleAfterLoad = win.isVisible(); });`, @@ -37,11 +44,32 @@ async function expectLoadedDesktopIsShown(desktop) { await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); } +function rendererPid(desktop) { + return desktop.evaluate(() => global.mainWindow.webContents.getOSProcessId()); +} + +async function expectDesktopReloadsAfterRendererIsTerminated(desktop) { + const terminated = await rendererPid(desktop); + process.kill(terminated, "SIGTERM"); + await expect.poll(() => rendererPid(desktop), { timeout: 15_000 }).not.toBe(terminated); + await expect + .poll( + () => + desktop.evaluate(() => + global.mainWindow.webContents.executeJavaScript("document.body.textContent"), + ), + { timeout: 15_000 }, + ) + .toBe("Desktop ready"); +} + let desktop; try { - desktop = await launchWindowWithoutHiddenFrames(); + desktop = await launchDesktopWindow(); await expectLoadedDesktopIsShown(desktop); console.log("Loaded desktop is visible without hidden compositor frames"); + await expectDesktopReloadsAfterRendererIsTerminated(desktop); + console.log("Desktop reloads its window after the renderer is terminated"); } finally { await desktop?.close(); await rm(root, { recursive: true, force: true }); diff --git a/packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts b/packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts new file mode 100644 index 0000000000..033e99009e --- /dev/null +++ b/packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts @@ -0,0 +1,68 @@ +import type { Page } from "@playwright/test"; +import { test, expect } from "../../app/e2e/support/fixtures"; +import { clickNewTerminal, gotoWorkspace } from "../../app/e2e/support/helpers/launcher"; +import { seedWorkspace } from "../../app/e2e/support/helpers/seed-client"; +import { waitForWorkspaceTabsVisible } from "../../app/e2e/support/helpers/workspace-tabs"; + +// macOS desktop switches tabs with Cmd+Shift+brackets, like other Mac apps. +// Web keeps Alt+Shift (the browser owns Cmd+Shift+brackets) and is covered in +// the app browser suite. Windows/Linux desktop can't be emulated here: shortcut +// OS detection falls back to the host user agent for non-darwin bridges. + +async function installMacDesktopBridge(page: Page): Promise { + await page.addInitScript(() => { + window.paseoDesktop = { + platform: "darwin", + events: { on: () => () => {} }, + invoke: async (command: string) => { + if (command === "get_desktop_settings") { + return { + releaseChannel: "stable", + daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true }, + }; + } + return null; + }, + }; + }); +} + +const terminalTabs = (page: Page) => + page.locator('[data-testid^="workspace-tab-terminal_"]').filter({ visible: true }); + +async function openTwoTerminalTabs(page: Page) { + await waitForWorkspaceTabsVisible(page); + await clickNewTerminal(page); + await expect(terminalTabs(page)).toHaveCount(1, { timeout: 30_000 }); + await clickNewTerminal(page); + await expect(terminalTabs(page)).toHaveCount(2, { timeout: 30_000 }); + const first = terminalTabs(page).nth(0); + const second = terminalTabs(page).nth(1); + await expect(second).toHaveAttribute("aria-selected", "true"); + return { first, second }; +} + +test.describe("Previous/next tab shortcuts on desktop", () => { + test("macOS desktop switches tabs with Cmd+Shift+[ and ], not Alt+Shift", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "tab-relative-mac-desktop-" }); + try { + await installMacDesktopBridge(page); + await gotoWorkspace(page, workspace.workspaceId); + const { first, second } = await openTwoTerminalTabs(page); + + await page.keyboard.press("Meta+Shift+BracketLeft"); + await expect(first).toHaveAttribute("aria-selected", "true"); + + await page.keyboard.press("Meta+Shift+BracketRight"); + await expect(second).toHaveAttribute("aria-selected", "true"); + + // Alt+Shift is the web and Windows/Linux binding and must not fire here. + // Had it moved to the first tab, Cmd+Shift+[ would wrap back to the second. + await page.keyboard.press("Alt+Shift+BracketLeft"); + await page.keyboard.press("Meta+Shift+BracketLeft"); + await expect(first).toHaveAttribute("aria-selected", "true"); + } finally { + await workspace.cleanup(); + } + }); +}); diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 6e1133d317..307c216a59 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.16.0-beta.1", + "version": "0.16.1", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/desktop/src/daemon/daemon-manager.ts b/packages/desktop/src/daemon/daemon-manager.ts index 98d5287932..44076bbc4b 100644 --- a/packages/desktop/src/daemon/daemon-manager.ts +++ b/packages/desktop/src/daemon/daemon-manager.ts @@ -269,7 +269,7 @@ function normalizeVersion(version: string | null): string | null { } function shouldRestartForVersion(current: DesktopDaemonStatus): boolean { - if (!current.ownedByDesktop) return false; + if (!current.desktopManaged) return false; const appVersion = normalizeVersion(resolveDesktopAppVersion()); const daemonVersion = normalizeVersion(current.version); return Boolean(appVersion && daemonVersion && appVersion !== daemonVersion); @@ -336,12 +336,13 @@ export async function stopDesktopDaemon( ): Promise { const home = getPaseoHome(); const instance = await readDaemonInstance(home); - const owned = Boolean( + const launchedThisSession = Boolean( instance && ownedLaunch && ownedLaunch.home === home && isSameDaemonInstance(instance, ownedLaunch.instance), ); + const owned = launchedThisSession || (await replacesDesktopDaemon(reason, instance)); const explicit = reason === "manual_ipc" && confirmedInstance && @@ -361,10 +362,28 @@ export async function stopDesktopDaemon( keepTerminals, }); await stopCapturedDaemon({ home, instance, reason, keepTerminals }); - if (owned) ownedLaunch = null; + if (launchedThisSession) ownedLaunch = null; return resolveDesktopDaemonStatus(); } +/** An app update or a version mismatch replaces the daemon with the one this Desktop bundles. */ +function isReplacement(reason: DesktopDaemonStopReason): boolean { + return reason === "app_update" || reason === "version_mismatch"; +} + +/** + * While Desktop manages the built-in daemon, a replacement applies to every daemon Desktop + * launched, which `paseo.pid` records as `desktopManaged`. That includes one an earlier Desktop + * session left running. Other automatic stops apply only to a daemon this session launched. + */ +async function replacesDesktopDaemon( + reason: DesktopDaemonStopReason, + instance: DaemonInstance | null, +): Promise { + if (!isReplacement(reason) || instance?.desktopManaged !== true) return false; + return (await getDesktopSettingsStore().get()).daemon.manageBuiltInDaemon; +} + export interface StopCapturedDaemonInput { home: string; instance: DaemonInstance; @@ -428,7 +447,7 @@ export function keepsTerminalsOnStop( platform: NodeJS.Platform, ): boolean { if (platform === "win32") return false; - return reason === "app_update" || reason === "version_mismatch"; + return isReplacement(reason); } async function restartDaemon(): Promise { diff --git a/packages/desktop/src/features/browser-automation/ipc.test.ts b/packages/desktop/src/features/browser-automation/ipc.test.ts index 427e86e1b1..2ea5f599c7 100644 --- a/packages/desktop/src/features/browser-automation/ipc.test.ts +++ b/packages/desktop/src/features/browser-automation/ipc.test.ts @@ -4,6 +4,8 @@ import { adaptWebContents, HostSnapshotEngineRegistry } from "./ipc.js"; import type { IsolatedKeyboardInputEvent } from "./trusted-input.js"; class FakeImage implements TabImage { + public constructor(private readonly alpha = 255) {} + public toPNG(): Uint8Array { return new Uint8Array([137, 80, 78, 71]); } @@ -11,6 +13,10 @@ class FakeImage implements TabImage { public getSize(): { width: number; height: number } { return { width: 640, height: 480 }; } + + public toBitmap(): Uint8Array { + return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]); + } } class FakeDebugger { @@ -268,6 +274,24 @@ describe("browser automation IPC adapter", () => { expect(contents.endedFrameSubscriptions).toBe(1); }); + test("skips frames with no painted pixels and captures the first painted frame", async () => { + const contents = new FakeWebContents(2004); + const tab = adaptWebContents(contents); + const controller = new AbortController(); + const capture = tab.captureFrame(controller.signal); + const unpainted = new FakeImage(0); + const painted = new FakeImage(255); + + contents.frameListener?.(unpainted); + expect(contents.frameListener).not.toBeNull(); + contents.frameListener?.(painted); + + expect(await capture).toBe(painted); + expect(contents.frameListener).toBeNull(); + controller.abort(); + expect(contents.endedFrameSubscriptions).toBe(1); + }); + test("cancels a pending frame subscription when the capture budget expires", async () => { const contents = new FakeWebContents(2001); const tab = adaptWebContents(contents); diff --git a/packages/desktop/src/features/browser-automation/ipc.ts b/packages/desktop/src/features/browser-automation/ipc.ts index 18e5b84544..5932ccd0b1 100644 --- a/packages/desktop/src/features/browser-automation/ipc.ts +++ b/packages/desktop/src/features/browser-automation/ipc.ts @@ -1,4 +1,4 @@ -import { ipcMain } from "electron"; +import { ipcMain, nativeImage } from "electron"; import { BrowserAutomationExecuteRequestSchema } from "@getpaseo/protocol/browser-automation/rpc-schemas"; import type { BrowserAutomationConsoleLogEntry, @@ -15,7 +15,7 @@ import { promptShimInstallScript, promptShimRestoreScript, } from "./dialog-handling.js"; -import { BrowserTabClosedError, executeAutomationCommand } from "./service.js"; +import { BrowserTabClosedError, executeAutomationCommand, hasPaintedPixels } from "./service.js"; import { BrowserSnapshotEngine } from "./snapshot-engine.js"; import { listRegisteredPaseoBrowserIds, @@ -133,6 +133,7 @@ export function adaptWebContents(contents: BrowserAutomationWebContents): TabCon goForward: () => contents.goForward(), reload: () => contents.reload(), captureFrame: (signal) => captureViewportFrame(contents, signal), + decodePng: (png) => nativeImage.createFromBuffer(Buffer.from(png)), invalidate: () => contents.invalidate(), withFrameProduction: async (capture) => { const previous = contents.getBackgroundThrottling(); @@ -182,6 +183,9 @@ function captureViewportFrame( // A resized resident guest can paint while capturePage's surface-copy // request remains pending. Subscribe to its rendered frames instead. contents.beginFrameSubscription(false, (image) => { + // Keep the subscription open until the page has painted; the capture + // budget turns a page that never paints into screenshot_no_frame. + if (!hasPaintedPixels(image)) return; stop(); resolve(image); }); diff --git a/packages/desktop/src/features/browser-automation/service.test.ts b/packages/desktop/src/features/browser-automation/service.test.ts index d793e138b7..5f892bbe59 100644 --- a/packages/desktop/src/features/browser-automation/service.test.ts +++ b/packages/desktop/src/features/browser-automation/service.test.ts @@ -22,6 +22,7 @@ class FakeImage implements TabImage { public constructor( private readonly bytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3]), private readonly size = { width: 640, height: 480 }, + private readonly alpha = 255, ) {} public toPNG(): Uint8Array { @@ -31,8 +32,14 @@ class FakeImage implements TabImage { public getSize(): { width: number; height: number } { return this.size; } + + public toBitmap(): Uint8Array { + return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]); + } } +const UNPAINTED_FULL_PAGE_PNG = "unpaintedPng"; + class FakeTab implements TabContents { public withFrameProduction(capture: () => Promise): Promise { return capture(); @@ -77,6 +84,7 @@ class FakeTab implements TabContents { public fullPageScreenshotThrows = false; public fullPageScreenshotErrorMessage = "UnknownVizError"; public fullPageCaptureFailuresBeforeSuccess = 0; + public fullPageUnpaintedCapturesBeforePainted = 0; public layoutMetrics = { cssLayoutViewport: { clientWidth: 390, clientHeight: 844 }, cssContentSize: { width: 390, height: 1200 }, @@ -191,6 +199,11 @@ class FakeTab implements TabContents { this.actions.push("invalidate"); } + public decodePng(png: Uint8Array): TabImage { + const unpainted = Buffer.from(png).equals(Buffer.from(UNPAINTED_FULL_PAGE_PNG, "base64")); + return new FakeImage(png, { width: 390, height: 1200 }, unpainted ? 0 : 255); + } + public getConsoleMessages(): BrowserAutomationConsoleLogEntry[] { return this.consoleMessages; } @@ -218,6 +231,10 @@ class FakeTab implements TabContents { if (this.fullPageScreenshotThrows) { throw new Error(this.fullPageScreenshotErrorMessage); } + if (this.fullPageUnpaintedCapturesBeforePainted > 0) { + this.fullPageUnpaintedCapturesBeforePainted -= 1; + return { data: UNPAINTED_FULL_PAGE_PNG }; + } return { data: this.fullPageScreenshotData }; } if (command === "Runtime.evaluate") { @@ -2035,6 +2052,56 @@ describe("executeAutomationCommand", () => { } }); + test("screenshot with fullPage waits for a CDP image with painted pixels", async () => { + vi.useFakeTimers(); + try { + const browser = new BrowserAutomationHarness(); + browser.tab.fullPageUnpaintedCapturesBeforePainted = 1; + + const resultPromise = browser.execute({ + command: "screenshot", + args: { browserId: BROWSER_A, fullPage: true }, + }); + await vi.advanceTimersByTimeAsync(200); + + await expect(resultPromise).resolves.toMatchObject({ + ok: true, + result: { command: "screenshot", dataBase64: "fullPagePng" }, + }); + expect( + browser.tab.debugCommands.filter((entry) => entry.command === "Page.captureScreenshot"), + ).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + + test("screenshot with fullPage returns no-frame when the page never paints", async () => { + vi.useFakeTimers(); + try { + const browser = new BrowserAutomationHarness(); + browser.tab.fullPageUnpaintedCapturesBeforePainted = Number.POSITIVE_INFINITY; + + const resultPromise = browser.execute({ + command: "screenshot", + args: { browserId: BROWSER_A, fullPage: true }, + }); + await vi.advanceTimersByTimeAsync(5_000); + + await expect(resultPromise).resolves.toEqual({ + requestId: "req-screenshot", + ok: false, + error: { + code: "screenshot_no_frame", + message: "The tab has not painted yet. Retry the screenshot.", + retryable: true, + }, + }); + } finally { + vi.useRealTimers(); + } + }); + test("screenshot with fullPage surfaces ordinary CDP capture errors", async () => { const browser = new BrowserAutomationHarness(); browser.tab.fullPageScreenshotThrows = true; diff --git a/packages/desktop/src/features/browser-automation/service.ts b/packages/desktop/src/features/browser-automation/service.ts index 34a01ed074..5f038dd453 100644 --- a/packages/desktop/src/features/browser-automation/service.ts +++ b/packages/desktop/src/features/browser-automation/service.ts @@ -36,6 +36,7 @@ export interface TabContents { goForward(): void; reload(): void; captureFrame(signal: AbortSignal): Promise; + decodePng(png: Uint8Array): TabImage; invalidate(): void; withFrameProduction(capture: () => Promise): Promise; sendInputEvent(event: IsolatedKeyboardInputEvent): void; @@ -52,6 +53,22 @@ export interface TabContents { export interface TabImage { toPNG(): Uint8Array; getSize(): { width: number; height: number }; + // Raw 32-bit pixels. Alpha is the fourth byte of each pixel in BGRA and RGBA order alike. + toBitmap(): Uint8Array; +} + +// Electron guest pages have a transparent base background, so a page that has +// painted nothing yet (for example a dev server hiding body until its JS boots) +// yields a frame where every pixel is transparent. That frame is not a +// screenshot of the page. +export function hasPaintedPixels(image: TabImage): boolean { + const bitmap = image.toBitmap(); + for (let alpha = 3; alpha < bitmap.length; alpha += 4) { + if (bitmap[alpha] !== 0) { + return true; + } + } + return false; } export interface BrowserRegistry { @@ -1348,11 +1365,18 @@ async function executeFullPageScreenshot( const metrics = await getCdpLayoutMetrics(target.contents); width = metrics.contentWidth; height = metrics.contentHeight; - return (await sendDebugCommand("Page.captureScreenshot", { + const result = (await sendDebugCommand("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, clip: { x: 0, y: 0, width, height, scale: 1 }, })) as CdpCaptureScreenshotResult; + if ( + result.data && + !hasPaintedPixels(target.contents.decodePng(Buffer.from(result.data, "base64"))) + ) { + throw new Error("Page.captureScreenshot returned no painted frame"); + } + return result; }); } catch (error) { if (isScreenshotNoFrameError(error)) { diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts index 072f96a26d..196f9a47f4 100644 --- a/packages/desktop/src/main.ts +++ b/packages/desktop/src/main.ts @@ -46,6 +46,7 @@ import { buildStandardContextMenuItems, } from "./window/window-manager.js"; import { setupDarwinCompositorWatchdog } from "./window/compositor-watchdog/index.js"; +import { reloadWhenRendererExits } from "./window/renderer-recovery.js"; import { showWindowWhenReady } from "./window/show-when-ready.js"; import { resolveDesktopWindowChromeMode, windowChromeModeArgument } from "./window/chrome.js"; import { registerDialogHandlers } from "./features/dialogs.js"; @@ -734,6 +735,7 @@ async function createWindow( } setupDarwinCompositorWatchdog(mainWindow); + reloadWhenRendererExits(mainWindow); setupWindowResizeEvents(mainWindow); if (windowStateStore) { setupWindowStatePersistence(mainWindow, windowStateStore); diff --git a/packages/desktop/src/window/renderer-recovery.test.ts b/packages/desktop/src/window/renderer-recovery.test.ts new file mode 100644 index 0000000000..2d1ba58e4c --- /dev/null +++ b/packages/desktop/src/window/renderer-recovery.test.ts @@ -0,0 +1,86 @@ +import { EventEmitter } from "node:events"; +import { describe, expect, it } from "vitest"; +import { reloadWhenRendererExits } from "./renderer-recovery.js"; + +class Contents extends EventEmitter { + reloads = 0; + url = "paseo://app/"; + getURL() { + return this.url; + } + reload() { + this.reloads += 1; + } + exit(reason: string) { + this.emit("render-process-gone", {}, { reason, exitCode: reason === "clean-exit" ? 0 : 15 }); + } +} + +class Window { + webContents = new Contents(); + destroyed = false; + isDestroyed() { + return this.destroyed; + } +} + +function recoverableWindow() { + const win = new Window(); + let time = 0; + reloadWhenRendererExits(win, { now: () => time }); + return { + win, + advance(ms: number) { + time += ms; + }, + }; +} + +describe("reloadWhenRendererExits", () => { + it("reloads the window when its renderer is killed", () => { + const { win } = recoverableWindow(); + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(1); + }); + + it("reloads after a renderer crash or out-of-memory exit", () => { + const { win, advance } = recoverableWindow(); + win.webContents.exit("crashed"); + advance(120_000); + win.webContents.exit("oom"); + expect(win.webContents.reloads).toBe(2); + }); + + it("leaves a renderer that exited cleanly alone", () => { + const { win } = recoverableWindow(); + win.webContents.exit("clean-exit"); + expect(win.webContents.reloads).toBe(0); + }); + + it("leaves a renderer that exits before the first page commits to Chromium", () => { + const { win } = recoverableWindow(); + win.webContents.url = ""; + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(0); + }); + + it("leaves a closed window closed", () => { + const { win } = recoverableWindow(); + win.destroyed = true; + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(0); + }); + + it("stops reloading a renderer that keeps exiting, and recovers again later", () => { + const { win, advance } = recoverableWindow(); + for (let exit = 0; exit < 5; exit += 1) { + win.webContents.exit("crashed"); + advance(1_000); + } + expect(win.webContents.reloads).toBe(3); + + advance(60_000); + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(4); + }); +}); diff --git a/packages/desktop/src/window/renderer-recovery.ts b/packages/desktop/src/window/renderer-recovery.ts new file mode 100644 index 0000000000..4c4befe3ea --- /dev/null +++ b/packages/desktop/src/window/renderer-recovery.ts @@ -0,0 +1,56 @@ +import log from "electron-log/main"; + +// A window whose renderer exits keeps its frame but shows nothing until it is +// reloaded. Reload it, but stop when the renderer keeps exiting so a page that +// crashes on load does not restart in a loop. +const MAX_RELOADS_PER_WINDOW = 3; +const RELOAD_WINDOW_MS = 60_000; + +interface RendererExit { + reason: string; + exitCode: number; +} + +interface RecoverableWindow { + isDestroyed(): boolean; + webContents: { + on( + event: "render-process-gone", + listener: (event: unknown, details: RendererExit) => void, + ): unknown; + getURL(): string; + reload(): void; + }; +} + +export function reloadWhenRendererExits( + win: RecoverableWindow, + options: { now?: () => number } = {}, +): void { + const now = options.now ?? Date.now; + let reloadTimes: number[] = []; + + win.webContents.on("render-process-gone", (_event, details) => { + if (details.reason === "clean-exit" || win.isDestroyed()) return; + // Before the first page commits, Chromium finishes the navigation in a new + // renderer by itself. Reloading then would abort the window's initial load. + if (win.webContents.getURL() === "") return; + + const time = now(); + reloadTimes = reloadTimes.filter((reloadTime) => time - reloadTime < RELOAD_WINDOW_MS); + if (reloadTimes.length >= MAX_RELOADS_PER_WINDOW) { + log.error( + `[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` + + `not reloading after ${reloadTimes.length} reloads in the last minute`, + ); + return; + } + + reloadTimes.push(time); + log.warn( + `[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` + + `reloading the window (reload ${reloadTimes.length} in the last minute)`, + ); + win.webContents.reload(); + }); +} diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index fb6aa1b517..eb2f399a5b 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 26a21299c2..6af3ddff26 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.16.0-beta.1", + "version": "0.16.1", "license": "Apache-2.0", "files": [ "dist", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 4d3f76849f..7ff628dc38 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Paseo plugin SDK package", "license": "Apache-2.0", "files": [ @@ -78,8 +78,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -89,8 +89,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 7b78940ba4..8b8cae6630 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -393,6 +393,7 @@ describe("lifecycle hook SDK types", () => { expect( typeErrors(` import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server"; + import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; export default function contribute(server: PluginServerContext) { server.addHook("worktree.create.before", async ({ request }) => { if (request.kind === "checkout-branch") { @@ -426,8 +427,17 @@ describe("lifecycle hook SDK types", () => { const { metadata, ...withoutMetadata } = request; return withoutMetadata; }); - server.addHook("agent.turn.after", async ({ agent, outcome, timeline }, { paseo, signal }) => { + server.addHook("agent.turn.after", async (event, { paseo, signal }) => { + const { agent, outcome } = event; const kind: "completed" | "failed" | "canceled" = outcome.kind; + // @ts-expect-error Turn payloads carry no history; read it from the agent's timeline. + event.timeline; + const turn = await paseo.agents + .ref(agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const items: readonly AgentTimelineItem[] = turn.entries + .filter((entry) => entry.turnId === event.turnId) + .map(({ item }) => item); // @ts-expect-error Notification payloads have no creation request. outcome.request; }); diff --git a/packages/plugin/src/client/contracts.ts b/packages/plugin/src/client/contracts.ts index 1949e5506e..72dc1f954d 100644 --- a/packages/plugin/src/client/contracts.ts +++ b/packages/plugin/src/client/contracts.ts @@ -121,6 +121,22 @@ export interface PluginSidebarViewContribution Component: ComponentType; } +export interface PluginWorkspaceRowBadgeItemProps extends PluginHostProps { + workspaceId: string; +} + +/** + * Part of the line under a workspace's title in the sidebar, on every workspace of the plugin's host. + * Render `WorkspaceRowBadge`, or nothing when there is nothing to say about this workspace. + */ +export interface PluginWorkspaceRowBadgeItemContribution { + id: string; + /** The item's toggle in the sidebar's Show menu. */ + title: Text; + icon: PluginIcon; + Component: ComponentType; +} + /** * A Lucide icon name, inline SVG markup, or a component. Components receive the surface's size * and color; buttons widen the props with their host and target context. @@ -214,6 +230,9 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl addSidebarHeaderItem(contribution: PluginSidebarItemContribution): PluginCleanup; addSidebarFooterItem(contribution: PluginSidebarItemContribution): PluginCleanup; addAgentPanel(contribution: PluginAgentPanelContribution): PluginCleanup; + addWorkspaceRowBadgeItem( + contribution: PluginWorkspaceRowBadgeItemContribution, + ): PluginCleanup; addWorkspacePanel(contribution: PluginWorkspacePanelContribution): PluginCleanup; addCommandCenterItem( contribution: PluginCommandCenterItemContribution, diff --git a/packages/plugin/src/client/index.ts b/packages/plugin/src/client/index.ts index 0597e56afe..9f99fcfb70 100644 --- a/packages/plugin/src/client/index.ts +++ b/packages/plugin/src/client/index.ts @@ -18,6 +18,8 @@ export type { PluginSidebarViewProps, PluginSidebarViewContribution, PluginSidebarItemContribution, + PluginWorkspaceRowBadgeItemProps, + PluginWorkspaceRowBadgeItemContribution, PluginIcon, PluginPanelLocation, PluginOpenPanelOptions, diff --git a/packages/plugin/src/client/ui.ts b/packages/plugin/src/client/ui.ts index 30ad3e178a..f72880b027 100644 --- a/packages/plugin/src/client/ui.ts +++ b/packages/plugin/src/client/ui.ts @@ -173,6 +173,19 @@ export declare const SidebarRow: ComponentType; /** A line between groups of rows. Render it from a sidebar item's `Component`. */ export declare const SidebarSeparator: ComponentType; +export type WorkspaceRowBadgeTone = "muted" | "success" | "warning" | "danger" | "info"; +export interface WorkspaceRowBadgeProps { + /** A Lucide icon name, inline SVG, or a component. */ + icon?: SidebarIcon; + label?: string; + /** Default "muted". */ + tone?: WorkspaceRowBadgeTone; + /** Defaults to `label`, then the item's `title`. */ + accessibilityLabel?: string; +} +/** One item on a sidebar workspace row's meta line. Render it from a workspace row badge item's `Component`. */ +export declare const WorkspaceRowBadge: ComponentType; + /** Paseo's loading state. Fills the panel; the panel decides when to show it. */ export declare const Loading: ComponentType; diff --git a/packages/plugin/src/contracts.ts b/packages/plugin/src/contracts.ts index dfb3ccab9e..bd34ffba77 100644 --- a/packages/plugin/src/contracts.ts +++ b/packages/plugin/src/contracts.ts @@ -90,6 +90,12 @@ export interface PluginThemeColors { accent?: string; mutedForeground: string; ring: string; + sidebar?: string; + sidebarHover?: string; + sidebarSelected?: string; + surface3?: string; + surface4?: string; + foregroundExtraMuted?: string; } export interface PluginThemeContribution { diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index 6c8ac31b71..570d3cd4ca 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -1527,7 +1527,9 @@ function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem { name: snapshot.name ?? snapshot.title, detail, }; - if (status === "failed") return { ...base, status, error: snapshot.output }; + if (status === "failed") { + return { ...base, status, error: snapshot.output ?? { message: "Tool failed" } }; + } return { ...base, status, error: null }; } diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index b022e0a5ef..ee96f3eb08 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -9,6 +9,7 @@ import { } from "@agentclientprotocol/sdk"; import type { ProviderConnection, ProviderEvent, ProviderInput } from "./provider.js"; import { afterEach, describe, expect, it } from "vitest"; +import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages"; import { runAcpProvider, type AcpStreamMessage } from "./acp.js"; const temporaryDirectories: string[] = []; @@ -890,6 +891,72 @@ lines.on("line", (line) => { }, ); + it.each([ + { status: "failed", output: undefined, error: { message: "Tool failed" } }, + { status: "failed", output: null, error: { message: "Tool failed" } }, + { + status: "failed", + output: { message: "File not found" }, + error: { message: "File not found" }, + }, + { status: "failed", output: "Permission denied", error: "Permission denied" }, + { status: "completed", output: null, error: null }, + ] as const)( + "keeps a $status ACP tool with output $output valid on the history wire", + async ({ status, output, error }) => { + const harness = connectorHarness({ + promptUpdates: () => [ + { + sessionUpdate: "tool_call", + toolCallId: "read-1", + title: "Read file", + kind: "read", + status: "in_progress", + }, + { sessionUpdate: "tool_call_update", toolCallId: "read-1", status, rawOutput: output }, + ], + }); + const registration = runAcpProvider({ + id: "tool-history-acp", + label: "Tool history ACP", + connector: harness.connector, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "first", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "Read a file" }] }, + }, + }); + await waitForEvent( + events, + (event) => event.type === "session.turn" && event.state === "completed", + ); + const rows = events.flatMap((event) => + event.type === "timeline.item" && event.item.id === "read-1" ? [event.item] : [], + ); + expect(rows).toHaveLength(2); + for (const row of rows) { + expect(AgentTimelineItemPayloadSchema.safeParse(row).success).toBe(true); + } + expect(rows.at(-1)).toMatchObject({ type: "tool_call", status, error }); + } finally { + await connection.close(); + } + }, + ); + it("serializes configuration mutations", async () => { let releaseMutation: (() => void) | null = null; const configOptions = [ diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index a048d93706..cedc2e3019 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -2,7 +2,6 @@ import type { AgentToolDefinition } from "./agent-tools.js"; import type { AgentPermissionRequest, AgentPermissionResponse, - AgentTimelineItem, AgentSessionConfig, JsonValue, } from "@getpaseo/protocol/agent-types"; @@ -89,6 +88,8 @@ export interface PluginSessionOpenRequest { readonly background: boolean; readonly labels: Readonly>; readonly metadata: Readonly>; + /** Instructions appended for this open; not saved on the agent. */ + appendSystemPrompt?: string[]; tools: AgentToolDefinition[]; env: Record; mcpServers: NonNullable; @@ -104,12 +105,13 @@ export interface PluginHookEvents { "agent.turn.after": { agent: PluginHookAgent; turnId: string | null; - outcome: PluginTurnOutcome; /** - * @deprecated Always empty. Fetch history on demand with - * context.paseo.agents.ref(agent.id).timeline.refetch({ direction: "tail", limit: 20 }). + * The payload carries no history. Read the turn with + * `paseo.agents.ref(agent.id).timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })` + * and keep the entries whose `turnId` equals this `turnId`. The result is empty when a newer turn + * started before the read, or when `turnId` is `null`. */ - timeline: readonly AgentTimelineItem[]; + outcome: PluginTurnOutcome; }; "agent.permission.before": { agent: PluginHookAgent; request: AgentPermissionRequest }; "agent.permission.after": { diff --git a/packages/plugin/src/server/provider.test.ts b/packages/plugin/src/server/provider.test.ts new file mode 100644 index 0000000000..7020c9a526 --- /dev/null +++ b/packages/plugin/src/server/provider.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; +import { ProviderInputSchema, type ProviderInput } from "./provider.js"; + +type ReviewMode = "uncommitted" | "base" | "all"; +type Delivery = "auto" | "steer"; + +const contextLine = { + oldLineNumber: null, + newLineNumber: 12, + type: "add", + content: "const value = 1;", +} as const; + +function reviewPrompt(mode: ReviewMode, delivery: Delivery): ProviderInput { + return { + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "message-1", + delivery, + input: { + type: "message", + content: [ + { + type: "review", + mimeType: "application/paseo-review", + cwd: "/workspace", + mode, + baseRef: "main", + comments: [ + { + filePath: "src/index.ts", + side: "new", + lineNumber: 12, + body: "Please review this change.", + context: { + hunkHeader: "@@ -10,2 +10,3 @@", + targetLine: contextLine, + lines: [{ ...contextLine, type: "context", oldLineNumber: 11 }, contextLine], + }, + }, + ], + }, + ], + }, + }, + }; +} + +describe("Provider review attachments", () => { + it.each(["uncommitted", "base", "all"] as const)( + "preserves mode %s on an ordinary prompt", + (mode) => { + const input = reviewPrompt(mode, "auto"); + expect(ProviderInputSchema.parse(input)).toEqual(input); + }, + ); + + it.each(["uncommitted", "base", "all"] as const)( + "preserves mode %s on a steering prompt", + (mode) => { + const input = reviewPrompt(mode, "steer"); + expect(ProviderInputSchema.parse(input)).toEqual(input); + }, + ); +}); diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index 5b9511f1f7..b928f5d168 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -213,7 +213,7 @@ interface ProviderReviewAttachment { type: "review"; mimeType: "application/paseo-review"; cwd: string; - mode: "uncommitted" | "base"; + mode: "uncommitted" | "base" | "all"; baseRef?: string | null; comments: Array<{ filePath: string; @@ -881,7 +881,7 @@ const providerContentSchema: z.ZodType = z.union([ type: z.literal("review"), mimeType: z.literal("application/paseo-review"), cwd: z.string(), - mode: z.enum(["uncommitted", "base"]), + mode: z.enum(["uncommitted", "base", "all"]), baseRef: z.string().nullable().optional(), comments: z.array( z diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 02a7d75321..8f196a4743 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Paseo shared protocol schemas and wire types", "license": "Apache-2.0", "files": [ diff --git a/packages/protocol/src/agent-attention-notification.test.ts b/packages/protocol/src/agent-attention-notification.test.ts index 04aabceb2c..9166d907de 100644 --- a/packages/protocol/src/agent-attention-notification.test.ts +++ b/packages/protocol/src/agent-attention-notification.test.ts @@ -71,6 +71,25 @@ describe("buildAgentAttentionNotificationPayload", () => { }); }); + it("includes the tool input when a permission has a reason but no title", () => { + const payload = buildAgentAttentionNotificationPayload({ + reason: "permission", + serverId: "srv-1", + workspaceId: "workspace-1", + agentId: "agent-1", + permissionRequest: { + id: "perm-1", + provider: "claude", + name: "Bash", + kind: "tool", + input: { command: "echo hello" }, + description: "Hook requires approval", + }, + }); + + expect(payload.body).toBe('{"command":"echo hello"} - Hook requires approval'); + }); + it("uses error-specific defaults when reason is error", () => { const payload = buildAgentAttentionNotificationPayload({ reason: "error", diff --git a/packages/protocol/src/agent-attention-notification.ts b/packages/protocol/src/agent-attention-notification.ts index 961e864d85..5b9d229d47 100644 --- a/packages/protocol/src/agent-attention-notification.ts +++ b/packages/protocol/src/agent-attention-notification.ts @@ -115,6 +115,11 @@ const buildPermissionDetails = ( if (title) { details.push(title); + } else if (description && request.input) { + const inputPreview = safeStringify(request.input); + if (inputPreview) { + details.push(inputPreview); + } } if (description && description !== title) { details.push(description); diff --git a/packages/protocol/src/git-remote.ts b/packages/protocol/src/git-remote.ts index 56f1363a96..1ba5b7fd9d 100644 --- a/packages/protocol/src/git-remote.ts +++ b/packages/protocol/src/git-remote.ts @@ -108,6 +108,26 @@ export function normalizeHost(host: string): string { return host.trim().replace(/\.+$/u, "").toLowerCase(); } +/** Whether `host` is one of the forge's public cloud hosts, SSH aliases included. */ +export function isForgeCloudHost(forge: string, host: string): boolean { + const cloudHosts = (getForgeDefinition(forge)?.cloudHosts ?? []).map(normalizeHost); + return cloudHosts.includes(normalizeHost(host)); +} + +/** + * Web host for a remote host of `forge`. A cloud SSH alias (a non-first entry + * in the forge's `cloudHosts`, e.g. ssh.github.com) maps to the forge's web + * host (`cloudHosts[0]`); any other host, self-hosted included, is returned + * as is. + */ +export function forgeWebHost(forge: string, host: string): string { + const normalized = normalizeHost(host); + if (!isForgeCloudHost(forge, normalized)) { + return normalized; + } + return normalizeHost(getForgeDefinition(forge)?.cloudHosts?.[0] ?? normalized); +} + function normalizeRemotePath(path: string): string | null { let normalized = path.trim().replace(/^\/+|\/+$/gu, ""); if (normalized.endsWith(".git")) normalized = normalized.slice(0, -4); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 271d3bab9e..e62cf8357e 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -19,7 +19,12 @@ import { HostsRouteFrameSchema, HostsRouteClosedSchema, } from "./hosts.js"; -import { PluginRegistryIdentitySchema } from "./plugin-registry.js"; +import { + PluginRegistryIdSchema, + PluginRegistryIdentitySchema, + PluginListingDetailSchema, + PluginListingIndexSchema, +} from "./plugin-registry.js"; import { AgentProfileSchema, AgentSkillSelectionSchema } from "./agent-profile.js"; export { AgentProfileSchema, @@ -1673,6 +1678,17 @@ export const PluginSourceStatusRequestSchema = z.object({ pluginId: PluginIdSchema.optional(), }); +export const PluginRegistryListRequestSchema = z.object({ + type: z.literal("plugin.registry.list.request"), + requestId: z.string(), +}); + +export const PluginRegistryGetRequestSchema = z.object({ + type: z.literal("plugin.registry.get.request"), + requestId: z.string(), + id: PluginRegistryIdSchema, +}); + export const PluginSourceUpdateRequestSchema = z.object({ type: z.literal("plugin.source.update.request"), requestId: z.string(), @@ -3560,6 +3576,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ PluginDirectoryInspectRequestSchema, PluginSourceInstallRequestSchema, PluginSourceStatusRequestSchema, + PluginRegistryListRequestSchema, + PluginRegistryGetRequestSchema, PluginSourceUpdateRequestSchema, PluginUpdatePreviewRequestSchema, PluginUpdateApplyRequestSchema, @@ -3973,6 +3991,8 @@ export const ServerInfoStatusPayloadSchema = z pluginSourceInstallation: z.boolean().optional(), // COMPAT(pluginSourceUpdates): added in v0.8.0; remove gate after 2027-03-16 once daemon floor supports reviewed updates. pluginSourceUpdates: z.boolean().optional(), + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + pluginRegistry: z.boolean().optional(), // COMPAT(pluginThemes): added in v0.5.0, remove gate after 2027-08-20. // A daemon that predates this flag keeps `addTheme` in the server bundle it compiles, // so a theme plugin cannot start there at all. @@ -4328,6 +4348,22 @@ export const WorkspaceScriptPayloadSchema = z.object({ terminalId: z.string().nullable().optional().default(null), }); +/** + * Where a workspace's forge is on the web, resolved by the daemon so every + * client builds the same links. + */ +export const ForgeWebSchema = z.object({ + /** Web host of the forge: the SSH config alias resolved, cloud SSH hosts mapped to their web host. */ + host: z.string(), + /** + * Repository path that owns issue and change-request numbers when it is not + * the origin repository, such as a fork's parent. Absent: the origin repository. + */ + referenceRepository: z.string().optional(), +}); + +export type ForgeWeb = z.infer; + const WorkspaceGitRuntimePayloadSchema = z .object({ currentBranch: z.string().nullable().optional(), @@ -4464,6 +4500,8 @@ export const WorkspaceDescriptorPayloadSchema = z // until 2027-01-17; remove the consumer fallback once the supported daemon // floor is >= v0.2.0. forge: z.string().optional(), + // Absent from daemons older than v0.16.0; clients then derive links from the origin remote. + forgeWeb: ForgeWebSchema.optional(), project: ProjectPlacementPayloadSchema.optional(), // COMPAT(directorySync): sequence of this latest directory projection. syncSeq: z.number().int().positive().optional(), @@ -5697,6 +5735,7 @@ const CheckoutStatusCommonSchema = z.object({ // upstream branch name is not necessarily currentBranch, so composing one is wrong. // aheadOfOrigin/behindOfOrigin are measured against exactly this ref. upstreamRef: z.string().nullable().optional(), + forgeWeb: ForgeWebSchema.optional(), }); const CheckoutStatusNotGitSchema = CheckoutStatusCommonSchema.extend({ @@ -7240,6 +7279,17 @@ export const PluginSourceStatusItemSchema = z.object({ }); export type PluginSourceStatusItem = z.infer; +/** The host's plugin directory index, fetched by the daemon from its configured registry. */ +export const PluginRegistryListResponseSchema = z.object({ + type: z.literal("plugin.registry.list.response"), + payload: z.object({ requestId: z.string(), index: PluginListingIndexSchema }), +}); + +export const PluginRegistryGetResponseSchema = z.object({ + type: z.literal("plugin.registry.get.response"), + payload: z.object({ requestId: z.string(), plugin: PluginListingDetailSchema }), +}); + export const PluginSourceStatusResponseSchema = z.object({ type: z.literal("plugin.source.status.response"), payload: z.object({ requestId: z.string(), plugins: z.array(PluginSourceStatusItemSchema) }), @@ -7390,6 +7440,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ PluginDirectoryInspectResponseSchema, PluginSourceInstallResponseSchema, PluginSourceStatusResponseSchema, + PluginRegistryListResponseSchema, + PluginRegistryGetResponseSchema, PluginSourceUpdateResponseSchema, PluginUpdatePreviewResponseSchema, PluginUpdateApplyResponseSchema, diff --git a/packages/protocol/src/messages.workspaces.test.ts b/packages/protocol/src/messages.workspaces.test.ts index 8a5bd13224..c056f68733 100644 --- a/packages/protocol/src/messages.workspaces.test.ts +++ b/packages/protocol/src/messages.workspaces.test.ts @@ -1251,6 +1251,15 @@ describe("workspace message schemas", () => { expect( WorkspaceDescriptorPayloadSchema.parse({ ...baseWorkspace, forge: "gitlab" }).forge, ).toBe("gitlab"); + + // forgeWeb is optional: an old daemon omits it, a new daemon's value round-trips. + expect(WorkspaceDescriptorPayloadSchema.parse(baseWorkspace).forgeWeb).toBeUndefined(); + expect( + WorkspaceDescriptorPayloadSchema.parse({ + ...baseWorkspace, + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }).forgeWeb, + ).toEqual({ host: "github.com", referenceRepository: "main-owner/repo" }); }); test("workspace.create.request rejects old flat backing shape and accepts new source envelope", () => { diff --git a/packages/protocol/src/paseo-config-schema.ts b/packages/protocol/src/paseo-config-schema.ts index 31935bd796..541f876229 100644 --- a/packages/protocol/src/paseo-config-schema.ts +++ b/packages/protocol/src/paseo-config-schema.ts @@ -47,6 +47,9 @@ export const PaseoWorktreeConfigRawSchema = z .object({ setup: PaseoLifecycleCommandRawSchema.optional(), teardown: PaseoLifecycleCommandRawSchema.optional(), + // Checked by WorktreeConfigSchema, where an invalid value falls back to the default, so it + // never stops paseo.json from being edited or sent to the app. + teardownTimeoutMs: z.unknown().optional(), terminals: z.unknown().optional(), servicePorts: PaseoServicePortAllocationSchema.optional(), }) @@ -79,9 +82,20 @@ export const PaseoConfigRawSchema = z }) .passthrough(); +// Node timers can't wait longer than this; a longer delay fires at once. +const MAX_TIMER_DELAY_MS = 2_147_483_647; + export const WorktreeConfigSchema = PaseoWorktreeConfigRawSchema.extend({ setup: z.unknown().optional().transform(normalizeLifecycleCommands), teardown: z.unknown().optional().transform(normalizeLifecycleCommands), + // Its own catch, so an invalid limit doesn't drop the commands with the rest of the worktree. + teardownTimeoutMs: z + .number() + .int() + .positive() + .max(MAX_TIMER_DELAY_MS) + .optional() + .catch(undefined), }) .passthrough() .catch({ setup: [], teardown: [] }); diff --git a/packages/protocol/src/plugin-registry.test.ts b/packages/protocol/src/plugin-registry.test.ts index c923193a36..d7b06fd77e 100644 --- a/packages/protocol/src/plugin-registry.test.ts +++ b/packages/protocol/src/plugin-registry.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { + PluginListingIndexSchema, PluginRegistryIndexSchema, PublishedPluginDetailSchema, pluginMediaKind, @@ -81,3 +82,15 @@ describe("plugin listing translations", () => { expect(result.success).toBe(false); }); }); + +describe("plugin listings sent to apps", () => { + it("keep a listing whose artifact kind or index version the app does not know", () => { + const future = { ...LEGACY_PLUGIN, id: "acme/future", artifact: { kind: "oci", image: "x" } }; + const index = PluginListingIndexSchema.parse({ + ...LEGACY_INDEX, + schemaVersion: 2, + plugins: [LEGACY_PLUGIN, future], + }); + expect(index.plugins.map((plugin) => plugin.artifact.kind)).toEqual(["git", "oci"]); + }); +}); diff --git a/packages/protocol/src/plugin-registry.ts b/packages/protocol/src/plugin-registry.ts index 08bbf07f18..bd08057176 100644 --- a/packages/protocol/src/plugin-registry.ts +++ b/packages/protocol/src/plugin-registry.ts @@ -79,12 +79,43 @@ export const PluginRegistryIndexSchema = z.object({ featured: z.array(z.string()), generatedAt: z.string(), }); + +/** + * A listing as a host sends it to apps. The registry's schema is closed, so its artifact is open + * here: an app older than its host keeps listing plugins whose artifact kind it does not know, and + * installs them through the host by ID. + */ +const PluginListingArtifactSchema = z.object({ + kind: z.string(), + package: z.string().optional(), + version: z.string().optional(), + commit: z.string().optional(), +}); +export const PluginListingSchema = PublishedPluginSchema.extend({ + artifact: PluginListingArtifactSchema, +}); +export const PluginListingDetailSchema = PublishedPluginDetailSchema.extend({ + artifact: PluginListingArtifactSchema, +}); +export const PluginListingIndexSchema = PluginRegistryIndexSchema.extend({ + schemaVersion: z.number().int(), + plugins: z.array(PluginListingSchema), +}); +export type PluginListing = z.infer; +export type PluginListingDetail = z.infer; +export type PluginListingIndex = z.infer; + export type PluginRegistryIdentity = z.infer; export type PluginRegistries = z.infer; +export type PublishedPlugin = z.infer; +export type PublishedPluginDetail = z.infer; +export type PluginRegistryIndex = z.infer; + +export const DEFAULT_PLUGIN_REGISTRY_URL = "https://plugins.paseo.sh"; export function parsePluginRegistryReference( source: string, - defaultUrl = "https://plugins.paseo.sh", + defaultUrl = DEFAULT_PLUGIN_REGISTRY_URL, ): PluginRegistryIdentity | null { const segments = source.split("/"); if (segments.length === 2 && PluginRegistryIdSchema.safeParse(source).success) diff --git a/packages/protocol/src/search/text-match.test.ts b/packages/protocol/src/search/text-match.test.ts index 8adff41f62..7a153b9f73 100644 --- a/packages/protocol/src/search/text-match.test.ts +++ b/packages/protocol/src/search/text-match.test.ts @@ -7,6 +7,7 @@ import { scoreMatch, scorePathMatch, scoreTextFields, + textFieldsMatchClass, } from "./text-match.js"; function markUp(query: string, text: string, options?: Parameters[2]): string { @@ -248,6 +249,24 @@ describe("scoreTextFields", () => { }); }); +describe("textFieldsMatchClass", () => { + it("keeps positional tier differences inside one class", () => { + expect(textFieldsMatchClass("lo", ["fix-login-bug"])).toBe("word"); + expect(textFieldsMatchClass("lo", ["Login page fix"])).toBe("word"); + }); + + it("takes the loosest token's class", () => { + expect(textFieldsMatchClass("auth", ["oauth-refactor"])).toBe("inside-word"); + expect(textFieldsMatchClass("fix auth", ["fix", "oauth"])).toBe("inside-word"); + expect(textFieldsMatchClass("fix lgn", ["fix", "login"])).toBe("scattered"); + expect(textFieldsMatchClass("stipe", ["stripe"], { typoTolerant: true })).toBe("scattered"); + }); + + it("returns null when a token matches no field", () => { + expect(textFieldsMatchClass("fix zebra", ["fix"])).toBeNull(); + }); +}); + describe("compareMatchScores", () => { it("sorts by tier ascending", () => { expect(compareMatchScores({ tier: 1, offset: 10 }, { tier: 2, offset: 0 })).toBeLessThan(0); diff --git a/packages/protocol/src/search/text-match.ts b/packages/protocol/src/search/text-match.ts index 14bce34a41..abcd20371e 100644 --- a/packages/protocol/src/search/text-match.ts +++ b/packages/protocol/src/search/text-match.ts @@ -331,16 +331,14 @@ export interface TextFieldsOptions { subsequence?: boolean; } -export function scoreTextFields( +/** Each token's best score across the fields, or null when some token matches none. */ +function scoreTokens( query: string, fields: string[], - options: TextFieldsOptions = {}, -): MatchScore | null { - const tokens = tokenizeQuery(query); - if (tokens.length === 0) return { tier: TIER_EXACT, offset: 0, spread: 0 }; - - const aggregate: MatchScore = { tier: TIER_EXACT, offset: 0, spread: 0 }; - for (const token of tokens) { + options: TextFieldsOptions, +): { token: string; score: MatchScore }[] | null { + const scores: { token: string; score: MatchScore }[] = []; + for (const token of tokenizeQuery(query)) { const fuzzy = options.typoTolerant ? fuzzyPolicyForToken(token) : null; let best: MatchScore | null = null; for (const field of fields) { @@ -350,9 +348,59 @@ export function scoreTextFields( } } if (!best) return null; - aggregate.tier += best.tier; - aggregate.offset += best.offset; - aggregate.spread = (aggregate.spread ?? 0) + (best.spread ?? token.length); + scores.push({ token, score: best }); + } + return scores; +} + +export function scoreTextFields( + query: string, + fields: string[], + options: TextFieldsOptions = {}, +): MatchScore | null { + const scores = scoreTokens(query, fields, options); + if (!scores) return null; + const aggregate: MatchScore = { tier: TIER_EXACT, offset: 0, spread: 0 }; + for (const { token, score } of scores) { + aggregate.tier += score.tier; + aggregate.offset += score.offset; + aggregate.spread = (aggregate.spread ?? 0) + (score.spread ?? token.length); } return aggregate; } + +/** + * How closely a query matched, coarser than a tier: every token at a word boundary, some token + * inside a word, or some token only scattered across a word or misspelled. Positional tier + * differences ("lo" at a title's start versus a branch's middle word) stay within one class. + */ +export type MatchClass = "word" | "inside-word" | "scattered"; + +const MATCH_CLASS_ORDER: readonly MatchClass[] = ["word", "inside-word", "scattered"]; + +function matchClassOfTier(tier: number): MatchClass { + if (tier <= TIER_WORD_START) return "word"; + if (tier === TIER_SUBSTRING) return "inside-word"; + return "scattered"; +} + +/** Closer classes first. */ +export function compareMatchClasses(a: MatchClass, b: MatchClass): number { + return MATCH_CLASS_ORDER.indexOf(a) - MATCH_CLASS_ORDER.indexOf(b); +} + +/** The class of the query's loosest token, or null when some token matches no field. */ +export function textFieldsMatchClass( + query: string, + fields: string[], + options: TextFieldsOptions = {}, +): MatchClass | null { + const scores = scoreTokens(query, fields, options); + if (!scores) return null; + let loosest: MatchClass = "word"; + for (const { score } of scores) { + const tokenClass = matchClassOfTier(score.tier); + if (compareMatchClasses(tokenClass, loosest) > 0) loosest = tokenClass; + } + return loosest; +} diff --git a/packages/relay/package.json b/packages/relay/package.json index f1f8c3588c..df8c1de7df 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Paseo relay for bridging daemon and client connections", "license": "Apache-2.0", "files": [ diff --git a/packages/server/package.json b/packages/server/package.json index fa14593632..f732124051 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.16.0-beta.1", + "version": "0.16.1", "description": "Paseo backend server", "license": "Apache-2.0", "files": [ @@ -107,13 +107,13 @@ }, "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", - "@anthropic-ai/claude-agent-sdk": "0.3.246", + "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/highlight": "0.16.0-beta.1", - "@getpaseo/plugin": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/relay": "0.16.0-beta.1", + "@getpaseo/client": "0.16.1", + "@getpaseo/highlight": "0.16.1", + "@getpaseo/plugin": "0.16.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/relay": "0.16.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/server/src/server/agent/activity-curator.test.ts b/packages/server/src/server/agent/activity-curator.test.ts index 6a1d85bcf0..6b8e5d4845 100644 --- a/packages/server/src/server/agent/activity-curator.test.ts +++ b/packages/server/src/server/agent/activity-curator.test.ts @@ -3,6 +3,7 @@ import { buildAgentForkContextAttachment, curateAgentActivity } from "./activity import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; import { formatAgentMessage, projectAgentMessages } from "./agent-messages/index.js"; +import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; function toolCallItem(params: { callId: string; @@ -39,6 +40,29 @@ function row(seq: number, item: AgentTimelineItem): AgentTimelineRow { }; } +/** Rows as the daemon hands them to a fork: projected by the timeline store. */ +function storeTimeline(items: readonly AgentTimelineItem[]) { + const store = new InMemoryAgentTimelineStore(); + store.initialize("agent-1"); + for (const item of items) store.append("agent-1", item); + const { epoch, rows } = store.fetch("agent-1", { limit: 0 }); + return { epoch, rows }; +} + +function backgroundTaskItem(input: { status: "running" | "completed"; log: string }) { + return toolCallItem({ + callId: "background-task", + name: "Task", + status: input.status, + detail: { + type: "sub_agent", + subAgentType: "Explore", + description: "Audit the migrations", + log: input.log, + }, + }); +} + describe("curateAgentActivity", () => { it("keeps reasoning before the assistant text that followed it", () => { const timeline: AgentTimelineItem[] = [ @@ -414,44 +438,48 @@ second line'`, expect(result.attachment.text).toContain("[Assistant] Done."); }); - it("rejects a checkpoint whose projected tool state changed later", () => { - expect(() => - buildAgentForkContextAttachment({ - boundaryMessageId: "assistant-1", - rows: [ - row(1, { type: "user_message", text: "Run it", messageId: "user-1" }), - row( - 2, - toolCallItem({ - callId: "terminal-1", - name: "terminal", - status: "running", - detail: { - type: "plain_text", - label: "before boundary", - }, - }), - ), - row(3, { - type: "assistant_message", - text: "Partial result.", - messageId: "assistant-1", - }), - row( - 4, - toolCallItem({ - callId: "terminal-1", - name: "terminal", - status: "completed", - detail: { - type: "plain_text", - label: "after boundary", - }, - }), - ), - ], - }), - ).toThrow("Fork from a later completed response"); + it("forks at a response that background work outlives, by message id", () => { + const { rows } = storeTimeline([ + { type: "user_message", text: "Audit in the background", messageId: "user-1" }, + backgroundTaskItem({ status: "running", log: "scanning" }), + { type: "assistant_message", text: "Audit started.", messageId: "assistant-1" }, + backgroundTaskItem({ status: "completed", log: "FINAL REPORT after the response" }), + { type: "user_message", text: "Any findings?", messageId: "user-2" }, + ]); + expect(rows[1]).toMatchObject({ seqStart: 2, seqEnd: 4 }); + + const result = buildAgentForkContextAttachment({ boundaryMessageId: "assistant-1", rows }); + + expect(result.itemCount).toBe(3); + expect(result.boundaryMessageId).toBe("assistant-1"); + expect(result.attachment.text).toContain( + "[User] Audit in the background\n[Explore] Audit the migrations\n[Assistant] Audit started.\n", + ); + expect(result.attachment.text).not.toContain("FINAL REPORT"); + expect(result.attachment.text).not.toContain("Any findings?"); + }); + + it("forks at a response that background work outlives, by timeline cursor", () => { + const { epoch, rows } = storeTimeline([ + { type: "user_message", text: "Audit in the background", messageId: "user-1" }, + backgroundTaskItem({ status: "running", log: "scanning" }), + { type: "assistant_message", text: "Audit started." }, + backgroundTaskItem({ status: "completed", log: "FINAL REPORT after the response" }), + { type: "assistant_message", text: "The audit finished." }, + ]); + + const result = buildAgentForkContextAttachment({ + cursorBoundary: { timelineEpoch: epoch, cursor: { epoch, seq: 3 } }, + rows, + }); + + expect(result.boundaryCursor).toEqual({ epoch, seq: 3 }); + expect(result.itemCount).toBe(3); + expect(result.attachment.text).toContain( + "[User] Audit in the background\n[Explore] Audit the migrations\n[Assistant] Audit started.\n", + ); + expect(result.attachment.text).not.toContain("FINAL REPORT"); + expect(result.attachment.text).not.toContain("The audit finished."); }); it("forks from a checkpoint when a plugin card was updated after it", () => { diff --git a/packages/server/src/server/agent/activity-curator.ts b/packages/server/src/server/agent/activity-curator.ts index a0c537254a..f76c0ffbb4 100644 --- a/packages/server/src/server/agent/activity-curator.ts +++ b/packages/server/src/server/agent/activity-curator.ts @@ -1,4 +1,4 @@ -import type { AgentTimelineItem } from "./agent-sdk-types.js"; +import type { AgentTimelineItem, ToolCallTimelineItem } from "./agent-sdk-types.js"; import type { AgentMessage } from "@getpaseo/protocol/agent-message"; import type { AgentAttachment } from "@getpaseo/protocol/messages"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; @@ -13,7 +13,7 @@ const MAX_TOOL_SUMMARY_CHARS = 200; const MAX_FORK_CONTEXT_CHARS = 100_000; const MAX_FORK_METADATA_CHARS = 1_000; const FORK_HISTORY_OMITTED = "[Earlier chat history omitted]\n"; -// A fork copies only these kinds, so only they can make a checkpoint stale. +// A fork copies only these kinds. const FORK_CONTEXT_KINDS: readonly AgentTimelineItem["type"][] = [ "user_message", "assistant_message", @@ -275,25 +275,25 @@ function selectForkContextRows(input: { ); } const boundarySeq = projectedRows[boundaryIndex].seqEnd; - if ( - projectedRows.some( - (row) => - FORK_CONTEXT_KINDS.includes(row.item.type) && - row.seqStart <= boundarySeq && - row.seqEnd > boundarySeq, - ) - ) { - throw new Error( - "This checkpoint changed after it was created. Fork from a later completed response instead.", - ); - } - const projected = projectedRows.filter((row) => row.seqEnd <= boundarySeq); + // Only tool calls and plugin cards fold later updates into an earlier row, and a fork doesn't + // copy plugin cards. So the only row that spans the checkpoint and still reaches the fork is a + // tool call. + const items = projectedRows.flatMap((row) => { + if (row.seqEnd <= boundarySeq) return [row.item]; + if (row.seqStart > boundarySeq || row.item.type !== "tool_call") return []; + return [toolCallAtCheckpoint(row.item)]; + }); - return { - items: projected.map((entry) => entry.item), - boundaryCursor, - boundaryMessageId, - }; + return { items, boundaryCursor, boundaryMessageId }; +} + +/** + * A tool call that started before the checkpoint and changed after it, such as background work + * that outlives a reply. The projection keeps only its latest payload, so the fork copies it as + * still running. + */ +function toolCallAtCheckpoint(item: ToolCallTimelineItem): ToolCallTimelineItem { + return { ...item, status: "running", error: null }; } function trimContextMetadata(value: string | null | undefined): string | null { diff --git a/packages/server/src/server/agent/agent-archive.test.ts b/packages/server/src/server/agent/agent-archive.test.ts index c4dd34b7e2..21be7eef5f 100644 --- a/packages/server/src/server/agent/agent-archive.test.ts +++ b/packages/server/src/server/agent/agent-archive.test.ts @@ -14,18 +14,19 @@ const BASE_RECORD: StoredAgentRecord = { config: null, }; +const ARCHIVE = { + archivedAt: "2025-01-03T00:00:00.000Z", + updatedAt: "2025-01-03T00:00:00.000Z", +}; + test("archives a stored agent without changing terminal statuses", () => { const statuses: Array = ["idle", "error", "closed"]; for (const status of statuses) { - const archived = buildArchivedAgentRecord( - { ...BASE_RECORD, lastStatus: status }, - { archivedAt: "2025-01-03T00:00:00.000Z" }, - ); + const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE); expect(archived.lastStatus).toBe(status); expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z"); - expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt); } }); @@ -33,10 +34,7 @@ test("archives busy stored agents as idle", () => { const statuses: Array = ["initializing", "running"]; for (const status of statuses) { - const archived = buildArchivedAgentRecord( - { ...BASE_RECORD, lastStatus: status }, - { archivedAt: "2025-01-03T00:00:00.000Z" }, - ); + const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE); expect(archived.lastStatus).toBe("idle"); } @@ -50,7 +48,7 @@ test("clears persisted attention when archiving", () => { attentionReason: "finished", attentionTimestamp: "2025-01-02T12:00:00.000Z", }, - { archivedAt: "2025-01-03T00:00:00.000Z" }, + ARCHIVE, ); expect(archived).toMatchObject({ @@ -60,11 +58,19 @@ test("clears persisted attention when archiving", () => { }); }); -test("can stamp updatedAt to the archive timestamp", () => { - const archived = buildArchivedAgentRecord(BASE_RECORD, { - archivedAt: "2025-01-03T00:00:00.000Z", - updatedAt: "2025-01-03T00:00:00.000Z", - }); +test("moves updatedAt to the archive time", () => { + const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE); expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z"); }); + +test("keeps a later updatedAt when the archive time is earlier", () => { + // Putting an original archive back after a failed unarchive must not move updatedAt backwards. + const archived = buildArchivedAgentRecord( + { ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" }, + ARCHIVE, + ); + + expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z"); + expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z"); +}); diff --git a/packages/server/src/server/agent/agent-archive.ts b/packages/server/src/server/agent/agent-archive.ts index 7e35d98f89..a66b82c620 100644 --- a/packages/server/src/server/agent/agent-archive.ts +++ b/packages/server/src/server/agent/agent-archive.ts @@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js"; export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string }; interface BuildArchivedAgentRecordOptions { - archivedAt?: string; - updatedAt?: string; + archivedAt: string; + /** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */ + updatedAt: string; } export function buildArchivedAgentRecord( record: StoredAgentRecord, - options?: BuildArchivedAgentRecordOptions, + options: BuildArchivedAgentRecordOptions, ): ArchivedStoredAgentRecord { - const archivedAt = options?.archivedAt ?? new Date().toISOString(); return { ...record, - archivedAt, - updatedAt: options?.updatedAt ?? record.updatedAt, + archivedAt: options.archivedAt, + updatedAt: latestTimestamp(record.updatedAt, options.updatedAt), lastStatus: normalizeArchivedStatus(record.lastStatus), requiresAttention: false, attentionReason: null, @@ -23,6 +23,13 @@ export function buildArchivedAgentRecord( }; } +// Archiving is the agent's latest change. An earlier archive time (an original archive put back +// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is +// older than the one they hold. +function latestTimestamp(current: string, archiveTime: string): string { + return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current; +} + function normalizeArchivedStatus( status: StoredAgentRecord["lastStatus"], ): StoredAgentRecord["lastStatus"] { diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 1491aaa6e7..3a91addcdb 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -20,13 +20,18 @@ import { type ManagedAgent, } from "./agent-manager.js"; import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js"; +import { AgentTurnStartCanceledError } from "./agent-sdk-types.js"; +import { ForegroundPromptStart } from "./agent-run-state.js"; +import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js"; +import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js"; import type { ProviderOptions } from "@getpaseo/protocol/agent-types"; import { projectTimelineRows } from "./timeline-projection.js"; import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; -import { startAgentRun } from "./agent-prompt.js"; +import { createAgentMessageDelivery } from "./agent-messages/index.js"; +import { AgentTurnBusyError, sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js"; import { StaleProviderSessionError } from "./stale-provider-session-error.js"; import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js"; import type { StoredAgentRecord } from "./agent-storage.js"; @@ -673,6 +678,48 @@ async function startAndSteerThroughManager( return { manager, agentId: agent.id, workdir }; } +test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-")); + const harness = new V2Harness(); + harness.info.location.directory = workdir; + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new OpenCodeV2AgentClient({ logger, runtime: harness.runtime }); + const manager = new AgentManager({ + clients: { opencode: client }, + registry: storage, + logger, + appendSystemPrompt: "Daemon instruction", + pluginLifecycle: { + emit: () => {}, + before: async (name, request) => + name === "agent.open.before" + ? { ...request, appendSystemPrompt: ["Plugin instruction"] } + : request, + }, + }); + const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + expect(harness.instructions.get("paseo")).toBe("Daemon instruction\n\nPlugin instruction"); + await manager.flush(); + const record = await storage.get(agent.id); + expect(record?.persistence?.metadata).not.toHaveProperty("pluginAppendSystemPrompt"); + expect(record?.persistence?.metadata).not.toHaveProperty("daemonAppendSystemPrompt"); + const live = manager.getAgent(agent.id)!; + expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty( + "pluginAppendSystemPrompt", + ); + expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty( + "daemonAppendSystemPrompt", + ); + } finally { + await manager.closeAgent(agent.id); + await client.shutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("stops an OpenCode execution already active when its conversation is reopened", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-opencode-resume-")); onTestFinished(() => rmSync(workdir, { recursive: true, force: true })); @@ -1167,7 +1214,7 @@ test("starts its own turn when the previous turn fails to start under a steer se ); startHeld.resolve(); - await expect(second).resolves.toEqual({ disposition: "turn_started" }); + await expect(second).resolves.toMatchObject({ disposition: "turn_started" }); await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"])); expect(session.interruptCount).toBe(0); } finally { @@ -1529,6 +1576,110 @@ test("does not replace a newer foreground turn after unavailable steer fallback } }); +test("concurrent interrupting sends each start their own turn in order", async () => { + const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); + const { manager, agentId, workdir } = await startAndSteerThroughManager(session, "interrupt"); + try { + const prompts = ["first interrupt", "second interrupt", "third interrupt"]; + await Promise.all( + prompts.map((prompt) => + startAgentRun(manager, agentId, prompt, logger, { + replaceRunning: true, + activeTurnBehavior: "interrupt", + runOptions: { clientMessageId: prompt }, + }), + ), + ); + await manager.waitForAgentRunStart(agentId); + expect(session.startPrompts.slice(-3)).toEqual(prompts); + expect(manager.getAgent(agentId)?.activeForegroundTurnId).toBe( + `active-turn-${session.startCount}`, + ); + } finally { + await manager.closeAgent(agentId); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("Stop can cancel startup while an interrupting send waits behind it", async () => { + const entered = deferred(); + const release = deferred(); + class SlowStartSession extends SteeringTestSession { + starting = false; + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt === "slow startup") { + this.starting = true; + entered.resolve(); + await release.promise; + this.starting = false; + } + return super.startTurn(prompt); + } + override async interrupt(): Promise { + if (this.starting) release.resolve(); + await super.interrupt(); + } + } + const session = new SlowStartSession({ provider: "codex", cwd: process.cwd() }); + const { manager, agentId, workdir } = await startAndSteerThroughManager(session, "interrupt"); + try { + await startAgentRun(manager, agentId, "slow startup", logger, { replaceRunning: true }); + await entered.promise; + const replacement = startAgentRun(manager, agentId, "queued replacement", logger, { + replaceRunning: true, + }); + void replacement.catch(() => undefined); + const stop = manager.cancelAgentRun(agentId); + await vi.waitFor(() => expect(session.interruptCount).toBe(3), { timeout: 1000 }); + await stop; + await replacement; + await manager.waitForAgentRunStart(agentId); + expect(session.startPrompts.slice(-2)).toEqual(["slow startup", "queued replacement"]); + } finally { + release.resolve(); + await manager.closeAgent(agentId); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("an interrupting send replaces a turn whose start never finishes", async () => { + class StalledStartSession extends SteeringTestSession { + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt === "stalled start") { + this.startPrompts.push(prompt); + return new Promise(() => {}); + } + return super.startTurn(prompt); + } + } + const session = new StalledStartSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stalled-start-")); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ + clients: { codex: client }, + logger, + rescueTimeouts: { interruptSessionMs: 10 }, + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + await startAgentRun(manager, agent.id, "stalled start", logger, { replaceRunning: true }); + await startAgentRun(manager, agent.id, "recovery", logger, { + replaceRunning: true, + activeTurnBehavior: "interrupt", + }); + expect(session.startPrompts).toEqual(["stalled start", "recovery"]); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("steers a tracked autonomous turn without creating a replacement run", async () => { const session = new SteeringTestSession({ provider: "claude", cwd: process.cwd() }); const workdir = mkdtempSync(join(tmpdir(), "agent-manager-autonomous-steer-")); @@ -2916,6 +3067,72 @@ test("opening during reload waits for the replacement", async () => { } }); +test("clearing attention during reload waits for the replacement", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reload-clear-attention-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new HeldReloadCloseClient(); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + try { + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + await manager.markAgentUnread(created.id); + const reloading = manager.reloadAgentSession(created.id); + await client.waitForCloseToStart(); + let cleared = false; + const clearing = manager.clearAgentAttention(created.id).then(() => { + cleared = true; + return true; + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(cleared).toBe(false); + client.finishClosing(); + await Promise.all([reloading, clearing]); + expect(manager.getAgent(created.id)?.attention.requiresAttention).toBe(false); + expect((await storage.get(created.id))?.requiresAttention).toBe(false); + await manager.closeAgent(created.id); + } finally { + client.finishClosing(); + await storage.flush(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("resuming after a queued attention clear keeps the agent read", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-resume-clear-attention-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + try { + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const handle = manager.getAgent(created.id)!.persistence!; + await manager.closeAgent(created.id); + await manager.markAgentUnread(created.id); + // A loader read the record before the clear landed, then queued the resume behind it. + const unreadAttention = { + requiresAttention: true, + attentionReason: "finished", + attentionTimestamp: new Date(), + } as const; + const clearing = manager.clearAgentAttention(created.id); + const resumed = await manager.resumeAgentFromPersistence(handle, { cwd: workdir }, created.id, { + attention: unreadAttention, + }); + await clearing; + expect(resumed.attention.requiresAttention).toBe(false); + expect((await storage.get(created.id))?.requiresAttention).toBe(false); + await manager.closeAgent(created.id); + } finally { + await storage.flush(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("closing during reload leaves the replacement closed", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reload-close-race-")); const storage = new AgentStorage(join(workdir, "agents"), logger); @@ -3256,6 +3473,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti } }); +test.each([ + { binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" }, + { binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" }, +] as const)( + "cancelAgentRun settles a $binding run bound to an already finalized turn", + async ({ binding, agentId }) => { + const fixture = await createControlledInterruptFixture({ + name: `interrupt-finalized-${binding}`, + agentId, + turnId: "finalized-turn", + interrupt: async () => {}, + }); + + try { + await fixture.startForegroundRun(); + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "settled", + }); + + if (binding === "foreground") { + await fixture.startForegroundRun(); + } else { + const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running"); + fixture.session.pushEvent({ + type: "turn_started", + provider: "codex", + turnId: "finalized-turn", + }); + await running; + } + + const cancellation = await Promise.race([ + fixture.manager.cancelAgentRun(fixture.agentId), + new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)), + ]); + expect(cancellation).toEqual({ status: "settled" }); + expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({ + lifecycle: "idle", + activeForegroundTurnId: null, + }); + + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "not_running", + }); + await fixture.startForegroundRun(); + expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({ + lifecycle: "running", + activeForegroundTurnId: "finalized-turn", + }); + } finally { + await fixture.cleanup(); + } + }, + 10_000, +); + +test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => { + const fixture = await createControlledInterruptFixture({ + name: "interrupt-finalized-provider-terminal", + agentId: "00000000-0000-4000-8000-000000000309", + turnId: "finalized-provider-terminal-turn", + interrupt: async () => {}, + }); + + try { + await fixture.startForegroundRun(); + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "settled", + }); + + await fixture.startForegroundRun(); + const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle"); + fixture.session.pushEvent({ + type: "turn_completed", + provider: "codex", + turnId: "finalized-provider-terminal-turn", + }); + const settlement = await Promise.race([ + idle.then(() => "idle" as const), + new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)), + ]); + + expect(settlement).toBe("idle"); + expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({ + lifecycle: "idle", + activeForegroundTurnId: null, + }); + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "not_running", + }); + } finally { + await fixture.cleanup(); + } +}, 10_000); + test("listProviderAvailability uses registered client keys, including custom providers", async () => { const customClient: AgentClient = { provider: "zai", @@ -6281,6 +6593,114 @@ test("archiveSnapshot dispatches archived state for stored-only agents", async ( expect(last.lifecycle).toBe("closed"); }); +test("archiveSnapshot moves a stored-only agent's updatedAt to its archive time, as a live archive does", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-updated-at-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + + const created = await manager.createAgent( + { provider: "codex", cwd: workdir, title: "Stored archive updatedAt" }, + undefined, + { workspaceId: undefined }, + ); + await manager.closeAgent(created.id); + const before = await storage.get(created.id); + expect(before?.updatedAt).toEqual(expect.any(String)); + + // Later than anything the agent did: lists sorted by updated_at put it first, as they do + // for an agent archived while loaded. + const archivedAt = new Date(Date.parse(before!.updatedAt) + 60_000).toISOString(); + const archived = await manager.archiveSnapshot(created.id, archivedAt); + + expect(archived.updatedAt).toBe(archivedAt); + expect((await storage.get(created.id))?.updatedAt).toBe(archivedAt); +}); + +test("archiveSnapshot restoring an earlier archive time keeps updatedAt at the unarchive", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + + const created = await manager.createAgent( + { provider: "codex", cwd: workdir, title: "Restore archive updatedAt" }, + undefined, + { workspaceId: undefined }, + ); + await manager.closeAgent(created.id); + const originalArchivedAt = (await manager.archiveSnapshot(created.id, new Date().toISOString())) + .archivedAt!; + await new Promise((resolve) => setTimeout(resolve, 5)); + await manager.unarchiveSnapshot(created.id); + const unarchivedAt = (await storage.get(created.id))!.updatedAt; + + const events: ManagedAgent[] = []; + manager.subscribe( + (event) => { + if (event.type === "agent_state" && event.agent.id === created.id) { + events.push(event.agent); + } + }, + { agentId: created.id, replayState: false }, + ); + + // A send that could not load the agent puts its original archive back. + await manager.archiveSnapshot(created.id, originalArchivedAt); + + // Clients keep the newer of two updates, so an older updatedAt would leave them showing it active. + const stored = await storage.get(created.id); + expect(stored?.archivedAt).toBe(originalArchivedAt); + expect(stored?.updatedAt).toBe(unarchivedAt); + expect(events.at(-1)?.updatedAt.toISOString()).toBe(unarchivedAt); +}); + +test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps updatedAt at the unarchive", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-loaded-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + + const created = await manager.createAgent( + { provider: "codex", cwd: workdir, title: "Restore loaded archive updatedAt" }, + undefined, + { workspaceId: undefined }, + ); + const { archivedAt: originalArchivedAt } = await manager.archiveAgent(created.id); + await new Promise((resolve) => setTimeout(resolve, 5)); + await manager.unarchiveSnapshot(created.id); + const unarchivedAt = Date.parse((await storage.get(created.id))!.updatedAt); + // The send resumed the agent before a later loading step failed, so it is still loaded. + await ensureAgentLoaded(created.id, { agentManager: manager, agentStorage: storage, logger }); + expect(manager.getAgent(created.id)).not.toBeNull(); + + const events: ManagedAgent[] = []; + manager.subscribe( + (event) => { + if (event.type === "agent_state" && event.agent.id === created.id) { + events.push(event.agent); + } + }, + { agentId: created.id, replayState: false }, + ); + + await manager.archiveSnapshot(created.id, originalArchivedAt); + + const stored = await storage.get(created.id); + expect(stored?.archivedAt).toBe(originalArchivedAt); + expect(Date.parse(stored!.updatedAt)).toBeGreaterThanOrEqual(unarchivedAt); + expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt); +}); + test("markAgentUnread restores error attention on a read errored agent", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-")); const storage = new AgentStorage(join(workdir, "agents"), logger); @@ -8112,6 +8532,8 @@ test("failed replacement cancellation preserves an autonomous running state", as activeForegroundTurnId: null, }); } finally { + await manager.flush(); + await storage.flush(); rmSync(workdir, { recursive: true, force: true }); } }); @@ -9426,6 +9848,464 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist ); }); +test("canceling a pending Codex start settles as canceled without accepting its prompt", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-cold-cancel-")); + const threadLoaded = deferred<{ data: string[] }>(); + const appServer = createFakeCodexAppServer({ "thread/loaded/list": () => threadLoaded.promise }); + class ColdStartClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new CodexAppServerAgentSession(config, null, logger, async () => appServer.child); + } + } + const manager = new AgentManager({ + clients: { codex: new ColdStartClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + }); + const events: AgentStreamEvent[] = []; + manager.subscribe((event) => { + if (event.type === "agent_stream") events.push(event.event); + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + // Drain the stream: a fresh Codex agent has no session handle for runAgent before its first turn. + const senderStart = new ForegroundPromptStart(agent.id); + const firstRun = drainAsyncGenerator( + manager.streamAgent( + agent.id, + "Canceled prompt", + { clientMessageId: "canceled-prompt" }, + senderStart, + ), + ); + void firstRun.catch(() => undefined); + await appServer.waitForRequest("thread/loaded/list"); + const senderRejection = expect(senderStart.started).rejects.toThrow( + "its prompt was not delivered", + ); + const cancel = manager.cancelAgentRun(agent.id); + await new Promise((resolve) => setTimeout(resolve, 0)); + threadLoaded.resolve({ data: ["thread-1"] }); + await expect(cancel).resolves.toEqual({ status: "settled" }); + await expect(firstRun).resolves.toBeUndefined(); + await senderRejection; + expect(manager.getAgent(agent.id)).toMatchObject({ lifecycle: "idle", lastError: undefined }); + expect(manager.hasInFlightRun(agent.id)).toBe(false); + expect(events.map((event) => event.type)).toEqual(["timeline", "turn_canceled"]); + // The canceled attempt stays in history like a rejected one, without being delivered. + expect(manager.getTimeline(agent.id)).toEqual([ + { + type: "user_message", + text: "Canceled prompt", + clientMessageId: "canceled-prompt", + messageId: "canceled-prompt", + }, + ]); + expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false); + + const nextRun = manager.runAgent(agent.id, "Next prompt", { clientMessageId: "next-prompt" }); + await appServer.waitForRequest("turn/start"); + appServer.startsTurn({ threadId: "thread-1", turnId: "next-turn" }); + appServer.completeTurn(); + await expect(nextRun).resolves.toMatchObject({ canceled: false }); + appServer.assertNoErrors(); + } finally { + threadLoaded.resolve({ data: ["thread-1"] }); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("stopping a Codex replacement of a stalled start clears replacement activity", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replacement-cancel-")); + const firstLoaded = deferred<{ data: string[] }>(); + const firstInterruptRequested = deferred(); + const replacementLoaded = deferred<{ data: string[] }>(); + const replacementEntered = deferred(); + let loadCount = 0; + const appServer = createFakeCodexAppServer({ + "thread/loaded/list": () => { + loadCount += 1; + if (loadCount === 1) return firstLoaded.promise; + replacementEntered.resolve(); + return replacementLoaded.promise; + }, + }); + class ColdStartSession extends CodexAppServerAgentSession { + override async interrupt(): Promise { + const interruption = super.interrupt(); + firstInterruptRequested.resolve(); + await interruption; + } + } + class ColdStartClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new ColdStartSession(config, null, logger, async () => appServer.child); + } + } + const manager = new AgentManager({ + clients: { codex: new ColdStartClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + rescueTimeouts: { interruptSessionMs: 10 }, + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const firstRun = drainAsyncGenerator(manager.streamAgent(agent.id, "Original prompt")); + await appServer.waitForRequest("thread/loaded/list"); + const replacement = manager.replaceAgentRun(agent.id, "Replacement prompt"); + await firstInterruptRequested.promise; + firstLoaded.resolve({ data: ["thread-1"] }); + const replacementStream = await replacement; + await expect(firstRun).resolves.toBeUndefined(); + expect(manager.getAgent(agent.id)?.lifecycle).toBe("running"); + const replacementEvent = replacementStream.next(); + await replacementEntered.promise; + const cancel = manager.cancelAgentRun(agent.id); + await new Promise((resolve) => setTimeout(resolve, 0)); + replacementLoaded.resolve({ data: ["thread-1"] }); + await expect(cancel).resolves.toEqual({ status: "settled" }); + await expect(replacementEvent).resolves.toMatchObject({ + value: { type: "turn_canceled" }, + }); + await expect(replacementStream.next()).resolves.toMatchObject({ done: true }); + expect(manager.hasInFlightRun(agent.id)).toBe(false); + expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle"); + expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false); + appServer.assertNoErrors(); + } finally { + firstLoaded.resolve({ data: ["thread-1"] }); + replacementLoaded.resolve({ data: ["thread-1"] }); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a stalled Codex start canceled by its replacement rejects its sender's start wait", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replaced-start-wait-")); + const firstLoaded = deferred<{ data: string[] }>(); + const firstInterruptRequested = deferred(); + let loadCount = 0; + const appServer = createFakeCodexAppServer({ + "thread/loaded/list": () => { + loadCount += 1; + return loadCount === 1 ? firstLoaded.promise : { data: ["thread-1"] }; + }, + }); + class ColdStartSession extends CodexAppServerAgentSession { + override async interrupt(): Promise { + const interruption = super.interrupt(); + firstInterruptRequested.resolve(); + await interruption; + } + } + class ColdStartClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new ColdStartSession(config, null, logger, async () => appServer.child); + } + } + const manager = new AgentManager({ + clients: { codex: new ColdStartClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + rescueTimeouts: { interruptSessionMs: 10 }, + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const firstStart = new ForegroundPromptStart(agent.id); + const secondStart = new ForegroundPromptStart(agent.id); + const firstRun = drainAsyncGenerator( + manager.streamAgent(agent.id, "First prompt", undefined, firstStart), + ); + await appServer.waitForRequest("thread/loaded/list"); + const firstWait = firstStart.started; + const replacement = manager.replaceAgentRun(agent.id, "Second prompt", undefined, secondStart); + await firstInterruptRequested.promise; + firstLoaded.resolve({ data: ["thread-1"] }); + const replacementStream = await replacement; + await expect(firstRun).resolves.toBeUndefined(); + + const secondWait = secondStart.started; + const replacementDrained = drainAsyncGenerator(replacementStream); + await appServer.waitForRequest("turn/start"); + appServer.startsTurn({ threadId: "thread-1", turnId: "second-turn" }); + await expect(secondWait).resolves.toBeUndefined(); + await expect(firstWait).rejects.toThrow("its prompt was not delivered"); + appServer.completeTurn(); + await replacementDrained; + expect(appServer.requests().filter((request) => request.method === "turn/start")).toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ + input: [expect.objectContaining({ text: "Second prompt" })], + }), + }), + ]); + appServer.assertNoErrors(); + } finally { + firstLoaded.resolve({ data: ["thread-1"] }); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a sender's start wait follows its prompt across a stale-session retry", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-wait-")); + const releaseStart = deferred(); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw new StaleProviderSessionError("stale-bridge"); + } + } + class StaleStartClient extends ResumeTrackingTestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + } + const client = new StaleStartClient(); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + const startedTurns: AgentStreamEvent[] = []; + manager.subscribe((event) => { + if (event.type === "agent_stream" && event.event.type === "turn_started") { + startedTurns.push(event.event); + } + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderWait = dispatchStarted( + await startAgentRun(manager, agent.id, "Retry this prompt", logger, { + runOptions: { clientMessageId: "stale-start-wait" }, + }), + ); + releaseStart.resolve(); + await client.waitForRetryStart(); + await manager.waitForAgentEvent(agent.id); + expect(client.resumeOverrides).toHaveLength(1); + expect(startedTurns).toHaveLength(1); + expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([ + expect.objectContaining({ text: "Retry this prompt", clientMessageId: "stale-start-wait" }), + ]); + await expect(senderWait).resolves.toBeUndefined(); + } finally { + releaseStart.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a sender's start wait follows its prompt when the session is stale before the wait begins", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-immediate-stale-start-")); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + throw new StaleProviderSessionError("stale-bridge"); + } + } + class StaleStartClient extends ResumeTrackingTestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + } + const client = new StaleStartClient(); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const dispatch = await startAgentRun(manager, agent.id, "Retry this prompt", logger, { + runOptions: { clientMessageId: "immediate-stale-start" }, + }); + // The stale start has failed and been cleared before the sender begins waiting. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(manager.hasInFlightRun(agent.id)).toBe(false); + await expect(dispatchStarted(dispatch)).resolves.toBeUndefined(); + await client.waitForRetryStart(); + expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([ + expect.objectContaining({ + text: "Retry this prompt", + clientMessageId: "immediate-stale-start", + }), + ]); + } finally { + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test.each(["reload", "retry", "stale retry"])( + "a sender's start wait rejects when its stale-session %s fails", + async (failure) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-failure-")); + const releaseStart = deferred(); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw new StaleProviderSessionError("stale-bridge"); + } + } + class FailedRetrySession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + if (failure === "stale retry") throw new StaleProviderSessionError("retry-bridge"); + throw new Error("retry failed"); + } + } + class FailedRetryClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + override async resumeSession(): Promise { + if (failure === "reload") throw new Error("reload failed"); + return new FailedRetrySession({ provider: "codex", cwd: workdir }); + } + } + const manager = new AgentManager({ clients: { codex: new FailedRetryClient() }, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderWait = dispatchStarted( + await startAgentRun(manager, agent.id, "Retry this prompt", logger), + ); + const rejection = expect(senderWait).rejects.toThrow( + failure === "retry" ? "retry failed" : "is stale after its plugin reloaded", + ); + releaseStart.resolve(); + await rejection; + } finally { + releaseStart.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test("a sender's start wait rejects when Stop cancels its pending stale-session retry", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-retry-stop-")); + const releaseStart = deferred(); + const retryEntered = deferred(); + const retryCanceled = deferred(); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw new StaleProviderSessionError("stale-bridge"); + } + } + class CanceledRetrySession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + retryEntered.resolve(); + await retryCanceled.promise; + throw new AgentTurnStartCanceledError(); + } + override async interrupt(): Promise { + retryCanceled.resolve(); + } + } + class RetryClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + override async resumeSession(): Promise { + return new CanceledRetrySession({ provider: "codex", cwd: workdir }); + } + } + const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderWait = dispatchStarted( + await startAgentRun(manager, agent.id, "Retry this prompt", logger), + ); + const rejection = expect(senderWait).rejects.toThrow("its prompt was not delivered"); + releaseStart.resolve(); + await retryEntered.promise; + await expect(manager.cancelAgentRun(agent.id)).resolves.toEqual({ status: "settled" }); + await rejection; + expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle"); + expect(manager.getTimeline(agent.id)).toEqual([]); + } finally { + releaseStart.resolve(); + retryCanceled.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a sender's start wait never adopts an unlinked run after a stale start", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-unlinked-start-")); + const releaseStart = deferred(); + const staleError = new StaleProviderSessionError("stale-bridge"); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw staleError; + } + } + class RetryClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + } + const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderStart = new ForegroundPromptStart(agent.id); + const firstRun = drainAsyncGenerator( + manager.streamAgent(agent.id, "First prompt", undefined, senderStart), + ); + const firstFailure = expect(firstRun).rejects.toBe(staleError); + const rejection = expect(senderStart.started).rejects.toThrow(staleError.message); + releaseStart.resolve(); + await firstFailure; + try { + await manager.reloadAgentSession(agent.id); + const otherStart = new ForegroundPromptStart(agent.id); + const otherRun = drainAsyncGenerator( + manager.streamAgent(agent.id, "Another sender", undefined, otherStart), + ); + await expect(otherStart.started).resolves.toBeUndefined(); + await otherRun; + } finally { + senderStart.end(); + } + await rejection; + expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual( + [], + ); + } finally { + releaseStart.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("acknowledged cancellation settles a pending run before it has a turn id", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-cancel-pending-start-")); const startEntered = deferred(); @@ -12173,11 +13053,18 @@ test("authoritative timeline records a daemon-handled submitted prompt before it test("tryRunOutOfBand gives providers the command another agent sent, not its envelope", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-agent-out-of-band-")); const seenPrompts: AgentPromptInput[] = []; + const acceptanceOrder: string[] = []; class SlashCommandSession extends TestAgentSession { override tryHandleOutOfBand(prompt: AgentPromptInput) { seenPrompts.push(prompt); - return prompt === "/handled" ? { run: async () => {} } : null; + return prompt === "/handled" + ? { + run: async () => { + acceptanceOrder.push("run"); + }, + } + : null; } } const client = new (class extends TestAgentClient { @@ -12192,12 +13079,22 @@ test("tryRunOutOfBand gives providers the command another agent sent, not its en try { const fromAgent = prepareAgentMessage("/handled", { kind: "agent-message", agentId: "sender" }); - expect(await manager.tryRunOutOfBand(agent.id, fromAgent.prompt)).toBe(true); + expect( + await manager.tryRunOutOfBand(agent.id, fromAgent.prompt, undefined, () => { + acceptanceOrder.push("accepted"); + }), + ).toBe(true); + await vi.waitFor(() => expect(acceptanceOrder).toEqual(["accepted", "run"])); expect(seenPrompts).toEqual(["/handled"]); // A human who pastes an envelope gets it quoted, and it stays a plain prompt. const pasted = prepareAgentMessage(String(fromAgent.prompt)); - expect(await manager.tryRunOutOfBand(agent.id, pasted.prompt)).toBe(false); + expect( + await manager.tryRunOutOfBand(agent.id, pasted.prompt, undefined, () => { + acceptanceOrder.push("unexpected"); + }), + ).toBe(false); + expect(acceptanceOrder).toEqual(["accepted", "run"]); expect(seenPrompts.at(-1)).toBe(pasted.prompt); } finally { await manager.closeAgent(agent.id); @@ -13230,7 +14127,6 @@ test.each([ }, turnId: "hook-turn", outcome, - timeline: [], }, }, ]); @@ -13316,6 +14212,78 @@ test.each(["live", "history", "accepted"] as const)( }, ); +test("the last assistant message is the newest turn's reply, not joined to the previous turn's", async () => { + const session = new TestAgentSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-last-reply-")); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ clients: { codex: client }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const reply = (turnId: string, messageId: string, text: string) => + session.pushEvent({ + type: "timeline", + provider: "codex", + turnId, + item: { type: "assistant_message", messageId, text }, + }); + try { + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn-1" }); + reply("turn-1", "message-1", "Earlier status, "); + reply("turn-1", "message-1", "streamed in two chunks."); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "turn-1" }); + await vi.waitFor(async () => + expect(await manager.getLastAssistantMessage(agent.id)).toBe( + "Earlier status, streamed in two chunks.", + ), + ); + + // A turn the provider starts on its own, such as a background task waking the agent, + // has no user message between its reply and the previous turn's. + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn-2" }); + reply("turn-2", "message-2", "New status."); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "turn-2" }); + await vi.waitFor(() => + expect(manager.getTimeline(agent.id).at(-1)).toMatchObject({ messageId: "message-2" }), + ); + expect(await manager.getLastAssistantMessage(agent.id)).toBe("New status."); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("the last assistant message read from rebuilt history is the newest reply, not joined to the one before it", async () => { + // Rows replayed from provider history have no turn id. A reply the agent starts on its own, + // such as Claude waking after a background subagent, follows the previous reply with no user + // message between them; only their message ids tell them apart. + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-last-reply-")); + const codex = fakeCodexEmitting({ + historyItems: [ + { type: "user_message", text: "Start a background task.", messageId: "user-1" }, + { type: "assistant_message", text: "Started it, ", messageId: "message-1" }, + { type: "assistant_message", text: "I will report back.", messageId: "message-1" }, + { type: "assistant_message", text: "The task finished.", messageId: "message-2" }, + ], + }); + const manager = new AgentManager({ clients: { codex }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + await manager.hydrateTimelineFromProvider(agent.id, { force: true }); + + expect(await manager.getLastAssistantMessage(agent.id)).toBe("The task finished."); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("reads the last durable assistant response without loading a stored-only child", async () => { const store = new RecordingTimelineStore(); await store.appendCommitted("stored-child", { @@ -13354,7 +14322,20 @@ function idleCleanupHarness() { const storage = new AgentStorage(join(workdir, "agents"), logger); const commands: AgentPromptInput[] = []; const prompts: AgentPromptInput[] = []; + const sessions: AgentSession[] = []; + const probes: Array<(() => Promise) | undefined> = []; + const closeEntered = deferred(); + let closeGate: Promise | undefined; + let closes = 0; const recordPrompts = (session: AgentSession) => { + const index = sessions.length; + session.canStopRuntime = async () => probes[index]?.() ?? false; + session.close = async () => { + closes++; + closeEntered.resolve(); + await closeGate; + }; + sessions.push(session); session.tryHandleOutOfBand = (prompt) => prompt === "/maintenance" ? { @@ -13370,11 +14351,6 @@ function idleCleanupHarness() { }; return session; }; - const sessions: AgentSession[] = []; - const probes: Array<(() => Promise) | undefined> = []; - const closeEntered = deferred(); - let closeGate: Promise | undefined; - let closes = 0; const client = new (class extends TestAgentClient { override async resumeSession( handle: AgentPersistenceHandle, @@ -13385,15 +14361,7 @@ function idleCleanupHarness() { return recordPrompts(session); } override async createSession(config: AgentSessionConfig): Promise { - const index = sessions.length; const session: AgentSession = await super.createSession(config); - session.canStopRuntime = async () => probes[index]?.() ?? false; - session.close = async () => { - closes++; - closeEntered.resolve(); - await closeGate; - }; - sessions.push(session); return recordPrompts(session); } })(); @@ -14255,6 +15223,115 @@ test("stops only a currently owned public background item with its current token await manager.closeAgent(agent.id); }); +test("lists and stops heartbeat background work across provider session closure", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-background-heartbeat-")); + const stopped: string[] = []; + let activeSession: TestAgentSession | undefined; + class StoppableSession extends TestAgentSession { + async stopBackgroundWork(id: string) { + stopped.push(id); + } + } + class BackgroundWorkClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + activeSession = new StoppableSession(config); + return activeSession; + } + } + const manager = new AgentManager({ + clients: { codex: new BackgroundWorkClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const events: AgentManagerEvent[] = []; + manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false }); + const heartbeat = { + agentId: agent.id, + scheduleId: "schedule-1", + name: "Check build", + createdAt: "2026-10-06T10:00:00.000Z", + stop: async () => { + stopped.push("schedule-1"); + manager.removeHeartbeatBackgroundWork(agent.id, "schedule-1"); + }, + }; + try { + manager.setHeartbeatBackgroundWork(heartbeat); + const [item] = manager.listAgentBackgroundWork(agent.id); + expect(item).toMatchObject({ + kind: "heartbeat", + description: "Check build", + startedAt: heartbeat.createdAt, + canStop: true, + stopToken: expect.any(String), + }); + manager.setHeartbeatBackgroundWork({ ...heartbeat, name: "Check CI" }); + const renamed = { ...item, description: "Check CI" }; + + activeSession?.pushEvent({ + type: "background_work", + provider: "codex", + items: [{ id: item.id, kind: "shell", description: null, canStop: true }], + }); + await vi.waitFor(() => + expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 2 }), + ); + const providerItem = manager + .listAgentBackgroundWork(agent.id) + .find((row) => row.kind === "shell")!; + expect(providerItem.id).not.toBe(item.id); + expect(events).toContainEqual({ + type: "background_work", + agentId: agent.id, + items: expect.arrayContaining([providerItem, renamed]), + }); + await manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: providerItem.id, + stopToken: providerItem.stopToken!, + }); + expect(stopped).toEqual([item.id]); + + const eventsBeforeClose = events.length; + await manager.closeAgent(agent.id); + expect(manager.getAgent(agent.id)).toBeNull(); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([renamed]); + expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 1 }); + expect(events.slice(eventsBeforeClose)).toContainEqual({ + type: "background_work", + agentId: agent.id, + items: [renamed], + }); + + const stop = { agentId: agent.id, itemId: item.id, stopToken: item.stopToken! }; + await expect(manager.stopAgentBackgroundWork(stop)).rejects.toThrow(); + await expect( + manager.stopAgentBackgroundWork({ + ...stop, + stopToken: providerItem.stopToken!, + canManageAutomation: true, + }), + ).rejects.toThrow(); + expect(stopped).toEqual([item.id]); + await manager.stopAgentBackgroundWork({ ...stop, canManageAutomation: true }); + expect(stopped).toEqual([item.id, "schedule-1"]); + expect(manager.getAgentBackgroundWorkSummary(agent.id)).toBeUndefined(); + expect(events.at(-1)).toEqual({ type: "background_work", agentId: agent.id, items: [] }); + + manager.setHeartbeatBackgroundWork(heartbeat); + await expect( + manager.stopAgentBackgroundWork({ ...stop, canManageAutomation: true }), + ).rejects.toThrow(); + expect(manager.listAgentBackgroundWork(agent.id)[0].stopToken).not.toBe(item.stopToken); + } finally { + if (manager.getAgent(agent.id)) await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("turns keep distinct identities across an idle runtime collection and resume", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-turn-identity-")); const storage = new AgentStorage(join(workdir, "agents"), logger); @@ -14303,16 +15380,368 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad labels: { [PARENT_AGENT_ID_LABEL]: parent.id }, workspaceId: undefined, }); - const stamp = "2026-11-09T00:00:00.000Z"; + // Archive stamps are taken when the archive happens, so they follow the agents' activity. + const stamp = new Date(Date.now() + 60_000).toISOString(); + const laterStamp = new Date(Date.now() + 120_000).toISOString(); await manager.archiveAgent(parent.id, stamp); expect((await storage.get(parent.id))?.archivedAt).toBe(stamp); expect((await storage.get(child.id))?.archivedAt).toBe(stamp); await ensureAgentLoaded(parent.id, { agentManager: manager, agentStorage: storage, logger }); - await manager.archiveAgent(parent.id, "2026-11-09T01:00:00.000Z"); + await manager.archiveAgent(parent.id, laterStamp); expect((await storage.get(parent.id))?.archivedAt).toBe(stamp); - expect((await storage.get(parent.id))?.updatedAt).toBe("2026-11-09T01:00:00.000Z"); + expect((await storage.get(parent.id))?.updatedAt).toBe(laterStamp); } finally { await storage.flush(); rmSync(workdir, { recursive: true, force: true }); } }); + +test("idle cleanup gives a newly restored runtime a fresh idle window while keeping historical updatedAt", async () => { + const h = idleCleanupHarness(); + const created = await h.create(); + h.probes[0] = async () => true; + h.probes[1] = async () => true; + await h.manager.closeAgent(created.id); + await h.storage.flush(); + const historicalUpdatedAt = new Date(Date.now() - 180 * 60_000); + const existingRecord = await h.storage.get(created.id); + expect(existingRecord).not.toBeNull(); + const staleRecord: StoredAgentRecord = { + ...existingRecord!, + updatedAt: historicalUpdatedAt.toISOString(), + lastActivityAt: historicalUpdatedAt.toISOString(), + }; + await h.storage.upsert(staleRecord); + await h.storage.flush(); + + const closesBeforeRestore = h.closes; + const restored = await h.manager.resumeAgentFromPersistence( + created.persistence!, + { cwd: created.cwd }, + created.id, + { updatedAt: historicalUpdatedAt }, + ); + expect(restored.updatedAt.getTime()).toBe(historicalUpdatedAt.getTime()); + + // Sweeping 1 minute after restoring an old agent must NOT immediately kill the newly opened runtime. + expect((await h.sweep({ now: h.later(1) })).collected).toEqual([]); + expect(h.closes).toBe(closesBeforeRestore); + + // Sweeping 61 minutes after restoration collects the runtime as expected. + expect((await h.sweep({ now: h.later(61) })).collected).toHaveLength(1); + expect(h.closes).toBe(closesBeforeRestore + 1); +}); + +test.each([ + ["supported", "turn_completed"], + ["supported", "turn_canceled"], + ["supported", "turn_failed"], + ["unsupported", "turn_completed"], + ["unsupported", "turn_canceled"], + ["unsupported", "turn_failed"], +] as const)( + "queued delivery after %s provider %s never steers or interrupts", + async (support, ending) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-queued-terminal-")); + const session = + support === "supported" + ? new SteeringTestSession({ provider: "codex", cwd: workdir }) + : new UnsupportedSteeringSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ clients: { codex: client }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + let tick = () => {}; + const delivery = createAgentMessageDelivery({ + isRunning: (id) => manager.hasInFlightRun(id), + subscribe: (notify) => + manager.subscribe( + (event) => { + if (event.type === "agent_state") notify(event.agent.id); + }, + { replayState: false }, + ), + schedule: (_delay, callback) => { + tick = callback; + return () => {}; + }, + dispatch: async (request) => + ( + await startAgentRun(manager, agent.id, request.prompt, logger, { + idleOnly: request.idleOnly, + replaceRunning: true, + activeTurnBehavior: request.activeTurnBehavior, + }) + ).disposition, + onError: (error) => { + throw error; + }, + }); + const providerStarted = new Promise((resolve) => { + const unsubscribe = session.subscribe((event) => { + if (event.type === "turn_started") { + unsubscribe(); + resolve(); + } + }); + }); + try { + await startAgentRun(manager, agent.id, "original", logger); + await manager.waitForAgentRunStart(agent.id); + const receipt = delivery.enqueue({ + recipientId: agent.id, + prompt: "queued", + source: { kind: "agent-message", agentId: "child" }, + }); + tick(); + expect(session.startCount).toBe(1); + expect(session.interruptCount).toBe(0); + const turnId = support === "supported" ? "active-turn-1" : "unsupported-turn-1"; + await providerStarted; + session.pushEvent({ + type: ending, + provider: "codex", + turnId, + ...(ending === "turn_failed" ? { error: "test failure" } : {}), + } as AgentStreamEvent); + await receipt.dispatched; + await manager.waitForAgentRunStart(agent.id); + expect(session.startCount).toBe(2); + expect(session.interruptCount).toBe(0); + } finally { + await delivery.close(); + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)( + "an autonomous %s publishes readiness after settling its run", + async (ending) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-autonomous-delivery-")); + const session = new SteeringTestSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ clients: { codex: client }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + let tick = () => {}; + const settledStates: boolean[] = []; + const delivery = createAgentMessageDelivery({ + isRunning: (id) => manager.hasInFlightRun(id), + subscribe: (notify) => + manager.subscribe( + (event) => { + if (event.type !== "agent_state") return; + if (event.agent.lifecycle !== "running") + settledStates.push(manager.hasInFlightRun(agent.id)); + notify(event.agent.id); + }, + { agentId: agent.id, replayState: false }, + ), + schedule: (_delay, callback) => { + tick = callback; + return () => {}; + }, + dispatch: async (request) => + ( + await startAgentRun(manager, agent.id, request.prompt, logger, { + idleOnly: request.idleOnly, + }) + ).disposition, + onError: (error) => { + throw error; + }, + }); + try { + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "autonomous" }); + await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true)); + delivery.enqueue({ + recipientId: agent.id, + prompt: "queued report", + source: { kind: "agent-message", agentId: "child" }, + }); + tick(); + expect(session.startCount).toBe(0); + session.pushEvent({ + type: ending, + provider: "codex", + turnId: "autonomous", + ...(ending === "turn_failed" ? { error: "test failure" } : {}), + } as AgentStreamEvent); + await new Promise((resolve) => setImmediate(resolve)); + expect(settledStates).toEqual([false]); + expect(session.startCount).toBe(1); + } finally { + await delivery.close(); + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test("an idle-only prompt rejects a busy recipient before changing its mode", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-queued-mode-")); + class ModeSession extends SteeringTestSession { + mode = "plan"; + applied: string[] = []; + startedModes: string[] = []; + override async setMode(mode?: string) { + if (!mode) throw new Error("Mode required"); + this.mode = mode; + this.applied.push(mode); + } + override async getCurrentMode() { + return this.mode; + } + override async startTurn(prompt: AgentPromptInput) { + this.startedModes.push(this.mode); + return super.startTurn(prompt); + } + } + const session = new ModeSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + await manager.setAgentMode(agent.id, "plan"); + session.applied.length = 0; + const providerStarted = new Promise((resolve) => { + const unsubscribe = session.subscribe((event) => { + if (event.type === "turn_started") { + unsubscribe(); + resolve(); + } + }); + }); + const startOther = async () => { + await startAgentRun(manager, agent.id, "other turn", logger); + await manager.waitForAgentRunStart(agent.id); + }; + try { + await startOther(); + await expect( + sendPreparedPromptToAgent({ + agentManager: manager, + agentStorage: storage, + agentId: agent.id, + prompt: "queued follow-up", + sessionMode: "full-access", + idleOnly: true, + logger, + }), + ).rejects.toBeInstanceOf(AgentTurnBusyError); + expect(session.mode).toBe("plan"); + expect(session.applied).toEqual([]); + expect(session.startedModes).toEqual(["plan"]); + await providerStarted; + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" }); + await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false)); + await sendPreparedPromptToAgent({ + agentManager: manager, + agentStorage: storage, + agentId: agent.id, + prompt: "queued follow-up", + sessionMode: "full-access", + idleOnly: true, + logger, + }); + await manager.waitForAgentRunStart(agent.id); + expect(session.mode).toBe("full-access"); + expect(session.applied).toEqual(["full-access"]); + expect(session.startedModes).toEqual(["plan", "full-access"]); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("plugin instructions are recomputed for each launch without changing saved config", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-prompt-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new TestAgentClient(); + let additions = ["Plugin one", "Plugin two"]; + const manager = new AgentManager({ + clients: { codex: client }, + registry: storage, + logger, + appendSystemPrompt: "Daemon", + pluginLifecycle: { + emit: () => {}, + before: async (name, request) => + name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request, + }, + }); + const snapshot = await manager.createAgent( + { provider: "codex", cwd: workdir, systemPrompt: "Saved" }, + undefined, + { workspaceId: undefined }, + ); + expect(client.createdConfigs[0]).toMatchObject({ + systemPrompt: "Saved", + daemonAppendSystemPrompt: "Daemon", + pluginAppendSystemPrompt: ["Plugin one", "Plugin two"], + }); + expect(snapshot.config.systemPrompt).toBe("Saved"); + expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved"); + const handle: AgentPersistenceHandle = { + provider: "codex", + sessionId: "prompt-session", + metadata: { provider: "codex", cwd: workdir, systemPrompt: "Saved" }, + }; + await manager.closeAgent(snapshot.id); + await manager.resumeAgentFromPersistence( + handle, + { cwd: workdir, systemPrompt: "Saved" }, + snapshot.id, + ); + expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual([ + "Plugin one", + "Plugin two", + ]); + additions = ["Changed"]; + await manager.closeAgent(snapshot.id); + await manager.resumeAgentFromPersistence( + handle, + { cwd: workdir, systemPrompt: "Saved" }, + snapshot.id, + ); + expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Changed"]); + additions = ["Refreshed"]; + await manager.reloadAgentSession(snapshot.id); + expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Refreshed"]); + additions = []; + await manager.closeAgent(snapshot.id); + await manager.resumeAgentFromPersistence( + handle, + { cwd: workdir, systemPrompt: "Saved" }, + snapshot.id, + ); + expect(client.resumeOverrides.at(-1)?.systemPrompt).toBe("Saved"); + expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon"); + expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved"); +}); + +function dispatchStarted(dispatch: Awaited>): Promise { + if (dispatch.disposition !== "turn_started") { + throw new Error(`Expected a started turn, got ${dispatch.disposition}`); + } + void dispatch.started.catch(() => undefined); + return dispatch.started; +} diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 50d25a7e1c..27dc9c0638 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -8,7 +8,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js"; import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js"; -import { projectTimelineRows } from "./timeline-projection.js"; +import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js"; import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js"; import { applyRecordPatch } from "../record-patch.js"; @@ -34,6 +34,7 @@ import { z } from "zod"; import type { TerminalManager } from "../../terminal/terminal-manager.js"; import { + AgentTurnStartCanceledError, getAgentStreamEventTurnId, type AgentCapabilityFlags, type AgentClient, @@ -97,6 +98,7 @@ import { import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { AgentRunState, + type ForegroundPromptStart, type ForegroundTurnWaiter, type PendingForegroundRun, } from "./agent-run-state.js"; @@ -116,7 +118,12 @@ import { type ProviderSubagentDescriptor, type ProviderSubagentStoreEvent, } from "./provider-subagents/store.js"; -import { AgentBackgroundWorkStore, type AgentBackgroundWorkItem } from "./background-work/index.js"; +import { + AgentBackgroundWorkStore, + isHeartbeatBackgroundWorkItem, + type AgentBackgroundWorkItem, + type HeartbeatBackgroundWorkInput, +} from "./background-work/index.js"; import { withTimeout } from "../../utils/promise-timeout.js"; import { buildSessionConfig, extractAttention } from "../persistence-hooks.js"; @@ -201,6 +208,7 @@ interface StopAgentBackgroundWorkOptions { agentId: string; itemId: string; stopToken: string; + canManageAutomation?: boolean; } async function resolveResumePurpose( @@ -646,7 +654,12 @@ function normalizePersistenceForConfig( if (!handle) { return null; } - const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {}; + const { + mcpServers: _launchMcpServers, + pluginAppendSystemPrompt: _pluginAppendSystemPrompt, + daemonAppendSystemPrompt: _daemonAppendSystemPrompt, + ...metadata + } = handle.metadata ?? {}; return { ...handle, metadata: { @@ -856,6 +869,7 @@ export class AgentManager { private readonly sessionEventTails = new Map>(); private readonly steerEventBarriers = new Map(); private readonly foregroundMutationTails = new Map>(); + private readonly replacementMutationTails = new Map>(); private readonly runs = new AgentRunState(); private readonly subscribers = new Set(); private readonly idFactory: () => string; @@ -867,7 +881,10 @@ export class AgentManager { private readonly inFlightAgentCloses = new Map>(); private readonly historySessions = new WeakSet(); private readonly reloadedSessionCloses = new WeakMap>(); - private readonly runtimeCleanupIdentities = new WeakMap(); + private readonly runtimeCleanupIdentities = new WeakMap< + AgentSession, + { readonly openedAt: number } + >(); private readonly collectingRuntimes = new Set(); private readonly lifecycleMutationTails = new Map>(); private readonly agentStreamCoalescer: AgentStreamCoalescer; @@ -1208,6 +1225,10 @@ export class AgentManager { return new Date(nextMs).toISOString(); } + hasPendingPermissions(agentId: string): boolean { + return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0; + } + hasInFlightRun(agentId: string): boolean { const agent = this.agents.get(agentId); if (!agent) { @@ -1510,37 +1531,56 @@ export class AgentManager { } listAgentBackgroundWork(agentId: string): AgentBackgroundWorkItem[] { - this.requirePublicAgent(agentId); + const agent = this.agents.get(agentId); + if (agent?.internal || (!agent && !this.backgroundWork.summary(agentId))) { + throw new Error(`Unknown agent '${agentId}'`); + } return this.backgroundWork.list(agentId); } + setHeartbeatBackgroundWork(input: HeartbeatBackgroundWorkInput): void { + this.publishBackgroundWork(input.agentId, this.backgroundWork.setHeartbeat(input)); + } + + removeHeartbeatBackgroundWork(agentId: string, scheduleId: string): void { + this.publishBackgroundWork(agentId, this.backgroundWork.removeHeartbeat(agentId, scheduleId)); + } + async stopAgentBackgroundWork({ agentId, itemId, stopToken, + canManageAutomation, }: StopAgentBackgroundWorkOptions): Promise { + if (isHeartbeatBackgroundWorkItem({ id: itemId })) { + if (this.agents.get(agentId)?.internal) throw new Error(`Unknown agent '${agentId}'`); + if (!canManageAutomation) + throw new Error("Managing automation is required to stop a heartbeat"); + await this.backgroundWork.stopHeartbeat(agentId, itemId, stopToken); + return; + } this.requirePublicAgent(agentId); // Inventory events share the session queue; drain events already received before // authorizing the token, including a reconnect's ownership revocation. await this.sessionEventTails.get(agentId)?.catch(() => undefined); - const agent = this.requirePublicAgent(agentId); - if (!agent.session || !agent.session.stopBackgroundWork) - throw new Error("Background work cannot be stopped"); - const item = this.backgroundWork.list(agentId).find((entry) => entry.id === itemId); - if (!item?.canStop || item.stopToken !== stopToken) - throw new Error("Background work is no longer available to stop"); - await agent.session.stopBackgroundWork(itemId); + const { session } = this.requirePublicAgent(agentId); + if (!session?.stopBackgroundWork) throw new Error("Background work cannot be stopped"); + const providerItemId = this.backgroundWork.authorizeProviderStop(agentId, itemId, stopToken); + await session.stopBackgroundWork(providerItemId); } getAgentBackgroundWorkSummary(agentId: string): { count: number } | undefined { return this.backgroundWork.summary(agentId); } - private clearBackgroundWork(agentId: string): void { - const items = this.backgroundWork.clear(agentId); + private publishBackgroundWork(agentId: string, items: AgentBackgroundWorkItem[] | null): void { if (items) this.dispatch({ type: "background_work", agentId, items }); } + private clearProviderBackgroundWork(agentId: string): void { + this.publishBackgroundWork(agentId, this.backgroundWork.clear(agentId)); + } + listProviderSubagentActivity(): ProviderSubagentDescriptor[] { const publicParentIds = new Set( Array.from(this.agents.values()) @@ -1813,12 +1853,15 @@ export class AgentManager { return this.registerSession(session, storedConfig, resolvedAgentId, { launchedOptions, ...options, - // The caller read its metadata before this turn in the lane; a setMetadata queued ahead of - // it has saved a newer record, the one the open hooks saw. - ...(record ? { metadata: record.metadata } : {}), + // The caller read its metadata and attention before this turn in the lane; a setMetadata + // or attention clear queued ahead of it has saved a newer record, the one the open hooks saw. + ...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}), workspaceId, launchEnv, - persistence: handle, + persistence: + purpose === "interactive" && session.persistenceUpdatedOnResume + ? (session.describePersistence() ?? handle) + : handle, restoring: true, }); } @@ -1999,7 +2042,7 @@ export class AgentManager { await this.closeReloadedSession(existing.session, agentId); await this.drainSessionEvents(agentId); this.cancelRunningProviderSubagents(agentId); - this.clearBackgroundWork(agentId); + this.clearProviderBackgroundWork(agentId); closedExisting = this.prepareAgentForClosure(existing, "agent reloaded"); await this.persistSnapshot(closedExisting); this.assertAcceptingAgentRegistrations(); @@ -2162,7 +2205,7 @@ export class AgentManager { const updatedAt = agent.updatedAt; let identity = this.runtimeCleanupIdentities.get(agent.session); if (!identity) { - identity = Object.freeze({}); + identity = Object.freeze({ openedAt: Date.now() }); this.runtimeCleanupIdentities.set(agent.session, identity); } const isEligible = () => @@ -2175,7 +2218,7 @@ export class AgentManager { parentAgentId: getParentAgentIdFromLabels(agent.labels) ?? undefined, provider: agent.provider, sessionId: agent.persistence?.sessionId ?? null, - lastActivityAt: updatedAt.getTime(), + lastActivityAt: Math.max(updatedAt.getTime(), identity.openedAt), isEligible, canStopRuntime: agent.session.canStopRuntime?.bind(agent.session), closeIfEligible: async (revalidate) => { @@ -2207,6 +2250,7 @@ export class AgentManager { agent.inFlightPermissionResponses.size === 0 && (this.collectingRuntimes.has(agent.id) || !this.lifecycleMutationTails.has(agent.id)) && !this.foregroundMutationTails.has(agent.id) && + !this.replacementMutationTails.has(agent.id) && !this.sessionEventTails.has(agent.id) && !this.providerSubagents.list(agent.id).some((child) => child.status === "running") ); @@ -2254,7 +2298,7 @@ export class AgentManager { await this.drainSessionEvents(agentId); this.cancelRunningProviderSubagents(agentId); // close() drops the session's subscribers before the provider could report an empty list. - this.clearBackgroundWork(agentId); + this.clearProviderBackgroundWork(agentId); const closedAgent = this.prepareAgentForClosure(agent, "agent closed"); let persistError: unknown; @@ -2428,7 +2472,7 @@ export class AgentManager { private async persistArchivedRecord( record: StoredAgentRecord, - options: { archivedAt: string; updatedAt?: string }, + options: { archivedAt: string; updatedAt: string }, ): Promise { const archivedRecord = buildArchivedAgentRecord(record, options); await this.requireRegistry().upsert(archivedRecord); @@ -2853,6 +2897,10 @@ export class AgentManager { } async clearAgentAttention(agentId: string): Promise { + return this.runLifecycleMutation(agentId, () => this.clearAgentAttentionUnlocked(agentId)); + } + + private async clearAgentAttentionUnlocked(agentId: string): Promise { const agent = this.agents.get(agentId); if (agent) { if (agent.attention.requiresAttention) { @@ -2944,7 +2992,11 @@ export class AgentManager { throw new Error(`Agent not found: ${agentId}`); } - const nextRecord = await this.persistArchivedRecord(record, { archivedAt }); + // Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent. + const nextRecord = await this.persistArchivedRecord(record, { + archivedAt, + updatedAt: archivedAt, + }); await this.syncNativeArchiveState(record.provider, record.persistence, "archive"); @@ -3116,6 +3168,7 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + onAccepted?: () => void, ): Promise { if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) { await this.waitForAgentClose(agentId); @@ -3135,6 +3188,7 @@ export class AgentManager { if (!handler) { return false; } + onAccepted?.(); this.touchUpdatedAt(agent); if (options?.clientMessageId) { this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted"); @@ -3211,7 +3265,7 @@ export class AgentManager { pendingRun: PendingForegroundRun; prompt: AgentPromptInput; options?: AgentRunOptions; - }): Promise { + }): Promise { const { agent, agentId, pendingRun, prompt, options } = params; try { const result = await agent.session.startTurn(prompt, options); @@ -3220,11 +3274,32 @@ export class AgentManager { } return result.turnId; } catch (error) { + if (error instanceof AgentTurnStartCanceledError) { + if (!pendingRun.settled) { + if (options?.clientMessageId) { + this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", { + messageId: options.clientMessageId, + }); + } + await this.handleStreamEvent(agent, { + type: "turn_canceled", + provider: agent.provider, + reason: "interrupted", + }); + this.finalizeForegroundTurn(agent); + this.runs.settleForegroundRun(agentId, pendingRun.token); + } + return null; + } if (pendingRun.settled) { throw error; } if (isStaleProviderSessionError(error)) { - this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message }); + this.runs.settleForegroundStart(pendingRun, { + status: "failed", + error: error.message, + stale: true, + }); agent.pendingReplacement = false; if (!agent.activeForegroundTurnId) agent.lifecycle = "idle"; this.runs.settleForegroundRun(agentId, pendingRun.token); @@ -3280,15 +3355,17 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): AsyncGenerator { await this.ensureInteractiveSession(agentId); - yield* this.streamAgent(agentId, prompt, options); + yield* this.streamAgent(agentId, prompt, options, promptStart); } private async *streamAfterRuntimeCollection( agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): AsyncGenerator { await this.waitForAgentClose(agentId); await ensureAgentLoaded(agentId, { @@ -3296,19 +3373,20 @@ export class AgentManager { agentStorage: this.requireRegistry(), logger: this.logger, }); - yield* this.streamAgent(agentId, prompt, options); + yield* this.streamAgent(agentId, prompt, options, promptStart); } streamAgent( agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): AsyncGenerator { if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry)) - return this.streamAfterRuntimeCollection(agentId, prompt, options); + return this.streamAfterRuntimeCollection(agentId, prompt, options, promptStart); const existingAgent = this.requireSessionAgent(agentId); if (this.historySessions.has(existingAgent.session)) - return this.streamAfterHistoryLoad(agentId, prompt, options); + return this.streamAfterHistoryLoad(agentId, prompt, options, promptStart); this.logger.trace( { agentId, @@ -3343,9 +3421,10 @@ export class AgentManager { agent.lastError = undefined; const pendingRun = this.runs.createPendingRun(agentId); + promptStart?.bind(pendingRun); const streamForwarder = async function* streamForwarder(this: AgentManager) { - let turnId: string; + let turnId: string | null; let turnStream: ReturnType | null = null; turnId = await this.startPendingForegroundTurn({ agent, @@ -3354,6 +3433,15 @@ export class AgentManager { prompt, options, }); + if (turnId === null) { + const canceledEvent: AgentStreamEvent = { + type: "turn_canceled", + provider: agent.provider, + reason: "interrupted", + }; + yield canceledEvent; + return; + } if (isReplacement) { agent.pendingReplacement = false; @@ -3508,32 +3596,10 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): Promise> { - const snapshot = this.requireAgent(agentId); - if ( - snapshot.lifecycle !== "running" && - !snapshot.activeForegroundTurnId && - !this.runs.hasRun(agentId) - ) { - return this.streamAgent(agentId, prompt, options); - } - - const agent = this.requireSessionAgent(agentId); - agent.pendingReplacement = true; - agent.lifecycle = "running"; - this.touchUpdatedAt(agent); - this.emitState(agent); - - try { - await this.cancelAgentRunBefore(agentId, "replace"); - return this.streamAgent(agentId, prompt, options); - } catch (error) { - const latest = this.agents.get(agentId); - if (latest) { - latest.pendingReplacement = false; - } - throw error; - } + this.requireSessionAgent(agentId); + return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart); } async steerAgentRun( @@ -3574,6 +3640,7 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentSteerOptions, + promptStart?: ForegroundPromptStart, ): Promise { // A turn that is still starting has no id to steer yet. Replacing it would drop its // prompt, so wait until it is accepted (or fails) and steer the turn it became. @@ -3621,6 +3688,7 @@ export class AgentManager { expectedTurnId, prompt, stripSteerOptions(options), + promptStart, ), }; } @@ -3657,18 +3725,26 @@ export class AgentManager { } private async runForegroundMutation(agentId: string, operation: () => Promise): Promise { - const previous = this.foregroundMutationTails.get(agentId) ?? Promise.resolve(); + return this.runQueuedMutation(this.foregroundMutationTails, agentId, operation); + } + + private async runQueuedMutation( + tails: Map>, + agentId: string, + operation: () => Promise, + ): Promise { + const previous = tails.get(agentId) ?? Promise.resolve(); const run = previous.catch(() => undefined).then(operation); const tail = run.then( () => undefined, () => undefined, ); - this.foregroundMutationTails.set(agentId, tail); + tails.set(agentId, tail); try { return await run; } finally { - if (this.foregroundMutationTails.get(agentId) === tail) { - this.foregroundMutationTails.delete(agentId); + if (tails.get(agentId) === tail) { + tails.delete(agentId); } } } @@ -3678,22 +3754,86 @@ export class AgentManager { expectedTurnId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): Promise> { this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId); - agent.pendingReplacement = true; - agent.lifecycle = "running"; - this.touchUpdatedAt(agent); - this.emitState(agent); + return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) => + this.assertSteerAdmissionOwnsTurn(live, expectedTurnId), + ); + } - try { - await this.cancelAgentRunBefore(agent.id, "replace"); - return this.streamAgent(agent.id, prompt, options); - } catch (error) { - const latest = this.agents.get(agent.id); - if (latest) { - latest.pendingReplacement = false; + /** + * Cancels the current run and reserves its replacement in one foreground mutation, so a + * concurrent replacement or Stop cannot land between the cancel and the new run's start. + */ + private async replaceRunInForegroundLane( + agentId: string, + prompt: AgentPromptInput, + options: AgentRunOptions | undefined, + promptStart?: ForegroundPromptStart, + assertAdmission?: (agent: ActiveManagedAgent) => void, + ): Promise> { + // Replacements queue in arrival order; each one holds the foreground lane only while + // it cancels and reserves, so Stop is never stuck behind a replacement that is waiting. + return this.runQueuedMutation(this.replacementMutationTails, agentId, () => + this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission), + ); + } + + private async replaceRunWhenAdmitted( + agentId: string, + prompt: AgentPromptInput, + options: AgentRunOptions | undefined, + promptStart?: ForegroundPromptStart, + assertAdmission?: (agent: ActiveManagedAgent) => void, + ): Promise> { + let stalledStart: PendingForegroundRun | null = null; + for (;;) { + const admission = await this.runForegroundMutation(agentId, async () => { + // Resolve the agent inside the lane: a reload while this send waited replaces it. + const agent = this.requireSessionAgent(agentId); + // A run that is still starting has no turn to interrupt yet. Canceling it would drop + // its prompt, so wait for it outside the lane, where Stop can still reach it. A start + // that outlasts the rescue timeout is canceled like any other run. + const starting = this.runs.getPendingRun(agent.id); + if (starting && starting.start.status !== "started" && starting !== stalledStart) { + return { status: "starting" as const, run: starting }; + } + assertAdmission?.(agent); + if (!this.hasInFlightRun(agent.id)) { + return { + status: "reserved" as const, + iterator: this.streamAgent(agent.id, prompt, options, promptStart), + }; + } + agent.pendingReplacement = true; + agent.lifecycle = "running"; + this.touchUpdatedAt(agent); + this.emitState(agent); + try { + const result = await this.cancelAgentRunNow(agent.id); + if (result.status === "refused") { + throw new AgentRunCancellationError(agent.id, "replace"); + } + return { + status: "reserved" as const, + iterator: this.streamAgent(agent.id, prompt, options, promptStart), + }; + } catch (error) { + agent.pendingReplacement = false; + throw error; + } + }); + if (admission.status === "reserved") { + return admission.iterator; + } + const started = await this.waitWithTimeout({ + operation: Promise.race([admission.run.turnStartedPromise, admission.run.settledPromise]), + timeoutMs: this.rescueTimeouts.interruptSessionMs, + }); + if (started === "timed_out") { + stalledStart = admission.run; } - throw error; } } @@ -3868,7 +4008,10 @@ export class AgentManager { } async cancelAgentRun(agentId: string): Promise { - return this.runForegroundMutation(agentId, () => this.cancelAgentRunNow(agentId)); + return this.runForegroundMutation(agentId, () => { + this.requireSessionAgent(agentId).pendingReplacement = false; + return this.cancelAgentRunNow(agentId); + }); } private async cancelAgentRunNow(agentId: string): Promise { @@ -4089,23 +4232,25 @@ export class AgentManager { private getLastAssistantMessageFromTimeline( timeline: readonly AgentTimelineItem[], ): string | null { - return this.getLastAssistantMessageSegmentFromTimeline(timeline)?.text ?? null; + return ( + this.getLastAssistantMessageSegmentFromTimeline(timeline.map((item) => ({ item })))?.text ?? + null + ); } private getLastAssistantMessageSegmentFromTimeline( - timeline: readonly AgentTimelineItem[], + timeline: readonly Pick[], ): { text: string; startsAtBeginning: boolean } | null { - // Collect the last contiguous assistant messages (Claude streams chunks) + // Collect the chunks of the last assistant message (Claude streams chunks). A turn the + // provider starts on its own has no user message before its reply. const chunks: string[] = []; let startsAtBeginning = false; for (let i = timeline.length - 1; i >= 0; i--) { - const item = timeline[i]; - if (item.type !== "assistant_message") { - if (chunks.length) { - break; - } - continue; + const { item } = timeline[i]; + if (chunks.length > 0 && !continuesAssistantMessage(timeline[i], timeline[i + 1])) { + break; } + if (item.type !== "assistant_message") continue; chunks.push(item.text); startsAtBeginning = i === 0; } @@ -4121,8 +4266,9 @@ export class AgentManager { } private async getLastAssistantMessageFromStores(agentId: string): Promise { - const liveTimeline = this.timelineStore.getItems(agentId); - const liveSegment = this.getLastAssistantMessageSegmentFromTimeline(liveTimeline); + const liveSegment = this.getLastAssistantMessageSegmentFromTimeline( + this.timelineStore.getRows(agentId), + ); if (!this.durableTimelineStore) { return liveSegment?.text ?? null; } @@ -4389,6 +4535,7 @@ export class AgentManager { } this.assertAcceptingAgentRegistrations(); + this.runtimeCleanupIdentities.set(session, Object.freeze({ openedAt: Date.now() })); this.agents.set(resolvedAgentId, managed); registered = true; // Initialize previousStatus to track transitions @@ -4647,7 +4794,7 @@ export class AgentManager { for (const event of this.providerSubagents.deleteParent(agentId)) { this.dispatch({ type: "provider_subagent", event }); } - this.clearBackgroundWork(agentId); + this.clearProviderBackgroundWork(agentId); } private emitClosedAgent(agent: ManagedAgentClosed, options?: { persist?: boolean }): void { @@ -4762,7 +4909,7 @@ export class AgentManager { event.items === null ? this.backgroundWork.clear(agent.id) : this.backgroundWork.apply(agent.id, event.items); - if (items) this.dispatch({ type: "background_work", agentId: agent.id, items }); + this.publishBackgroundWork(agent.id, items); return; } const turnId = getAgentStreamEventTurnId(event); @@ -5105,7 +5252,8 @@ export class AgentManager { if ( eventTurnId && isTurnTerminalEvent(event) && - this.runs.hasFinalizedTurn(agent, eventTurnId) + this.runs.hasFinalizedTurn(agent, eventTurnId) && + this.runs.getTurnId(agent.id) !== eventTurnId ) { return false; } @@ -5149,6 +5297,9 @@ export class AgentManager { this.runs.settleTerminalRun(agent.id, eventTurnId); if (isForegroundEvent) { this.finalizeForegroundTurn(agent, eventTurnId); + } else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) { + // Publish autonomous readiness only after the tracked run has settled. + this.emitState(agent); } } @@ -5418,7 +5569,6 @@ export class AgentManager { !agent.pendingReplacement ) { (agent as ActiveManagedAgent).lifecycle = "idle"; - this.emitState(agent); } void this.refreshRuntimeInfo(agent); } @@ -5459,9 +5609,6 @@ export class AgentManager { options, ); this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed"); - if (!isForegroundEvent && !agent.activeForegroundTurnId) { - this.emitState(agent); - } } private onStreamTurnCanceled(params: { @@ -5495,9 +5642,6 @@ export class AgentManager { } agent.lastError = undefined; this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted"); - if (!isForegroundEvent && !agent.activeForegroundTurnId) { - this.emitState(agent); - } } private onStreamTurnStarted(params: { @@ -6209,6 +6353,7 @@ export class AgentManager { // A plugin changing during this open must still make the resulting session stale. const generation = this.sessionOpenGeneration; this.detachPluginTools(agentId); + let appendSystemPrompt: string[] | undefined; let mcpServers: AgentSessionConfig["mcpServers"]; let mcpServerOwners: Record | undefined; if (this.pluginLifecycle) { @@ -6230,7 +6375,12 @@ export class AgentManager { env = transformed.env; if (request.purpose === "interactive") { this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]); - const { mcpServerOwners: _owners, ...opened } = transformed; + appendSystemPrompt = transformed.appendSystemPrompt; + const { + mcpServerOwners: _owners, + appendSystemPrompt: _instructions, + ...opened + } = transformed; this.pluginOpenRequests.set(agentId, { ...opened, tools: [], mcpServers: {} }); mcpServers = transformed.mcpServers; mcpServerOwners = transformed.mcpServerOwners; @@ -6238,6 +6388,7 @@ export class AgentManager { } const context: AgentLaunchContext = { agentId, + ...pluginPromptContext(appendSystemPrompt), mcpServers, mcpServerOwners, env: { @@ -6284,6 +6435,7 @@ export class AgentManager { throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`); } } + launchConfig = { ...launchConfig, pluginAppendSystemPrompt: launchContext.appendSystemPrompt }; const merged = Object.keys(launchContext.mcpServers ?? {}).length > 0 ? { @@ -6421,3 +6573,9 @@ export function commandMayHaveChangedExternalState(command: string): boolean { /\bgit\s+fetch\b/.test(normalized) ); } + +function pluginPromptContext( + appendSystemPrompt: string[] | undefined, +): Pick { + return appendSystemPrompt?.length ? { appendSystemPrompt } : {}; +} diff --git a/packages/server/src/server/agent/agent-messages/delivery.test.ts b/packages/server/src/server/agent/agent-messages/delivery.test.ts index bbe3d4fb3d..0225bc2435 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.test.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.test.ts @@ -1,3 +1,4 @@ +import { AgentTurnBusyError } from "../agent-prompt.js"; import { expect, test } from "vitest"; import { createAgentMessageDelivery, parseAgentMessages } from "./index.js"; import type { AgentPromptInput } from "../agent-sdk-types.js"; @@ -117,7 +118,6 @@ test("explicit interrupt and conflicting session modes retain ordered dispatch b const delivery = createAgentMessageDelivery({ dispatch: async (request) => { sent.push(request); - request.onDispatch("steered"); return "steered"; }, onError: (error) => { @@ -313,3 +313,555 @@ test("runtime safety sees queued messages until provider dispatch settles", asyn await delivery.close(); expect(delivery.hasPending("parent")).toBe(false); }); + +test("messages wait across quiet windows and batch after the recipient turn ends", async () => { + const clock = createClock(); + let running = true; + const sent: Array = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + dispatch: async (request) => { + sent.push(request.messageIds); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const source = { kind: "agent-message" as const, agentId: "child" }; + const report = delivery.enqueue({ + recipientId: "parent", + messageId: "report", + source, + prompt: "report", + }); + clock.advance(2000); + await Promise.resolve(); + expect(sent).toEqual([]); + clock.advance(13000); + const finish = delivery.enqueue({ + recipientId: "parent", + messageId: "finish", + source: { kind: "agent-notification", agentId: "child", event: "finished" }, + prompt: "finished", + activeTurnBehavior: "steer", + }); + clock.advance(2000); + await Promise.resolve(); + expect(sent).toEqual([]); + running = false; + clock.advance(2000); + await Promise.all([report.dispatched, finish.dispatched]); + expect(sent).toEqual([["report", "finish"]]); + await delivery.close(); +}); + +test("a turn starting during dispatch preparation keeps receipts queued and joins later arrivals", async () => { + const clock = createClock(); + let busy = true; + const sent: Array = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + dispatch: async (request) => { + if (busy) throw new AgentTurnBusyError("concurrent turn"); + sent.push(request.messageIds); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "report", + }; + const first = delivery.enqueue({ ...message, messageId: "first" }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + expect(delivery.hasPending("parent")).toBe(true); + const second = delivery.enqueue({ ...message, messageId: "second" }); + busy = false; + clock.advance(2000); + await Promise.all([first.dispatched, second.dispatched]); + expect(sent).toEqual([["first", "second"]]); + await delivery.close(); +}); + +test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => { + const clock = createClock(); + const sent: Array = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + dispatch: async (request) => { + sent.push(request.messageIds); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "report", + }; + delivery.enqueue({ ...message, messageId: "wait" }); + const interrupt = delivery.enqueue({ + ...message, + messageId: "interrupt", + activeTurnBehavior: "interrupt", + }); + clock.advance(2000); + await interrupt.dispatched; + expect(sent).toEqual([["interrupt"]]); + expect(delivery.hasPending("parent")).toBe(true); + await delivery.close(); + expect(sent).toEqual([["interrupt"], ["wait"]]); +}); + +test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => { + const clock = createClock(); + let release!: () => void; + const preparing = new Promise((resolve) => { + release = resolve; + }); + const modes: boolean[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + dispatch: async (request) => { + modes.push(request.idleOnly); + if (request.idleOnly) { + await preparing; + throw new AgentTurnBusyError("busy"); + } + return "turn_started"; + }, + onError: () => {}, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "report", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + const closing = delivery.close(); + release(); + await closing; + await expect(receipt.dispatched).resolves.toBe("turn_started"); + expect(modes).toEqual([true, false]); +}); + +test("conflicting modes dispatch on separate turn ends without changing the active turn mode", async () => { + const clock = createClock(); + let busy = false; + let mode = "initial"; + let wake!: (recipientId: string) => void; + const sent: Array<{ ids: readonly string[]; mode?: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => busy, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + dispatch: async (request) => { + // Mode preparation precedes run admission in the real dispatcher. + mode = request.sessionMode ?? mode; + if (busy) throw new AgentTurnBusyError("concurrent turn"); + sent.push({ ids: request.messageIds, mode }); + busy = true; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "message", + }; + const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" }); + const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" }); + clock.advance(2000); + await a.dispatched; + await new Promise((resolve) => setImmediate(resolve)); + expect(mode).toBe("plan"); + expect(sent).toEqual([{ ids: ["A"], mode: "plan" }]); + busy = false; + wake("parent"); + await b.dispatched; + expect(mode).toBe("default"); + expect(sent).toEqual([ + { ids: ["A"], mode: "plan" }, + { ids: ["B"], mode: "default" }, + ]); + await delivery.close(); +}); + +test("interrupts retain separate mode choices while the recipient is busy", async () => { + const clock = createClock(); + const sent: Array<{ ids: readonly string[]; mode?: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + dispatch: async (request) => { + sent.push({ ids: request.messageIds, mode: request.sessionMode }); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "message", + activeTurnBehavior: "interrupt" as const, + }; + const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" }); + const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" }); + clock.advance(2000); + await Promise.all([a.dispatched, b.dispatched]); + expect(sent).toEqual([ + { ids: ["A"], mode: "plan" }, + { ids: ["B"], mode: "default" }, + ]); + await delivery.close(); +}); + +test("a settled-turn event releases a ready batch without waiting for the next timer sample", async () => { + const clock = createClock(); + let running = true; + let settled: (id: string) => void = () => {}; + let subscribed = true; + const sent: string[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + settled = listener; + return () => { + subscribed = false; + }; + }, + dispatch: async (request) => { + sent.push(request.recipientId); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + delivery.enqueue({ + recipientId: "parent", + prompt: "report", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + expect(sent).toEqual([]); + running = false; + settled("parent"); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent).toEqual(["parent"]); + running = true; + await delivery.close(); + expect(subscribed).toBe(false); +}); + +test.each([false, true])( + "completion waits report permission checkpoints without draining messages (initial: %s)", + async (initial) => { + const clock = createClock(); + let permission = initial; + let changed: (id: string) => void = () => {}; + let reported = false; + let sent = 0; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + hasPendingPermission: () => permission, + subscribe: (listener) => { + changed = listener; + return () => {}; + }, + dispatch: async () => { + sent++; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + delivery.enqueue({ + recipientId: "child", + prompt: "follow up", + source: { kind: "agent-message", agentId: "parent" }, + }); + const wait = delivery.waitForDispatch("child", new AbortController().signal).then(() => { + reported = true; + return undefined; + }); + permission = true; + changed("child"); + await new Promise((resolve) => setImmediate(resolve)); + expect(reported).toBe(true); + expect(sent).toBe(0); + expect(delivery.hasPending("child")).toBe(true); + await wait; + await delivery.close(); + }, +); + +test("a busy admission retry stays ready for the next settled-turn event", async () => { + const clock = createClock(); + let running = false; + let raced = true; + let notify: (id: string) => void = () => {}; + const sent: string[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + notify = listener; + return () => {}; + }, + dispatch: async (request) => { + if (raced) { + running = true; + throw new AgentTurnBusyError("next turn started"); + } + sent.push(request.recipientId); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + delivery.enqueue({ + recipientId: "parent", + prompt: "report", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + raced = false; + running = false; + notify("parent"); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent).toEqual(["parent"]); + await delivery.close(); +}); + +test("out-of-band acceptance owns callbacks and receipts; a failed attempt does not block waiting messages", async () => { + const clock = createClock(); + let running = true; + let wake!: (recipientId: string) => void; + const callbacks: string[] = []; + const sent: string[] = []; + const errors: unknown[] = []; + const failure = new Error("recipient could not load"); + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + tryRunOutOfBand: async (request, onAccepted) => { + const text = parseAgentMessages(String(request.prompt))[0]!.text; + if (text === "failure") throw failure; + if (text !== "/handled") return false; + onAccepted(); + callbacks.push("command ran"); + return true; + }, + dispatch: async (request) => { + sent.push(...parseAgentMessages(String(request.prompt)).map((message) => message.text)); + return "turn_started"; + }, + onError: (error) => { + errors.push(error); + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + }; + const ordinary = delivery.enqueue({ + ...message, + prompt: "ordinary", + beforeDispatch: () => { + callbacks.push("ordinary"); + }, + }); + const failed = delivery.enqueue({ + ...message, + prompt: "failure", + beforeDispatch: () => { + callbacks.push("failure"); + }, + }); + const command = delivery.enqueue({ + ...message, + prompt: "/handled", + beforeDispatch: () => { + callbacks.push("command accepted"); + }, + onDispatch: (disposition) => { + callbacks.push(disposition); + }, + }); + clock.advance(2000); + await expect(failed.dispatched).rejects.toBe(failure); + await expect(command.dispatched).resolves.toBe("out_of_band"); + expect(errors).toEqual([failure]); + expect(callbacks).toEqual(["command accepted", "command ran", "out_of_band"]); + expect(sent).toEqual([]); + running = false; + wake("parent"); + await ordinary.dispatched; + expect(callbacks.at(-1)).toBe("ordinary"); + expect(sent).toEqual(["ordinary"]); + await delivery.close(); +}); + +test("shutdown waits for an in-flight out-of-band attempt and drains its unhandled message", async () => { + const clock = createClock(); + let release!: () => void; + let attempted!: () => void; + const started = new Promise((resolve) => { + attempted = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const dispatched: boolean[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + tryRunOutOfBand: async () => { + attempted(); + await gate; + return false; + }, + dispatch: async (request) => { + dispatched.push(request.idleOnly); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "ordinary", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await started; + const closing = delivery.close(); + release(); + await closing; + await expect(receipt.dispatched).resolves.toBe("turn_started"); + expect(dispatched).toEqual([false]); +}); + +test("a declined out-of-band message is offered once across running-turn retries", async () => { + const clock = createClock(); + let running = true; + let accepts = false; + let offers = 0; + let dispatched = 0; + let wake!: (recipientId: string) => void; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + tryRunOutOfBand: async (_request, onAccepted) => { + offers++; + if (accepts) onAccepted(); + return accepts; + }, + dispatch: async () => { + dispatched++; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "message", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + expect(offers).toBe(1); + // A later provider state change does not reinterpret a declined message. + accepts = true; + for (let retry = 0; retry < 3; retry++) { + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + } + expect(offers).toBe(1); + expect(dispatched).toBe(0); + running = false; + wake("parent"); + await receipt.dispatched; + expect(dispatched).toBe(1); + await delivery.close(); +}); + +test("a command with an explicit mode waits for turn end without an out-of-band offer", async () => { + const clock = createClock(); + let running = true; + let offers = 0; + let wake!: (recipientId: string) => void; + const dispatched: Array<{ prompt: AgentPromptInput; sessionMode?: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + tryRunOutOfBand: async (_request, onAccepted) => { + offers++; + onAccepted(); + return true; + }, + dispatch: async (request) => { + dispatched.push(request); + return "out_of_band"; + }, + onError: (error) => { + throw error; + }, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "/handled", + sessionMode: "plan", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + expect(offers).toBe(0); + expect(dispatched).toEqual([]); + running = false; + wake("parent"); + await receipt.dispatched; + expect(dispatched).toHaveLength(1); + expect(dispatched[0]!.sessionMode).toBe("plan"); + expect(parseAgentMessages(String(dispatched[0]!.prompt))![0]!.text).toBe("/handled"); + await delivery.close(); +}); diff --git a/packages/server/src/server/agent/agent-messages/delivery.ts b/packages/server/src/server/agent/agent-messages/delivery.ts index f26d83ec50..2852b7f04b 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.ts @@ -1,4 +1,4 @@ -import type { PromptDispatchDisposition } from "../agent-prompt.js"; +import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js"; import { randomUUID } from "node:crypto"; import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js"; import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js"; @@ -21,6 +21,8 @@ interface Receipt { dispatched: Promise; } interface Admitted extends Message { + sequence: number; + outOfBandDeclined: boolean; receipt: Receipt; resolve(disposition: PromptDispatchDisposition): void; reject(error: unknown): void; @@ -30,12 +32,18 @@ interface DispatchRequest { messageIds: readonly string[]; prompt: AgentPromptInput; activeTurnBehavior: "steer" | "interrupt"; + idleOnly: boolean; sessionMode?: string; clearPendingPermissions: boolean; unarchive: boolean; - onDispatch(disposition: PromptDispatchDisposition): void; } interface Dependencies { + /** Includes admitted starts and provider turns, including compaction. */ + isRunning?: (recipientId: string) => boolean; + hasPendingPermission?: (recipientId: string) => boolean; + /** Notify when recipient state changes; admission still checks whether it is idle. */ + subscribe?: (listener: (recipientId: string) => void) => () => void; + tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise; dispatch(request: DispatchRequest): Promise; onError(error: unknown, request: DispatchRequest): void; /** Return a cancellation function. Production uses the daemon's event loop. */ @@ -47,7 +55,7 @@ export interface AgentMessageDelivery { hasPending(recipientId: string): boolean; /** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */ close(): Promise; - /** Existing completion waits include agent messages admitted before the wait. */ + /** Completion waits include admitted messages, but return at permission checkpoints. */ waitForDispatch(recipientId: string, signal: AbortSignal): Promise; } @@ -59,12 +67,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes const timer = setTimeout(callback, delayMs); return () => clearTimeout(timer); }); - const pending = new Map(); + const pending = new Map(); const dispatching = new Map>(); + const receipts = new Map>(); + let sequence = 0; let closed = false; let closing: Promise | undefined; - function dispatch(recipientId: string, messages: Admitted[]): void { + function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest { const prompts = messages.map( (message) => prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt, @@ -74,39 +84,55 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes : prompts.flatMap((entry): AgentPromptContentBlock[] => typeof entry === "string" ? [{ type: "text", text: entry }] : entry, ); - const request: DispatchRequest = { + return { recipientId, + idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt", messageIds: messages.map((message) => message.receipt.messageId), prompt, activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer", sessionMode: messages.find((message) => message.sessionMode)?.sessionMode, clearPendingPermissions: messages.some((message) => message.clearPendingPermissions), unarchive: messages.some((message) => message.unarchive !== false), - onDispatch: (disposition) => { + }; + } + + function dispatch(recipientId: string, messages: Admitted[]): void { + const request = requestFor(recipientId, messages); + queueDispatch(recipientId, async () => { + try { + for (const message of messages) message.beforeDispatch?.(); + let disposition: PromptDispatchDisposition; + try { + disposition = await dependencies.dispatch(request); + } catch (error) { + if (!(error instanceof AgentTurnBusyError) || !closed) throw error; + // Shutdown drains admitted messages before closing the recipients. + disposition = await dependencies.dispatch({ ...request, idleOnly: false }); + } for (const message of messages) { try { message.onDispatch?.(disposition); } catch (error) { dependencies.onError(error, request); } + message.resolve(disposition); } - }, - }; + return undefined; + } catch (error) { + if (error instanceof AgentTurnBusyError && !closed) { + requeue(recipientId, messages); + return; + } + for (const message of messages) message.reject(error); + dependencies.onError(error, request); + throw error; + } + }); + } + + function queueDispatch(recipientId: string, operation: () => Promise): void { const previous = dispatching.get(recipientId) ?? Promise.resolve(); - const dispatched = previous - .catch(() => undefined) - .then(async () => { - try { - for (const message of messages) message.beforeDispatch?.(); - const disposition = await dependencies.dispatch(request); - for (const message of messages) message.resolve(disposition); - return undefined; - } catch (error) { - for (const message of messages) message.reject(error); - dependencies.onError(error, request); - throw error; - } - }); + const dispatched = previous.catch(() => undefined).then(operation); dispatching.set(recipientId, dispatched); void dispatched .finally(() => { @@ -115,30 +141,121 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes .catch(() => undefined); } + function requeue(recipientId: string, messages: Admitted[]): void { + const entry = pending.get(recipientId) ?? { + messages: [], + ready: true, + cancel: () => {}, + }; + entry.cancel(); + entry.messages.push(...messages); + entry.messages.sort((a, b) => a.sequence - b.sequence); + entry.cancel = schedule(2000, () => flush(recipientId)); + pending.set(recipientId, entry); + } + function flush(recipientId: string): void { const entry = pending.get(recipientId); if (!entry) return; - pending.delete(recipientId); + entry.ready = true; entry.cancel(); + if (!closed && dependencies.isRunning?.(recipientId)) { + const interrupts = entry.messages.filter( + (message) => message.activeTurnBehavior === "interrupt", + ); + entry.messages = entry.messages.filter( + (message) => message.activeTurnBehavior !== "interrupt", + ); + if (interrupts.length) dispatchGroups(recipientId, interrupts); + if (entry.messages.length && dependencies.tryRunOutOfBand) { + pending.delete(recipientId); + offerOutOfBand(recipientId, entry.messages); + } else if (entry.messages.length) { + entry.cancel = schedule(2000, () => flush(recipientId)); + } else { + pending.delete(recipientId); + } + return; + } + pending.delete(recipientId); + dispatchGroups(recipientId, entry.messages); + } + + function offerOutOfBand(recipientId: string, messages: Admitted[]): void { + queueDispatch(recipientId, async () => { + const waiting: Admitted[] = []; + for (const message of messages) { + if ( + message.outOfBandDeclined || + message.sessionMode !== undefined || + closed || + !dependencies.isRunning?.(recipientId) + ) { + waiting.push(message); + continue; + } + const request = requestFor(recipientId, [message]); + try { + const accepted = await dependencies.tryRunOutOfBand!(request, () => + message.beforeDispatch?.(), + ); + if (!accepted) { + message.outOfBandDeclined = true; + waiting.push(message); + continue; + } + try { + message.onDispatch?.("out_of_band"); + } catch (error) { + dependencies.onError(error, request); + } + message.resolve("out_of_band"); + } catch (error) { + message.reject(error); + dependencies.onError(error, request); + } + } + if (waiting.length) requeue(recipientId, waiting); + if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))) + flush(recipientId); + }); + } + + function dispatchGroups(recipientId: string, messages: Admitted[]): void { + const groups: Admitted[][] = []; let group: Admitted[] = []; let mode: string | undefined; - for (const message of entry.messages) { + for (const message of messages) { // Explicitly conflicting send options require separate, ordered dispatches. if ( group.length && ((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") || (mode && message.sessionMode && mode !== message.sessionMode)) ) { - dispatch(recipientId, group); + groups.push(group); group = []; mode = undefined; } group.push(message); mode ??= message.sessionMode; } - if (group.length) dispatch(recipientId, group); + if (group.length) groups.push(group); + let started = false; + for (const batch of groups) { + if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") { + requeue(recipientId, batch); + } else { + dispatch(recipientId, batch); + started = true; + } + } } + const unsubscribe = dependencies.subscribe?.((recipientId) => { + if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)) + flush(recipientId); + }); + return { hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId), enqueue(message) { @@ -155,17 +272,47 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes messageId: message.messageId ?? randomUUID(), dispatched, }; - const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} }; + const owned = receipts.get(message.recipientId) ?? new Set(); + owned.add(receipt); + receipts.set(message.recipientId, owned); + void dispatched + .finally(() => { + owned.delete(receipt); + if (!owned.size) receipts.delete(message.recipientId); + }) + .catch(() => undefined); + const entry = pending.get(message.recipientId) ?? { + messages: [], + ready: false, + cancel: () => {}, + }; entry.cancel(); - entry.messages.push({ ...message, receipt, resolve, reject }); + entry.ready = false; + entry.messages.push({ + ...message, + receipt, + resolve, + reject, + sequence: sequence++, + outOfBandDeclined: false, + }); entry.cancel = schedule(2000, () => flush(message.recipientId)); pending.set(message.recipientId, entry); return receipt; }, async waitForDispatch(recipientId, signal) { signal.throwIfAborted(); - const admitted = - pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? []; + const admitted = Array.from(receipts.get(recipientId) ?? [], (receipt) => receipt.dispatched); + let unsubscribePermission: (() => void) | undefined; + const permission = new Promise((resolve) => { + const check = () => { + if (dependencies.hasPendingPermission?.(recipientId)) resolve(); + }; + unsubscribePermission = dependencies.subscribe?.((agentId) => { + if (agentId === recipientId) check(); + }); + check(); + }); let aborted!: () => void; const cancellation = new Promise((_resolve, reject) => { aborted = () => reject(new DOMException("Wait aborted", "AbortError")); @@ -175,17 +322,22 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes await Promise.race([ Promise.all([dispatching.get(recipientId), ...admitted]), cancellation, + permission, ]); } finally { signal.removeEventListener("abort", aborted); + unsubscribePermission?.(); } }, close() { if (closing) return closing; closed = true; + unsubscribe?.(); for (const recipientId of pending.keys()) flush(recipientId); // Each failure is reported and rejects its receipts; shutdown still drains other recipients. - closing = Promise.allSettled(dispatching.values()).then(() => undefined); + closing = Promise.allSettled( + [...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)), + ).then(() => undefined); return closing; }, }; diff --git a/packages/server/src/server/agent/agent-projections.test.ts b/packages/server/src/server/agent/agent-projections.test.ts index 5e4fa77eab..5be66c4b61 100644 --- a/packages/server/src/server/agent/agent-projections.test.ts +++ b/packages/server/src/server/agent/agent-projections.test.ts @@ -337,6 +337,7 @@ describe("toAgentPayload", () => { nativeHandle: { id: "native" } as unknown, metadata: { restored: new Date("2025-03-01T00:00:00.000Z"), + paseoInstructionReceipt: { threadId: "persist-99", digest: "internal-digest" }, empty: {}, mcpServers: { hub: { @@ -387,6 +388,8 @@ describe("toAgentPayload", () => { sessionId: "persist-stored", metadata: { conversationId: "conversation-stored", + pluginAppendSystemPrompt: ["plugin instruction"], + daemonAppendSystemPrompt: "daemon instruction", mcpServers: { hub: { type: "http", @@ -402,6 +405,8 @@ describe("toAgentPayload", () => { expect(record.persistence?.metadata).toEqual({ conversationId: "conversation-stored", + pluginAppendSystemPrompt: ["plugin instruction"], + daemonAppendSystemPrompt: "daemon instruction", mcpServers: { hub: { type: "http", diff --git a/packages/server/src/server/agent/agent-projections.ts b/packages/server/src/server/agent/agent-projections.ts index 09d9461858..3a3af01166 100644 --- a/packages/server/src/server/agent/agent-projections.ts +++ b/packages/server/src/server/agent/agent-projections.ts @@ -260,10 +260,18 @@ function buildStoredOptionControls( }; } +function visibleStoredBackgroundWork( + record: StoredAgentRecord, + summary: AgentSnapshotPayload["backgroundWork"], +): AgentSnapshotPayload["backgroundWork"] { + return record.internal || record.archivedAt ? undefined : summary; +} + export function buildStoredAgentPayload( record: StoredAgentRecord, validProviders: Iterable, effectiveOptionsFor: EffectiveOptionsResolver, + backgroundWork?: AgentSnapshotPayload["backgroundWork"], ): AgentSnapshotPayload { const defaultCapabilities = { supportsStreaming: false, @@ -304,6 +312,7 @@ export function buildStoredAgentPayload( updatedAt: updatedAt.toISOString(), lastUserMessageAt: lastUserMessageAt ? lastUserMessageAt.toISOString() : null, status: record.lastStatus, + backgroundWork: visibleStoredBackgroundWork(record, backgroundWork), capabilities: defaultCapabilities, currentModeId: record.lastModeId ?? null, availableModes: [], @@ -495,6 +504,9 @@ function projectPersistenceHandleForWire( return projected; } delete projected.metadata.mcpServers; + delete projected.metadata.pluginAppendSystemPrompt; + delete projected.metadata.daemonAppendSystemPrompt; + delete projected.metadata.paseoInstructionReceipt; if (Object.keys(projected.metadata).length === 0) { delete projected.metadata; } diff --git a/packages/server/src/server/agent/agent-prompt.test.ts b/packages/server/src/server/agent/agent-prompt.test.ts index 2c150bd2e1..6a169c6df4 100644 --- a/packages/server/src/server/agent/agent-prompt.test.ts +++ b/packages/server/src/server/agent/agent-prompt.test.ts @@ -15,6 +15,7 @@ import { join } from "node:path"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { AgentManager } from "./agent-manager.js"; import { waitForAgentRunStartWithTimeout } from "./agent-prompt.js"; +import { ForegroundPromptStart } from "./agent-run-state.js"; import type { AgentClient, AgentRunResult, @@ -161,7 +162,7 @@ class SlowStartAgentClient implements AgentClient { async function createRunStartScenario(startDelayMs: number | null): Promise<{ agentManager: AgentManager; agentId: string; - startRun: () => Promise; + startRun: () => Promise<{ started: Promise }>; cleanup: () => Promise; }> { const workdir = mkdtempSync(join(tmpdir(), "agent-run-start-budget-")); @@ -178,14 +179,16 @@ async function createRunStartScenario(startDelayMs: number | null): Promise<{ return { agentManager, agentId: snapshot.id, - // streamAgent registers the pending run synchronously, so the wait always observes it. + // Returns the sender's start, bound to the run streamAgent registers. startRun: async () => { - const run = agentManager.streamAgent(snapshot.id, "start the run"); + const start = new ForegroundPromptStart(snapshot.id); + const run = agentManager.streamAgent(snapshot.id, "start the run", undefined, start); drained = (async () => { for await (const _event of run) { // Drain whatever the turn produces. } })().catch(() => undefined); + return { started: start.started }; }, cleanup: async () => { // Release any turn still held open, then close. The drain is deliberately not @@ -207,8 +210,8 @@ test("waiting for a run start outlasts the slowest provider startup budget", asy vi.useFakeTimers(); try { - await scenario.startRun(); - const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId); + const { started } = await scenario.startRun(); + const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started); let settled = false; const markSettled = () => { settled = true; @@ -233,8 +236,8 @@ test("waiting for a run start still gives up at the run start budget", async () vi.useFakeTimers(); try { - await scenario.startRun(); - const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId); + const { started } = await scenario.startRun(); + const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started); const rejection = expect(wait).rejects.toThrow( "codex run did not start within 60 seconds (phase: run start)", ); diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index dde5c02bbd..4cccd28be2 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -3,6 +3,7 @@ import type { Logger } from "pino"; import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js"; import type { AgentManager, ManagedAgent } from "./agent-manager.js"; +import { ForegroundPromptStart } from "./agent-run-state.js"; import type { AgentStorage } from "./agent-storage.js"; import { ensureAgentLoaded } from "./agent-loading.js"; import { isStaleProviderSessionError } from "./stale-provider-session-error.js"; @@ -23,7 +24,10 @@ export type AgentRunController = Pick< reloadAgentSession(agentId: string): Promise; }; +export class AgentTurnBusyError extends Error {} + export interface StartAgentRunOptions { + idleOnly?: boolean; /** Called after selecting the run, before consuming its events. */ onDispatch?: (disposition: PromptDispatchDisposition) => void; replaceRunning?: boolean; @@ -35,11 +39,17 @@ export interface StartAgentRunOptions { export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started"; +/** A dispatched prompt. A started turn carries its sender's start outcome. */ +export type PromptDispatchResult = + | { disposition: "turn_started"; started: Promise } + | { disposition: Exclude }; + async function steerOrReplaceActiveRun( agentManager: AgentRunController, agentId: string, prompt: AgentPromptInput, options: StartAgentRunOptions | undefined, + promptStart: ForegroundPromptStart, ): Promise< | { disposition: "steered" } | { @@ -54,7 +64,12 @@ async function steerOrReplaceActiveRun( const steerOptions = options.clearPendingPermissions ? { ...options.runOptions, clearPendingPermissions: true } : options.runOptions; - const result = await agentManager.steerOrReplaceActiveTurn(agentId, prompt, steerOptions); + const result = await agentManager.steerOrReplaceActiveTurn( + agentId, + prompt, + steerOptions, + promptStart, + ); if (result.status === "steered") { return { disposition: "steered" }; } @@ -69,14 +84,15 @@ async function startOrReplaceRun( agentId: string, prompt: AgentPromptInput, options: StartAgentRunOptions | undefined, + promptStart: ForegroundPromptStart, ): Promise<{ iterator: AsyncGenerator; replaced: boolean; }> { const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId)); const iterator = replaced - ? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions) - : agentManager.streamAgent(agentId, prompt, options?.runOptions); + ? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart) + : agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart); return { iterator, replaced }; } @@ -94,7 +110,7 @@ export async function startAgentRun( prompt: AgentPromptInput, logger: Logger, options?: StartAgentRunOptions, -): Promise<{ disposition: PromptDispatchDisposition }> { +): Promise { const snapshot = agentManager.getAgent(agentId); logger.trace( { @@ -115,16 +131,25 @@ export async function startAgentRun( options?.onDispatch?.("out_of_band"); return { disposition: "out_of_band" }; } + const promptStart = new ForegroundPromptStart(agentId); try { - await agentManager.reloadStalePluginSession(agentId); - return await startAgentRunInner(agentManager, agentId, prompt, logger, options); + try { + await agentManager.reloadStalePluginSession(agentId); + return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart); + } catch (error) { + if (!isStaleProviderSessionError(error)) throw error; + logger.info( + { agentId, err: error }, + "Provider session went stale; reopening from persistence", + ); + // The live session belongs to a retired plugin runtime. Reload swaps in a + // fresh session on the current runtime while preserving history and labels. + await agentManager.reloadAgentSession(agentId); + return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart); + } } catch (error) { - if (!isStaleProviderSessionError(error)) throw error; - logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence"); - // The live session belongs to a retired plugin runtime. Reload swaps in a - // fresh session on the current runtime while preserving history and labels. - await agentManager.reloadAgentSession(agentId); - return await startAgentRunInner(agentManager, agentId, prompt, logger, options); + promptStart.end(); + throw error; } } @@ -133,17 +158,23 @@ async function startAgentRunInner( agentId: string, prompt: AgentPromptInput, logger: Logger, - options?: StartAgentRunOptions, -): Promise<{ disposition: PromptDispatchDisposition }> { + options: StartAgentRunOptions | undefined, + promptStart: ForegroundPromptStart, +): Promise { const snapshot = agentManager.getAgent(agentId); - const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options); + const steered = options?.idleOnly + ? null + : await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart); + if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) { + throw new AgentTurnBusyError(`Agent ${agentId} is running`); + } if (steered?.disposition === "steered") { options?.onDispatch?.("steered"); return steered; } const { iterator, replaced } = steered ? { iterator: steered.iterator, replaced: true } - : await startOrReplaceRun(agentManager, agentId, prompt, options); + : await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart); logger.trace( { agentId, @@ -165,7 +196,7 @@ async function startAgentRunInner( "Provider session went stale; reopening from persistence", ); await agentManager.reloadAgentSession(agentId); - const retry = await startOrReplaceRun(agentManager, agentId, prompt, options); + const retry = await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart); await drainAgentRunIterator(retry.iterator); } logger.trace( @@ -187,9 +218,11 @@ async function startAgentRunInner( "agent.session.iterator.error", ); logger.error({ err: error, agentId }, "Agent stream failed"); + } finally { + promptStart.end(); } })(); - return { disposition: "turn_started" }; + return { disposition: "turn_started", started: promptStart.started }; } /** @@ -210,6 +243,9 @@ export async function unarchiveAgentState( } export interface SendPromptToAgentParams { + idleOnly?: boolean; + /** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */ + beforeDispatch?: () => Promise; onDispatch?: StartAgentRunOptions["onDispatch"]; agentManager: AgentManager; agentStorage: AgentStorage; @@ -259,8 +295,9 @@ export interface StartCreatedAgentInitialPromptParams { const AGENT_RUN_START_TIMEOUT_MS = 60_000; export async function waitForAgentRunStartWithTimeout( - agentManager: AgentManager, + agentManager: Pick, agentId: string, + started: Promise, signal?: AbortSignal, ): Promise { const provider = agentManager.getAgent(agentId)?.provider ?? "provider"; @@ -275,15 +312,28 @@ export async function waitForAgentRunStartWithTimeout( AGENT_RUN_START_TIMEOUT_MS, ); + const abortSignal = signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal; + let onAbort: (() => void) | null = null; + const aborted = new Promise((_, reject) => { + onAbort = () => reject(createStartAbortError(abortSignal.reason)); + if (abortSignal.aborted) onAbort(); + else abortSignal.addEventListener("abort", onAbort, { once: true }); + }); try { - await agentManager.waitForAgentRunStart(agentId, { - signal: signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal, - }); + await Promise.race([started, aborted]); } finally { clearTimeout(startTimeout); + if (onAbort) abortSignal.removeEventListener("abort", onAbort); } } +function createStartAbortError(reason: unknown): Error { + let message = "wait_for_agent_start aborted"; + if (typeof reason === "string") message = reason; + else if (reason instanceof Error) message = reason.message; + return Object.assign(new Error(message), { name: "AbortError" }); +} + async function resolvePromptSource( source: AgentPromptSource | undefined, manager: Pick, @@ -309,7 +359,7 @@ async function resolvePromptSource( */ export async function sendPromptToAgent( params: SendPromptToAgentParams, -): Promise<{ disposition: PromptDispatchDisposition }> { +): Promise { const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage); const delivery = prepareAgentMessage(params.prompt, source, params.messageId); return sendPreparedPromptToAgent({ @@ -324,14 +374,14 @@ export async function sendPromptToAgent( /** Dispatch daemon-prepared context without reclassifying it as human input. */ export async function sendPreparedPromptToAgent( params: Omit, -): Promise<{ disposition: PromptDispatchDisposition }> { +): Promise { const unarchive = params.unarchive ?? true; const record = await params.agentStorage.get(params.agentId); let archivedAtToRestore: string | null = null; if (record?.archivedAt) { if (!unarchive) { - return { disposition: "turn_started" }; + return { disposition: "turn_started", started: Promise.resolve() }; } if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) { archivedAtToRestore = record.archivedAt; @@ -353,12 +403,17 @@ export async function sendPreparedPromptToAgent( throw error; } + if (params.idleOnly && params.agentManager.hasInFlightRun(params.agentId)) { + throw new AgentTurnBusyError(`Agent ${params.agentId} is running`); + } if (params.sessionMode) { await params.agentManager.setAgentMode(params.agentId, params.sessionMode); } + await params.beforeDispatch?.(); return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, { - replaceRunning: true, + replaceRunning: !params.idleOnly, + idleOnly: params.idleOnly, onDispatch: params.onDispatch, activeTurnBehavior: params.activeTurnBehavior, clearPendingPermissions: params.clearPendingPermissions, @@ -392,7 +447,11 @@ export async function startCreatedAgentInitialPrompt( ); if (dispatchResult.disposition === "turn_started") { - await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId); + await waitForAgentRunStartWithTimeout( + params.agentManager, + params.agentId, + dispatchResult.started, + ); } const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null; diff --git a/packages/server/src/server/agent/agent-run-state.ts b/packages/server/src/server/agent/agent-run-state.ts index 0ea85f6d81..3408fac978 100644 --- a/packages/server/src/server/agent/agent-run-state.ts +++ b/packages/server/src/server/agent/agent-run-state.ts @@ -13,7 +13,7 @@ export interface ForegroundTurnWaiter { type ForegroundRunStart = | { status: "pending" } | { status: "started"; turnId: string } - | { status: "failed"; error: string }; + | { status: "failed"; error: string; stale?: true }; export interface PendingForegroundRun { token: string; @@ -343,3 +343,59 @@ function settleTrackedRun(run: TrackedAgentRun): void { run.settled = true; run.resolveSettled(); } + +/** + * Follows one sender's prompt to the foreground run that starts it. Each run created for the + * prompt, including a stale-session retry, is bound here, so `started` settles for this + * sender's prompt and never for another run the agent tracks. + */ +export class ForegroundPromptStart { + readonly started: Promise; + private resolveStarted!: () => void; + private rejectStarted!: (error: Error) => void; + private run: PendingForegroundRun | null = null; + private done = false; + + constructor(private readonly agentId: string) { + this.started = new Promise((resolve, reject) => { + this.resolveStarted = resolve; + this.rejectStarted = reject; + }); + // Steered and fire-and-forget dispatches never wait on the start. + this.started.catch(() => undefined); + } + + /** A run was created for this prompt. */ + bind(run: PendingForegroundRun): void { + this.run = run; + void Promise.race([run.turnStartedPromise, run.settledPromise]).then(() => + this.settle(run, { ended: false }), + ); + } + + /** The prompt's dispatch is over; no further run will be created for it. */ + end(): void { + this.settle(this.run, { ended: true }); + } + + private settle(run: PendingForegroundRun | null, { ended }: { ended: boolean }): void { + if (this.done || run !== this.run) return; + if (run?.start.status === "started") { + this.done = true; + this.resolveStarted(); + return; + } + // A stale-session failure is retried with a new run; wait for it unless dispatch ended. + if (run?.start.status === "failed" && run.start.stale && !ended) return; + this.done = true; + this.rejectStarted(new Error(this.describeUnstarted(run))); + } + + private describeUnstarted(run: PendingForegroundRun | null): string { + if (run?.start.status === "failed") return run.start.error; + if (run?.settled) { + return `Agent ${this.agentId} run was canceled before its turn started; its prompt was not delivered`; + } + return `Agent ${this.agentId} run finished before starting`; + } +} diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 0267876d0d..ad7f97b834 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -528,6 +528,14 @@ export type AgentPermissionResponse = interrupt?: boolean; }; +/** A requested turn was canceled before the provider accepted it. */ +export class AgentTurnStartCanceledError extends Error { + constructor() { + super("Turn was canceled before starting"); + this.name = "AgentTurnStartCanceledError"; + } +} + export interface AgentRunResult { sessionId: string; finalText: string; @@ -621,6 +629,8 @@ export interface AgentSessionConfig { * persisted into agent config so daemon setting changes apply cleanly. */ daemonAppendSystemPrompt?: string; + /** Plugin instructions for this launch; never persisted. */ + pluginAppendSystemPrompt?: string[]; modeId?: string; model?: string; thinkingOptionId?: string; @@ -636,6 +646,8 @@ export interface AgentSessionConfig { } export interface AgentLaunchContext { + /** Launch-only instructions contributed by plugins. */ + appendSystemPrompt?: string[]; /** Launch-only plugin MCP servers and their owners; never persisted. */ mcpServers?: Record; mcpServerOwners?: Record; @@ -688,6 +700,8 @@ export interface AgentUsageSession { } export interface AgentSession { + /** Persist the session's current handle immediately after an interactive resume. */ + readonly persistenceUpdatedOnResume?: boolean; usageSession?(): AgentUsageSession | null; readonly provider: AgentProvider; readonly id: string | null; diff --git a/packages/server/src/server/agent/agent-timeline-content.ts b/packages/server/src/server/agent/agent-timeline-content.ts index 5117073e14..4f9cc8f690 100644 --- a/packages/server/src/server/agent/agent-timeline-content.ts +++ b/packages/server/src/server/agent/agent-timeline-content.ts @@ -1,5 +1,6 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; +import { PluginIdSchema } from "@getpaseo/protocol/plugin-config"; export const PLUGIN_TIMELINE_DATA_MAX_BYTES = 64 * 1024; @@ -14,6 +15,15 @@ const MARKER_COST = 32; const SHORT_STRING = 1024; const MAX_DEPTH = 64; +// The app registers renderer kinds under the plugin ID rule, so stored kinds must use that format. +export function assertPluginTimelineKind(kind: string): void { + if (!PluginIdSchema.safeParse(kind).success) { + throw new Error( + `Plugin timeline item kind must start with a lowercase letter and contain only lowercase letters, digits, and dashes: ${JSON.stringify(kind)}`, + ); + } +} + export function assertPluginTimelineDataSize(data: JsonValue): void { const serializedBytes = Buffer.byteLength(JSON.stringify(data), "utf8"); if (serializedBytes > PLUGIN_TIMELINE_DATA_MAX_BYTES) { diff --git a/packages/server/src/server/agent/background-work/index.ts b/packages/server/src/server/agent/background-work/index.ts index 3290f13503..90df243bb2 100644 --- a/packages/server/src/server/agent/background-work/index.ts +++ b/packages/server/src/server/agent/background-work/index.ts @@ -14,55 +14,137 @@ export interface AgentBackgroundWorkItem extends AgentBackgroundWorkInput { stopToken?: string; } +export interface HeartbeatBackgroundWorkInput { + agentId: string; + scheduleId: string; + name: string | null; + createdAt: string; + stop: () => Promise; +} + +interface HeartbeatBackgroundWork { + item: AgentBackgroundWorkItem; + stop: HeartbeatBackgroundWorkInput["stop"]; +} + +const HEARTBEAT_ID_PREFIX = "heartbeat:"; +const PROVIDER_ID_ESCAPE = "provider:"; + +export function isHeartbeatBackgroundWorkItem(item: { id: string }): boolean { + return item.id.startsWith(HEARTBEAT_ID_PREFIX); +} + +function encodeProviderItemId(id: string): string { + // Preserve existing wire IDs outside the reserved namespaces. + return id.startsWith(HEARTBEAT_ID_PREFIX) || id.startsWith(PROVIDER_ID_ESCAPE) + ? PROVIDER_ID_ESCAPE + id + : id; +} + /** - * Live background work per agent. Providers report the whole list on every change, so `apply` - * replaces it. `startedAt` is stamped the first time an id is seen and kept while it stays listed. - * Nothing is persisted; providers determine when their live inventory is no longer available. + * Live inventory per agent. Providers replace their entire contribution with `apply`. + * The scheduler publishes heartbeats individually and retains ownership across provider closure. */ export class AgentBackgroundWorkStore { - private readonly items = new Map(); + private readonly providerItems = new Map(); + private readonly heartbeats = new Map>(); apply( agentId: string, inputs: readonly AgentBackgroundWorkInput[], timestamp: string = new Date().toISOString(), ): AgentBackgroundWorkItem[] | null { - const known = this.items.has(agentId); - const previous = this.items.get(agentId) ?? []; - const previousById = new Map(previous.map((item) => [item.id, item])); + const previous = this.providerItems.get(agentId); + const previousById = new Map(previous?.map((item) => [item.id, item])); const seen = new Set(); const next: AgentBackgroundWorkItem[] = []; for (const input of inputs) { - if (seen.has(input.id)) continue; - seen.add(input.id); + const id = encodeProviderItemId(input.id); + if (seen.has(id)) continue; + seen.add(id); next.push({ - id: input.id, + id, kind: input.kind, description: input.description, ...(input.command ? { command: input.command } : {}), ...(input.canStop - ? { canStop: true, stopToken: previousById.get(input.id)?.stopToken ?? randomUUID() } + ? { canStop: true, stopToken: previousById.get(id)?.stopToken ?? randomUUID() } : {}), - startedAt: previousById.get(input.id)?.startedAt ?? timestamp, + startedAt: previousById.get(id)?.startedAt ?? timestamp, }); } - if (known && sameItems(previous, next)) return null; - this.items.set(agentId, next); - return [...next]; + if (previous && sameItems(previous, next)) return null; + this.providerItems.set(agentId, next); + return this.list(agentId); + } + + setHeartbeat({ + agentId, + scheduleId, + name, + createdAt, + stop, + }: HeartbeatBackgroundWorkInput): AgentBackgroundWorkItem[] | null { + const id = HEARTBEAT_ID_PREFIX + scheduleId; + const heartbeats = this.heartbeats.get(agentId) ?? new Map(); + const previous = heartbeats.get(id)?.item; + const item: AgentBackgroundWorkItem = { + id, + kind: "heartbeat", + description: name, + startedAt: createdAt, + canStop: true, + stopToken: previous?.stopToken ?? randomUUID(), + }; + heartbeats.set(id, { item, stop }); + this.heartbeats.set(agentId, heartbeats); + return previous?.description === name && previous.startedAt === createdAt + ? null + : this.list(agentId); + } + + removeHeartbeat(agentId: string, scheduleId: string): AgentBackgroundWorkItem[] | null { + const heartbeats = this.heartbeats.get(agentId); + if (!heartbeats?.delete(HEARTBEAT_ID_PREFIX + scheduleId)) return null; + if (heartbeats.size === 0) this.heartbeats.delete(agentId); + return this.list(agentId); + } + + async stopHeartbeat(agentId: string, itemId: string, stopToken: string): Promise { + const heartbeat = this.heartbeats.get(agentId)?.get(itemId); + if (!heartbeat || heartbeat.item.stopToken !== stopToken) { + throw new Error("Background work is no longer available to stop"); + } + await heartbeat.stop(); + } + + authorizeProviderStop(agentId: string, itemId: string, stopToken: string): string { + const item = this.providerItems.get(agentId)?.find(({ id }) => id === itemId); + if (!item?.canStop || item.stopToken !== stopToken) { + throw new Error("Background work is no longer available to stop"); + } + return itemId.startsWith(PROVIDER_ID_ESCAPE) ? itemId.slice(PROVIDER_ID_ESCAPE.length) : itemId; } list(agentId: string): AgentBackgroundWorkItem[] { - return [...(this.items.get(agentId) ?? [])]; + const items = [...(this.providerItems.get(agentId) ?? [])]; + for (const { item } of this.heartbeats.get(agentId)?.values() ?? []) { + items.push(item); + } + return items; } summary(agentId: string): { count: number } | undefined { - const items = this.items.get(agentId); - return items ? { count: items.length } : undefined; + const items = this.providerItems.get(agentId); + const heartbeats = this.heartbeats.get(agentId); + return items || heartbeats + ? { count: (items?.length ?? 0) + (heartbeats?.size ?? 0) } + : undefined; } clear(agentId: string): AgentBackgroundWorkItem[] | null { - if (!this.items.delete(agentId)) return null; - return []; + if (!this.providerItems.delete(agentId)) return null; + return this.list(agentId); } } diff --git a/packages/server/src/server/agent/create-agent/create.test.ts b/packages/server/src/server/agent/create-agent/create.test.ts index 4943628b17..b27b3c7c8a 100644 --- a/packages/server/src/server/agent/create-agent/create.test.ts +++ b/packages/server/src/server/agent/create-agent/create.test.ts @@ -10,6 +10,7 @@ import { AgentManager } from "../agent-manager.js"; import { AgentStorage } from "../agent-storage.js"; import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js"; import { createAgentCommand } from "./create.js"; +import { ForegroundPromptStart } from "../agent-run-state.js"; import type { ManagedAgent } from "../agent-manager.js"; const logger = createTestLogger(); @@ -89,9 +90,12 @@ test("session create forwards clientMessageId to the initial prompt run options" firstAgentContext: { attachments: [] }, }); - expect(streamAgent).toHaveBeenCalledWith("agent-1", "hello from create", { - clientMessageId: "msg-create-1", - }); + expect(streamAgent).toHaveBeenCalledWith( + "agent-1", + "hello from create", + { clientMessageId: "msg-create-1" }, + expect.any(ForegroundPromptStart), + ); }); test("session create validates the requested mode against the provider's modes", async () => { diff --git a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts index 9e18f87948..acd44998b5 100644 --- a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts +++ b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts @@ -498,3 +498,26 @@ test("finish recovery protects callers before durable intent has loaded", async expect(recovered.hasPendingForCaller("parent")).toBe(true); expect(recovered.hasPendingForCaller("unrelated")).toBe(false); }); + +test("an undispatched follow-up does not block the running child's permission notification", async () => { + const state = await scenario(); + await state.service.register(intent); + await until(() => state.observation.waits.length === 1); + await state.service.register(intent, true); + const result = outcome("running"); + result.status = "permission"; + result.final!.pendingPermissions = [ + { + id: "approval", + provider: "codex", + name: "Bash", + kind: "tool", + input: { command: "run tests" }, + } as NonNullable["pendingPermissions"][number], + ]; + state.observation.waits[0]!.result.resolve(result); + await until(() => state.delivery.prompts.length === 1); + expect(state.delivery.prompts[0]).toContain("needs permission"); + expect(state.delivery.prompts[0]).toContain("approval"); + expect(await state.store.list()).toHaveLength(2); +}); diff --git a/packages/server/src/server/agent/finish-subscriptions/index.ts b/packages/server/src/server/agent/finish-subscriptions/index.ts index 22324f0ecc..226ed5af51 100644 --- a/packages/server/src/server/agent/finish-subscriptions/index.ts +++ b/packages/server/src/server/agent/finish-subscriptions/index.ts @@ -267,7 +267,9 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio continue; } if (signal.aborted) return; - await decisions(group); + // A queued follow-up cannot start until the current permission is answered. + // Its pending registration must not hold the running turn's checkpoint. + if (pending.status !== "permission" || watch.pending) await decisions(group); if (signal.aborted) return; if (await suppressed(record, pending)) { await remove(watch); diff --git a/packages/server/src/server/agent/host-operations/index.test.ts b/packages/server/src/server/agent/host-operations/index.test.ts index fbd492e881..bc54209e60 100644 --- a/packages/server/src/server/agent/host-operations/index.test.ts +++ b/packages/server/src/server/agent/host-operations/index.test.ts @@ -107,11 +107,17 @@ async function olderHost() { return { client, socket }; } -function resolverFor(client: DaemonClient, callerBackground: boolean) { +interface Caller { + background: boolean; + provider: string; + currentModeId: string | null; +} + +function resolverFor(client: DaemonClient, caller: Caller | null) { return createHostResolver({ serverId: "origin", - callerAgentId: "caller", - caller: () => ({ background: callerBackground }), + callerAgentId: caller ? "caller" : undefined, + caller: () => caller, local: {} as HostOperations, hosts: () => ({ directory: async () => ({ self: { serverId: "origin", label: "Origin" }, hosts: [] }), @@ -120,6 +126,12 @@ function resolverFor(client: DaemonClient, callerBackground: boolean) { }); } +const visibleCodexCaller: Caller = { + background: false, + provider: "codex", + currentModeId: "full-access", +}; + const createArgs = { workspaceId: workspace.id, provider: "codex/gpt-5.4", @@ -129,7 +141,7 @@ const createArgs = { test("a visible caller still creates agents on a host without background agents", async () => { const { client, socket } = await olderHost(); - const creating = resolverFor(client, false).use("srv_older", (host) => + const creating = resolverFor(client, visibleCodexCaller).use("srv_older", (host) => host.createAgent(createArgs, {} as never), ); creating.catch(() => {}); @@ -143,7 +155,37 @@ test("a background caller's remote child asks the host to update instead of turn const { client, socket } = await olderHost(); await expect( - resolverFor(client, true).use("srv_older", (host) => host.createAgent(createArgs, {} as never)), + resolverFor(client, { ...visibleCodexCaller, background: true }).use("srv_older", (host) => + host.createAgent(createArgs, {} as never), + ), ).rejects.toThrow("Update the host to use background agents."); expect(socket.requests.map((request) => request.type)).not.toContain("create_agent_request"); }); + +async function forwardedMode(caller: Caller | null, args: Record = createArgs) { + const { client, socket } = await olderHost(); + const creating = resolverFor(client, caller).use("srv_older", (host) => + host.createAgent(args, {} as never), + ); + creating.catch(() => {}); + const request = (await socket.createRequest()) as { config: { modeId?: string } }; + return request.config.modeId; +} + +test("a remote child of the same provider starts in its caller's mode", async () => { + expect(await forwardedMode(visibleCodexCaller)).toBe("full-access"); +}); + +test("an explicit mode wins over the caller's mode on a remote host", async () => { + expect( + await forwardedMode(visibleCodexCaller, { ...createArgs, settings: { modeId: "auto" } }), + ).toBe("auto"); +}); + +test("a remote child of another provider leaves its mode to the host", async () => { + expect(await forwardedMode({ ...visibleCodexCaller, provider: "claude" })).toBeUndefined(); +}); + +test("a remote create without a caller agent leaves its mode to the host", async () => { + expect(await forwardedMode(null)).toBeUndefined(); +}); diff --git a/packages/server/src/server/agent/host-operations/index.ts b/packages/server/src/server/agent/host-operations/index.ts index f6ae774375..93b7ad2233 100644 --- a/packages/server/src/server/agent/host-operations/index.ts +++ b/packages/server/src/server/agent/host-operations/index.ts @@ -203,8 +203,8 @@ export function createHostResolver(input: { local: HostOperations; hosts: () => ToolHosts; callerAgentId?: string; - /** The destination can't see the caller, so its background defaults resolve before routing. */ - caller: () => BackgroundCaller | null; + /** The destination can't see the caller, so its background and mode defaults resolve before routing. */ + caller: () => (BackgroundCaller & { provider: string; currentModeId: string | null }) | null; lockedCwd?: string; }) { return { @@ -222,6 +222,11 @@ export function createHostResolver(input: { async createAgent(args) { const parsed = remoteCreate.parse(args); const { provider, model } = resolveRequiredProviderModel(parsed.provider); + const caller = input.caller(); + // Same-provider children inherit the caller's mode, as they would on the same host. + const modeId = + parsed.settings?.modeId ?? + (caller?.provider === provider ? (caller.currentModeId ?? undefined) : undefined); const workspace = await client.findWorkspace(parsed.workspaceId); if (!workspace) throw new Error(`Workspace ${parsed.workspaceId} not found`); const labels = { @@ -236,15 +241,13 @@ export function createHostResolver(input: { model, cwd: workspace.workspaceDirectory, title: parsed.title, - modeId: parsed.settings?.modeId, + modeId, thinkingOptionId: parsed.settings?.thinkingOptionId, featureValues: parsed.settings?.features, }, workspaceId: parsed.workspaceId, // Older hosts reject any background with a workspaceId, so a visible create omits it. - ...(inheritAgentBackground(parsed.background, input.caller()) - ? { background: true } - : {}), + ...(inheritAgentBackground(parsed.background, caller) ? { background: true } : {}), labels, initialPrompt: parsed.initialPrompt, idempotencyKey: parsed.idempotencyKey, @@ -295,7 +298,7 @@ export function createHostResolver(input: { status: agent.status, guidance: receipt.deliveryStatus === "queued" - ? "Queued for delivery after two quiet seconds. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false." + ? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false." : "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.", }); }, diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 6d267ff53a..071084b1fa 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -1,3 +1,4 @@ +import { AgentRunState, ForegroundPromptStart } from "./agent-run-state.js"; import { createFinishSubscriptions, createFinishObservation, @@ -172,11 +173,12 @@ function registeredTool( async function invokeToolWithParsedInput( tool: RegisteredMcpToolWithHandler, input: Record, + awaitDispatch = true, ) { const parsed = await tool.inputSchema.safeParseAsync(input); expect(parsed.success).toBe(true); const response = await tool.handler(parsed.data); - if (response.structuredContent.deliveryStatus === "queued") { + if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") { await toolDeliveries .get(tool)! .waitForDispatch(input.agentId as string, new AbortController().signal); @@ -264,6 +266,7 @@ function buildAgentManagerSpies() { archiveAgent: vi.fn().mockResolvedValue({ archivedAt: new Date().toISOString() }), notifyAgentState: vi.fn(), getAgent: vi.fn(), + getAgentBackgroundWorkSummary: vi.fn().mockReturnValue(undefined), listAgents: vi.fn().mockReturnValue([]), getTimeline: vi.fn().mockReturnValue([]), resumeAgentFromPersistence: vi.fn(), @@ -274,11 +277,19 @@ function buildAgentManagerSpies() { effectiveOptionsFor: (_provider: string, own?: Record) => own ?? {}, reloadStalePluginSession: async () => {}, hasInFlightRun: vi.fn().mockReturnValue(false), + hasPendingPermissions: () => false, steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }), tryRunOutOfBand: vi.fn().mockReturnValue(false), subscribe: vi.fn().mockReturnValue(() => {}), - streamAgent: vi.fn(() => (async function* noop() {})()), - waitForAgentRunStart: vi.fn().mockResolvedValue(undefined), + streamAgent: vi.fn( + (agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => { + const runs = new AgentRunState(); + const run = runs.createPendingRun(agentId); + runs.settleForegroundStart(run, { status: "started", turnId: `${agentId}-turn` }); + start?.bind(run); + return (async function* noop() {})(); + }, + ), respondToPermission: vi.fn(), cancelAgentRun: vi.fn(), getPendingPermissions: vi.fn(), @@ -623,6 +634,12 @@ class FakeBrowserToolsBroker { } class BoundaryAgentManagerFake { + subscribe() { + return () => {}; + } + hasPendingPermissions() { + return false; + } public getPluginTools(): [] { return []; } @@ -877,8 +894,9 @@ function createPaseoWorktreeForMcpTest(options: { async function createAgentMcpServer( options: Parameters[0], subscriptionStore?: FinishSubscriptionStore, + schedule?: (delayMs: number, callback: () => void) => () => void, ) { - const messages = createTestAgentMessages(options); + const messages = createTestAgentMessages({ ...options, schedule }); const records = new Map(); const subscriptions = createFinishSubscriptions({ store: subscriptionStore ?? { @@ -3677,15 +3695,15 @@ class HeldTurnAgentClient implements AgentClient { describe("send_agent_prompt MCP tool", () => { it.each([ - { agentScoped: true, behavior: undefined, available: true, steered: true }, - { agentScoped: true, behavior: "interrupt", available: true, steered: false }, - { agentScoped: true, behavior: "steer", available: true, steered: true }, - { agentScoped: false, behavior: undefined, available: true, steered: false }, - { agentScoped: false, behavior: "steer", available: true, steered: true }, - { agentScoped: true, behavior: undefined, available: false, steered: false }, + { agentScoped: true, behavior: undefined, available: true }, + { agentScoped: true, behavior: "interrupt", available: true }, + { agentScoped: true, behavior: "steer", available: true }, + { agentScoped: false, behavior: undefined, available: true }, + { agentScoped: false, behavior: "steer", available: true }, + { agentScoped: true, behavior: undefined, available: false }, ] as const)( "dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available", - async ({ agentScoped, behavior, available, steered }) => { + async ({ agentScoped, behavior, available }) => { const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); const storage = new AgentStorage(join(workdir, "agents"), logger); const client = new HeldTurnAgentClient("codex", true, { @@ -3717,18 +3735,33 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, }); const originalTurn = manager.getAgent(child.id)!.activeTurnId; - const response = await invokeToolWithParsedInput(tool, { - agentId: child.id, - prompt: "New message", - notifyOnFinish: false, - ...(behavior ? { activeTurnBehavior: behavior } : {}), - }); + const queued = agentScoped && behavior !== "interrupt"; + const steered = !agentScoped && behavior === "steer"; + const response = await invokeToolWithParsedInput( + tool, + { + agentId: child.id, + prompt: "New message", + notifyOnFinish: false, + ...(behavior ? { activeTurnBehavior: behavior } : {}), + }, + !queued, + ); expect(response.structuredContent).toMatchObject({ success: true, ...(agentScoped ? { deliveryStatus: "queued" } : { disposition: steered ? "steered" : "turn_started" }), }); + if (queued) { + expect(client.sessions[1]!.prompts).toHaveLength(1); + expect(client.sessions[1]!.steeredPrompts).toEqual([]); + expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn); + client.sessions[1]!.finishTurn(); + await serverDeliveries + .get(server)! + .waitForDispatch(child.id, new AbortController().signal); + } expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2); expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0); expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered); @@ -3740,18 +3773,16 @@ describe("send_agent_prompt MCP tool", () => { it.each([ { rejected: false, priorNotification: false }, - { rejected: true, priorNotification: false }, { rejected: false, priorNotification: true }, + { rejected: true, priorNotification: false }, + { rejected: true, priorNotification: true }, ])( - "buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)", + "keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)", async ({ rejected, priorNotification }) => { - const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); + const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-")); const storage = new AgentStorage(join(workdir, "agents"), logger); - const client = new HeldTurnAgentClient("codex", true, { - steerResult: "accepted", - finishDuringSteer: true, - rejectSteer: rejected, - }); + const options: HeldTurnOptions = {}; + const client = new HeldTurnAgentClient("codex", true, options); const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); let mcpClient: Client | undefined; try { @@ -3773,104 +3804,47 @@ describe("send_agent_prompt MCP tool", () => { logger, }); mcpClient = await connectInMemoryMcpClient(server); - const send = (input: Record) => - sendMcpAndAwaitDispatch(mcpClient!, server, input); - await send({ + await sendMcpAndAwaitDispatch(mcpClient, server, { agentId: child.id, prompt: "Original work", notifyOnFinish: priorNotification, }); - const sending = send({ - agentId: child.id, - prompt: "New message", - notifyOnFinish: true, + const session = client.sessions[1]!; + const release = session.holdTurnStart(); + options.finishTurnsDuringStart = true; + if (rejected) session.rejectNextTurnStart(new Error("Start rejected")); + const response = await mcpClient.callTool({ + name: "send_agent_prompt", + arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true }, }); - if (rejected) { - await expect(sending).rejects.toThrow("Steer rejected"); - // Flush asynchronous notification work before checking that a rejected - // dispatch did not notify. Then prove a later successful send still can. - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(client.sessions[0]!.prompts).toHaveLength(0); - await send({ - agentId: child.id, - prompt: "Retry after rejection", + expect(response.structuredContent).toMatchObject({ + success: true, + deliveryStatus: "queued", + }); + const dispatch = serverDeliveries + .get(server)! + .waitForDispatch(child.id, new AbortController().signal); + const rejectedDispatch = rejected + ? expect(dispatch).rejects.toThrow("Start rejected") + : null; + expect(client.sessions[0]!.prompts).toHaveLength(0); + session.finishTurn(); + await vi.waitFor(() => expect(session.prompts).toHaveLength(2)); + expect(client.sessions[0]!.prompts).toHaveLength(0); + release(); + if (rejectedDispatch) await rejectedDispatch; + else await dispatch; + if (!rejected || priorNotification) { + await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), { + timeout: 5000, + }); + expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({ + source: { kind: "agent-notification", agentId: child.id, event: "finished" }, }); - client.sessions[1]!.finishTurn(); } else { - const response = await sending; - expect(response.structuredContent).toMatchObject({ - success: true, - deliveryStatus: "queued", - }); - } - await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1)); - expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({ - source: { kind: "agent-notification", agentId: child.id, event: "finished" }, - }); - } finally { - await mcpClient?.close(); - await removeAgentStateDir(manager, storage, workdir); - } - }, - ); - - it.each([false, true])( - "preserves the original notification after rejection (completion during send: %s)", - async (finishDuringSteer) => { - const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); - const storage = new AgentStorage(join(workdir, "agents"), logger); - const client = new HeldTurnAgentClient("codex", true, { - steerResult: "accepted", - finishDuringSteer, - rejectSteer: true, - }); - const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); - let mcpClient: Client | undefined; - try { - const parent = await manager.createAgent( - { provider: "codex", cwd: existingCwd }, - undefined, - { - workspaceId: "wks_parent", - }, - ); - const child = await manager.createAgent( - { provider: "codex", cwd: existingCwd }, - undefined, - { - workspaceId: "wks_parent", - }, - ); - const server = await createAgentMcpServer({ - agentManager: manager, - agentStorage: storage, - callerAgentId: parent.id, - providerSnapshotManager: createOpenCodeManager().manager, - logger, - }); - mcpClient = await connectInMemoryMcpClient(server); - const send = (input: Record) => - sendMcpAndAwaitDispatch(mcpClient!, server, input); - await send({ - agentId: child.id, - prompt: "Original work", - notifyOnFinish: true, - }); - const sending = send({ - agentId: child.id, - prompt: "New message", - notifyOnFinish: true, - }); - await expect(sending).rejects.toThrow("Steer rejected"); - if (!finishDuringSteer) { - await new Promise((resolve) => setTimeout(resolve, 50)); + await serverSubscriptions.get(server)!.close(); expect(client.sessions[0]!.prompts).toHaveLength(0); - client.sessions[1]!.finishTurn(); } - await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1)); - expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({ - source: { kind: "agent-notification", agentId: child.id, event: "finished" }, - }); } finally { await mcpClient?.close(); await removeAgentStateDir(manager, storage, workdir); @@ -4012,7 +3986,7 @@ describe("send_agent_prompt MCP tool", () => { const response = await tool.handler(parsed.data as Record); expect(response.structuredContent).toMatchObject({ deliveryStatus: "queued" }); - expect(spies.agentManager.subscribe).not.toHaveBeenCalled(); + expect(serverSubscriptionRecords.get(server)!.size).toBe(1); await serverDeliveries .get(server)! .waitForDispatch("child-agent", new AbortController().signal); @@ -4053,7 +4027,7 @@ describe("send_agent_prompt MCP tool", () => { await tool.handler(parsed.data as Record); - expect(spies.agentManager.subscribe).not.toHaveBeenCalled(); + expect(serverSubscriptionRecords.get(server)!.size).toBe(0); expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled(); }); @@ -4096,7 +4070,7 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, }); - expect(spies.agentManager.subscribe).not.toHaveBeenCalled(); + expect(serverSubscriptionRecords.get(server)!.size).toBe(0); expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled(); }); @@ -4220,11 +4194,15 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, }); if (scenario !== "startup_failure") { - const response = await invokeToolWithParsedInput(tool, { - agentId: child.id, - prompt: "/side-command", - activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer", - }); + const response = await invokeToolWithParsedInput( + tool, + { + agentId: child.id, + prompt: "/side-command", + activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer", + }, + scenario !== "out_of_band", + ); expect(response.structuredContent).toMatchObject({ success: true, deliveryStatus: "queued", @@ -4236,6 +4214,9 @@ describe("send_agent_prompt MCP tool", () => { }); expect(parentClient.sessions[0]!.prompts).toHaveLength(0); childClient.sessions[0]!.finishTurn("Ongoing task done"); + await serverDeliveries + .get(server)! + .waitForDispatch(child.id, new AbortController().signal); await vi.waitFor(() => { expect(parentClient.sessions[0]!.prompts).toHaveLength(1); expect(parentClient.sessions[0]!.prompts[0]).toContain("finished."); @@ -4243,7 +4224,11 @@ describe("send_agent_prompt MCP tool", () => { } else { childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start")); await expect( - invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }), + invokeToolWithParsedInput(tool, { + agentId: child.id, + prompt: "Replacement task", + activeTurnBehavior: "interrupt", + }), ).rejects.toThrow("Requested turn could not start"); // A later real turn must not inherit a subscription from the rejected dispatch. await invokeToolWithParsedInput(tool, { @@ -4354,6 +4339,7 @@ describe("send_agent_prompt MCP tool", () => { const sent = await invokeToolWithParsedInput(registeredTool(server, "send_agent_prompt"), { agentId: childId, prompt: "Stop and reply instead", + activeTurnBehavior: "interrupt", }); expect(sent.structuredContent).toMatchObject({ success: true, @@ -4517,7 +4503,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => { const logger = createTestLogger(); const existingCwd = process.cwd(); - async function setupOmpChild() { + async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) { const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-")); const storage = new AgentStorage(join(workdir, "agents"), logger); const parentClient = new HeldTurnAgentClient("claude", false); @@ -4545,13 +4531,17 @@ describe("send_agent_prompt MCP tool to an OMP child", () => { undefined, { workspaceId: "wks_parent" }, ); - const server = await createAgentMcpServer({ - agentManager, - agentStorage: storage, - callerAgentId: parent.id, - providerSnapshotManager: createOpenCodeManager().manager, - logger, - }); + const server = await createAgentMcpServer( + { + agentManager, + agentStorage: storage, + callerAgentId: parent.id, + providerSnapshotManager: createOpenCodeManager().manager, + logger, + }, + undefined, + schedule, + ); return { agentManager, storage, @@ -4581,37 +4571,63 @@ describe("send_agent_prompt MCP tool to an OMP child", () => { { command: "follow-up", streamingBehavior: "followUp" }, { command: "steer", streamingBehavior: "steer" }, ] as const)( - "delivers /$command into a turn OMP started on its own, without aborting it", + "delivers /$command to a running OMP child while ordinary messages in the same quiet window wait", async ({ command, streamingBehavior }) => { - const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } = - await setupOmpChild(); + let flush!: () => void; + const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild( + (_delay, callback) => { + flush = callback; + return () => {}; + }, + ); try { ompSession.beginTurn(); ompSession.streamAssistantText("background job finished, working on it"); await vi.waitFor(() => { expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/); }); - - const response = await invokeToolWithParsedInput(tool, { - agentId: childId, - prompt: `/${command} then summarize the logs`, - }); - - expect(response.structuredContent).toMatchObject({ - success: true, - deliveryStatus: "queued", - status: "running", + const activeTurnId = agentManager.getAgent(childId)?.activeTurnId; + const delivery = toolDeliveries.get(tool)!; + let ordinaryBeforeDispatch = 0; + const ordinary = delivery.enqueue({ + recipientId: childId, + source: { kind: "agent-message", agentId: "parent" }, + prompt: "ordinary follow-up", + beforeDispatch: () => { + ordinaryBeforeDispatch++; + }, }); + const response = await invokeToolWithParsedInput( + tool, + { + agentId: childId, + prompt: `/${command} then summarize the logs`, + }, + false, + ); + flush(); await vi.waitFor(() => { expect(ompSession.prompts).toEqual([ { message: "then summarize the logs", imageCount: 0, streamingBehavior }, ]); }); + expect(ordinaryBeforeDispatch).toBe(0); + expect(agentManager.getAgent(childId)?.activeTurnId).toBe(activeTurnId); + expect(response.structuredContent).toMatchObject({ + success: true, + deliveryStatus: "queued", + status: "running", + }); expect(ompSession.abortRequested).toBe(false); expect(agentManager.getAgent(childId)?.lifecycle).toBe("running"); ompSession.finishTurn(); - await expectOneFinishNotification(agentManager, parentClient, childId); + await ordinary.dispatched; + expect(ordinaryBeforeDispatch).toBe(1); + expect(ompSession.prompts).toHaveLength(2); + expect(ompSession.prompts[1]!.message).toContain("ordinary follow-up"); + ompSession.beginTurn(); + ompSession.finishTurn(); } finally { await removeAgentStateDir(agentManager, storage, workdir); } @@ -6181,6 +6197,51 @@ describe("agent snapshot MCP serialization", () => { expect(structured.agents[0]).not.toHaveProperty("pendingPermissions"); }); + it.each(["loaded", "stored"])( + "reports background work for a %s agent from get_agent_status and list_agents", + async (source) => { + const { agentManager, agentStorage, spies } = createTestDeps(); + const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD }); + if (source === "stored") { + const record = createStoredRecord({ + id: agent.id, + cwd: agent.cwd, + archivedAt: null, + lastStatus: "idle", + updatedAt: new Date().toISOString(), + }); + spies.agentStorage.get.mockResolvedValue(record); + spies.agentStorage.listActive.mockResolvedValue([record]); + } else { + spies.agentManager.getAgent.mockReturnValue(agent); + spies.agentManager.listAgents.mockReturnValue([agent]); + } + spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 }); + + const server = await createAgentMcpServer({ + agentManager, + agentStorage, + providerSnapshotManager: createClaudeOnlyManager(), + logger, + }); + const status = await registeredTool(server, "get_agent_status").handler({ + agentId: "agent-with-shell", + }); + const list = await registeredTool(server, "list_agents").handler({}); + + expect(status.structuredContent).toEqual({ + status: "idle", + snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }), + }); + expect(list.structuredContent).toEqual({ + agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })], + }); + expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith( + "agent-with-shell", + ); + }, + ); + it("returns archived agent snapshots from storage for get_agent_status", async () => { const { agentManager, agentStorage, spies } = createTestDeps(); const record = createStoredRecord({ diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 9820acf2e0..e3633ee58b 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -496,6 +496,58 @@ async function pluginMessages(session: Awaited { + await withPluginRewindSession( + { + async handleInput(input, emit) { + if (input.type !== "session.open" || input.history !== "replay") return false; + emit({ + type: "session.opened", + requestId: input.requestId, + sessionId: input.sessionId, + capabilities: CAPABILITIES, + restoration: "core", + persistence: input.persistence, + cwd: input.config.cwd, + }); + emit({ + type: "session.opened", + sessionId: "rewound-child", + parentSessionId: input.sessionId, + capabilities: [], + restoration: "parent", + cwd: input.config.cwd, + }); + emit({ type: "session.closed", sessionId: "rewound-child" }); + emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId }); + return true; + }, + }, + async (session, harness) => { + const open = harness.inputs.find((input) => input.type === "session.open")!; + harness.emit({ + type: "session.opened", + sessionId: "rewound-child", + parentSessionId: open.sessionId, + capabilities: [], + restoration: "parent", + cwd: tmpdir(), + }); + harness.emit({ + type: "session.turn", + sessionId: "rewound-child", + turnId: "withdrawn-turn", + state: "failed", + }); + await session.revertConversation!({ messageId: "user-B" }); + const history = await Array.fromAsync(session.streamHistory()); + expect(history.findLast((event) => event.type === "provider_subagent")).toMatchObject({ + event: { type: "upsert", id: "rewound-child", status: "completed" }, + }); + }, + ); +}); + test("combined plugin rewind replays the retained native branch", async () => { await withPluginRewindSession({}, async (session) => { await session.revertBoth!({ messageId: "user-B" }); @@ -1690,6 +1742,11 @@ describe("PluginAgentClientRegistry", () => { expect(manager.listProviderSubagents(agent.id)).toMatchObject([ { id: child.id, title: child.title, status: outcome }, ]); + harness.emit({ type: "session.closed", sessionId: "reusable-child" }); + await nextTurn(); + expect(manager.listProviderSubagents(agent.id)).toMatchObject([ + { id: child.id, title: child.title, status: outcome }, + ]); } finally { await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); await plugins.shutdown(); @@ -1724,6 +1781,7 @@ describe("PluginAgentClientRegistry", () => { turnId: "second-turn", state, }); + emit({ type: "session.closed", sessionId: "reusable-child" }); } }, }); @@ -1750,6 +1808,100 @@ describe("PluginAgentClientRegistry", () => { } }, ); + test("keeps a child's canceled or failed turn when the child closes normally", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + const session = await registry.clients()[harness.registration.id]!.createSession({ + provider: harness.registration.id, + cwd: "/workspace", + }); + try { + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + const open = harness.inputs.find((input) => input.type === "session.open")!; + const outcomes = [ + ["child-canceled", "canceled"], + ["child-failed", "failed"], + ["child-completed", "completed"], + ] as const; + for (const [sessionId, state] of outcomes) { + harness.emit({ + type: "session.opened", + sessionId, + parentSessionId: open.sessionId, + capabilities: [], + restoration: "parent", + cwd: "/workspace", + }); + harness.emit({ type: "session.turn", sessionId, turnId: "turn", state: "started" }); + harness.emit({ type: "session.turn", sessionId, turnId: "turn", state }); + harness.emit({ type: "session.closed", sessionId }); + } + + const lastStatus = (id: string) => + events + .flatMap((event) => + event.type === "provider_subagent" && + event.event.type === "upsert" && + event.event.id === id + ? [event.event.status] + : [], + ) + .at(-1); + expect(lastStatus("child-canceled")).toBe("canceled"); + expect(lastStatus("child-failed")).toBe("failed"); + expect(lastStatus("child-completed")).toBe("completed"); + } finally { + await session.close(); + registry.replace([]); + } + }); + + test.each([ + { turns: [], error: false, expected: "completed" }, + { turns: ["canceled", "started"], error: false, expected: "completed" }, + { turns: ["failed", "started", "completed"], error: false, expected: "completed" }, + { turns: ["canceled"], error: true, expected: "failed" }, + ] as const)( + "closes a plugin child using its latest turn: $turns, error=$error", + async ({ turns, error, expected }) => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + try { + const session = await registry.clients()[harness.registration.id]!.createSession({ + provider: harness.registration.id, + cwd: tmpdir(), + }); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + const open = harness.inputs.find((input) => input.type === "session.open")!; + harness.emit({ + type: "session.opened", + sessionId: "close-control", + parentSessionId: open.sessionId, + capabilities: [], + restoration: "parent", + cwd: tmpdir(), + }); + for (const state of turns) { + harness.emit({ type: "session.turn", sessionId: "close-control", turnId: "turn", state }); + } + harness.emit({ + type: "session.closed", + sessionId: "close-control", + ...(error ? { error: { message: "Provider failed to close" } } : {}), + }); + expect(events.at(-1)).toMatchObject({ + type: "provider_subagent", + event: { type: "upsert", id: "close-control", status: expected }, + }); + } finally { + await registry.shutdown(); + } + }, + ); test("gates persistence operations on negotiated provider capabilities", async () => { const harness = createProviderHarness({ capabilities: ["session.persistence"] }); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 32657b19a5..3b64f7c9f9 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1202,6 +1202,8 @@ class PluginAgentSession implements AgentSession { { session: ProviderRuntimeSession; unsubscribe: () => void } >(); private readonly childSnapshots = new Map>(); + // Outcome of each child's latest finished turn, so a plain close does not report it as completed. + private readonly childTurnOutcomes = new Map(); private unsubscribe: (() => void) | null = null; /** How the opened session differs from the options it was given. */ readonly openOptionsPatch: Record; @@ -1766,6 +1768,11 @@ class PluginAgentSession implements AgentSession { return; } if (event.type === "session.turn") { + if (event.state === "started") { + this.childTurnOutcomes.delete(childId); + } else { + this.childTurnOutcomes.set(childId, event.state); + } this.publish({ type: "provider_subagent", provider: this.provider, @@ -1784,7 +1791,10 @@ class PluginAgentSession implements AgentSession { event: { type: "upsert", id: childId, - status: event.type === "session.runtime_failed" || event.error ? "failed" : "completed", + status: + event.type === "session.runtime_failed" || event.error + ? "failed" + : (this.childTurnOutcomes.get(childId) ?? "completed"), }, }); } @@ -1802,6 +1812,7 @@ class PluginAgentSession implements AgentSession { this.history.clear(); this.timelineSnapshots.clear(); this.childSnapshots.clear(); + this.childTurnOutcomes.clear(); this.revertTokens.clear(); this.pendingPermissions.clear(); this.permissionResponses.clear(); @@ -1938,7 +1949,11 @@ function mapSessionConfig( return { cwd: config.cwd, env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }), - systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt), + systemPrompt: combineSystemPrompts( + config.systemPrompt, + config.daemonAppendSystemPrompt, + ...(config.pluginAppendSystemPrompt ?? []), + ), mcpServers: { ...config.mcpServers }, toolPolicy: config.toolPolicy ? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) } @@ -1957,8 +1972,9 @@ function mapSessionConfig( function combineSystemPrompts( systemPrompt: string | undefined, daemonPrompt: string | undefined, + ...pluginPrompts: string[] ): string | undefined { - const parts = [systemPrompt, daemonPrompt].filter( + const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter( (value): value is string => typeof value === "string" && value.trim().length > 0, ); return parts.length > 0 ? parts.join("\n\n") : undefined; diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index 2449b9a90b..b671eb0fab 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -448,6 +448,9 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession get initialTimeline() { return inner.initialTimeline; }, + get persistenceUpdatedOnResume() { + return inner.persistenceUpdatedOnResume; + }, get controls() { return inner.controls; }, diff --git a/packages/server/src/server/agent/provider-session-import.test.ts b/packages/server/src/server/agent/provider-session-import.test.ts new file mode 100644 index 0000000000..b9f7073ebc --- /dev/null +++ b/packages/server/src/server/agent/provider-session-import.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; +import type { + AgentPersistenceHandle, + AgentSession, + AgentSessionConfig, + ImportProviderSessionContext, +} from "./agent-sdk-types.js"; +import { importSessionFromPersistence } from "./provider-session-import.js"; + +const SESSION_FILE = "/Users/dev/.omp/agent/sessions/project/2026-01-01_session-id.jsonl"; +const SESSION_ID = "session-id"; + +function config(cwd: string): AgentSessionConfig { + return { provider: "omp", cwd }; +} + +function context(cwd: string): ImportProviderSessionContext { + return { config: config(cwd), storedConfig: config(cwd) }; +} + +function fakeSession(described: AgentPersistenceHandle | null): AgentSession { + return { + async *streamHistory() {}, + describePersistence: () => described, + } as unknown as AgentSession; +} + +describe("importSessionFromPersistence", () => { + it("persists the resumed session identity instead of the listed file handle", async () => { + const cwd = "/Users/dev/code/project"; + const imported = await importSessionFromPersistence({ + provider: "omp", + request: { providerHandleId: SESSION_FILE, cwd }, + context: context(cwd), + resumeSession: async () => + fakeSession({ + provider: "omp", + sessionId: SESSION_ID, + nativeHandle: SESSION_FILE, + metadata: { cwd, model: "resumed-model" }, + }), + }); + + expect(imported.persistence).toMatchObject({ + provider: "omp", + sessionId: SESSION_ID, + nativeHandle: SESSION_FILE, + metadata: { cwd, provider: "omp", model: "resumed-model" }, + }); + }); + + it("keeps the requested handle when the provider describes no identity", async () => { + const cwd = "/Users/dev/code/project"; + const imported = await importSessionFromPersistence({ + provider: "omp", + request: { providerHandleId: SESSION_FILE, cwd }, + context: context(cwd), + resumeSession: async () => fakeSession(null), + }); + + expect(imported.persistence).toMatchObject({ + provider: "omp", + sessionId: SESSION_FILE, + nativeHandle: SESSION_FILE, + }); + }); +}); diff --git a/packages/server/src/server/agent/provider-session-import.ts b/packages/server/src/server/agent/provider-session-import.ts index b09a5ab874..c75cd2d70d 100644 --- a/packages/server/src/server/agent/provider-session-import.ts +++ b/packages/server/src/server/agent/provider-session-import.ts @@ -38,12 +38,32 @@ export async function importSessionFromPersistence(input: { return { session, config: storedConfig, - persistence, + persistence: canonicalImportPersistence(persistence, session), timeline: history.timeline, providerSubagentEvents: history.providerSubagentEvents, }; } +/** + * Import handles identify a session by whatever the provider lists, which is not + * always the session id: OMP lists session files. Persist the resumed session's own + * identity instead, so records, dedupe and resume all agree, while the provider's + * native handle still resolves the session. + */ +function canonicalImportPersistence( + requested: AgentPersistenceHandle, + session: ImportedProviderSession["session"], +): AgentPersistenceHandle { + const described = session.describePersistence(); + if (!described?.sessionId) return requested; + return { + ...described, + provider: requested.provider, + nativeHandle: described.nativeHandle ?? requested.nativeHandle, + metadata: { ...requested.metadata, ...described.metadata }, + }; +} + function buildImportPersistenceHandle( provider: AgentProvider, input: ImportProviderSessionInput, diff --git a/packages/server/src/server/agent/providers/acp-agent.test.ts b/packages/server/src/server/agent/providers/acp-agent.test.ts index b94a6de940..748d2b462f 100644 --- a/packages/server/src/server/agent/providers/acp-agent.test.ts +++ b/packages/server/src/server/agent/providers/acp-agent.test.ts @@ -19,6 +19,7 @@ import { RequestPermissionRequest, SessionConfigOption, SessionUpdate, + type NewSessionResponse, } from "@agentclientprotocol/sdk"; import { @@ -50,7 +51,6 @@ import { } from "./copilot-acp-agent.js"; import { GenericACPAgentClient } from "./generic-acp-agent.js"; import { parseKiroExtensionCommands } from "./kiro-acp-agent.js"; -import { transformPiModels } from "./pi/agent.js"; import type { AgentStreamEvent } from "../agent-sdk-types.js"; import type { AgentCapabilityFlags, @@ -2114,6 +2114,117 @@ describe("deriveModelDefinitionsFromACP", () => { }, ]); }); + + test("gives a model that reports its own reasoning levels those levels and default", () => { + const models = deriveModelDefinitionsFromACP( + "acp", + { + currentModelId: "startup", + availableModels: [ + { modelId: "startup", name: "Startup" }, + { + modelId: "other", + name: "Other", + _meta: { + reasoningEffort: "xhigh", + reasoningEfforts: [ + { id: "high", label: "High" }, + { id: "xhigh", label: "Extra high" }, + ], + }, + }, + ], + }, + [selectConfigOption("thought_level", ["none", "low"], "low")], + ); + + expect(models[0]).toMatchObject({ + thinkingOptions: [{ id: "none" }, { id: "low" }], + defaultThinkingOptionId: "low", + }); + expect(models[1]).toMatchObject({ + thinkingOptions: [ + { id: "high", label: "High", isDefault: false }, + { id: "xhigh", label: "Extra high", isDefault: true }, + ], + defaultThinkingOptionId: "xhigh", + }); + }); + + test("uses the wire value and a model's marked default when no reasoningEffort is provided", () => { + const models = deriveModelDefinitionsFromACP("acp", { + currentModelId: "current", + availableModels: [ + { + modelId: "current", + name: "Current", + _meta: { + reasoningEfforts: [ + { + id: "display-id", + value: "wire/id@large", + label: "Custom", + default: true, + }, + ], + }, + }, + ], + }); + + expect(models[0]).toMatchObject({ + thinkingOptions: [{ id: "wire/id@large", label: "Custom", isDefault: true }], + defaultThinkingOptionId: "wire/id@large", + }); + }); + + test.each([{ supportsReasoningEffort: false }, { reasoningEfforts: [] }])( + "shows no thinking options for a model that reports none: %j", + (metadata) => { + const models = deriveModelDefinitionsFromACP( + "acp", + { + currentModelId: "current", + availableModels: [{ modelId: "current", name: "Current", _meta: metadata }], + }, + [selectConfigOption("thought_level", ["low", "high"], "high")], + ); + + expect(models[0].thinkingOptions).toBeUndefined(); + expect(models[0].defaultThinkingOptionId).toBeUndefined(); + }, + ); + + test.each([ + { supportsReasoningEffort: true }, + { reasoningEfforts: [{ id: "high", label: "High", description: 42 }] }, + { + reasoningEfforts: [ + { id: "high", label: "High" }, + { id: "high", label: "Duplicate" }, + ], + }, + ])( + "keeps session thinking options when a model's reasoning table is unusable: %j", + (metadata) => { + const models = deriveModelDefinitionsFromACP( + "acp", + { + currentModelId: "default", + availableModels: [ + { modelId: "default", name: "Default" }, + { modelId: "other", name: "Other", _meta: metadata }, + ], + }, + [selectConfigOption("thought_level", ["off", "on"], "on")], + ); + + expect(models[1]).toMatchObject({ + thinkingOptions: [{ id: "off" }, { id: "on" }], + defaultThinkingOptionId: "on", + }); + }, + ); }); describe("ACPAgentClient modelTransformer", () => { @@ -2148,7 +2259,12 @@ describe("ACPAgentClient modelTransformer", () => { provider: "pi", logger: createTestLogger(), defaultCommand: ["test-acp"], - modelTransformer: transformPiModels, + modelTransformer: (models) => + models.map((model) => ({ + ...model, + label: model.label.split("/").at(-1) ?? model.label, + description: model.id, + })), }); await expect( @@ -2171,6 +2287,164 @@ describe("ACPAgentClient modelTransformer", () => { }); describe("ACPAgentClient catalog discovery without a model resolver", () => { + test.each(["magpie/workbuddy/deepseek-v4.1-flash", "grok-4.7"])( + "reads each exact model's reasoning metadata through the ACP response schema with default %s without switching models", + async (currentModelId) => { + const requests: string[] = []; + const response: NewSessionResponse = { + sessionId: "catalog-session", + models: { + currentModelId, + availableModels: [ + { + modelId: "grok-4.7", + name: "Grok 4.7", + _meta: { + supportsReasoningEffort: true, + reasoningEffort: "high", + reasoningEfforts: [ + { id: "xhigh", value: "xhigh", label: "Extra High", default: false }, + { id: "high", value: "high", label: "High", default: true }, + { id: "medium", value: "medium", label: "Medium", default: false }, + { id: "low", value: "low", label: "Low", default: false }, + ], + }, + }, + { + modelId: "magpie/codex/gpt-6.1-sol", + name: "Sol", + _meta: { + supportsReasoningEffort: true, + reasoningEffort: "low", + reasoningEfforts: [ + { id: "low", value: "low", label: "Low", description: null, default: false }, + { id: "medium", value: "medium", label: "Medium", default: false }, + { id: "high", value: "high", label: "High", default: false }, + { id: "xhigh", value: "xhigh", label: "X-High", default: false }, + { id: "max", value: "max", label: "Max", default: false }, + ], + }, + }, + { + modelId: "magpie/workbuddy/deepseek-v4.1-flash", + name: "DeepSeek", + _meta: { + supportsReasoningEffort: true, + reasoningEffort: "high", + reasoningEfforts: [ + { id: "none", value: "none", label: "None", default: false }, + { id: "low", value: "low", label: "Low", default: false }, + { id: "high", value: "high", label: "High", default: false }, + { id: "max", value: "max", label: "Max", default: false }, + ], + }, + }, + ], + }, + configOptions: [ + selectConfigOption( + "thought_level", + currentModelId === "grok-4.7" + ? ["xhigh", "high", "medium", "low"] + : ["none", "low", "high", "max"], + currentModelId === "grok-4.7" ? "medium" : "high", + ), + selectConfigOption("mode", ["https://example.com/modes#agent"]), + ], + }; + const clientToAgent = new TransformStream(); + const agentToClient = new TransformStream(); + const agent: Agent = { + async initialize() { + return { protocolVersion: PROTOCOL_VERSION, agentCapabilities: {} }; + }, + async newSession({ cwd }) { + requests.push(`session/new:${cwd}`); + return response; + }, + async setSessionConfigOption() { + throw new Error("Catalog discovery must not change the selected model"); + }, + async prompt() { + throw new Error("Catalog discovery must not send a prompt"); + }, + async authenticate() {}, + async cancel() {}, + }; + const agentConnection = new AgentSideConnection( + () => agent, + ndJsonStream(agentToClient.writable, clientToAgent.readable), + ); + const connection = new ClientSideConnection( + () => ({ + async requestPermission() { + return { outcome: { outcome: "cancelled" } }; + }, + async sessionUpdate() {}, + }), + ndJsonStream(clientToAgent.writable, agentToClient.readable), + ); + const initialize = await connection.initialize({ protocolVersion: PROTOCOL_VERSION }); + class CatalogClient extends GenericACPAgentClient { + protected override async spawnProcess(): Promise { + return { child: createProbeChildStub(), connection, initialize }; + } + protected override async closeProbe(): Promise { + requests.push("close"); + } + } + const client = new CatalogClient({ + logger: createTestLogger(), + command: ["test-acp"], + providerId: "grok", + }); + + const catalog = await client.fetchCatalog({ + scope: "workspace", + cwd: "/tmp/sc/.worktrees/model-options", + }); + + const modelOptions = []; + for (const model of catalog.models) { + modelOptions.push({ + id: model.id, + isDefault: model.isDefault, + thinking: model.thinkingOptions?.map((option) => option.id), + defaultThinkingOptionId: model.defaultThinkingOptionId, + }); + } + expect(modelOptions).toEqual([ + { + id: "grok-4.7", + isDefault: currentModelId === "grok-4.7", + thinking: ["xhigh", "high", "medium", "low"], + defaultThinkingOptionId: currentModelId === "grok-4.7" ? "medium" : "high", + }, + { + id: "magpie/codex/gpt-6.1-sol", + isDefault: false, + thinking: ["low", "medium", "high", "xhigh", "max"], + defaultThinkingOptionId: "low", + }, + { + id: "magpie/workbuddy/deepseek-v4.1-flash", + isDefault: currentModelId === "magpie/workbuddy/deepseek-v4.1-flash", + thinking: ["none", "low", "high", "max"], + defaultThinkingOptionId: "high", + }, + ]); + expect(catalog.models[1].thinkingOptions?.[0]).toMatchObject({ + id: "low", + label: "Low", + isDefault: true, + description: undefined, + }); + expect(catalog.modes.map(({ id }) => id)).toEqual(["https://example.com/modes#agent"]); + expect(requests).toEqual(["session/new:/tmp/sc/.worktrees/model-options", "close"]); + expect(agentConnection.signal.aborted).toBe(false); + }, + ); + test("never switches models during catalog discovery even with multiple models and a thinking picker", async () => { // Model discovery extensions live on providers that opt in. The base // client ships no catalog model resolver, so a slow or nonconforming ACP can't @@ -2644,60 +2918,6 @@ describe("ACP providers advertise session listing", () => { }); }); -describe("transformPiModels", () => { - test("keeps slash-free labels unchanged", () => { - expect( - transformPiModels([ - { - provider: "pi", - id: "gpt-4.1-mini", - label: "GPT 4.1 Mini", - description: "Fast", - }, - ]), - ).toEqual([ - { - provider: "pi", - id: "gpt-4.1-mini", - label: "GPT 4.1 Mini", - description: "Fast", - }, - ]); - }); - - test("uses the last path segment as label and preserves existing descriptions", () => { - expect( - transformPiModels([ - { - provider: "pi", - id: "openrouter/openai/gpt-4.1-mini", - label: "openrouter/openai/gpt-4.1-mini", - description: undefined, - }, - { - provider: "pi", - id: "anthropic/claude-sonnet-4", - label: "anthropic/claude-sonnet-4", - description: "Balanced", - }, - ]), - ).toEqual([ - { - provider: "pi", - id: "openrouter/openai/gpt-4.1-mini", - label: "gpt-4.1-mini", - description: "openrouter/openai/gpt-4.1-mini", - }, - { - provider: "pi", - id: "anthropic/claude-sonnet-4", - label: "claude-sonnet-4", - description: "Balanced", - }, - ]); - }); -}); - describe("ACPAgentSession slash commands", () => { test("returns immediately for ACP sessions that do not wait for async command discovery", async () => { const session = new ACPAgentSession( diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index 33664f7ad8..0086e9b6d9 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -64,6 +64,7 @@ import { type Stream as ACPStream, } from "@agentclientprotocol/sdk"; import type { Logger } from "pino"; +import { z } from "zod"; import { getAgentStreamEventTurnId, @@ -838,32 +839,126 @@ export function deriveModelDefinitionsFromACP( models: SessionModelState | null | undefined, configOptions?: SessionConfigOption[] | null, ): AgentModelDefinition[] { - const thinkingOptions = deriveSelectorOptions(configOptions, "thought_level"); - const defaultThinkingOptionId = thinkingOptions.find((option) => option.isDefault)?.id ?? null; + const sessionThinking = deriveSessionThinking(configOptions); if (models?.availableModels?.length) { - return models.availableModels.map((model) => ({ - provider, - id: model.modelId, - label: model.name, - description: model.description ?? undefined, - isDefault: model.modelId === models.currentModelId, - thinkingOptions: thinkingOptions.length > 0 ? thinkingOptions : undefined, - defaultThinkingOptionId: defaultThinkingOptionId ?? undefined, - })); + return models.availableModels.map((model) => { + const isDefault = model.modelId === models.currentModelId; + const thinking = deriveACPModelThinking({ + metadata: model._meta, + isDefault, + sessionThinking, + }); + return { + provider, + id: model.modelId, + label: model.name, + description: model.description ?? undefined, + isDefault, + thinkingOptions: thinking.thinkingOptions, + defaultThinkingOptionId: thinking.defaultThinkingOptionId, + }; + }); } const modelOptions = deriveSelectorOptions(configOptions, "model"); - return modelOptions.map((option) => ({ - provider, - id: option.id, - label: option.label, - description: option.description, - isDefault: option.isDefault, - thinkingOptions: thinkingOptions.length > 0 ? thinkingOptions : undefined, - defaultThinkingOptionId: defaultThinkingOptionId ?? undefined, - metadata: option.metadata, - })); + return modelOptions.map((option) => { + const thinking = deriveACPModelThinking({ + metadata: option.metadata, + isDefault: option.isDefault === true, + sessionThinking, + }); + return { + provider, + id: option.id, + label: option.label, + description: option.description, + isDefault: option.isDefault, + thinkingOptions: thinking.thinkingOptions, + defaultThinkingOptionId: thinking.defaultThinkingOptionId, + metadata: option.metadata, + }; + }); +} + +type ACPModelThinking = Pick; + +const NO_THINKING: ACPModelThinking = { + thinkingOptions: undefined, + defaultThinkingOptionId: undefined, +}; + +// Some ACP agents describe each model's reasoning levels in the model's `_meta`. +const ACPModelReasoningSchema = z.object({ + supportsReasoningEffort: z.boolean().optional(), + reasoningEffort: z.string().min(1).nullish(), + reasoningEfforts: z + .array( + z.object({ + id: z.string().min(1), + value: z.string().min(1).optional(), + label: z.string(), + description: z.string().nullish(), + default: z.boolean().optional(), + }), + ) + .optional(), +}); + +function deriveSessionThinking( + configOptions: SessionConfigOption[] | null | undefined, +): ACPModelThinking { + const thinkingOptions = deriveSelectorOptions(configOptions, "thought_level"); + if (thinkingOptions.length === 0) { + return NO_THINKING; + } + return { + thinkingOptions, + defaultThinkingOptionId: thinkingOptions.find((option) => option.isDefault)?.id, + }; +} + +// A model's own reasoning metadata describes that model. A model that reports none +// keeps the session's thought_level options, which describe the startup model. +function deriveACPModelThinking(input: { + metadata: Record | null | undefined; + isDefault: boolean; + sessionThinking: ACPModelThinking; +}): ACPModelThinking { + const { metadata, isDefault, sessionThinking } = input; + const parsed = ACPModelReasoningSchema.safeParse(metadata ?? {}); + if (!parsed.success) { + return sessionThinking; + } + const { supportsReasoningEffort, reasoningEffort, reasoningEfforts } = parsed.data; + if (supportsReasoningEffort === false || reasoningEfforts?.length === 0) { + return NO_THINKING; + } + if (!reasoningEfforts) { + return sessionThinking; + } + + const ids = reasoningEfforts.map((effort) => effort.value ?? effort.id); + if (new Set(ids).size !== ids.length) { + return sessionThinking; + } + const markedDefault = reasoningEfforts.find((effort) => effort.default); + const defaultCandidates = [ + isDefault ? sessionThinking.defaultThinkingOptionId : undefined, + reasoningEffort, + markedDefault ? (markedDefault.value ?? markedDefault.id) : undefined, + ]; + const defaultThinkingOptionId = + defaultCandidates.find((id) => id && ids.includes(id)) ?? undefined; + return { + thinkingOptions: reasoningEfforts.map((effort, index) => ({ + id: ids[index], + label: effort.label, + description: effort.description ?? undefined, + isDefault: ids[index] === defaultThinkingOptionId, + })), + defaultThinkingOptionId, + }; } export function deriveControlsFromACP( diff --git a/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts b/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts index 711dea79ec..7f37a50e1f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "vitest"; import type { CanUseTool, PermissionMode, Query } from "@anthropic-ai/claude-agent-sdk"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; -import type { AgentPermissionRequest } from "../../agent-sdk-types.js"; +import type { AgentPermissionRequest, AgentStreamEvent } from "../../agent-sdk-types.js"; import { ClaudeAgentClient } from "./agent.js"; // The injected SDK adapter supplies requests through Claude's permission callback. @@ -90,3 +90,112 @@ test.each([ await plan.session.close(); } }); + +async function createBypassSession() { + let requestPermission: CanUseTool | undefined; + const query = Object.assign((async function* () {})(), { + async setPermissionMode(_mode: PermissionMode) {}, + close() {}, + }); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + resolveBinary: async () => "/test/claude", + queryFactory: ({ options }) => { + requestPermission = options.canUseTool; + return query as Query; + }, + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + modeId: "bypassPermissions", + }); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + await session.setMode("bypassPermissions"); + if (!requestPermission) throw new Error("SDK permission callback was not installed"); + return { session, events, requestPermission }; +} + +test("bypass approves Claude's own checks without publishing permission events and follows live mode changes", async () => { + const { session, events, requestPermission } = await createBypassSession(); + try { + const controller = new AbortController(); + const input = { command: "rm -rf build" }; + // Claude Code sends these fields, but this SDK version does not declare them on CanUseTool. + const ownCheck = { + signal: controller.signal, + toolUseID: "execution", + decisionReason: "Dangerous rm command", + decisionReasonType: "safetyCheck", + }; + const result = requestPermission("Bash", input, ownCheck); + // Abort also settles a prompting callback, so this test never hangs. + controller.abort(); + await expect(result).resolves.toMatchObject({ behavior: "allow", updatedInput: input }); + expect(events.filter((event) => event.type.startsWith("permission_"))).toEqual([]); + + for (const [mode, tool, toolInput] of [ + ["bypassPermissions", "AskUserQuestion", { questions: [] }], + ["bypassPermissions", "ExitPlanMode", { plan: "Review this" }], + ["default", "Bash", input], + ["plan", "Bash", input], + ] as const) { + await session.setMode(mode); + const resolution = requestPermission(tool, toolInput, { + ...ownCheck, + signal: new AbortController().signal, + toolUseID: tool, + }); + const requestEvent = events.at(-1); + expect(requestEvent?.type).toBe("permission_requested"); + if (requestEvent?.type !== "permission_requested") + throw new Error("Missing permission request"); + await session.respondToPermission(requestEvent.request.id, { behavior: "deny" }); + await expect(resolution).resolves.toMatchObject({ behavior: "deny" }); + } + } finally { + await session.close(); + } +}); + +test.each([ + ["an ask rule", { decisionReasonType: "rule" }], + ["a hook", { decisionReasonType: "hook", decisionReason: "Confirm before posting" }], + [ + "an ask rule on Claude's own check", + { + decisionReasonType: "safetyCheck", + matchedAskRule: { source: "policySettings", toolName: "Bash", ruleContent: "rm *" }, + }, + ], + [ + "a tool the user answers on the card", + { decisionReasonType: "other", requiresUserInteraction: true }, + ], + ["a compound command with an ask rule in one part", { decisionReasonType: "subcommandResults" }], + [ + "a read the user blocked outside the working directories", + { decisionReasonType: "safetyCheck", decisionReasonCode: "outside_reads_blocked" }, + ], + [ + "an organization's ask limit", + { decisionReasonType: "workingDir", decisionReasonCode: "org_ask_ceiling" }, + ], + ["a sandbox override the user's read block raised", { decisionReasonType: "sandboxOverride" }], + ["a Claude Code that does not say why it asks", {}], +])("bypass still asks the user about %s", async (_source, why) => { + const { session, events, requestPermission } = await createBypassSession(); + try { + const ask = { signal: new AbortController().signal, toolUseID: "execution", ...why }; + const resolution = requestPermission("Bash", { command: "gh pr comment 1" }, ask); + const requestEvent = events.at(-1); + expect(requestEvent?.type).toBe("permission_requested"); + if (requestEvent?.type !== "permission_requested") + throw new Error("Missing permission request"); + await session.respondToPermission(requestEvent.request.id, { behavior: "deny" }); + await expect(resolution).resolves.toMatchObject({ behavior: "deny" }); + } finally { + await session.close(); + } +}); diff --git a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts index 432071741f..aaad3592a3 100644 --- a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts @@ -1,5 +1,12 @@ import { ClaudeRuntimeSafety } from "./runtime-safety.js"; -import type { Query, SDKMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { + HookCallback, + Query, + SDKMessage, + SDKUserMessage, + SessionCronSummary, + StopHookInput, +} from "@anthropic-ai/claude-agent-sdk"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -884,6 +891,7 @@ test("Claude session runtime safety observes pumped background work and autonomo wake?.(); }; let nativeInput!: AsyncIterator; + let stopHook: HookCallback | undefined; let connected!: () => void; const connection = new Promise((resolve) => { connected = resolve; @@ -908,9 +916,10 @@ test("Claude session runtime safety observes pumped background work and autonomo const session = await new ClaudeAgentClient({ logger: createTestLogger(), resolveBinary: async () => "/test/claude/bin", - queryFactory: ({ prompt }) => { + queryFactory: ({ prompt, options }) => { if (typeof prompt === "string") throw new Error("Expected streaming input"); nativeInput = prompt[Symbol.asyncIterator](); + stopHook = options?.hooks?.Stop?.[0]?.hooks[0]; connected(); return query; }, @@ -957,6 +966,22 @@ test("Claude session runtime safety observes pumped background work and autonomo expect(await session.canStopRuntime!()).toBe(false); await push(result); expect(await session.canStopRuntime!()).toBe(true); + // A session-only cron lives in this process, and Claude reports it only to the Stop hook. + const stop = (session_crons: SessionCronSummary[]) => { + const stopInput: StopHookInput = { + hook_event_name: "Stop", + session_id: "runtime-safety", + transcript_path: "", + cwd: process.cwd(), + stop_hook_active: false, + session_crons, + }; + return stopHook!(stopInput, undefined, { signal: new AbortController().signal }); + }; + await stop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" }]); + expect(await session.canStopRuntime!()).toBe(false); + await stop([]); + expect(await session.canStopRuntime!()).toBe(true); } finally { await session.close(); } diff --git a/packages/server/src/server/agent/providers/claude/agent.env.test.ts b/packages/server/src/server/agent/providers/claude/agent.env.test.ts index 6d268e932c..b4db648b9f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.env.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.env.test.ts @@ -153,6 +153,56 @@ describe("Claude SDK env", () => { } }); + test("resume uses current plugin instructions and excludes them from persistence", async () => { + const prompts: unknown[] = []; + const queryFactory = ({ options }: ClaudeQueryInput) => { + prompts.push(options.systemPrompt); + return createQueryMock([ + { + type: "system", + subtype: "init", + session_id: "persisted-session", + permissionMode: "default", + model: "opus", + }, + { type: "assistant", message: { content: "done" } }, + { + type: "result", + subtype: "success", + usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 }, + total_cost_usd: 0, + }, + ]); + }; + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const first = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + pluginAppendSystemPrompt: ["Plugin instructions"], + }); + await first.run("first"); + const handle = first.describePersistence()!; + expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt"); + await first.close(); + const resumed = await client.resumeSession(handle, { + cwd: process.cwd(), + pluginAppendSystemPrompt: undefined, + }); + try { + await resumed.run("after disable"); + expect(prompts).toEqual([ + { type: "preset", preset: "claude_code", append: "Plugin instructions" }, + { type: "preset", preset: "claude_code", append: "" }, + ]); + } finally { + await resumed.close(); + } + }); + test("forwards launch-context env through Claude resume env", async () => { let capturedEnv: Record | undefined; const launchContext: AgentLaunchContext = { diff --git a/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts b/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts index cb272ebecb..5f90adba8b 100644 --- a/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts @@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)( try { await session.startTurn("Run the foreground command"); await running.promise; - expect(await session.setThinkingOption?.("medium")).toMatchObject({ + // Ultracode is launched with the query, so the change waits for a restart. + expect(await session.setThinkingOption?.("ultracode")).toMatchObject({ message: "Thinking level applies next turn", }); if (control === "mode") await session.setMode("acceptEdits"); @@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)( await session.startTurn("Run another command with the new thinking level"); queries[1].work.resolve(); expect(await terminal.promise).toBe("turn_completed"); - expect(efforts).toEqual(["low", "medium"]); + expect(efforts).toEqual(["low", "xhigh"]); } finally { await session.close(); } diff --git a/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts b/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts index d70d068717..b700ff81ac 100644 --- a/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts @@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que close: vi.fn(() => undefined), setPermissionMode: vi.fn(async () => undefined), setModel: vi.fn(async () => undefined), + applyFlagSettings: vi.fn(async () => undefined), supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]), supportedCommands: vi.fn(async () => []), rewindFiles: vi.fn(async () => ({ canRewind: true })), @@ -382,6 +383,84 @@ describe("Claude runtime exit", () => { } }); + test("keeps the process and its background work when the effort level changes", async () => { + let capturedOptions: Options | undefined; + const child = createChildProcessStub(); + const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, { + tail: new Promise(() => undefined), + onReturn: () => child.emit("exit", 0, null), + }); + const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => { + capturedOptions = options; + return query; + }); + vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + thinkingOptionId: "low", + }); + + try { + await session.run("start a background shell"); + capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + + await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined(); + // A pending restart would be carried out here. + await session.listCommands(); + + expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" }); + expect(queryFactory).toHaveBeenCalledTimes(1); + expect(query.return).not.toHaveBeenCalled(); + expect(child.killSignals).toEqual([]); + expect(events).not.toContainEqual( + expect.objectContaining({ type: "background_work", provider: "claude", items: null }), + ); + } finally { + await session.close(); + } + }); + + test("restarts with the new effort level when the running process does not take it", async () => { + const efforts: Options["effort"][] = []; + const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => { + efforts.push(options.effort); + const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, { + tail: new Promise(() => undefined), + }); + vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported")); + return query; + }); + vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub()); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + thinkingOptionId: "low", + }); + + try { + await session.run("start a background shell"); + await session.setThinkingOption?.("high"); + await session.listCommands(); + + expect(efforts).toEqual(["low", "high"]); + } finally { + await session.close(); + } + }); + test("ignores background work a retired query reports after its restart", async () => { let capturedOptions: Options | undefined; let deliverLateEvent: ((event: unknown) => void) | undefined; diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index 3aa96635fc..fbb7907b2a 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -998,6 +998,43 @@ describe("ClaudeAgentSession features", () => { } }); + test("carries the SDK decision reason onto the permission request description", async () => { + const { queryFactory } = createQueryMock(); + const session = await new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }).createSession({ provider: "claude", cwd: process.cwd(), modeId: "default" }); + const events: AgentStreamEvent[] = []; + const unsubscribe = session.subscribe((event) => events.push(event)); + + try { + await session.startTurn("run the tool"); + const canUseTool = queryFactory.mock.calls[0]?.[0].options.canUseTool; + if (!canUseTool) throw new Error("Expected canUseTool callback"); + canUseTool( + "Bash", + { command: "printf test" }, + { + toolUseID: "tool-hook-ask", + decisionReason: + "\u001b[33mHeredoc input to python3 -- cannot statically verify safety\u001b[0m", + }, + ).catch(() => undefined); + + expect(events.find((event) => event.type === "permission_requested")).toMatchObject({ + type: "permission_requested", + request: { + name: "Bash", + description: "Heredoc input to python3 -- cannot statically verify safety", + }, + }); + } finally { + unsubscribe(); + await session.close(); + } + }); + test("passes exact configured Fable 5 IDs through to Claude Code", async () => { const { queryFactory, queryMock } = createQueryMock(); const client = new ClaudeAgentClient({ @@ -1507,6 +1544,60 @@ describe("ClaudeAgentSession features", () => { } }); + test("accepts a steer while Claude compacts, so the compaction is not interrupted", async () => { + const { queryFactory, push } = createStreamingQueryMock(); + const client = new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ provider: "claude", cwd: process.cwd() }); + const events: AgentStreamEvent[] = []; + const unsubscribe = session.subscribe((event) => events.push(event)); + try { + const { turnId } = await session.startTurn("/compact"); + const input = queryFactory.mock.calls[0]?.[0].prompt as AsyncIterable; + const iterator = input[Symbol.asyncIterator](); + await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } }); + await vi.waitFor(() => + expect(events).toContainEqual( + expect.objectContaining({ + type: "timeline", + item: expect.objectContaining({ type: "user_message" }), + }), + ), + ); + push({ + type: "system", + subtype: "status", + status: "compacting", + session_id: "session-1", + } as unknown as SDKMessage); + await vi.waitFor(() => + expect(events).toContainEqual( + expect.objectContaining({ + type: "timeline", + item: { type: "compaction", status: "loading" }, + }), + ), + ); + + const admission = await session.steerActiveTurn?.("message during compaction", { + expectedTurnId: turnId, + }); + + // Claude Code holds a `next` message until the compaction finishes. Refusing it makes the + // manager replace the turn, and the interrupt cancels the compaction. + expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) }); + await expect(iterator.next()).resolves.toMatchObject({ + value: { type: "user", priority: "next" }, + }); + } finally { + unsubscribe(); + await session.close(); + } + }); + test("a human steer supersedes blocking permissions until Claude reads it", async () => { const { queryFactory } = createQueryMock(); const client = new ClaudeAgentClient({ diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index bee13ed78e..ba559dedf7 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -9,10 +9,13 @@ import fs from "node:fs"; import { promises } from "node:fs"; import path from "node:path"; import { LRUCache } from "lru-cache"; +import stripAnsi from "strip-ansi"; import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.js"; +import { bypassApprovesAsk } from "./bypass-approval.js"; import { type AgentDefinition, type CanUseTool, + type HookCallback, type McpServerConfig as ClaudeSdkMcpServerConfig, type PermissionMode, type PermissionResult, @@ -81,7 +84,7 @@ import { type ClaudeProviderOptions, } from "./options.js"; import { renderPromptAttachmentAsText } from "../../prompt-attachments.js"; -import { discoverClaudeModels } from "./model-discovery.js"; +import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js"; import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js"; import { findSteeredMessageParent, @@ -1749,6 +1752,10 @@ export class ClaudeAgentClient implements AgentClient { }; } + async shutdown(): Promise { + await killExitingClaudeModelDiscoveries(); + } + async resolveDefaultModeId({ env: launchEnv }: ResolveAgentDefaultModeInput): Promise { return claudeModeCatalog(this.buildProviderEnv(launchEnv)).defaultModeId; } @@ -2630,7 +2637,10 @@ class ClaudeAgentSession implements AgentSession { return { status: "unavailable" }; } const activeTurnId = this.activeForegroundTurnId ?? this.autonomousTurn?.id; - if (this.compacting || activeTurnId !== options.expectedTurnId) { + // A compacting turn still takes a steer: Claude Code holds a `next` message until the + // compaction finishes. Refusing it makes the manager replace the turn, and that interrupt + // cancels the compaction. + if (activeTurnId !== options.expectedTurnId) { return { status: "unavailable" }; } @@ -2852,6 +2862,7 @@ class ClaudeAgentSession implements AgentSession { ? thinkingOptionId : null; + const previousThinkingOptionId = this.config.thinkingOptionId; if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") { this.config.thinkingOptionId = undefined; } else if (isClaudeThinkingOption(normalizedThinkingOptionId)) { @@ -2860,12 +2871,35 @@ class ClaudeAgentSession implements AgentSession { } else { throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`); } - this.queryRestartNeeded = true; + if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) { + this.queryRestartNeeded = true; + } if (this.activeForegroundTurnId || this.autonomousTurn) { return THINKING_APPLIES_NEXT_TURN_NOTICE; } } + // A move between two effort levels changes only the effort, which a running Claude process + // takes through flag settings, so the process and its background work stay. Switching thinking + // off, to ultracode or back to the default changes how the query is launched, so it still + // restarts the query. The recorded option feeds every later launch either way. + private async applyEffortToRunningQuery( + previousThinkingOptionId: string | undefined, + ): Promise { + const effort = this.config.thinkingOptionId; + if (!this.query || this.queryRestartNeeded) return false; + if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) { + return false; + } + try { + await this.query.applyFlagSettings({ effortLevel: effort }); + return true; + } catch (error) { + this.logger.warn({ err: error, effort }, "Claude did not take a live effort change"); + return false; + } + } + async applyOptions(options: ProviderOptions): Promise { // Every option but Fast is read when the query is built, and replacing a started query would // end its background work, so once it exists only Fast can change. @@ -3042,7 +3076,11 @@ class ClaudeAgentSession implements AgentSession { if (!this.claudeSessionId) { return null; } - const { providerOptions: _providerOptions, ...persistedConfig } = this.config; + const { + providerOptions: _providerOptions, + pluginAppendSystemPrompt: _pluginAppendSystemPrompt, + ...persistedConfig + } = this.config; this.persistence = { provider: "claude", sessionId: this.claudeSessionId, @@ -3710,7 +3748,11 @@ class ClaudeAgentSession implements AgentSession { private buildAppendedSystemPrompt(): string { return ( - composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt) ?? "" + composeSystemPromptParts( + this.config.systemPrompt, + this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), + ) ?? "" ); } @@ -3803,7 +3845,7 @@ class ClaudeAgentSession implements AgentSession { // subagents keep running. Without this declaration an interrupt kills every one of them. // Claude stops a helper itself with its TaskStop tool. perTaskStopAffordance: true, - hooks: this.buildSubagentEffortHooks(), + hooks: { ...this.buildSubagentEffortHooks(), Stop: [{ hooks: [this.observeStopHook] }] }, ...(this.persistSession === undefined ? {} : { persistSession: this.persistSession }), env: sdkEnv, }; @@ -5305,6 +5347,11 @@ class ClaudeAgentSession implements AgentSession { input, options, ): Promise => { + // Decide before publishing anything: bypassed asks never enter the permission UI. + if (this.currentMode === "bypassPermissions" && bypassApprovesAsk(toolName, options)) { + return { behavior: "allow", updatedInput: input, toolUseID: options.toolUseID }; + } + const requestId = `permission-${randomUUID()}`; const kind = resolvePermissionKind(toolName, input); const requestInput = normalizeClaudeAskUserQuestionRequestInput(toolName, input); @@ -5330,6 +5377,7 @@ class ClaudeAgentSession implements AgentSession { provider: "claude", name: toolName, kind, + description: readNonEmptyString(stripAnsi(options.decisionReason ?? ""))?.trim(), ...buildClaudeQuestionPermissionSummary(toolName, input), input: requestInput, detail: toolDetail, @@ -5478,6 +5526,12 @@ class ClaudeAgentSession implements AgentSession { }; } + // Observation-only, like the effort hooks: it never alters turn control. + private readonly observeStopHook: HookCallback = async (input) => { + if (input.hook_event_name === "Stop") this.runtimeSafety.observeStop(input.session_crons); + return {}; + }; + private notifySubscribers(event: AgentStreamEvent): void { const turnId = getAgentStreamEventTurnId(event) ?? this.activeForegroundTurnId ?? this.autonomousTurn?.id; diff --git a/packages/server/src/server/agent/providers/claude/bypass-approval.ts b/packages/server/src/server/agent/providers/claude/bypass-approval.ts new file mode 100644 index 0000000000..cd871439ea --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/bypass-approval.ts @@ -0,0 +1,43 @@ +import type { CanUseTool } from "@anthropic-ai/claude-agent-sdk"; + +type PermissionOptions = Parameters[2]; + +// In bypassPermissions, Claude Code still forwards an ask when the user configured one +// (a permissions.ask rule, including managed policy, or a PreToolUse hook), when the tool +// needs an answer, or when one of its own checks fires. Bypass approves only Claude's own +// checks. A missing or unknown reason type stays with the user. +// `subcommandResults` is left out: a compound or piped command uses it as a container, +// including when a user's ask rule matched one of its parts. `sandboxOverride` is left +// out: in Bypass, Claude Code forwards it only when the user's read block or hook raised it. +const CLAUDE_OWN_CHECK_TYPES: ReadonlySet = new Set([ + "safetyCheck", + "workingDir", + "mode", + "classifier", + "asyncAgent", +]); + +// Settings the user or organization chose, which Claude Code reports under its own types: +// permissions.blockReadsOutsideWorkingDirectories, and an organization's ask limit. +const CONFIGURED_ASK_CODES: ReadonlySet = new Set([ + "outside_reads_blocked", + "org_ask_ceiling", +]); + +const QUESTION_TOOLS: ReadonlySet = new Set(["AskUserQuestion", "ExitPlanMode"]); + +export function bypassApprovesAsk(toolName: string, options: PermissionOptions): boolean { + if (QUESTION_TOOLS.has(toolName) || options.matchedAskRule) { + return false; + } + // The SDK forwards these from Claude Code without declaring them on CanUseTool. + if ("requiresUserInteraction" in options && options.requiresUserInteraction === true) { + return false; + } + const reasonCode = "decisionReasonCode" in options ? options.decisionReasonCode : undefined; + if (typeof reasonCode === "string" && CONFIGURED_ASK_CODES.has(reasonCode)) { + return false; + } + const reasonType = "decisionReasonType" in options ? options.decisionReasonType : undefined; + return typeof reasonType === "string" && CLAUDE_OWN_CHECK_TYPES.has(reasonType); +} diff --git a/packages/server/src/server/agent/providers/claude/model-discovery.ts b/packages/server/src/server/agent/providers/claude/model-discovery.ts index d74898472b..674a61982e 100644 --- a/packages/server/src/server/agent/providers/claude/model-discovery.ts +++ b/packages/server/src/server/agent/providers/claude/model-discovery.ts @@ -6,6 +6,10 @@ import type { ProviderRuntimeSettings } from "../../provider-launch-config.js"; import { terminateWithTreeKill } from "../../../../utils/tree-kill.js"; import { claudeQuery, type ClaudeQueryInput, type ClaudeQueryContext } from "./query.js"; +const DISCOVERY_WAIT_MS = 5_000; +// Long enough for the CLI to finish an OAuth token refresh it started before the wait ended. +const DISCOVERY_EXIT_GRACE_MS = 60_000; + interface ClaudeModelDiscoveryOptions { resolveBinary: () => Promise; runtimeSettings?: ProviderRuntimeSettings; @@ -18,19 +22,24 @@ type OpenDiscoveryQuery = ( context: ClaudeQueryContext, ) => Pick; +type DiscoveryQuery = ReturnType; + +// Discovery processes left to exit on their own after their caller stopped waiting. +const exitingDiscoveries = new Map Promise>(); + // The curated catalog survives a failed or slow probe. This process never receives // a prompt and must not persist a session or launch user MCP servers/hooks. export async function discoverClaudeModels( options: ClaudeModelDiscoveryOptions, openQuery: OpenDiscoveryQuery = claudeQuery, ): Promise { - const controller = new AbortController(); + const waitController = new AbortController(); const signal = options.signal - ? AbortSignal.any([options.signal, controller.signal]) - : controller.signal; + ? AbortSignal.any([options.signal, waitController.signal]) + : waitController.signal; const timer = setTimeout( - () => controller.abort(new Error("Claude model discovery timed out")), - 5_000, + () => waitController.abort(new Error("Claude model discovery timed out")), + DISCOVERY_WAIT_MS, ); let endInput!: () => void; const ended = new Promise((resolve) => { @@ -46,7 +55,7 @@ export async function discoverClaudeModels( }; }, }; - let query: ReturnType | undefined; + let query: DiscoveryQuery | undefined; let child: ChildProcess | undefined; try { signal.throwIfAborted(); @@ -64,7 +73,8 @@ export async function discoverClaudeModels( strictMcpConfig: true, settingSources: ["user"], settings: { disableAllHooks: true }, - abortController: controller, + // No abortController: the SDK kills the process when it aborts, and the end of + // the wait must not. }, }, { @@ -78,12 +88,56 @@ export async function discoverClaudeModels( } finally { clearTimeout(timer); endInput(); - try { - query?.close(); - } finally { - if (child) { - await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 }); - } + if (query && child && !hasExited(child)) { + // The CLI may be refreshing an expired OAuth token, even after it has answered. + // Claude Code rotates the refresh token before saving the new pair, so killing it now + // leaves a revoked token on disk and logs the user out (#9314). With its input ended + // it exits once that work is done; the grace period and daemon shutdown bound the wait. + letDiscoveryExit(query, child); + } else { + await retireDiscovery(query, child); } } } + +/** Kills discovery processes still exiting after their wait ended. Called on daemon shutdown. */ +export async function killExitingClaudeModelDiscoveries(): Promise { + await Promise.all(Array.from(exitingDiscoveries.values(), (kill) => kill())); +} + +function letDiscoveryExit(query: DiscoveryQuery, child: ChildProcess): void { + function forget(): void { + clearTimeout(graceTimer); + child.off("exit", onExit); + exitingDiscoveries.delete(child); + } + function onExit(): void { + forget(); + query.close(); + } + async function kill(): Promise { + forget(); + await retireDiscovery(query, child); + } + const graceTimer = setTimeout(() => void kill(), DISCOVERY_EXIT_GRACE_MS); + graceTimer.unref(); + child.once("exit", onExit); + exitingDiscoveries.set(child, kill); +} + +async function retireDiscovery( + query: DiscoveryQuery | undefined, + child: ChildProcess | undefined, +): Promise { + try { + query?.close(); + } finally { + if (child) { + await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 }); + } + } +} + +function hasExited(child: ChildProcess): boolean { + return child.exitCode !== null || child.signalCode !== null; +} diff --git a/packages/server/src/server/agent/providers/claude/models.test.ts b/packages/server/src/server/agent/providers/claude/models.test.ts index 1287fd6335..d9a7ddc98d 100644 --- a/packages/server/src/server/agent/providers/claude/models.test.ts +++ b/packages/server/src/server/agent/providers/claude/models.test.ts @@ -1,3 +1,4 @@ +import { ChildProcess } from "node:child_process"; import * as fs from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; @@ -1173,4 +1174,127 @@ describe("Claude model discovery process", () => { await expect(result).rejects.toBe(failure); expect(closed).toBe(true); }); + + describe("when the CLI is still starting up at the deadline", () => { + // Without a pid, terminateWithTreeKill signals the child directly instead of a real tree. + class StartingClaudeProcess extends ChildProcess { + readonly signals: string[] = []; + override kill(signal?: NodeJS.Signals | number): boolean { + this.signals.push(String(signal)); + this.emit("exit", null, signal); + return true; + } + exitOnItsOwn(): void { + this.emit("exit", 0, null); + } + } + + interface StalledDiscoveryState { + closed: boolean; + inputEnded: boolean; + } + + async function recordInputEnd( + prompt: AsyncIterable, + state: StalledDiscoveryState, + ): Promise { + await prompt[Symbol.asyncIterator]().next(); + state.inputEnded = true; + } + + // By default the CLI never answers: an expired OAuth token is refreshed first. + function startStalledDiscovery( + supportedModels: () => Promise = () => new Promise(() => {}), + ) { + const child = new StartingClaudeProcess(); + const state: StalledDiscoveryState = { closed: false, inputEnded: false }; + const result = discoverClaudeModels( + { resolveBinary: async () => "/claude", env: {} }, + (input, context) => { + if (typeof input.prompt === "string") throw new Error("unexpected inference prompt"); + void recordInputEnd(input.prompt, state); + context.onChildProcess?.(child); + return { + supportedModels, + close: () => { + state.closed = true; + }, + }; + }, + ); + return { child, state, result }; + } + + afterEach(() => { + vi.useRealTimers(); + }); + + it("stops waiting at the limit but lets the CLI finish instead of killing it", async () => { + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(); + const settled = expect(result).rejects.toThrow("Claude model discovery timed out"); + + await vi.advanceTimersByTimeAsync(5_000); + await settled; + expect(state.inputEnded).toBe(true); + expect(child.signals).toEqual([]); + expect(state.closed).toBe(false); + + await vi.advanceTimersByTimeAsync(59_999); + expect(child.signals).toEqual([]); + + await vi.advanceTimersByTimeAsync(1); + expect(child.signals).toEqual(["SIGTERM"]); + expect(state.closed).toBe(true); + }); + + async function answerAtOnce(): Promise { + return []; + } + + it("lets the CLI finish after it answers instead of killing it", async () => { + // The CLI answers supportedModels() before its startup token refresh has saved the + // rotated refresh token, so a kill right after the answer also logs the user out. + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(answerAtOnce); + await expect(result).resolves.toEqual([]); + await vi.advanceTimersByTimeAsync(0); + expect(state.inputEnded).toBe(true); + expect(child.signals).toEqual([]); + + await vi.advanceTimersByTimeAsync(1_000); + child.exitOnItsOwn(); + expect(state.closed).toBe(true); + await vi.advanceTimersByTimeAsync(120_000); + expect(child.signals).toEqual([]); + }); + + it("never signals a CLI that exits on its own during the grace period", async () => { + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(); + const settled = expect(result).rejects.toThrow("Claude model discovery timed out"); + await vi.advanceTimersByTimeAsync(5_000); + await settled; + + await vi.advanceTimersByTimeAsync(2_000); + child.exitOnItsOwn(); + expect(state.closed).toBe(true); + + await vi.advanceTimersByTimeAsync(120_000); + expect(child.signals).toEqual([]); + }); + + it("tree-kills a still-running CLI when the daemon shuts down", async () => { + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(); + const settled = expect(result).rejects.toThrow("Claude model discovery timed out"); + await vi.advanceTimersByTimeAsync(5_000); + await settled; + expect(child.signals).toEqual([]); + + await new ClaudeAgentClient({ logger: createTestLogger() }).shutdown(); + expect(child.signals).toEqual(["SIGTERM"]); + expect(state.closed).toBe(true); + }); + }); }); diff --git a/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts b/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts index 6651f3e909..a56516a70d 100644 --- a/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts +++ b/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts @@ -46,3 +46,47 @@ test("enriches only live tasks with their correlated launch metadata", () => { runtime.observe(message({ type: "system", subtype: "background_tasks_changed", tasks: [] })), ).toEqual([]); }); + +test("keeps the runtime while Claude's last Stop hook lists session crons", () => { + const runtime = new ClaudeRuntimeSafety(); + runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" })); + const cron = { id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" }; + + runtime.observeStop([cron]); + expect(runtime.canStopRuntime()).toBe(false); + + runtime.observeStop(undefined); + expect(runtime.canStopRuntime()).toBe(false); + + runtime.observeStop([]); + expect(runtime.canStopRuntime()).toBe(true); + + runtime.observeStop([cron]); + runtime.reset(); + runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" })); + expect(runtime.canStopRuntime()).toBe(true); +}); + +test("holds the runtime when a turn that called a cron tool ends without a Stop hook", () => { + const runtime = new ClaudeRuntimeSafety(); + runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" })); + const callTool = (name: string) => + runtime.observe( + message({ + type: "assistant", + message: { content: [{ type: "tool_use", id: `${name}-1`, name, input: {} }] }, + }), + ); + + // The turn schedules a cron and is interrupted, so no Stop hook reports it. + callTool("CronCreate"); + expect(runtime.canStopRuntime()).toBe(false); + + runtime.observeStop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "hi" }]); + callTool("CronDelete"); + runtime.observeStop([]); + expect(runtime.canStopRuntime()).toBe(true); + + callTool("ScheduleWakeup"); + expect(runtime.canStopRuntime()).toBe(false); +}); diff --git a/packages/server/src/server/agent/providers/claude/runtime-safety.ts b/packages/server/src/server/agent/providers/claude/runtime-safety.ts index 8688e93f45..e8ff315a58 100644 --- a/packages/server/src/server/agent/providers/claude/runtime-safety.ts +++ b/packages/server/src/server/agent/providers/claude/runtime-safety.ts @@ -1,8 +1,10 @@ -import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { SDKMessage, SessionCronSummary } from "@anthropic-ai/claude-agent-sdk"; import type { AgentBackgroundWorkInput } from "../../background-work/index.js"; import { parseClaudeCodeVersion } from "./model-manifest.js"; import { toBackgroundWorkInputs, type ClaudeBackgroundTask } from "./background-work.js"; +const SESSION_CRON_TOOLS = new Set(["CronCreate", "CronDelete", "ScheduleWakeup"]); + /** Process-local background ownership. Completion delivery can follow an empty roster. */ export class ClaudeRuntimeSafety { private inventoryState: "unknown" | "supported" | "retired" = "unknown"; @@ -16,8 +18,15 @@ export class ClaudeRuntimeSafety { private readonly monitorTools = new Set(); private readonly toolInputs = new Map(); private readonly taskTools = new Map(); + // Session-only crons and wakeups live in the process and die with it. Only the Stop hook + // lists them, and Claude runs it only for turns that complete. A cron tool call makes the + // count unknown until the next Stop, so an interrupted or failed turn keeps the runtime. + private sessionCrons = 0; + private sessionCronsUnknown = false; reset(): void { + this.sessionCrons = 0; + this.sessionCronsUnknown = false; this.inventoryState = "unknown"; this.turnSeen = false; this.liveTasks = []; @@ -38,6 +47,13 @@ export class ClaudeRuntimeSafety { this.turnSeen = true; } + /** Called with the session crons of each main-thread Stop hook. Older CLIs omit them. */ + observeStop(sessionCrons: readonly SessionCronSummary[] | undefined): void { + if (this.inventoryState === "retired") return; + this.sessionCronsUnknown = false; + if (sessionCrons) this.sessionCrons = sessionCrons.length; + } + /** Returns a full replacement only when the visible inventory changes. */ observe(message: SDKMessage): AgentBackgroundWorkInput[] | undefined { if (this.inventoryState === "retired") return undefined; @@ -54,6 +70,8 @@ export class ClaudeRuntimeSafety { if (message.type === "assistant") { let relevant = false; for (const block of message.message.content) { + if (block.type === "tool_use" && SESSION_CRON_TOOLS.has(block.name)) + this.sessionCronsUnknown = true; if (block.type === "tool_use" && (block.name === "Monitor" || block.name === "Bash")) { if (block.name === "Monitor") relevant = this.observeMonitor(block.id) || relevant; relevant = this.observeInput(block.id, block.input) || relevant; @@ -129,6 +147,8 @@ export class ClaudeRuntimeSafety { if (this.inventoryState === "unknown" && !this.turnSeen) return true; return ( this.inventoryState === "supported" && + this.sessionCrons === 0 && + !this.sessionCronsUnknown && this.liveTasks.length === 0 && this.awaitingNotifications.size === 0 ); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts index 77c36b4fd0..236dfe469a 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts @@ -22,6 +22,18 @@ function isCodexInstalled(): boolean { } } +function supportsInstructionSnapshots(): boolean { + try { + const match = execFileSync("codex", ["--version"], { encoding: "utf8" }).match( + /(\d+)\.(\d+)\.(\d+)/, + ); + if (!match) return false; + return Number(match[1]) > 0 || Number(match[2]) >= 121; + } catch { + return false; + } +} + function sse(events: unknown[]): string { return events .map((event) => { @@ -133,7 +145,7 @@ async function startMockResponsesServer(sequence: string[]): Promise<{ }> { const requestBodies: string[] = []; let index = 0; - const server = createServer((req, res) => { + const server = createServer({ maxHeaderSize: 1024 * 1024 }, (req, res) => { const chunks: Buffer[] = []; req.on("data", (chunk) => chunks.push(Buffer.from(chunk))); req.on("end", () => { @@ -221,6 +233,85 @@ function waitForEvent(params: { } describe("Codex app-server provider (local e2e)", () => { + test.runIf(supportsInstructionSnapshots())( + "delivers changed and removed instructions to the model across process restarts", + async () => { + const artifactDir = path.resolve(process.cwd(), "../../.artifacts"); + mkdirSync(artifactDir, { recursive: true }); + const cwd = mkdtempSync(path.join(artifactDir, "codex-snapshot-cwd-")); + const codexHome = mkdtempSync(path.join(artifactDir, "codex-snapshot-home-")); + const server = await startMockResponsesServer([]); + const client = new CodexAppServerAgentClient(createTestLogger()); + const base = { provider: "codex" as const, cwd, modeId: "auto", model: "mock-model" }; + const launch = { env: { CODEX_HOME: codexHome } }; + const run = async (session: Awaited>) => { + const finished = waitForEvent({ + session, + timeoutMs: 20_000, + label: "turn completion", + predicate: ( + event, + ): event is Extract< + AgentStreamEvent, + { type: "turn_completed" | "turn_failed" | "turn_canceled" } + > => + event.type === "turn_completed" || + event.type === "turn_failed" || + event.type === "turn_canceled", + }); + await session.startTurn("continue"); + const result = await finished; + if (result.type !== "turn_completed") throw new Error(JSON.stringify(result)); + const handle = session.describePersistence(); + if (!handle) throw new Error("Expected persisted Codex thread"); + await session.close(); + return handle; + }; + try { + writeMockCodexConfig(codexHome, server.url); + let handle = await run( + await client.createSession( + { ...base, pluginAppendSystemPrompt: ["old snapshot"] }, + launch, + ), + ); + expect(server.requestBodies.at(-1)).toContain("old snapshot"); + expect(server.requestBodies.at(-1)).not.toContain("paseo_instruction_snapshot"); + handle = await run( + await client.resumeSession( + handle, + { ...base, pluginAppendSystemPrompt: ["new snapshot"] }, + launch, + ), + ); + expect(server.requestBodies.at(-1)).toContain("new snapshot"); + expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2); + handle = await run( + await client.resumeSession( + handle, + { ...base, pluginAppendSystemPrompt: ["new snapshot"] }, + launch, + ), + ); + expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2); + await run( + await client.resumeSession( + handle, + { ...base, pluginAppendSystemPrompt: undefined }, + launch, + ), + ); + expect(server.requestBodies.at(-1)).toContain('\\"instructions\\":\\"\\"'); + expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(4); + } finally { + await server.close(); + rmSync(cwd, { recursive: true, force: true }); + rmSync(codexHome, { recursive: true, force: true }); + } + }, + 60_000, + ); + test.runIf(isCodexInstalled())( "concurrent import scans initialize successfully in a fresh shared Codex home", async () => { diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 667c0965fb..d1c1a5055e 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -7,6 +7,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { PassThrough } from "node:stream"; import { fileURLToPath } from "node:url"; +import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js"; import type { AgentClient, @@ -100,6 +101,7 @@ import { import { createTestLogger } from "../../../test-utils/test-logger.js"; import { asInternals as castInternals, createStub } from "../../test-utils/class-mocks.js"; import { AgentManager } from "../agent-manager.js"; +import { AgentStorage } from "../agent-storage.js"; import { buildProviderRegistry } from "../provider-registry.js"; interface CollaborationModeRecord { @@ -173,6 +175,9 @@ function createSession( ) as CodexTestSession; session.connectionState = "connected"; session.currentThreadId = "test-thread"; + castInternals<{ instructionSnapshot: { recordNewThread(id: string): void } }>( + session, + ).instructionSnapshot.recordNewThread("test-thread"); session.activeForegroundTurnId = "test-turn"; return session; } @@ -683,7 +688,7 @@ function codexAgentItem(text: string) { // An AgentManager over a real Codex provider whose every spawn gets a fresh fake // app-server serving `threads` from thread/read. -function createReopenableCodexAgent(threads: Record) { +function createReopenableCodexAgent(threads: Record, registry?: AgentStorage) { const appServers: FakeCodexAppServer[] = []; const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, { appServerProcess: createFakeCodexAppServerProcess(() => { @@ -715,7 +720,11 @@ function createReopenableCodexAgent(threads: Record) { }, resumeSession: (...args) => provider.resumeSession(...args), }; - const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() }); + const manager = new AgentManager({ + clients: { codex: client }, + registry, + logger: createTestLogger(), + }); const agentId = "00000000-0000-4000-8000-000000000001"; const handle = { provider: "codex", sessionId: "saved-thread" }; const config = createConfig({ cwd: process.cwd() }); @@ -728,6 +737,9 @@ function createReopenableCodexAgent(threads: Record) { return { manager, agentId, + handle, + config, + appServers, latestAppServer: () => appServers[appServers.length - 1], threadMethods: (index: number) => appServers[index] @@ -1406,6 +1418,216 @@ describe("Codex app-server provider", () => { } }); + test("reopening drops disabled plugin instructions and starts with fresh collaboration settings", async () => { + const modes = { + data: [ + { + name: "Code", + mode: "default", + model: null, + reasoning_effort: null, + }, + ], + }; + const firstServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes }); + const first = await createProviderWithFakeAppServer(firstServer).createSession( + createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }), + ); + await first.startTurn("first"); + const firstTurn = await firstServer.waitForTurnStart(); + expect( + firstServer.requests().find((request) => request.method === "thread/start")?.params, + ).toMatchObject({ developerInstructions: "Plugin instructions" }); + expect(firstTurn).toMatchObject({ + collaborationMode: { + settings: { developer_instructions: null }, + }, + }); + const started = waitForNextEvent(first, "thread_started"); + firstServer.startsTurn({ threadId: "thread-1" }); + await started; + const handle = first.describePersistence()!; + expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt"); + await first.close(); + + const secondServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes }); + const resumed = await createProviderWithFakeAppServer(secondServer).resumeSession(handle, { + pluginAppendSystemPrompt: undefined, + }); + try { + const resume = secondServer.requests().find((request) => request.method === "thread/resume"); + expect(resume?.params).not.toHaveProperty("developerInstructions"); + await resumed.startTurn("after disable"); + const secondTurn = await secondServer.waitForTurnStart(); + expect(secondTurn).not.toHaveProperty("developerInstructions"); + expect(secondTurn).toMatchObject({ + collaborationMode: { settings: { developer_instructions: null } }, + }); + firstServer.assertNoErrors(); + secondServer.assertNoErrors(); + } finally { + await resumed.close(); + } + }); + + test("reopen injects current instructions once, including an explicit empty snapshot", async () => { + const handlers = { + initialize: () => ({ userAgent: "codex/0.165.0" }), + "thread/inject_items": () => ({}), + }; + const firstServer = createFakeCodexAppServer(handlers); + const first = await createProviderWithFakeAppServer(firstServer).createSession( + createConfig({ pluginAppendSystemPrompt: ["Old plugin"] }), + ); + await first.startTurn("first"); + const started = waitForNextEvent(first, "thread_started"); + firstServer.startsTurn({ threadId: "thread-1" }); + await started; + expect( + firstServer.requests().filter((request) => request.method === "thread/inject_items"), + ).toEqual([]); + const original = first.describePersistence()!; + expect(original.metadata).toHaveProperty("paseoInstructionReceipt"); + await first.close(); + + const changedServer = createFakeCodexAppServer(handlers); + const changed = await createProviderWithFakeAppServer(changedServer).resumeSession(original, { + pluginAppendSystemPrompt: ["New plugin"], + }); + const injected = changedServer + .requests() + .filter((request) => request.method === "thread/inject_items"); + expect(injected).toHaveLength(1); + expect(JSON.stringify(injected[0]?.params)).toContain("New plugin"); + const changedHandle = changed.describePersistence()!; + expect(changedHandle.metadata?.paseoInstructionReceipt).not.toEqual( + original.metadata?.paseoInstructionReceipt, + ); + await changed.close(); + + const sameServer = createFakeCodexAppServer(handlers); + const same = await createProviderWithFakeAppServer(sameServer).resumeSession(changedHandle, { + pluginAppendSystemPrompt: ["New plugin"], + }); + expect( + sameServer.requests().filter((request) => request.method === "thread/inject_items"), + ).toEqual([]); + await same.close(); + + const emptyServer = createFakeCodexAppServer(handlers); + const empty = await createProviderWithFakeAppServer(emptyServer).resumeSession(changedHandle, { + pluginAppendSystemPrompt: undefined, + }); + const removal = emptyServer + .requests() + .filter((request) => request.method === "thread/inject_items"); + expect(removal).toHaveLength(1); + expect(JSON.stringify(removal[0]?.params)).toContain('\\"instructions\\":\\"\\"'); + await empty.close(); + }); + + test("requires a compatible Codex version before creating a thread with plugin instructions", async () => { + const appServer = createFakeCodexAppServer({ + initialize: () => ({ userAgent: "codex/0.120.0" }), + }); + await expect( + createProviderWithFakeAppServer(appServer).createSession( + createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }), + ), + ).rejects.toThrow("Update Codex to 0.121.0 or newer"); + }); + + test("retries an instruction snapshot when injection fails", async () => { + const snapshot = new CodexInstructionSnapshot("current", undefined); + const request = vi + .fn() + .mockRejectedValueOnce(new Error("connection lost")) + .mockResolvedValue({}); + await expect(snapshot.apply("thread-1", request, true)).rejects.toThrow("connection lost"); + expect(snapshot.describe("thread-1")).toBeUndefined(); + await snapshot.apply("thread-1", request, true); + expect(snapshot.describe("thread-1")).toEqual({ + threadId: "thread-1", + digest: expect.any(String), + }); + await snapshot.apply("thread-1", request, true); + expect(request).toHaveBeenCalledTimes(2); + }); + + test("keeps built-in Plan instructions while sending plugin instructions to the thread", async () => { + const appServer = createFakeCodexAppServer({ + "collaborationMode/list": () => ({ + data: [ + { name: "Plan", mode: "plan", model: null, reasoning_effort: "medium" }, + { name: "Default", mode: "default", model: null, reasoning_effort: null }, + ], + }), + }); + const session = await createProviderWithFakeAppServer(appServer).createSession( + createConfig({ + pluginAppendSystemPrompt: ["Plugin instructions"], + providerOptions: { plan_mode: true }, + }), + ); + try { + await session.startTurn("make a plan"); + const start = appServer.requests().find((request) => request.method === "thread/start"); + expect(start?.params).toMatchObject({ developerInstructions: "Plugin instructions" }); + expect(await appServer.waitForTurnStart()).toMatchObject({ + collaborationMode: { mode: "plan", settings: { developer_instructions: null } }, + }); + expect( + appServer.requests().find((request) => request.method === "turn/start")?.params, + ).not.toHaveProperty("developerInstructions"); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + + test.each([ + { instructions: undefined, expected: undefined }, + { instructions: ["Current plugin"], expected: "Current plugin" }, + ])( + "rebuilds restored instructions with an unavailable collaboration catalog: $expected", + async ({ instructions, expected }) => { + const appServer = createFakeCodexAppServer({ + "collaborationMode/list": () => ({ data: [] }), + "thread/resume": () => ({ + thread: { id: "saved-thread" }, + collaborationMode: { + mode: "default", + settings: { + model: "gpt-5.4", + reasoning_effort: "medium", + developer_instructions: "Old plugin", + }, + }, + }), + }); + const session = await createProviderWithFakeAppServer(appServer).resumeSession( + { sessionId: "saved-thread" }, + { pluginAppendSystemPrompt: instructions }, + ); + try { + const resume = appServer.requests().find((request) => request.method === "thread/resume"); + if (expected) expect(resume?.params).toMatchObject({ developerInstructions: expected }); + else expect(resume?.params).not.toHaveProperty("developerInstructions"); + await session.startTurn("after reopen"); + const turn = await appServer.waitForTurnStart(); + expect(turn).toMatchObject({ + collaborationMode: { + mode: "default", + settings: { model: "gpt-5.4", developer_instructions: null }, + }, + }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }, + ); + test("keeps the default effort when a session without one is resumed after a restart", async () => { const beforeRestart = createFakeCodexAppServer(); const firstSession = await createProviderWithFakeAppServer(beforeRestart).createSession( @@ -2215,6 +2437,36 @@ describe("Codex app-server provider", () => { appServer.assertNoErrors(); }); + test("lets idle cleanup release a session opened only to read its history", async () => { + let spawns = 0; + const appServer = createFakeCodexAppServer({ + "thread/resume": () => + Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))), + "thread/read": () => ({ thread: { turns: [] } }), + }); + const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, { + appServerProcess: createFakeCodexAppServerProcess(() => { + spawns += 1; + return appServer.child; + }), + }); + const internals = castInternals<{ + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + }>(provider); + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + + const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, { + purpose: "history", + }); + + expect(await session.canStopRuntime!()).toBe(true); + expect(spawns).toBe(1); + await session.close(); + appServer.assertNoErrors(); + }); + test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => { const threadRequests: string[] = []; let resumeAttempts = 0; @@ -2285,7 +2537,12 @@ describe("Codex app-server provider", () => { ]); // Background terminal observation is independent of conversation history loading. const historyMethods = (index: number) => - codex.threadMethods(index).filter((method) => method !== "thread/backgroundTerminals/list"); + codex + .threadMethods(index) + .filter( + (method) => + method !== "thread/backgroundTerminals/list" && method !== "thread/inject_items", + ); expect(historyMethods(0)).toEqual([ "thread/loaded/list", "thread/resume", @@ -2299,6 +2556,34 @@ describe("Codex app-server provider", () => { } }); + test("persists an acknowledged instruction snapshot before a turn on repeated opens", async () => { + const artifactDir = path.resolve(process.cwd(), "../../.artifacts"); + mkdirSync(artifactDir, { recursive: true }); + const dir = await mkdtemp(path.join(artifactDir, "codex-receipt-")); + const storage = new AgentStorage(dir, createTestLogger()); + const codex = createReopenableCodexAgent({}, storage); + try { + let handle = codex.handle; + for (let i = 0; i < 3; i++) { + await codex.manager.resumeAgentFromPersistence(handle, codex.config, codex.agentId); + await storage.flush(); + const saved = await storage.get(codex.agentId); + expect(saved?.persistence?.metadata?.paseoInstructionReceipt).toEqual(expect.any(Object)); + handle = saved!.persistence!; + await codex.manager.closeAgent(codex.agentId); + } + expect( + codex.appServers + .flatMap((server) => server.requests()) + .filter((request) => request.method === "thread/inject_items"), + ).toHaveLength(1); + } finally { + if (codex.manager.getAgent(codex.agentId)) await codex.manager.closeAgent(codex.agentId); + await storage.flush(); + rmSync(dir, { recursive: true, force: true }); + } + }); + test("rewinds an agent reopened without reading its Codex history", async () => { const firstTurn = { id: "turn-1", @@ -2706,11 +2991,14 @@ describe("Codex app-server provider", () => { turnId: "turn-next", itemId: "new", processId: "12", - command: "echo hello", + command: "sleep 99", }); await vi.waitFor(() => expect(hasBackgroundListRequest(appServer, "forked-thread")).toBe(true), ); + await new Promise((resolve) => setImmediate(resolve)); + expect(latestBackgroundWork(events)).toMatchObject({ items: [{ command: "sleep 180" }] }); + appServer.completeTurn({ threadId: "forked-thread" }); await vi.waitFor(() => expect(latestBackgroundWork(events)).toMatchObject({ items: [{ command: "sleep 180" }, { command: "sleep 99" }], @@ -2815,6 +3103,9 @@ describe("Codex app-server provider", () => { const session = new CodexAppServerAgentSession( createConfig({ cwd: "/workspace/project", + systemPrompt: "Agent instructions", + daemonAppendSystemPrompt: "Daemon instructions", + pluginAppendSystemPrompt: ["Plugin instructions"], mcpServers: { paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" }, }, @@ -2846,6 +3137,24 @@ describe("Codex app-server provider", () => { await session.revertConversation({ messageId: "codex-first" }); + const forkRequest = appServer.requests().find((request) => request.method === "thread/fork"); + expect(forkRequest?.params).toMatchObject({ + developerInstructions: "Agent instructions\n\nDaemon instructions\n\nPlugin instructions", + }); + const rewindRequests = appServer + .requests() + .filter((request) => + ["thread/fork", "thread/rollback", "thread/inject_items"].includes( + String(request.method), + ), + ); + expect(rewindRequests.map((request) => request.method)).toEqual( + historyMode === "legacy" + ? ["thread/fork", "thread/rollback", "thread/inject_items"] + : ["thread/fork", "thread/inject_items"], + ); + expect(rewindRequests.at(-1)?.params).toMatchObject({ threadId: "forked-thread" }); + expect(JSON.stringify(rewindRequests.at(-1)?.params)).toContain("Plugin instructions"); const forkConfigs = appServer .requests() .filter((request) => request.method === "thread/fork") @@ -5119,7 +5428,7 @@ describe("Codex app-server provider", () => { threadStart.resolve({ thread: { id: "thread-1" } }); await expect(interruptPromise).resolves.toBeUndefined(); - await expect(resultPromise).rejects.toThrow("interrupted before reaching Codex"); + await expect(resultPromise).resolves.toMatchObject({ canceled: true, timeline: [] }); expect(appServer.requests()).not.toContainEqual( expect.objectContaining({ method: "turn/start" }), ); @@ -8221,6 +8530,49 @@ describe("Codex denied plan approvals", () => { }); describe("Codex interactive resume startup", () => { + test("keeps an autonomous command started during resume out of background work until settlement", async () => { + const appServer = createFakeCodexAppServer({ + "thread/resume": () => { + appServer.startsTurn({ threadId: "saved-thread", turnId: "autonomous-turn" }); + appServer.startsTerminalCommand({ + threadId: "saved-thread", + turnId: "autonomous-turn", + itemId: "resumed-command", + processId: "123", + command: "sleep 120", + }); + return { thread: { id: "saved-thread" } }; + }, + "thread/read": () => ({ thread: { turns: [] } }), + "thread/backgroundTerminals/list": () => ({ + data: [{ itemId: "resumed-command", processId: "123", command: "sleep 120" }], + nextCursor: null, + }), + }); + const session = new CodexAppServerAgentSession( + createConfig({ modeId: "full-access" }), + { sessionId: "saved-thread" }, + createTestLogger(), + async () => appServer.child, + ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.connect(); + await expect.poll(() => latestBackgroundWork(events)?.items).toEqual([]); + appServer.completeTurn({ threadId: "saved-thread" }); + await expect + .poll(() => latestBackgroundWork(events)?.items) + .toMatchObject([{ command: "sleep 120" }]); + expect( + events.filter((event) => event.type === "background_work" && event.items?.length), + ).toHaveLength(1); + } finally { + await session.close(); + appServer.assertNoErrors(); + } + }); + test("delivers an autonomous turn that starts during resume to the first subscriber", async () => { const appServer = createFakeCodexAppServer({ "turn/interrupt": () => ({}), @@ -8312,6 +8664,93 @@ describe("Codex interactive resume startup", () => { ); }); +test.each([true, false])( + "Codex background work excludes a live turn's commands (inventory item IDs: %s)", + async (itemIds) => { + let terminals = [{ itemId: "earlier", processId: "1", command: "sleep 180" }]; + const appServer = createFakeCodexAppServer({ + "thread/backgroundTerminals/list": () => ({ + data: terminals.map(({ itemId, ...row }) => (itemIds ? { ...row, itemId } : row)), + nextCursor: null, + }), + }); + const session = new CodexAppServerAgentSession( + createConfig(), + null, + createTestLogger(), + async () => appServer.child, + ); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.startTurn("first"); + await appServer.waitForTurnStart(); + appServer.completeTurn(); + await expect + .poll(() => latestBackgroundWork(events)?.items) + .toMatchObject([{ command: "sleep 180" }]); + await session.startTurn("git status"); + appServer.startsTurn({ threadId: "thread-1", turnId: "second" }); + terminals = [...terminals, { itemId: "status", processId: "2", command: "git status" }]; + const before = appServer.requests().length; + appServer.startsTerminalCommand({ + threadId: "thread-1", + turnId: "second", + itemId: "status", + processId: itemIds ? undefined : "2", + command: "git status", + }); + await expect + .poll(() => + appServer + .requests() + .slice(before) + .some((request) => request.method === "thread/backgroundTerminals/list"), + ) + .toBe(true); + await new Promise((resolve) => setImmediate(resolve)); + expect(latestBackgroundWork(events)?.items).toMatchObject([{ command: "sleep 180" }]); + terminals = terminals.filter((row) => row.itemId !== "status"); + appServer.completesCommand({ + threadId: "thread-1", + callId: "status", + command: "git status", + output: "clean", + }); + terminals.push({ itemId: "server", processId: "3", command: "npm run dev" }); + appServer.startsTerminalCommand({ + threadId: "thread-1", + turnId: "second", + itemId: "server", + processId: itemIds ? undefined : "3", + command: "npm run dev", + }); + // A process surviving settlement becomes background work even if its item has not completed. + appServer.completeTurn(); + await expect + .poll(() => latestBackgroundWork(events)?.items) + .toMatchObject([{ command: "sleep 180" }, { command: "npm run dev" }]); + expect( + events + .filter((event) => event.type === "background_work") + .flatMap((event) => event.items ?? []) + .some((item) => item.command === "git status"), + ).toBe(false); + terminals = []; + appServer.completesCommand({ + threadId: "thread-1", + callId: "server", + command: "npm run dev", + output: "exited", + }); + await expect.poll(() => latestBackgroundWork(events)?.items).toEqual([]); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }, +); + test("Codex runtime safety queries live terminals and retains unsupported app servers", async () => { let response: unknown = { data: [], nextCursor: null }; const appServer = createFakeCodexAppServer({ "thread/backgroundTerminals/list": () => response }); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 269801fd73..caae0c2261 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -3,6 +3,7 @@ import { applyProviderOptionsPatch } from "../option-controls.js"; import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js"; import { CodexBackgroundInventory } from "./codex/background-inventory.js"; import { + AgentTurnStartCanceledError, getAgentStreamEventTurnId, type AgentPermissionAction, type AgentCapabilityFlags, @@ -55,7 +56,8 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { z } from "zod"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; -import { composeSystemPromptParts } from "../system-prompt.js"; +import { composeAgentSystemPrompt } from "../system-prompt.js"; +import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js"; import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js"; import { fileChangesToPreview, @@ -3591,9 +3593,12 @@ interface ConsumedRootCompaction { export class CodexAppServerAgentSession implements AgentSession { readonly provider = CODEX_PROVIDER; readonly capabilities = CODEX_APP_SERVER_CAPABILITIES; + readonly persistenceUpdatedOnResume = true; private readonly logger: Logger; private readonly config: AgentSessionConfig; + private readonly instructionSnapshot: CodexInstructionSnapshot; + private supportsInstructionSnapshots = false; private readonly asyncQuestions: CodexAsyncQuestions; private readonly codexHome: string; private currentMode: string; @@ -3706,6 +3711,13 @@ export class CodexAppServerAgentSession implements AgentSession { reasoning_effort?: string | null; developer_instructions?: string | null; }> = []; + private restoredCollaborationMode: { + name: string; + mode: string; + model: string; + reasoning_effort: string | null; + developer_instructions?: never; + } | null = null; private resolvedCollaborationMode: { mode: string; settings: Record; @@ -3751,6 +3763,10 @@ export class CodexAppServerAgentSession implements AgentSession { this.providerOptions = validateProviderOptions("codex", CodexProviderOptionsSchema, config.providerOptions) ?? {}; this.config = config; + this.instructionSnapshot = new CodexInstructionSnapshot( + composeAgentSystemPrompt(config), + resumeHandle?.metadata?.paseoInstructionReceipt, + ); this.harnessEnvironment = deps.environment ?? buildCodexAppServerEnv(); this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions); this.codexHome = deps.codexHome ?? resolveCodexHomeDir(process.env); @@ -3827,6 +3843,9 @@ export class CodexAppServerAgentSession implements AgentSession { throw this.createClosedError(); } this.client = client; + // Resume can emit autonomous commands before connection setup finishes. Their + // ownership must live for the whole connection, including startup notifications. + this.background.start({ client, thread: null }); client.setUnexpectedTerminationHandler((error) => { this.pendingNotifications = this.queueUnexpectedTermination(error); }); @@ -3834,9 +3853,17 @@ export class CodexAppServerAgentSession implements AgentSession { this.registerRequestHandlers(); try { - this.threadRollbackAvailable = codexServerHasThreadRollback( - toObjectRecord(initialized)?.userAgent, - ); + const userAgent = toObjectRecord(initialized)?.userAgent; + this.threadRollbackAvailable = codexServerHasThreadRollback(userAgent); + this.supportsInstructionSnapshots = + typeof userAgent === "string" && codexVersionAtLeast(userAgent, [0, 121, 0]); + if ( + !this.currentThreadId && + this.config.pluginAppendSystemPrompt?.length && + !this.supportsInstructionSnapshots + ) { + throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates."); + } this.speedModels = CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? []; @@ -3854,7 +3881,7 @@ export class CodexAppServerAgentSession implements AgentSession { throw this.createClosedError(); } this.connectionState = "connected"; - this.background.start({ client, thread: this.currentThreadId }); + this.background.changed(this.currentThreadId); } catch (error) { try { if (this.client === client) { @@ -4034,18 +4061,17 @@ export class CodexAppServerAgentSession implements AgentSession { settings: Record; name: string; } | null { - const match = this.findCollaborationMode(this.planModeEnabled ? "plan" : "code"); + const match = + this.findCollaborationMode(this.planModeEnabled ? "plan" : "code") ?? + this.restoredCollaborationMode; if (!match) return null; const settings: Record = {}; if (match.model) settings.model = match.model; if (match.reasoning_effort) settings.reasoning_effort = match.reasoning_effort; - const developerInstructions = composeSystemPromptParts( - match.developer_instructions, - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); - if (developerInstructions) settings.developer_instructions = developerInstructions; + // Codex applies thread instructions separately. Null asks it to supply the + // built-in collaboration mode instructions instead of replacing them. + settings.developer_instructions = match.developer_instructions ?? null; if (this.config.model) settings.model = this.config.model; const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId); if (thinkingOptionId) settings.reasoning_effort = thinkingOptionId; @@ -4305,10 +4331,7 @@ export class CodexAppServerAgentSession implements AgentSession { // the unnamespaced key emitted by earlier Paseo versions. params.modelProvider = this.deps.customCodexConfig.model_provider; } - const developerInstructions = composeSystemPromptParts( - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); + const developerInstructions = composeAgentSystemPrompt(this.config); if (developerInstructions) { params.developerInstructions = developerInstructions; } @@ -4319,11 +4342,11 @@ export class CodexAppServerAgentSession implements AgentSession { try { const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {})); const ids = Array.isArray(loaded?.data) ? loaded.data : []; - if (ids.includes(this.currentThreadId)) { - return; + if (!ids.includes(this.currentThreadId)) { + const response = await this.client.request("thread/resume", params); + this.rememberResolvedSandboxPolicy(response); + this.rememberRestoredCollaborationMode(response); } - const response = await this.client.request("thread/resume", params); - this.rememberResolvedSandboxPolicy(response); } catch (error) { const threadId = this.currentThreadId; const message = error instanceof Error ? error.message : String(error); @@ -4337,12 +4360,34 @@ export class CodexAppServerAgentSession implements AgentSession { } const response = await this.client.request("thread/resume", params); this.rememberResolvedSandboxPolicy(response); + this.rememberRestoredCollaborationMode(response); this.logger.info({ threadId }, "Unarchived Codex thread to restore active Paseo agent"); - return; + } else { + this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread"); + throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error }); } - this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread"); - throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error }); } + await this.instructionSnapshot.apply( + this.currentThreadId, + this.client.request.bind(this.client), + this.supportsInstructionSnapshots, + ); + } + + private rememberRestoredCollaborationMode(response: unknown): void { + const mode = toObjectRecord(toObjectRecord(response)?.collaborationMode); + const settings = toObjectRecord(mode?.settings); + if (typeof mode?.mode !== "string" || typeof settings?.model !== "string") return; + // The resumed mode can contain instructions from a previous launch. Keep its + // identity and model, and let Codex restore the built-in mode instructions. + this.restoredCollaborationMode = { + name: mode.mode, + mode: mode.mode, + model: settings.model, + reasoning_effort: + typeof settings.reasoning_effort === "string" ? settings.reasoning_effort : null, + }; + this.refreshResolvedCollaborationMode(); } private parseSlashCommandInput(text: string): { commandName: string; args?: string } | null { @@ -4458,13 +4503,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (options?.outputSchema) { params.outputSchema = normalizeCodexOutputSchema(options.outputSchema); } - const developerInstructions = composeSystemPromptParts( - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); - if (developerInstructions) { - params.developerInstructions = developerInstructions; - } + const developerInstructions = composeAgentSystemPrompt(this.config); const codexConfig = this.buildCodexInnerConfig(); if (codexConfig) { params.config = codexConfig; @@ -4658,7 +4697,7 @@ export class CodexAppServerAgentSession implements AgentSession { // outlives it into the new turn. await this.waitForInterruptedTurnCleanup(); if (pendingStart.cancelRequested) { - throw new Error("Codex turn start was interrupted before reaching Codex"); + throw new AgentTurnStartCanceledError(); } await this.client.request("turn/start", turnStart.params, TURN_START_TIMEOUT_MS); return { turnId }; @@ -5223,6 +5262,9 @@ export class CodexAppServerAgentSession implements AgentSession { systemPrompt: this.config.systemPrompt, mcpServers: this.config.mcpServers, asyncQuestions: this.asyncQuestions.serialize(), + ...(this.instructionSnapshot.describe(threadId) + ? { paseoInstructionReceipt: this.instructionSnapshot.describe(threadId) } + : {}), }, }; } @@ -5253,9 +5295,15 @@ export class CodexAppServerAgentSession implements AgentSession { model: this.config.model ?? null, serviceTier: this.serviceTier, config: this.buildCodexInnerConfig(), + developerInstructions: composeAgentSystemPrompt(this.config), userMessageTurns: this.codexUserMessageTurns(), threadRollbackAvailable: this.threadRollbackAvailable, setThreadId: async (threadId) => { + await this.instructionSnapshot.apply( + threadId, + this.client!.request.bind(this.client), + this.supportsInstructionSnapshots, + ); this.currentThreadId = threadId; // Codex writes a forked thread's rollout when it forks it, even before any turn. this.savedThreadId = threadId; @@ -5338,6 +5386,8 @@ export class CodexAppServerAgentSession implements AgentSession { } async canStopRuntime(): Promise { + // A history session released its app-server once it read the thread, so nothing runs. + if (this.connectionState === "history-ready") return true; if ( !this.client || this.client.hasPendingRequests() || @@ -5789,6 +5839,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.cachedRuntimeInfo = null; } this.currentThreadId = threadId; + this.instructionSnapshot.recordNewThread(threadId); } private buildThreadStartRequest(model: string): { @@ -5800,10 +5851,7 @@ export class CodexAppServerAgentSession implements AgentSession { const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined; const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined; const innerConfig = this.buildCodexInnerConfig(); - const developerInstructions = composeSystemPromptParts( - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); + const developerInstructions = composeAgentSystemPrompt(this.config); const params: Record = { model, cwd: this.config.cwd ?? null, @@ -5944,15 +5992,34 @@ export class CodexAppServerAgentSession implements AgentSession { ) { this.settleStreamRetry({ status: "completed" }); } - if ( - parsed.kind === "turn_completed" || - parsed.kind === "exec_command_started" || + this.observeBackgroundWork(parsed); + await this.dispatchParsedNotification(parsed); + } + + private observeBackgroundWork(parsed: ParsedCodexNotification): void { + const backgroundThread = getCodexNotificationThreadId(parsed) ?? this.currentThreadId; + if (backgroundThread && parsed.kind === "turn_started") + this.background.turnStarted(backgroundThread); + else if (backgroundThread && parsed.kind === "turn_completed") + this.background.turnSettled(backgroundThread); + else if (backgroundThread && parsed.kind === "exec_command_started") + this.background.commandStarted({ thread: backgroundThread, itemId: parsed.callId }); + else if ( + backgroundThread && + parsed.kind === "item_started" && + normalizeCodexThreadItemType(parsed.item.type) === "commandExecution" + ) + this.background.commandStarted({ + thread: backgroundThread, + itemId: parsed.item.id ?? null, + processId: typeof parsed.item.processId === "string" ? parsed.item.processId : undefined, + }); + else if ( parsed.kind === "exec_command_completed" || ((parsed.kind === "item_started" || parsed.kind === "item_completed") && normalizeCodexThreadItemType(parsed.item.type) === "commandExecution") ) this.background.changed(this.currentThreadId); - await this.dispatchParsedNotification(parsed); } private async dispatchSubAgentNotification( diff --git a/packages/server/src/server/agent/providers/codex/background-inventory.ts b/packages/server/src/server/agent/providers/codex/background-inventory.ts index 856634dbcb..91f6fcf11c 100644 --- a/packages/server/src/server/agent/providers/codex/background-inventory.ts +++ b/packages/server/src/server/agent/providers/codex/background-inventory.ts @@ -6,12 +6,27 @@ type InventoryEvent = Extract; interface Client { request(method: string, params?: unknown, timeoutMs?: number): Promise; } +interface ForegroundCommands { + items: Set; + processes: Set; +} +interface CommandStartedInput { + thread: string; + itemId: string | null; + processId?: string; +} +interface ReadInventoriesInput { + client: Client; + threads: readonly string[]; + foreground: ReadonlyMap; +} export class CodexBackgroundInventory { private generation = 0; private client: Client | null = null; private thread: string | null = null; private readonly threads = new Set(); + private readonly foreground = new Map(); private origins = new Map(); private pending = false; private dirty = false; @@ -85,6 +100,7 @@ export class CodexBackgroundInventory { this.client = null; this.thread = null; this.threads.clear(); + this.foreground.clear(); this.origins.clear(); this.pending = false; this.dirty = false; @@ -101,6 +117,24 @@ export class CodexBackgroundInventory { this.dirty = true; if (!this.retrying) this.refresh(); } + turnStarted(thread: string) { + if (!this.foreground.has(thread)) + this.foreground.set(thread, { items: new Set(), processes: new Set() }); + } + commandStarted({ thread, itemId, processId }: CommandStartedInput) { + let turn = this.foreground.get(thread); + if (!turn) { + turn = { items: new Set(), processes: new Set() }; + this.foreground.set(thread, turn); + } + if (itemId) turn.items.add(itemId); + if (processId) turn.processes.add(processId); + this.changed(thread); + } + turnSettled(thread: string) { + this.foreground.delete(thread); + this.changed(thread); + } private refresh() { if (this.pending || !this.client || !this.thread || this.unsupported) return; if (this.timer) clearTimeout(this.timer); @@ -113,7 +147,11 @@ export class CodexBackgroundInventory { void (async () => { let failed = false; try { - const { items, origins, activeThreads } = await readInventories(client, threads); + const { items, origins, activeThreads } = await readInventories({ + client, + threads, + foreground: this.foreground, + }); if (generation !== this.generation || this.dirty) return; this.origins = origins; this.threads.clear(); @@ -149,7 +187,7 @@ export class CodexBackgroundInventory { } } -async function readInventories(client: Client, threads: string[]) { +async function readInventories({ client, threads, foreground }: ReadInventoriesInput) { const items: NonNullable = []; const origins = new Map(); const activeThreads = new Set(); @@ -158,7 +196,9 @@ async function readInventories(client: Client, threads: string[]) { do { const page = z .object({ - data: z.array(z.object({ processId: z.string(), command: z.string() })), + data: z.array( + z.object({ itemId: z.string().optional(), processId: z.string(), command: z.string() }), + ), nextCursor: z.string().nullable(), }) .parse( @@ -169,9 +209,17 @@ async function readInventories(client: Client, threads: string[]) { ), ); for (const row of page.data) { + activeThreads.add(threadId); + // Codex registers processes before the initial tool call returns. Only commands + // surviving their owning turn belong in the background-work presentation. + const turn = foreground.get(threadId); + if ( + turn && + ((row.itemId && turn.items.has(row.itemId)) || turn.processes.has(row.processId)) + ) + continue; const id = JSON.stringify([threadId, row.processId]); origins.set(id, { threadId, processId: row.processId }); - activeThreads.add(threadId); items.push({ id, kind: "shell", diff --git a/packages/server/src/server/agent/providers/codex/instruction-snapshot.ts b/packages/server/src/server/agent/providers/codex/instruction-snapshot.ts new file mode 100644 index 0000000000..848c4ab1f6 --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/instruction-snapshot.ts @@ -0,0 +1,69 @@ +import { createHash } from "node:crypto"; +import { CodexAppServerRpcError } from "./app-server-transport.js"; + +/** The receipt records only which snapshot was delivered to a particular native thread. */ +interface InstructionReceipt { + threadId: string; + digest: string; +} + +function readReceipt(value: unknown): InstructionReceipt | null { + if (!value || typeof value !== "object") return null; + const receipt = value as Record; + if (typeof receipt.threadId !== "string" || typeof receipt.digest !== "string") return null; + if (!/^[a-f0-9]{64}$/.test(receipt.digest)) return null; + return { threadId: receipt.threadId, digest: receipt.digest }; +} + +export class CodexInstructionSnapshot { + private receipt: InstructionReceipt | null; + private readonly digest: string; + + constructor( + private readonly instructions: string | undefined, + receipt: unknown, + ) { + this.receipt = readReceipt(receipt); + this.digest = createHash("sha256") + .update(JSON.stringify({ version: 1, instructions: instructions ?? "" })) + .digest("hex"); + } + + /** A new thread receives its first snapshot through thread/start. */ + recordNewThread(threadId: string): void { + this.receipt = { threadId, digest: this.digest }; + } + + describe(threadId: string): InstructionReceipt | undefined { + return this.receipt?.threadId === threadId ? { ...this.receipt } : undefined; + } + + async apply( + threadId: string, + request: (method: string, params: unknown) => Promise, + supported: boolean, + ): Promise { + if (this.receipt?.threadId === threadId && this.receipt.digest === this.digest) return; + if (!supported) + throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates."); + const snapshot = JSON.stringify({ version: 1, instructions: this.instructions ?? "" }); + const text = + "This is the complete current set of Paseo-supplied instructions. It supersedes all earlier Paseo-supplied instructions in the conversation, including earlier snapshots. An empty instruction string means there are no current Paseo-supplied instructions. Provider and collaboration instructions remain in effect.\n\n" + + snapshot + + ""; + try { + await request("thread/inject_items", { + threadId, + items: [{ type: "message", role: "developer", content: [{ type: "input_text", text }] }], + }); + } catch (error) { + if (error instanceof CodexAppServerRpcError && error.code === -32601) { + throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.", { + cause: error, + }); + } + throw error; + } + this.receipt = { threadId, digest: this.digest }; + } +} diff --git a/packages/server/src/server/agent/providers/codex/rewind.ts b/packages/server/src/server/agent/providers/codex/rewind.ts index a22931b92b..bdff3c0c5d 100644 --- a/packages/server/src/server/agent/providers/codex/rewind.ts +++ b/packages/server/src/server/agent/providers/codex/rewind.ts @@ -49,6 +49,7 @@ export async function revertCodexConversation(input: { model?: string | null; serviceTier?: string | null; config?: Record | null; + developerInstructions?: string; userMessageTurns: CodexUserMessageTurnIndex; threadRollbackAvailable: boolean; setThreadId: (threadId: string) => void | Promise; @@ -76,6 +77,7 @@ export async function revertCodexConversation(input: { model: input.model ?? null, serviceTier: input.serviceTier ?? null, ...(input.config ? { config: input.config } : {}), + ...(input.developerInstructions ? { developerInstructions: input.developerInstructions } : {}), // Paseo re-reads the rewound thread through paged history, not the fork reply. excludeTurns: true, persistExtendedHistory: true, diff --git a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts index ccd8a60ac6..69448af846 100644 --- a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts +++ b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts @@ -33,7 +33,7 @@ interface FakeTerminalCommand { threadId: string; turnId: string; itemId: string; - processId: string; + processId?: string; command: string; } interface FakeTerminalInput { @@ -171,7 +171,7 @@ export function createFakeCodexAppServer( const child = createCodexAppServerChildProcess(); const recordedRollbacks: JsonObject[] = []; const responseHandlers: Record = { - initialize: () => ({}), + initialize: () => ({ userAgent: "codex/0.150.0" }), "collaborationMode/list": () => ({ data: [] }), "config/read": () => ({ config: {} }), getUserSavedConfig: () => ({ config: {} }), @@ -189,6 +189,7 @@ export function createFakeCodexAppServer( "thread/loaded/list": () => ({ data: [] }), "thread/backgroundTerminals/list": () => ({ data: [], nextCursor: null }), "thread/resume": () => ({}), + "thread/inject_items": () => ({}), "turn/start": () => ({}), "thread/fork": (params) => ({ thread: { diff --git a/packages/server/src/server/agent/providers/codex/thread-history.test.ts b/packages/server/src/server/agent/providers/codex/thread-history.test.ts index 3feb737aa8..3f0e35801a 100644 --- a/packages/server/src/server/agent/providers/codex/thread-history.test.ts +++ b/packages/server/src/server/agent/providers/codex/thread-history.test.ts @@ -147,7 +147,7 @@ describe("Codex thread history", () => { appServer.assertNoErrors(); }); - test("a page too big to send shows a warning row and stops loading", async () => { + test("a page too big to send retries smaller pages, then warns at the item that cannot fit", async () => { const answers = Array.from({ length: 120 }, (_, index) => agentItem(`agent-${index}`, `Answer ${index}`), ); @@ -163,11 +163,12 @@ describe("Codex thread history", () => { ); const loaded = [ { type: "user_message", text: "One", messageId: "user-1" }, - ...answers.slice(0, 99).map((answer) => ({ + ...answers.map((answer) => ({ type: "assistant_message", text: answer.text, messageId: answer.id, })), + { type: "user_message", text: "Two", messageId: "user-2" }, { type: "notification", level: "warning", @@ -176,6 +177,12 @@ describe("Codex thread history", () => { ]; try { expect(timelineItems(await readHistory(session))).toEqual(loaded); + // Each oversized page retries the same cursor at half the size until it fits. + expect( + historyRequests(appServer) + .filter((request) => request.method === "thread/items/list") + .map((request) => (request.params as { limit: number }).limit), + ).toEqual([100, 100, 50, 25, 12, 12, 6, 6, 3, 3, 1, 1]); // The oversized reply failed only its own request; the session still answers. expect(timelineItems(await readHistory(session))).toEqual(loaded); } finally { diff --git a/packages/server/src/server/agent/providers/codex/thread-history.ts b/packages/server/src/server/agent/providers/codex/thread-history.ts index bf7461deb6..557d92150b 100644 --- a/packages/server/src/server/agent/providers/codex/thread-history.ts +++ b/packages/server/src/server/agent/providers/codex/thread-history.ts @@ -124,15 +124,28 @@ async function* readPaginatedHistory( ): AsyncGenerator { const seenCursors = new Set(); let cursor: string | undefined; + let limit = PAGE_SIZE; for (;;) { - const page = CodexItemsPageSchema.parse( - await requestHistory( - client, - "thread/items/list", - { threadId, limit: PAGE_SIZE, sortDirection: "asc", cursor }, + let response: unknown; + try { + response = await client.request("thread/items/list", { + threadId, + limit, + sortDirection: "asc", + cursor, + }); + } catch (error) { + if (!(error instanceof CodexAppServerResponseTooLargeError)) throw error; + // Image-heavy items can push a full page past the line cap; retry the same cursor smaller. + if (limit > 1) { + limit = Math.max(1, Math.floor(limit / 2)); + continue; + } + throw new CodexThreadHistoryTooLargeError( "The rest of this Codex thread's history is too large to load.", - ), - ); + ); + } + const page = CodexItemsPageSchema.parse(response); for (const row of page.data) { yield { item: row.item, diff --git a/packages/server/src/server/agent/providers/model-label.ts b/packages/server/src/server/agent/providers/model-label.ts new file mode 100644 index 0000000000..952a9957a9 --- /dev/null +++ b/packages/server/src/server/agent/providers/model-label.ts @@ -0,0 +1,21 @@ +// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a +// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept. +function stripVendorPrefix(label: string): string { + const vendorSeparatorIndex = label.indexOf(": "); + if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) { + return label; + } + return label.slice(vendorSeparatorIndex + 2).trim(); +} + +// The label Pi and OMP show for a model from their catalogs. A model name is either a path +// ("google/gemini_2.5-flash", as OpenRouter reports it) or free text that can contain slashes +// and underscores ("IQ3_S ... 52/56"). Only paths are shortened. +export function modelDisplayLabel(model: { id: string; name?: string }): string { + const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim(); + if (/\s/.test(text)) { + return stripVendorPrefix(text); + } + const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text; + return stripVendorPrefix(lastSegment.replace(/_+/g, " ")); +} diff --git a/packages/server/src/server/agent/providers/omp/agent.test.ts b/packages/server/src/server/agent/providers/omp/agent.test.ts index 832bd208a8..6201e25e66 100644 --- a/packages/server/src/server/agent/providers/omp/agent.test.ts +++ b/packages/server/src/server/agent/providers/omp/agent.test.ts @@ -1855,3 +1855,69 @@ test("closing OMP during image conversion rejects its pending start", async () = await session.close(); await rejected; }); + +describe("OMP catalog model labels", () => { + test.each([ + { + name: "keeps slashes and underscores inside a free-text model name", + model: { + provider: "llama-swap", + id: "s-q3fn(p-t)", + name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", + }, + label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", + }, + { + name: "keeps a free-text name that ends in a slash-separated word", + model: { + provider: "llama-swap", + id: "ds-strata-6", + name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", + }, + label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", + }, + { + name: "keeps a colon inside a free-text model name", + model: { + provider: "llama-swap", + id: "qwen3-tail", + name: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + label: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + { + name: "keeps an OMP catalog name as it is", + model: { + provider: "openrouter", + id: "anthropic/claude-opus-4.1:batch", + name: "Claude Opus 4.1 (batch)", + }, + label: "Claude Opus 4.1 (batch)", + }, + { + name: "drops the vendor prefix from an upstream model name", + model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" }, + label: "GPT-5.5", + }, + { + name: "falls back to the last segment of a path-like id", + model: { provider: "pioneer", id: "canada-quant/glm_5.2" }, + label: "glm 5.2", + }, + ])("$name", async ({ model, label }) => { + const runtime = new FakeOmp(); + runtime.queueSessionSetup((session) => { + session.models = [model]; + }); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + + const catalog = await client.fetchCatalog({ + scope: "workspace", + cwd: "/workspace/project", + force: false, + }); + + expect(catalog.models.map((entry) => entry.label)).toEqual([label]); + expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`); + }); +}); diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index d10692ca6f..292377a193 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -15,7 +15,6 @@ import { type AgentLaunchContext, type AgentMetadata, type AgentMode, - type AgentModelDefinition, type AgentPermissionRequest, type AgentPermissionResponse, type AgentProviderNotice, @@ -252,36 +251,6 @@ interface OmpSlashCommandInvocation { type AutoCompactMode = boolean | "toggle" | "unknown"; -function normalizeOmpModelLabel(label: string): string { - const normalizedLabel = label.trim().replace(/[_\s]+/g, " "); - const vendorSeparatorIndex = normalizedLabel.indexOf(": "); - if (vendorSeparatorIndex === -1) { - return normalizedLabel; - } - - return normalizedLabel.slice(vendorSeparatorIndex + 2).trim(); -} - -export function transformOmpModels(models: AgentModelDefinition[]): AgentModelDefinition[] { - return models.map((model) => { - if (!model.label.includes("/")) { - return model; - } - - const segments = model.label.split("/").filter((segment) => segment.length > 0); - const rawLabel = segments.at(-1); - if (!rawLabel) { - return model; - } - - return { - ...model, - label: normalizeOmpModelLabel(rawLabel), - description: model.description ?? model.label, - }; - }); -} - function isOmpThinkingLevel(value: string | null | undefined): value is OmpThinkingLevel { return ( value === "off" || @@ -466,6 +435,7 @@ function buildResumeStartInput(input: { systemPrompt: composeSystemPromptParts( input.resumeConfig.config.systemPrompt, input.resumeConfig.config.daemonAppendSystemPrompt, + ...(input.resumeConfig.config.pluginAppendSystemPrompt ?? []), ), }; } @@ -2370,7 +2340,11 @@ export class OmpAgentClient implements AgentClient { noSession: config.internal === true, modeId: launchMode.modeId, extraArgs: launchMode.extraArgs, - systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt), + systemPrompt: composeSystemPromptParts( + config.systemPrompt, + config.daemonAppendSystemPrompt, + ...(config.pluginAppendSystemPrompt ?? []), + ), env: launchContext?.env, }; const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession( @@ -2571,13 +2545,11 @@ export class OmpAgentClient implements AgentClient { }); if (!runtimeSession) throw new Error("OMP catalog runtime did not start"); const catalogSession = runtimeSession; - const models = transformOmpModels( - ( - await runProviderRefreshActivity(context, "get_available_models", () => - catalogSession.getAvailableModels(null), - ) - ).map((model) => mapOmpModel(model, this.provider)), - ); + const models = ( + await runProviderRefreshActivity(context, "get_available_models", () => + catalogSession.getAvailableModels(null), + ) + ).map((model) => mapOmpModel(model, this.provider)); return { models, modes: [...OMP_MODES] }; } finally { context?.signal.removeEventListener("abort", handleAbort); diff --git a/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts b/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts index da86a38ba7..b68fd74697 100644 --- a/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts +++ b/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts @@ -164,7 +164,7 @@ describe("mapOmpModel thinking options", () => { expect(result.provider).toBe("omp"); expect(result.id).toBe("pioneer/canada-quant/glm-5.2"); - expect(result.label).toBe("pioneer/GLM-5.2"); + expect(result.label).toBe("GLM-5.2"); expect(result.metadata).toEqual({ provider: "pioneer", modelId: "canada-quant/glm-5.2" }); }); }); diff --git a/packages/server/src/server/agent/providers/omp/map-omp-model.ts b/packages/server/src/server/agent/providers/omp/map-omp-model.ts index 094b1adf35..69bcefed18 100644 --- a/packages/server/src/server/agent/providers/omp/map-omp-model.ts +++ b/packages/server/src/server/agent/providers/omp/map-omp-model.ts @@ -3,6 +3,7 @@ import type { AgentProvider, AgentSelectOption, } from "../../agent-sdk-types.js"; +import { modelDisplayLabel } from "../model-label.js"; import type { OmpModel, OmpThinkingLevel } from "./rpc-types.js"; export const DEFAULT_OMP_THINKING_LEVEL: OmpThinkingLevel = "medium"; @@ -43,7 +44,7 @@ export function mapOmpModel(model: OmpModel, provider: AgentProvider): AgentMode return { provider, id: `${model.provider}/${model.id}`, - label: `${model.provider}/${model.name ?? model.id}`, + label: modelDisplayLabel(model), description: `${model.provider}/${model.id}`, metadata: { provider: model.provider, diff --git a/packages/server/src/server/agent/providers/omp/tool-call-detail.ts b/packages/server/src/server/agent/providers/omp/tool-call-detail.ts index cece7f0398..296d2c5de3 100644 --- a/packages/server/src/server/agent/providers/omp/tool-call-detail.ts +++ b/packages/server/src/server/agent/providers/omp/tool-call-detail.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import type { ToolCallDetail } from "../../agent-sdk-types.js"; +import { omitNullArgs } from "../tool-call-args.js"; interface BashToolInput { command: string; @@ -324,7 +325,7 @@ export function parseToolArgs(toolName: string, rawArgs: unknown): OmpTrackedToo } const schema = SIMPLE_TOOL_SCHEMAS[toolName as SimpleToolKind]; if (schema) { - const parsed = schema.safeParse(rawArgs); + const parsed = schema.safeParse(omitNullArgs(rawArgs)); if (parsed.success) { return { kind: toolName as SimpleToolKind, diff --git a/packages/server/src/server/agent/providers/opencode-agent.test.ts b/packages/server/src/server/agent/providers/opencode-agent.test.ts index 8b8b0d491d..c0c16a15d0 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.test.ts @@ -2477,6 +2477,42 @@ describe("OpenCode adapter startTurn error handling", () => { await session.close(); }); + test("reports a question rejected by a human steer as resolved", async () => { + const { parent: session, openCode } = await createParentSession("ses_steer_question"); + openCode.sessionPromptAsyncEvents = []; + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + const { turnId } = await session.startTurn("first"); + openCode.emitEvent({ + type: "question.asked", + properties: { + id: "question-steer", + sessionID: "ses_steer_question", + questions: [{ question: "Which color?", header: "Color", options: [] }], + }, + }); + await vi.waitFor(() => expect(session.getPendingPermissions()).toHaveLength(1)); + + await expect( + session.steerActiveTurn?.("never mind", { + expectedTurnId: turnId, + clearPendingPermissions: true, + }), + ).resolves.toEqual({ status: "accepted" }); + + expect(openCode.calls.questionReject).toContainEqual( + expect.objectContaining({ requestID: "question-steer" }), + ); + expect(events).toContainEqual( + expect.objectContaining({ + type: "permission_resolved", + requestId: "question-steer", + resolution: expect.objectContaining({ behavior: "deny" }), + }), + ); + await session.close(); + }); + test("keeps multiple native steers correlated in admission order", async () => { const { parent: session, openCode } = await createParentSession("ses_native_steer_fifo"); openCode.sessionPromptAsyncEvents = []; diff --git a/packages/server/src/server/agent/providers/opencode-agent.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index 85c32e978f..daf3156e30 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -30,6 +30,7 @@ import { type AgentDraftControls, type AgentOptionControl, type AgentLaunchContext, + type AgentResumeSessionOptions, type AgentMode, type AgentModelDefinition, type AgentPermissionAction, @@ -1521,6 +1522,7 @@ export class OpenCodeAgentClient implements AgentClient { handle: AgentPersistenceHandle, overrides?: Partial, launchContext?: AgentLaunchContext, + _options?: AgentResumeSessionOptions, ): Promise { const metadata = (handle.metadata ?? {}) as Partial; const cwd = overrides?.cwd ?? metadata.cwd; @@ -3692,6 +3694,7 @@ class OpenCodeAgentSession implements AgentSession { const systemPrompt = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), ); const model = this.parseModel(this.config.model); const effectiveMode = resolveOpenCodeRuntimeAgentId(this.currentMode); @@ -4029,6 +4032,7 @@ class OpenCodeAgentSession implements AgentSession { const systemPrompt = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), ); const promptResponse = await this.client.session.promptAsync({ sessionID: this.sessionId, @@ -5045,22 +5049,24 @@ class OpenCodeAgentSession implements AgentSession { answers, }); } - - this.pendingPermissions.delete(requestId); - this.pendingPermissionDirectories.delete(requestId); - return; + } else { + const reply = resolveOpenCodePermissionReply(response); + await this.client.permission.reply({ + requestID: requestId, + directory, + reply, + message: response.behavior === "deny" ? response.message : undefined, + }); } - const reply = resolveOpenCodePermissionReply(response); - await this.client.permission.reply({ - requestID: requestId, - directory, - reply, - message: response.behavior === "deny" ? response.message : undefined, - }); - this.pendingPermissions.delete(requestId); this.pendingPermissionDirectories.delete(requestId); + this.notifySubscribers({ + type: "permission_resolved", + provider: "opencode", + requestId, + resolution: response, + }); } describePersistence(): AgentPersistenceHandle | null { diff --git a/packages/server/src/server/agent/providers/opencode/bridge.test.ts b/packages/server/src/server/agent/providers/opencode/bridge.test.ts index aa7acb830c..45ce16be2b 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.test.ts @@ -77,6 +77,157 @@ function readPluginOptions(env: Record): { } describe("OpenCodeBridge", () => { + test("discovers only the requested session's catalog and retains global discovery", async () => { + const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-discovery-")); + temporaryDirectories.push(paseoHome); + const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() }); + const catalog = createCatalog(); + bridge.setManifestCatalog(catalog); + await bridge.start(); + const unbind = bridge.bindSession({ sessionId: "bound", env: {}, tools: catalog }); + bridge.bindSession({ sessionId: "disabled", env: {} }); + try { + const { baseUrl, token } = bridge.sharedV2Connection(); + async function discover(query: string) { + const response = await fetch(`${baseUrl}/_internal/opencode/tools${query}`, { + headers: { Authorization: `Bearer ${token}` }, + }); + return { status: response.status, body: await response.json() }; + } + const expected = { + status: 200, + body: { + tools: [ + { + name: "echo_context", + title: "Echo context", + description: "Returns the supplied value.", + inputSchema: serializePaseoToolInputParameters(catalog.getTool("echo_context")!), + }, + ], + }, + }; + expect(await discover("")).toEqual(expected); + expect(await discover("?sessionID=bound")).toEqual(expected); + expect(await discover("?sessionID=disabled")).toEqual({ status: 200, body: { tools: [] } }); + const missing = { + status: 404, + body: { error: "OpenCode session is not bound to a Paseo agent" }, + }; + expect(await discover("?sessionID=unknown")).toEqual(missing); + expect(await discover("?sessionID=")).toEqual(missing); + unbind(); + expect(await discover("?sessionID=bound")).toEqual(missing); + } finally { + await bridge.close(); + } + }); + + test("registers and executes session-only tools without exposing them to other sessions", async () => { + const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-session-tools-")); + temporaryDirectories.push(paseoHome); + const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() }); + const builtin = createCatalog(); + const pluginTool = { + name: "plugin_action", + description: "Run a session-specific plugin action.", + inputSchema: { value: z.string() }, + }; + const tools = new Map([...builtin.tools, [pluginTool.name, pluginTool] as const]); + const calls: unknown[] = []; + const author: PaseoToolCatalog = { + tools, + getTool: (name) => tools.get(name), + executeTool: async (name, input, context) => { + if (name !== pluginTool.name) return builtin.executeTool(name, input, context); + calls.push(input); + return { content: [{ type: "text", text: "Plugin action complete" }] }; + }, + }; + bridge.setManifestCatalog(builtin); + await bridge.start(); + bridge.bindSession({ sessionId: "author/one", env: {}, tools: author }); + bridge.bindSession({ sessionId: "other", env: {}, tools: builtin }); + bridge.bindSession({ sessionId: "disabled", env: {} }); + try { + const registered = new Map(); + const hooks: Array<(input: V2TestContext) => Promise> = []; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ + add: (tool) => { + registered.set(tool.name, tool); + }, + }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async ({ sessionID }) => ({ + parentID: sessionID === "child" ? "author/one" : undefined, + }), + hook: async (_name, hook) => { + hooks.push(hook); + return { dispose: async () => undefined }; + }, + }, + }, + ["author/one", "other", "disabled"], + ); + try { + expect([...registered.keys()]).toEqual([ + "paseo_structured_output", + "paseo_echo_context", + `paseo_${pluginTool.name}`, + ]); + const submit = registered.get(`paseo_${pluginTool.name}`)!; + expect(submit.input).toEqual(serializePaseoToolInputParameters(pluginTool)); + const visibleTools = [ + ["author/one", ["paseo_echo_context", `paseo_${pluginTool.name}`, "native"]], + ["child", ["paseo_echo_context", `paseo_${pluginTool.name}`, "native"]], + ["other", ["paseo_echo_context", "native"]], + ["disabled", ["native"]], + ["unrelated", ["native"]], + ] as const; + for (const [sessionID, expected] of visibleTools) { + const input = { + sessionID, + tools: Object.fromEntries([...registered.keys(), "native"].map((name) => [name, {}])), + }; + for (const hook of hooks) await hook(input); + expect(Object.keys(input.tools)).toEqual(expected); + } + await expect( + submit.execute({ value: "revision" }, { sessionID: "author/one" }), + ).resolves.toMatchObject({ content: [{ type: "text", text: "Plugin action complete" }] }); + await expect( + submit.execute({ value: "child revision" }, { sessionID: "child" }), + ).resolves.toMatchObject({ content: [{ type: "text", text: "Plugin action complete" }] }); + await expect(submit.execute({}, { sessionID: "other" })).rejects.toThrow( + "Paseo tool not found", + ); + await expect(submit.execute({}, { sessionID: "disabled" })).rejects.toThrow( + "Paseo tools are disabled", + ); + await expect(submit.execute({}, { sessionID: "unrelated" })).rejects.toThrow("not bound"); + expect(calls).toEqual([{ value: "revision" }, { value: "child revision" }]); + await expect( + registered + .get("paseo_echo_context")! + .execute({ value: "builtin" }, { sessionID: "other" }), + ).resolves.toMatchObject({ content: [{ type: "text", text: "builtin" }] }); + } finally { + await dispose(); + } + } finally { + await bridge.close(); + } + }); + test("advertises agent-scoped schemas that execute through both bridge plugins", async () => { const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-manifest-")); temporaryDirectories.push(paseoHome); diff --git a/packages/server/src/server/agent/providers/opencode/bridge.ts b/packages/server/src/server/agent/providers/opencode/bridge.ts index 87ee07798b..3b04ecb6cf 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.ts @@ -166,7 +166,9 @@ export class OpenCodeBridge { } const url = new URL(request.url ?? "/", this.requireBaseUrl()); if (request.method === "GET" && url.pathname === `${INTERNAL_PREFIX}/tools`) { - sendJson(response, 200, { tools: this.serializeManifest() }); + sendJson(response, 200, { + tools: this.serializeManifest(url.searchParams.get("sessionID")), + }); return; } @@ -228,8 +230,15 @@ export class OpenCodeBridge { } } - private serializeManifest(): Array> { - const catalog = this.manifestCatalog; + private serializeManifest(sessionId: string | null): Array> { + let catalog: Pick | null | undefined = this.manifestCatalog; + if (sessionId !== null) { + const binding = this.sessions.get(sessionId); + if (!binding) { + throw new OpenCodeBridgeClientError(404, "OpenCode session is not bound to a Paseo agent"); + } + catalog = binding.tools; + } if (!catalog) return []; return [...catalog.tools.values()].map((tool) => { const definition: Record = { diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts index 910a68cfef..fbccc0cbf3 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts @@ -113,6 +113,111 @@ test.each([ } }); +test("re-probes a v1 runtime on a forced refresh after OpenCode is updated to v2", async () => { + const { mkdtemp, writeFile, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const root = await mkdtemp(join(tmpdir(), "opencode-version-upgrade-")); + const script = join(root, "version.cjs"); + const client = new OpenCodeRuntimeClient(createTestLogger(), { + command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, + }); + const controlLabel = async () => + (await client.listControls({ provider: "opencode", cwd: root })).controls[0]?.label; + try { + await writeFile(script, 'console.log("1.14.46")'); + expect(await controlLabel()).toBe("Auto Accept"); + await writeFile(script, 'console.log("opencode v2.0.10")'); + expect(await controlLabel()).toBe("Auto Accept"); + + // The fake binary cannot serve, so the refresh fails on the v2 startup path it switched to. + await expect(client.fetchCatalog({ scope: "global", force: true })).rejects.toThrow( + "OpenCode v2 server exited during startup", + ); + + expect(await controlLabel()).toBe("Auto-accept"); + } finally { + await client.shutdown(); + await rm(root, { recursive: true, force: true }); + } +}); + +async function createCountingVersionBinary(prefix: string) { + const { mkdtemp, writeFile, readFile, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const root = await mkdtemp(join(tmpdir(), prefix)); + const script = join(root, "version.cjs"); + const probes = join(root, "probes"); + await writeFile(probes, ""); + const client = new OpenCodeRuntimeClient(createTestLogger(), { + command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, + }); + return { + client, + root, + report: (version: string) => + writeFile( + script, + `if (process.argv.includes("--version")) require("node:fs").appendFileSync(${JSON.stringify(probes)}, "x"); console.log(${JSON.stringify(version)})`, + ), + probeCount: async () => (await readFile(probes, "utf8")).length, + controlLabel: async () => + (await client.listControls({ provider: "opencode", cwd: root })).controls[0]?.label, + dispose: async () => { + await client.shutdown(); + await rm(root, { recursive: true, force: true }); + }, + }; +} + +test("keeps a v2 runtime on a forced refresh without probing the binary again", async () => { + const binary = await createCountingVersionBinary("opencode-v2-refresh-"); + try { + await binary.report("opencode v2.0.10"); + expect(await binary.controlLabel()).toBe("Auto-accept"); + expect(await binary.probeCount()).toBe(1); + + await expect(binary.client.fetchCatalog({ scope: "global", force: true })).rejects.toThrow( + "OpenCode v2 server exited during startup", + ); + + expect(await binary.probeCount()).toBe(1); + expect(await binary.controlLabel()).toBe("Auto-accept"); + } finally { + await binary.dispose(); + } +}); + +test.each([0, 1, 2, 3, 4, 5, 6, 8])( + "probes once when a second forced refresh starts %i microtasks after the first", + async (ticks) => { + const binary = await createCountingVersionBinary("opencode-concurrent-refresh-"); + try { + await binary.report("1.14.46"); + expect(await binary.controlLabel()).toBe("Auto Accept"); + await binary.report("opencode v2.0.10"); + + const first = binary.client.fetchCatalog({ scope: "global", force: true }); + for (let tick = 0; tick < ticks; tick++) await Promise.resolve(); + const second = binary.client.fetchCatalog({ scope: "global", force: true }); + const results = await Promise.allSettled([first, second]); + + expect(results.map((result) => result.status)).toEqual(["rejected", "rejected"]); + expect(await binary.probeCount()).toBe(2); + expect(await binary.controlLabel()).toBe("Auto-accept"); + } finally { + await binary.dispose(); + } + }, +); + test("appends a first notice after old history and records a changed major version", async () => { const { withOpenCodeRuntimeNotice } = await import("./runtime-notice.js"); const { V2Harness } = await import("./test-utils/v2-harness.js"); diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.ts index 6e65c7637e..25447db718 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.ts @@ -4,6 +4,7 @@ import type { AgentSessionConfig, AgentLaunchContext, AgentCreateSessionOptions, + AgentResumeSessionOptions, AgentPersistenceHandle, FetchCatalogOptions, ProviderRefreshContext, @@ -149,14 +150,25 @@ export class OpenCodeRuntimeClient implements AgentClient { handle: AgentPersistenceHandle, config?: Partial, launch?: AgentLaunchContext, + options?: AgentResumeSessionOptions, ) { const client = await this.client(); - const session = await client.resumeSession(handle, config, launch); + const session = await client.resumeSession(handle, config, launch, options); return client === this.legacy ? session : withOpenCodeRuntimeNotice(session, 2, handle); } async fetchCatalog(options: FetchCatalogOptions, context?: ProviderRefreshContext) { + if (options.force) await this.reprobeLegacySelection(); return (await this.client()).fetchCatalog(options, context); } + // Updating the binary does not change provider config, so the client survives it. A forced + // refresh re-probes a v1 pick so a 1.x to 2.x update takes effect without a daemon restart. + // A v2 pick owns live sessions and stays. + private async reprobeLegacySelection() { + const current = this.selected; + if (!current) return; + const client = await current.catch(() => null); + if (client === this.legacy && this.selected === current) this.selected = null; + } async listCommands(config: AgentSessionConfig) { return (await this.client()).listCommands(config); } diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts index 66ee191707..46ec3d7d15 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts @@ -28,6 +28,7 @@ export class V2Harness { readonly prompts: string[] = []; readonly environments: Array<{ sessionID: string; variables: Record }> = []; readonly mcpAdds: string[] = []; + readonly instructions = new Map(); releases = 0; active = false; activeReads = 0; @@ -153,7 +154,17 @@ export class V2Harness { environment: async (input) => { this.environments.push(input); }, - instructions: { entry: { list: unexpected, put: unexpected, remove: unexpected } }, + instructions: { + entry: { + list: async () => [...this.instructions].map(([key, value]) => ({ key, value })), + put: async ({ key, value }) => { + this.instructions.set(key, String(value)); + }, + remove: async ({ key }) => { + this.instructions.delete(key); + }, + }, + }, prompt: async (input, options) => { const before = this.executions.length; await this.prompt(input, options); diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts index 58e9ffaefb..e8ec8eac81 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts @@ -17,6 +17,54 @@ function terminalEvents(events: AgentStreamEvent[]) { } describe("OpenCode v2 session lifecycle", () => { + test("reopening replaces and removes plugin instructions", async () => { + const harness = new V2Harness(); + const client = new OpenCodeV2AgentClient({ + logger: createTestLogger(), + runtime: harness.runtime, + }); + const created = await client.createSession({ + provider: "opencode", + cwd: "/tmp/project", + pluginAppendSystemPrompt: ["first"], + }); + expect(harness.instructions.get("paseo")).toBe("first"); + const handle = created.describePersistence()!; + await created.close(); + const resumed = await client.resumeSession(handle, { + cwd: "/tmp/project", + pluginAppendSystemPrompt: ["changed"], + }); + expect(harness.instructions.get("paseo")).toBe("changed"); + await resumed.close(); + const cleared = await client.resumeSession(handle, { + cwd: "/tmp/project", + pluginAppendSystemPrompt: undefined, + }); + expect(harness.instructions.has("paseo")).toBe(false); + await cleared.close(); + }); + + test("opening history does not change an existing session instruction", async () => { + const harness = new V2Harness(); + harness.instructions.set("paseo", "Existing plugin instruction"); + const client = new OpenCodeV2AgentClient({ + logger: createTestLogger(), + runtime: harness.runtime, + }); + const session = await client.resumeSession( + { provider: "opencode", sessionId: "session", metadata: { cwd: "/tmp/project" } }, + { cwd: "/tmp/project" }, + undefined, + { purpose: "history" }, + ); + try { + expect(harness.instructions.get("paseo")).toBe("Existing plugin instruction"); + } finally { + await session.close(); + } + }); + test("refreshes the existing location before reading a forced catalog", async () => { const harness = new V2Harness(); const refreshed: string[] = []; diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.ts index 44b4647955..d7139c097c 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.ts @@ -17,6 +17,7 @@ import type { AgentCapabilityFlags, AgentClient, AgentCreateSessionOptions, + AgentResumeSessionOptions, AgentDraftControls, AgentLaunchContext, AgentPersistenceHandle, @@ -131,6 +132,7 @@ export class OpenCodeV2AgentClient implements AgentClient { handle: AgentPersistenceHandle, overrides?: Partial, launch?: AgentLaunchContext, + options?: AgentResumeSessionOptions, ): Promise { const cwd = overrides?.cwd ?? handle.metadata?.cwd; if (typeof cwd !== "string") @@ -151,7 +153,14 @@ export class OpenCodeV2AgentClient implements AgentClient { sessionID: handle.nativeHandle ?? handle.sessionId, }); await applyResumeOverrides(connection.client, info, overrides); - return await this.attach(connection, info, config, launch, true); + return await this.attach( + connection, + info, + config, + launch, + true, + options?.purpose === "history", + ); } catch (error) { await connection.release(); throw error; @@ -163,6 +172,7 @@ export class OpenCodeV2AgentClient implements AgentClient { config: AgentSessionConfig, launch: AgentLaunchContext | undefined, persist: boolean, + historyOnly = false, ) { const acquire = () => this.runtime.acquire( @@ -209,6 +219,7 @@ export class OpenCodeV2AgentClient implements AgentClient { bindChild, acquire, moved, + historyOnly, ); try { await session.initialize( diff --git a/packages/server/src/server/agent/providers/opencode/v2/session.ts b/packages/server/src/server/agent/providers/opencode/v2/session.ts index 1724bacbe7..dcd59b67f3 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session.ts @@ -75,6 +75,7 @@ export class OpenCodeV2Session implements AgentSession { bindChild?: (id: string) => void, private readonly acquire?: () => Promise, private readonly moved?: (connection: V2Connection) => void, + private readonly historyOnly = false, ) { this.background = new OpenCodeBackgroundInventory({ id: info.id, @@ -193,16 +194,24 @@ export class OpenCodeV2Session implements AgentSession { }); await this.awaitMcp(server); } + if (this.historyOnly) return; const system = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), ); - if (system) + if (system) { await this.client.session.instructions.entry.put({ sessionID: this.id, key: "paseo", value: system, }); + } else { + const entries = await this.client.session.instructions.entry.list({ sessionID: this.id }); + if (entries.some((entry) => entry.key === "paseo")) { + await this.client.session.instructions.entry.remove({ sessionID: this.id, key: "paseo" }); + } + } } private async startStream() { let ready!: () => void; diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs index 4be98bfba9..2331be4edf 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs @@ -1,5 +1,12 @@ import { STRUCTURED_OUTPUT_TOOL } from "./structured-output-plugin.mjs"; +// A refused fetch proves the previous bridge stopped listening. Runtimes report +// it differently: Node puts the code on `cause`, Bun puts it on the error. +export function isRefused(error) { + const code = error?.code ?? error?.cause?.code; + return code === "ECONNREFUSED" || code === "ConnectionRefused"; +} + // OpenCode owns this plugin for the lifetime of a location. Paseo supplies only // live, per-session bindings over the authenticated OpenCode RPC channel. export async function registerSharedBridge(context) { @@ -38,7 +45,10 @@ export async function registerSharedBridge(context) { return null; } async function install(binding) { - const manifest = await request(binding, "/tools"); + const manifest = await request( + binding, + `/tools?sessionID=${encodeURIComponent(binding.sessionID)}`, + ); for (const definition of manifest.tools) await installDefinition(definition); } async function installDefinition(definition) { @@ -127,12 +137,7 @@ export async function registerSharedBridge(context) { } catch (error) { // Refusal or rejected credentials mean this endpoint no longer // serves the previous binding. Other failures are inconclusive. - if ( - error?.status !== 401 && - error?.cause?.code !== "ECONNREFUSED" && - error?.code !== "ConnectionRefused" - ) - throw error; + if (error?.status !== 401 && !isRefused(error)) throw error; } if (active) return { error: "OpenCode session is already bound to another Paseo bridge" }; diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts index c560fa6558..20427357dd 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts @@ -1,4 +1,6 @@ import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -27,7 +29,8 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions" const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() }); const tool = { name: "echo", description: "echo", inputSchema: { value: z.string() } }; const tools = new Map([[tool.name, tool]]); - bridge.setManifestCatalog({ tools }); + // Session-only tools must survive plugin reload without a global definition. + bridge.setManifestCatalog({ tools: new Map() }); await bridge.start(); const unbind = bridge.bindSession({ sessionId: "paseo", @@ -166,3 +169,88 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions" await rm(home, { recursive: true, force: true }); } }); + +test("a shared plugin rebinds a session after the previous bridge stops listening", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-refused-")); + const previous = createServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json", Connection: "close" }); + response.end(JSON.stringify({ tools: [] })); + }); + await new Promise((resolve) => previous.listen(0, "127.0.0.1", resolve)); + const previousPort = (previous.address() as AddressInfo).port; + const current = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() }); + current.setManifestCatalog({ tools: new Map() }); + let rpc: Record Promise> = {}; + let dispose: (() => Promise) | undefined; + let releaseCurrent: (() => void) | undefined; + try { + const plugin = { + package: await current.materializeV2Plugin(), + options: { baseUrl: `http://127.0.0.1:${previousPort}`, token: "previous-bridge" }, + }; + const module = await import( + pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href + ); + dispose = await module.default.setup({ + options: {}, + location: { directory: home }, + provider: { reload: async () => {} }, + model: { reload: async () => {} }, + agent: { reload: async () => {} }, + command: { reload: async () => {} }, + skill: { reload: async () => {} }, + rpc: { + register: async (_definition: unknown, handlers: typeof rpc) => { + rpc = handlers; + return { dispose: async () => {} }; + }, + }, + tool: { transform: async () => ({ dispose: async () => {} }) }, + session: { + context: async () => [], + get: async () => ({ parentID: "" }), + hook: async () => ({ dispose: async () => {} }), + }, + }); + await expect(rpc.bind({ sessionID: "paseo", ...plugin.options })).resolves.toEqual({}); + await current.start(); + // The restarted daemon owns the agent again, so its bridge serves this session. + releaseCurrent = current.bindSession({ sessionId: "paseo", env: {} }); + await new Promise((resolve) => { + previous.close(() => resolve()); + previous.closeAllConnections(); + }); + await expect( + rpc.bind({ sessionID: "paseo", ...current.sharedV2Connection() }), + ).resolves.toEqual({}); + } finally { + await dispose?.(); + releaseCurrent?.(); + await current.close(); + await new Promise((resolve) => previous.close(() => resolve())); + await rm(home, { recursive: true, force: true }); + } +}); + +test("a refused connection is the only probe failure that clears a binding", async () => { + const source = new URL("./shared-bridge-plugin.mjs", import.meta.url).href; + const { isRefused } = (await import(source)) as { isRefused: (error: unknown) => boolean }; + const nodeShape = Object.assign(new Error("fetch failed"), { + cause: Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }), + }); + const olderBunShape = Object.assign(new TypeError("Unable to connect"), { + code: "ConnectionRefused", + }); + // OpenCode 2.2.5 runs on Bun 1.4.4, which carries the code on the error and + // leaves `cause` unset. Node puts the same failure on `cause` instead. + const bunShape = Object.assign( + new TypeError("ECONNREFUSED: Unable to connect. Is the computer able to access the url?"), + { code: "ECONNREFUSED" }, + ); + const inconclusive = Object.assign(new Error("request timed out"), { code: "ETIMEDOUT" }); + expect(isRefused(nodeShape)).toBe(true); + expect(isRefused(olderBunShape)).toBe(true); + expect(isRefused(bunShape)).toBe(true); + expect(isRefused(inconclusive)).toBe(false); + expect(isRefused(undefined)).toBe(false); +}); diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index d152810a92..30f06c5648 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -19,12 +19,7 @@ import { pathToFileURL } from "node:url"; import { describe, expect, onTestFinished, test } from "vitest"; import type { AgentSession, AgentSessionConfig, AgentStreamEvent } from "../../agent-sdk-types.js"; -import { - PiProviderOptionsSchema, - PiRpcAgentClient, - PiRpcAgentSession, - transformPiModels, -} from "./agent.js"; +import { PiProviderOptionsSchema, PiRpcAgentClient, PiRpcAgentSession } from "./agent.js"; import { PiCliRuntime } from "./cli-runtime.js"; import { FakePi } from "./test-utils/fake-pi.js"; import { createPiExtensionHost } from "./extensions/index.js"; @@ -1892,6 +1887,7 @@ describe("PiRpcAgentSession", () => { createConfig({ systemPrompt: "Agent prompt", daemonAppendSystemPrompt: "Daemon prompt", + pluginAppendSystemPrompt: ["Plugin one", "Plugin two"], }), ); @@ -1910,7 +1906,9 @@ describe("PiRpcAgentSession", () => { await expect( applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"), - ).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt"); + ).resolves.toBe( + "Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two", + ); await session.close(); }); @@ -1933,6 +1931,7 @@ describe("PiRpcAgentSession", () => { }, { daemonAppendSystemPrompt: "Daemon prompt", + pluginAppendSystemPrompt: ["Plugin one", "Plugin two"], }, ); @@ -1956,7 +1955,9 @@ describe("PiRpcAgentSession", () => { ]); await expect( applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"), - ).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt"); + ).resolves.toBe( + "Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two", + ); }); test("updates model and thinking through Pi runtime commands", async () => { @@ -3970,35 +3971,73 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => { }); }); -describe("transformPiModels", () => { - test("normalizes labels that include the upstream provider prefix", () => { - expect( - transformPiModels([ - { - provider: "pi", - id: "openrouter/google/gemini-2.5-flash-lite", - label: "openrouter/google/gemini_2.5 flash lite", - }, - { - provider: "pi", - id: "openrouter/openai/gpt-5.5", - label: "openrouter/OpenAI: GPT-5.5", - }, - ]), - ).toEqual([ - { - provider: "pi", - id: "openrouter/google/gemini-2.5-flash-lite", - label: "gemini 2.5 flash lite", - description: "openrouter/google/gemini_2.5 flash lite", +describe("Pi catalog model labels", () => { + test.each([ + { + name: "keeps slashes and underscores inside a free-text model name", + model: { + provider: "llama-swap", + id: "s-q3fn(p-t)", + name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", }, - { - provider: "pi", - id: "openrouter/openai/gpt-5.5", - label: "GPT-5.5", - description: "openrouter/OpenAI: GPT-5.5", + label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", + }, + { + name: "keeps a free-text name that ends in a slash-separated word", + model: { + provider: "llama-swap", + id: "ds-strata-6", + name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", }, - ]); + label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", + }, + { + name: "keeps a colon inside a free-text model name", + model: { + provider: "llama-swap", + id: "qwen3-tail", + name: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + label: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + { + name: "drops the vendor prefix from an upstream model name", + model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" }, + label: "GPT-5.5", + }, + { + name: "shortens a path-like name to its last segment", + model: { + provider: "openrouter", + id: "google/gemini-2.5-flash-lite", + name: "google/gemini-2.5-flash-lite", + }, + label: "gemini-2.5-flash-lite", + }, + { + name: "falls back to the last segment of a path-like id", + model: { provider: "openrouter", id: "google/gemini_2.5-flash-lite" }, + label: "gemini 2.5-flash-lite", + }, + { + name: "falls back to an id with spaces when the name is blank", + model: { provider: "local", id: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", name: " " }, + label: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", + }, + ])("$name", async ({ model, label }) => { + const pi = new FakePi(); + pi.queueSessionSetup((session) => { + session.models = [model]; + }); + + const catalog = await createClient(pi).fetchCatalog({ + scope: "workspace", + cwd: "/workspace/project", + force: false, + }); + + expect(catalog.models.map((entry) => entry.label)).toEqual([label]); + expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`); }); }); diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index 60d745ea24..1ef5d0ec21 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -52,7 +52,7 @@ import { type ResolvedProviderLaunch, } from "../../provider-launch-config.js"; import { renderPromptAttachmentAsText } from "../../prompt-attachments.js"; -import { composeSystemPromptParts } from "../../system-prompt.js"; +import { composeAgentSystemPrompt } from "../../system-prompt.js"; import { buildBinaryDiagnosticRows, buildCommandResolutionDiagnosticRows, @@ -83,6 +83,7 @@ import { listPiImportableSessions, readPiImportSessionConfig, } from "./session-descriptor.js"; +import { modelDisplayLabel } from "../model-label.js"; import type { PiRuntime, PiRuntimeSession, PiStartSessionInput } from "./runtime.js"; import type { PiAgentSessionEvent, @@ -313,36 +314,6 @@ interface PiSlashCommandInvocation { type AutoCompactMode = boolean | "toggle" | "unknown"; -function normalizePiModelLabel(label: string): string { - const normalizedLabel = label.trim().replace(/[_\s]+/g, " "); - const vendorSeparatorIndex = normalizedLabel.indexOf(": "); - if (vendorSeparatorIndex === -1) { - return normalizedLabel; - } - - return normalizedLabel.slice(vendorSeparatorIndex + 2).trim(); -} - -export function transformPiModels(models: AgentModelDefinition[]): AgentModelDefinition[] { - return models.map((model) => { - if (!model.label.includes("/")) { - return model; - } - - const segments = model.label.split("/").filter((segment) => segment.length > 0); - const rawLabel = segments.at(-1); - if (!rawLabel) { - return model; - } - - return { - ...model, - label: normalizePiModelLabel(rawLabel), - description: model.description ?? model.label, - }; - }); -} - function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel { return ( value === "off" || @@ -1166,7 +1137,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti return { provider, id: `${model.provider}/${model.id}`, - label: `${model.provider}/${model.name ?? model.id}`, + label: modelDisplayLabel(model), description: `${model.provider}/${model.id}`, metadata: { provider: model.provider, @@ -2630,7 +2601,7 @@ export class PiRpcAgentClient implements AgentClient { const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime); const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null; const paseoExtension = createPiPaseoExtensionFile({ - systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt), + systemPrompt: composeAgentSystemPrompt(config), mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined, }); let runtimeSession: PiRuntimeSession; @@ -2699,10 +2670,7 @@ export class PiRpcAgentClient implements AgentClient { ); const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null; const paseoExtension = createPiPaseoExtensionFile({ - systemPrompt: composeSystemPromptParts( - resumeConfig.config.systemPrompt, - resumeConfig.config.daemonAppendSystemPrompt, - ), + systemPrompt: composeAgentSystemPrompt(resumeConfig.config), mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined, }); const tempFiles = mcpConfigFile ? [mcpConfigFile, paseoExtension] : [paseoExtension]; @@ -2817,15 +2785,13 @@ export class PiRpcAgentClient implements AgentClient { "get_state", () => catalogSession.getState(), ); - const models = transformPiModels( - piModels.map((model) => { - const mapped = mapPiModel(model, PI_PROVIDER); - const isConfigured = - model.provider === configuredModel?.provider && model.id === configuredModel?.id; - if (isConfigured) mapped.isDefault = true; - return mapped; - }), - ); + const models = piModels.map((model) => { + const mapped = mapPiModel(model, PI_PROVIDER); + const isConfigured = + model.provider === configuredModel?.provider && model.id === configuredModel?.id; + if (isConfigured) mapped.isDefault = true; + return mapped; + }); return { models, modes: [] }; } finally { context?.signal.removeEventListener("abort", handleAbort); diff --git a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts index 8fbba690b8..9360667f8b 100644 --- a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import type { ToolCallDetail } from "../../agent-sdk-types.js"; import type { ProviderImageOutput } from "../provider-image-output.js"; +import { omitNullArgs } from "../tool-call-args.js"; interface BashToolInput { command: string; @@ -331,7 +332,7 @@ export function parseToolArgs(toolName: string, rawArgs: unknown): PiTrackedTool } const schema = SIMPLE_TOOL_SCHEMAS[toolName as SimpleToolKind]; if (schema) { - const parsed = schema.safeParse(rawArgs); + const parsed = schema.safeParse(omitNullArgs(rawArgs)); if (parsed.success) { return { kind: toolName as SimpleToolKind, toolName, args: parsed.data } as PiTrackedToolCall; } diff --git a/packages/server/src/server/agent/providers/provider-runner.ts b/packages/server/src/server/agent/providers/provider-runner.ts index 94ec047706..4fa8d1c851 100644 --- a/packages/server/src/server/agent/providers/provider-runner.ts +++ b/packages/server/src/server/agent/providers/provider-runner.ts @@ -1,4 +1,5 @@ import { + AgentTurnStartCanceledError, getAgentStreamEventTurnId, type AgentPromptInput, type AgentRunOptions, @@ -90,6 +91,9 @@ export async function runProviderTurn({ processEvent(event); } await completion; + } catch (error) { + if (!(error instanceof AgentTurnStartCanceledError)) throw error; + return { sessionId: await getSessionId(), finalText: "", timeline: [], canceled: true }; } finally { unsubscribe(); } diff --git a/packages/server/src/server/agent/providers/tool-call-args.test.ts b/packages/server/src/server/agent/providers/tool-call-args.test.ts new file mode 100644 index 0000000000..87b38a0329 --- /dev/null +++ b/packages/server/src/server/agent/providers/tool-call-args.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from "vitest"; + +import { parseToolArgs as parseOmpToolArgs } from "./omp/tool-call-detail.js"; +import { parseToolArgs as parsePiToolArgs } from "./pi/tool-call-mapper.js"; + +// Models send `null` for optional arguments (captured in #7011: read offset/limit), which the +// runtimes treat as omitted. Rejecting them turned every such call into an unknown card. +describe.each([ + ["Pi", parsePiToolArgs], + ["OMP", parseOmpToolArgs], +])("%s tool args with null optional values", (_provider, parseToolArgs) => { + test.each([ + ["read", { path: "./preview.png", offset: null, limit: null }, { path: "./preview.png" }], + ["bash", { command: "ls", timeout: null }, { command: "ls" }], + ])("parses %s as its own tool kind", (toolName, rawArgs, args) => { + expect(parseToolArgs(toolName, rawArgs)).toEqual({ kind: toolName, toolName, args }); + }); +}); diff --git a/packages/server/src/server/agent/providers/tool-call-args.ts b/packages/server/src/server/agent/providers/tool-call-args.ts new file mode 100644 index 0000000000..baf9d2d3bb --- /dev/null +++ b/packages/server/src/server/agent/providers/tool-call-args.ts @@ -0,0 +1,9 @@ +// Models routinely send `null` for optional tool arguments (e.g. read offset/limit); the +// runtimes treat that as omitted, so the mappers must too or the call degrades to an +// unknown card that carries the raw result. +export function omitNullArgs(rawArgs: unknown): unknown { + if (!rawArgs || typeof rawArgs !== "object" || Array.isArray(rawArgs)) { + return rawArgs; + } + return Object.fromEntries(Object.entries(rawArgs).filter(([, value]) => value !== null)); +} diff --git a/packages/server/src/server/agent/restart-recovery/index.test.ts b/packages/server/src/server/agent/restart-recovery/index.test.ts index 77adf359c4..c058f5c14d 100644 --- a/packages/server/src/server/agent/restart-recovery/index.test.ts +++ b/packages/server/src/server/agent/restart-recovery/index.test.ts @@ -1,9 +1,12 @@ import { expect, test } from "vitest"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, mkdir, writeFile, readdir, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; +import { execFileSync, spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; import { join } from "node:path"; import { AgentStorage, parseStoredAgentRecord } from "../agent-storage.js"; import { createTestLogger } from "../../../test-utils/test-logger.js"; +import { readPersistedConfig } from "../../persisted-config.js"; import { createRestartRecovery } from "./index.js"; test("recovery saves intent before normalization, clears before dispatch, and resumes each agent independently", async () => { @@ -103,3 +106,130 @@ test("opt-out consumes pending recovery and excludes archived, private, owned an await rm(root, { recursive: true, force: true }); } }); + +const bashAvailable = + process.platform !== "win32" && + spawnSync("bash", ["-c", "true"], { stdio: "ignore" }).status === 0; +for (const seeder of ["setup", "shell", "setup-bom"] as const) { + test.skipIf(seeder === "shell" && !bashAvailable)( + `${seeder} seed never dispatches copied running or pending agents and excludes automation`, + async () => { + const root = await mkdtemp(join(tmpdir(), "inert-seed-")); + try { + const source = join(root, "source"); + const targetRoot = join(root, "target"); + const target = join(targetRoot, ".dev/paseo-home"); + const storage = new AgentStorage(join(root, "source-records"), createTestLogger()); + for (const [id, lastStatus, resumeOnStartup] of [ + ["live", "running", false], + ["crashed", "running", true], + ["stopped", "closed", true], + ] as const) { + await storage.upsert( + parseStoredAgentRecord({ + id, + lastStatus, + resumeOnStartup, + provider: "codex", + cwd: root, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + ); + } + await storage.flush(); + await mkdir(source, { recursive: true }); + await symlink( + join(root, "source-records"), + join(source, "agents"), + process.platform === "win32" ? "junction" : "dir", + ); + await mkdir(join(source, "schedules"), { recursive: true }); + await writeFile(join(source, "schedules", "schedule.json"), '{"kind":"scheduled"}'); + await writeFile(join(source, "schedules", "heartbeat.json"), '{"kind":"heartbeat"}'); + await writeFile( + join(source, "config.json"), + (seeder === "setup-bom" ? "\uFEFF" : "") + + JSON.stringify({ + version: 1, + agents: { resumeOnStartup: true, resumePrompt: "Continue" }, + }), + ); + const repo = fileURLToPath(new URL("../../../../../../", import.meta.url)); + const env = { + ...process.env, + PASEO_SOURCE_CHECKOUT_PATH: join(root, "checkout"), + PASEO_WORKTREE_PATH: targetRoot, + PASEO_DEV_SEED_HOME: source, + PASEO_HOME: target, + }; + if (seeder !== "shell") + execFileSync(process.execPath, [join(repo, "scripts/seed-worktree-dev-state.mjs")], { + env, + }); + else { + const linkedRepo = join(root, "linked-checkout"); + await symlink(repo, linkedRepo, "dir"); + execFileSync("bash", [join(linkedRepo, "scripts/dev-home.sh")], { env }); + } + expect((await readdir(target)).sort()).toEqual(["agents", "config.json"]); + const config = readPersistedConfig(target); + const copied = new AgentStorage(join(target, "agents"), createTestLogger()); + const dispatched: string[] = []; + const recovery = createRestartRecovery({ + storage: copied, + settings: () => ({ + enabled: config.agents?.resumeOnStartup === true, + prompt: "Continue", + }), + eligible: async () => true, + dispatch: async (id) => { + dispatched.push(id); + }, + report: () => {}, + }); + await recovery.prepareStartup(); + recovery.resumePending(); + for (const record of await copied.listAll()) + await recovery.waitForResume(record.id, new AbortController().signal); + expect(dispatched).toEqual([]); + expect((await copied.listAll()).map((r) => [r.lastStatus, r.resumeOnStartup])).toEqual([ + ["closed", false], + ["closed", false], + ["closed", false], + ]); + expect(readPersistedConfig(source).agents?.resumeOnStartup).toBe(true); + const unchangedSource = new AgentStorage(join(root, "source-records"), createTestLogger()); + expect((await unchangedSource.get("live"))?.lastStatus).toBe("running"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }, + ); +} + +test("seeding skips an existing home without reading invalid source config", async () => { + const root = await mkdtemp(join(tmpdir(), "seed-skip-")); + try { + const source = join(root, "source"); + const targetRoot = join(root, "target"); + const target = join(targetRoot, ".dev/paseo-home"); + await mkdir(source, { recursive: true }); + await mkdir(target, { recursive: true }); + await writeFile(join(source, "config.json"), "invalid JSON"); + await writeFile(join(target, "keep.json"), "{}"); + const repo = fileURLToPath(new URL("../../../../../../", import.meta.url)); + execFileSync(process.execPath, [join(repo, "scripts/seed-worktree-dev-state.mjs")], { + env: { + ...process.env, + PASEO_SOURCE_CHECKOUT_PATH: join(root, "checkout"), + PASEO_WORKTREE_PATH: targetRoot, + PASEO_DEV_SEED_HOME: source, + PASEO_DEV_RESET_HOME: "0", + }, + }); + expect(await readdir(target)).toEqual(["keep.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/system-prompt.ts b/packages/server/src/server/agent/system-prompt.ts index 2aafc3759b..5dff1e6602 100644 --- a/packages/server/src/server/agent/system-prompt.ts +++ b/packages/server/src/server/agent/system-prompt.ts @@ -8,3 +8,15 @@ export function composeSystemPromptParts( return prompt.length > 0 ? prompt : undefined; } + +export function composeAgentSystemPrompt(config: { + systemPrompt?: string; + daemonAppendSystemPrompt?: string; + pluginAppendSystemPrompt?: string[]; +}): string | undefined { + return composeSystemPromptParts( + config.systemPrompt, + config.daemonAppendSystemPrompt, + ...(config.pluginAppendSystemPrompt ?? []), + ); +} diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index bd5357e581..905748d752 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -241,6 +241,23 @@ function mergeReasoningChunks(entries: readonly WorkingEntry[]): WorkingEntry[] return output; } +/** + * Whether `next`, the row right after `previous`, is another chunk of the same assistant + * message. A turn id or message id change starts a new message, which matters where rows + * replayed from provider history carry no turn id. + */ +export function continuesAssistantMessage( + previous: Pick, + next: Pick, +): boolean { + return ( + previous.item.type === "assistant_message" && + next.item.type === "assistant_message" && + previous.turnId === next.turnId && + (next.item.messageId === undefined || next.item.messageId === previous.item.messageId) + ); +} + function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] { const output: WorkingEntry[] = []; @@ -248,10 +265,8 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] const previous = output[output.length - 1]; const shouldMerge = previous && - previous.item.type === "assistant_message" && - entry.item.type === "assistant_message" && previous.seqEnd + 1 === entry.seqStart && - previous.turnId === entry.turnId; + continuesAssistantMessage(previous, entry); if (!shouldMerge || !previous) { output.push(entry); @@ -262,13 +277,6 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] { type: "assistant_message" } >; const entryAssistant = entry.item as Extract; - if ( - entryAssistant.messageId !== undefined && - previousAssistant.messageId !== entryAssistant.messageId - ) { - output.push(entry); - continue; - } const collapsedKinds = new Set([ ...previous.collapsed, diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 1107ad5e9d..1123e59ced 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -15,7 +15,7 @@ import { ensureValidJson } from "../../json-utils.js"; import type { Logger } from "pino"; import type { AgentMode, AgentProvider, AgentSessionConfig } from "../agent-sdk-types.js"; -import type { AgentManager } from "../agent-manager.js"; +import type { AgentManager, ManagedAgent } from "../agent-manager.js"; import { ActiveTurnBehaviorSchema, AgentProfileSchema } from "@getpaseo/protocol/messages"; import type { DaemonConfigStore } from "../../daemon-config-store.js"; import { featuresFromControls } from "@getpaseo/protocol/option-controls"; @@ -33,7 +33,7 @@ import { toAgentPayload, } from "../agent-projections.js"; import { summarizeAgentActivity } from "../activity-curator.js"; -import type { AgentStorage } from "../agent-storage.js"; +import type { AgentStorage, StoredAgentRecord } from "../agent-storage.js"; import { AgentNotFoundError, ensureAgentLoaded } from "../agent-loading.js"; import { isStoredAgentProviderAvailable } from "../../persistence-hooks.js"; import { @@ -1281,7 +1281,7 @@ function createToolCatalog( .strict(); const commonSendAgentPromptInputSchema = { activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe( - 'How to send into a running turn: "steer" joins it, falling back to interrupt when unavailable; "interrupt" replaces it. Defaults to steer for agent callers and interrupt otherwise.', + 'Agent callers: "steer" (default) waits until the current turn ends; "interrupt" replaces it. Human callers: "steer" joins the turn, falling back to interrupt; default is interrupt.', ), agentId: z.string(), prompt: z.string(), @@ -1968,7 +1968,7 @@ function createToolCatalog( { title: "Send agent prompt", description: - "Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient. Completion reports include the target’s last response by default. Paseo supplies caller identity.", + "Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient and waits for the current turn to end unless interrupt is requested. Completion reports include the target’s last response by default. Paseo supplies caller identity.", inputSchema: sendAgentPromptInputSchema, outputSchema: { success: z.boolean(), @@ -2045,13 +2045,13 @@ function createToolCatalog( messageId: receipt.messageId, status: agentManager.getAgent(agentId)?.lifecycle ?? "idle", guidance: notifying - ? `Queued for delivery after two quiet seconds. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}` - : "Queued for delivery after two quiet seconds; provider dispatch has not occurred.", + ? `Queued for delivery after two quiet seconds and the current turn ends. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}` + : "Queued for delivery after two quiet seconds and the current turn ends; provider dispatch has not occurred.", }, }; } - const { disposition } = await sendPromptToAgent({ + const dispatch = await sendPromptToAgent({ agentManager, agentStorage, agentId, @@ -2070,11 +2070,14 @@ function createToolCatalog( }); // Return once the provider has accepted the turn, so the status reports it running. - if (disposition === "turn_started") { - await waitForAgentRunStartWithTimeout(agentManager, agentId).catch((error) => { - rejectNotification(); - throw error; - }); + const { disposition } = dispatch; + if (dispatch.disposition === "turn_started") { + await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch( + (error) => { + rejectNotification(); + throw error; + }, + ); } const currentSnapshot = agentManager.getAgent(agentId); @@ -2096,6 +2099,22 @@ function createToolCatalog( }, ); + // Match the WebSocket snapshot: idle agents can still own background work. + async function projectLiveAgent(agent: ManagedAgent) { + const snapshot = await serializeSnapshotWithMetadata(agentStorage, agent, childLogger); + const backgroundWork = agentManager.getAgentBackgroundWorkSummary(agent.id); + return backgroundWork ? { ...snapshot, backgroundWork } : snapshot; + } + + function projectStoredAgent(record: StoredAgentRecord) { + return buildStoredAgentPayload( + record, + new Set(providerSnapshotManager.listRegisteredProviderIds()), + (provider, own) => agentManager.effectiveOptionsFor(provider, own), + agentManager.getAgentBackgroundWorkSummary(record.id), + ); + } + registerTool( "get_agent_status", { @@ -2113,11 +2132,7 @@ function createToolCatalog( async ({ agentId }) => { const snapshot = agentManager.getAgent(agentId); if (snapshot) { - const structuredSnapshot = await serializeSnapshotWithMetadata( - agentStorage, - snapshot, - childLogger, - ); + const structuredSnapshot = await projectLiveAgent(snapshot); return { content: [], structuredContent: ensureValidJson({ @@ -2132,11 +2147,7 @@ function createToolCatalog( throw new PaseoToolInputError(`Agent ${agentId} not found`); } - const structuredSnapshot = buildStoredAgentPayload( - record, - new Set(providerSnapshotManager.listRegisteredProviderIds()), - (provider, own) => agentManager.effectiveOptionsFor(provider, own), - ); + const structuredSnapshot = projectStoredAgent(record); return { content: [], structuredContent: ensureValidJson({ @@ -2185,14 +2196,8 @@ function createToolCatalog( manager: agentManager, storage: agentStorage, workspaces: options.workspaceRegistry, - projectLive: (snapshot) => - serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger), - projectStored: (record) => - buildStoredAgentPayload( - record, - new Set(providerSnapshotManager.listRegisteredProviderIds()), - (provider, own) => agentManager.effectiveOptionsFor(provider, own), - ), + projectLive: projectLiveAgent, + projectStored: projectStoredAgent, isProviderVisible: () => true, isStoredProviderAvailable: (record) => isStoredAgentProviderAvailable( diff --git a/packages/server/src/server/authorization/index.ts b/packages/server/src/server/authorization/index.ts index e79f5d28e7..dec5bca819 100644 --- a/packages/server/src/server/authorization/index.ts +++ b/packages/server/src/server/authorization/index.ts @@ -29,7 +29,7 @@ export class SessionAuthorization { this.permissions = new Set(permissions); } - allowsInbound(message: SessionInboundMessage): boolean { + allowsInbound(message: Pick): boolean { return this.allows(requiredPermissionForInbound(message.type)); } diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 1f44e10dc4..2015316b07 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -149,6 +149,8 @@ const INBOUND_PERMISSION = { "plugin.rpc.subscribe.request": "daemon.manage", "plugin.source.install.request": "daemon.manage", "plugin.source.status.request": "daemon.manage", + "plugin.registry.list.request": "daemon.manage", + "plugin.registry.get.request": "daemon.manage", "plugin.source.update.request": "daemon.manage", "plugin.source.update.preview.request": "daemon.manage", "plugin.source.update.apply.request": "daemon.manage", @@ -399,6 +401,8 @@ const OUTBOUND_PERMISSION = { "plugin.rpc.closed": "daemon.manage", "plugin.source.install.response": "daemon.manage", "plugin.source.status.response": "daemon.manage", + "plugin.registry.list.response": "daemon.manage", + "plugin.registry.get.response": "daemon.manage", "plugin.source.update.response": "daemon.manage", "plugin.source.update.preview.response": "daemon.manage", "plugin.source.update.apply.response": "daemon.manage", diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 7e04dd5eeb..e2a1582340 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: { ); } -import { VoiceAssistantWebSocketServer } from "./websocket-server.js"; +import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js"; import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js"; import { createWorkspaceLabelService } from "./workspace-labels/index.js"; import { createGitHubService } from "../services/github-service.js"; @@ -813,7 +813,7 @@ export async function createPaseoDaemon( app.use((req, res, next) => { const origin = req.headers.origin; - if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) { + if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) { res.setHeader("Access-Control-Allow-Origin", origin); res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); diff --git a/packages/server/src/server/checkout-diff-manager.test.ts b/packages/server/src/server/checkout-diff-manager.test.ts index da2947c24d..8274bad3ff 100644 --- a/packages/server/src/server/checkout-diff-manager.test.ts +++ b/packages/server/src/server/checkout-diff-manager.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { tmpdir } from "node:os"; import pino from "pino"; import { expect, test } from "vitest"; +import { DiffOpcode } from "@getpaseo/protocol/binary-frames/index"; import { CheckoutDiffManager, type CheckoutDiffSnapshotPayload } from "./checkout-diff-manager.js"; import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; import { createFileObserver } from "./file-observer/index.js"; @@ -137,6 +138,84 @@ test("cancelling a legacy subscriber during a shared revision does not revive it }); }, 30_000); +test("legacy subscribers are not re-sent a snapshot that did not change", async () => { + await withCheckout(async ({ cwd, manager }) => { + await writeFile(join(cwd, ".gitignore"), "*.log\n"); + await writeFile(join(cwd, "x.ts"), "const value = 1;\n"); + let revisions = 0; + const modern = await manager.streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + if (frame.opcode === DiffOpcode.End) revisions++; + }, + ); + await modern.start(); + const updates: CheckoutDiffSnapshotPayload[] = []; + const legacy = await manager.subscribe({ cwd, compare: { mode: "uncommitted" } }, (snapshot) => + updates.push(snapshot), + ); + try { + expect(legacy.initial.files.map((file) => file.path)).toEqual([".gitignore", "x.ts"]); + await waitForSubscriberCount(manager, 2); + const before = revisions; + await writeFile(join(cwd, "app.log"), "ignored\n"); + await writeFile(join(cwd, "README"), "base\n"); + await writeFile(join(cwd, "x.ts"), "const value = 1;\n"); + await manager.scheduleRefreshForCwd(cwd); + await expect.poll(() => revisions, { timeout: 10_000 }).toBeGreaterThan(before); + expect(updates).toHaveLength(0); + await writeFile(join(cwd, "x.ts"), "const value = 2;\n"); + await expect.poll(() => updates.length, { timeout: 10_000 }).toBe(1); + expect(updates[0].files[1].hunks[0].lines).toContainEqual( + expect.objectContaining({ type: "add", content: "const value = 2;" }), + ); + } finally { + await legacy.unsubscribe(); + await modern.release(); + } + }); +}, 30_000); + +test("legacy All subscribers are not re-sent the snapshot when a commit only moves HEAD", async () => { + await withCheckout(async ({ cwd, manager, git }) => { + git("checkout", "-b", "feature"); + await writeFile(join(cwd, "x.ts"), "const value = 1;\n"); + const endedHeads: string[] = []; + let beganHead = ""; + const modern = await manager.streams.subscribe( + { + cwd, + base: { kind: "rev", rev: "main" }, + checkoutBase: { compare: { mode: "all", baseRef: "main" }, paseoHome: cwd }, + head: { kind: "worktree" }, + mergeBase: true, + }, + async (frame) => { + if (frame.opcode === DiffOpcode.Begin) beganHead = frame.headSha; + if (frame.opcode === DiffOpcode.End) endedHeads.push(beganHead); + }, + ); + await modern.start(); + const updates: CheckoutDiffSnapshotPayload[] = []; + const legacy = await manager.subscribe( + { cwd, compare: { mode: "all", baseRef: "main" } }, + (snapshot) => updates.push(snapshot), + ); + try { + expect(legacy.initial.files.map((file) => file.path)).toEqual(["x.ts"]); + await waitForSubscriberCount(manager, 2); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "feature"); + const head = git("rev-parse", "HEAD"); + await expect.poll(() => endedHeads.at(-1), { timeout: 10_000 }).toBe(head); + expect(updates).toHaveLength(0); + } finally { + await legacy.unsubscribe(); + await modern.release(); + } + }); +}, 30_000); + async function waitForSubscriberCount(manager: CheckoutDiffManager, count: number): Promise { await expect .poll(() => manager.getMetrics().checkoutDiffSubscriptionCount, { timeout: 10_000 }) @@ -181,7 +260,7 @@ test("legacy diffs retain successful bodies when an oversized sibling is removed ]); await rm(join(cwd, "b.txt")); await manager.scheduleRefreshForCwd(cwd); - await expect.poll(() => updates.at(-1)?.error).toBeNull(); + await expect.poll(() => updates.at(-1)?.error, { timeout: 10000 }).toBeNull(); expect(updates.at(-1)?.files[0]).toMatchObject({ path: "a.ts", hunks: [ @@ -192,7 +271,7 @@ test("legacy diffs retain successful bodies when an oversized sibling is removed }); subscription.unsubscribe(); }); -}); +}, 30000); test("legacy subscriptions reselect the preferred base when a remote ref appears", async () => { await withCheckout(async ({ cwd, manager, git }) => { diff --git a/packages/server/src/server/checkout-diff-manager.ts b/packages/server/src/server/checkout-diff-manager.ts index 921934e70e..6eb83de4e8 100644 --- a/packages/server/src/server/checkout-diff-manager.ts +++ b/packages/server/src/server/checkout-diff-manager.ts @@ -73,6 +73,7 @@ export class CheckoutDiffManager { resolveInitial = resolve; }); let delivered = false; + let deliveredFingerprint = ""; let pending: DiffBegin | null = null; let files = new Map(); let bodies = new Map(); @@ -114,6 +115,11 @@ export class CheckoutDiffManager { payload = legacySnapshot(cwd, [...next.values()]); } pending = null; + // The engine commits a revision per observed input change, including ones that only move the + // resolved SHAs this snapshot omits. Old clients get a snapshot only when it differs. + const fingerprint = JSON.stringify(payload); + if (fingerprint === deliveredFingerprint) return; + deliveredFingerprint = fingerprint; if (delivered) listener(payload); else { delivered = true; diff --git a/packages/server/src/server/checkout/status-projection.test.ts b/packages/server/src/server/checkout/status-projection.test.ts index 5a5ac1558b..336138bd67 100644 --- a/packages/server/src/server/checkout/status-projection.test.ts +++ b/packages/server/src/server/checkout/status-projection.test.ts @@ -1,13 +1,52 @@ import { describe, expect, test } from "vitest"; -import { CheckoutPrStatusSchema } from "@getpaseo/protocol/messages"; +import { CheckoutPrStatusSchema, CheckoutStatusResponseSchema } from "@getpaseo/protocol/messages"; import type { WorkspaceGitRuntimeSnapshot } from "../workspace-git-service.js"; import { buildCheckoutPrStatusPayloadFromSnapshot, + buildCheckoutStatusPayloadFromSnapshot, normalizeCheckoutPrStatusPayload, } from "./status-projection.js"; describe("checkout status projection", () => { + test("publishes where the forge is on the web with the checkout status", () => { + const snapshot: WorkspaceGitRuntimeSnapshot = { + cwd: "/repo", + git: { + isGit: true, + repoRoot: "/repo", + mainRepoRoot: null, + currentBranch: "main", + remoteUrl: "git@github.com-work:fork-owner/repo.git", + isPaseoOwnedWorktree: false, + isDirty: false, + baseRef: "main", + aheadBehind: null, + upstreamRef: null, + aheadOfOrigin: null, + behindOfOrigin: null, + hasRemote: true, + diffStat: null, + }, + forge: { featuresEnabled: true, authState: "authenticated", pullRequest: null, error: null }, + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }; + + const payload = buildCheckoutStatusPayloadFromSnapshot({ + cwd: "/repo", + requestId: "req-1", + snapshot, + }); + + expect(payload.forgeWeb).toEqual({ + host: "github.com", + referenceRepository: "main-owner/repo", + }); + expect( + CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload, + ).toMatchObject({ forgeWeb: payload.forgeWeb }); + }); + test("includes repository identity fields on the PR status wire payload", () => { const payload = normalizeCheckoutPrStatusPayload( { diff --git a/packages/server/src/server/checkout/status-projection.ts b/packages/server/src/server/checkout/status-projection.ts index 93242cb941..00f9ce05c5 100644 --- a/packages/server/src/server/checkout/status-projection.ts +++ b/packages/server/src/server/checkout/status-projection.ts @@ -69,6 +69,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({ behindOfOrigin: snapshot.git.behindOfOrigin ?? null, hasRemote: snapshot.git.hasRemote, remoteUrl: snapshot.git.remoteUrl, + ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), isPaseoOwnedWorktree: true, error: null, requestId, @@ -91,6 +92,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({ behindOfOrigin: snapshot.git.behindOfOrigin ?? null, hasRemote: snapshot.git.hasRemote, remoteUrl: snapshot.git.remoteUrl, + ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), isPaseoOwnedWorktree: false, error: null, requestId, diff --git a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts index 5b618f0670..5caf88217d 100644 --- a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts +++ b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts @@ -2127,6 +2127,57 @@ test( }, ); +test( + "a remote child without a mode starts in its same-provider caller's mode", + { timeout: 30000 }, + async () => { + const a = await daemon({ mcpEnabled: true }); + const b = await daemon(); + const origin = await api(a); + const destination = await api(b); + await origin.paseo.hosts.add({ connection: `127.0.0.1:${b.port}` }); + const directory = await online(origin.paseo); + const workspace = await origin.paseo.workspaces.create({ + source: { kind: "directory", path: a.staticDir }, + }); + const remoteWorkspace = await destination.paseo.workspaces.create({ + source: { kind: "directory", path: b.staticDir }, + }); + const parent = await workspace.agents.create({ + config: { provider: "claude/claude-test", modeId: "bypassPermissions" }, + title: "Mode parent", + }); + const mcp = new Client({ name: "mode-parent", version: "1" }); + cleanup.push(() => mcp.close()); + await mcp.connect( + new StreamableHTTPClientTransport( + new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`), + ), + ); + const remoteMode = async (provider: string, settings?: { modeId: string }) => { + const response = await mcp.callTool({ + name: "create_agent", + arguments: { + serverId: directory.hosts[0]!.serverId, + workspaceId: remoteWorkspace.id, + provider, + title: "Mode child", + initialPrompt: "Report your mode", + settings, + }, + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + const childId = (response.structuredContent as { agentId: string }).agentId; + return (await destination.client.fetchAgent(childId))?.agent.currentModeId; + }; + + expect(await remoteMode("claude/claude-test")).toBe("bypassPermissions"); + expect(await remoteMode("claude/claude-test", { modeId: "default" })).toBe("default"); + // Another provider's modes are unknown here, so the destination applies its own default. + expect(await remoteMode("codex/gpt-5.4")).toBeNull(); + }, +); + test( "remote finish observation survives a permission checkpoint until resumed completion", { timeout: 30000 }, diff --git a/packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts new file mode 100644 index 0000000000..eb8352c348 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts @@ -0,0 +1,88 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; +import { beforeAll, beforeEach, describe, expect, test } from "vitest"; + +import type { AgentStreamEvent } from "../agent/agent-sdk-types.js"; +import { + canRunRealProvider, + createRealProviderClient, + getRealProviderConfig, +} from "./real-provider-test-config.js"; + +describe("real claude: idle runtime cleanup and session crons", () => { + let canRun = false; + beforeAll(async () => { + canRun = await canRunRealProvider("claude"); + }); + beforeEach((context) => { + if (!canRun) context.skip(); + }); + + test("a runtime holding a session-only cron is kept until the cron is deleted", async () => { + const logger = pino({ level: "silent" }); + const client = createRealProviderClient("claude", logger); + const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-session-cron-")); + const session = await client.createSession({ + cwd, + ...getRealProviderConfig("claude"), + }); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.run( + "Call the CronCreate tool exactly once with cron '0 */6 * * *', recurring true, durable false, prompt 'say hi'. Then reply with exactly: DONE", + ); + const cronResult = events.find( + (event) => + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.name === "CronCreate" && + event.item.status === "completed", + ); + expect(cronResult, JSON.stringify(events.slice(-5))).toBeDefined(); + expect(await session.canStopRuntime!()).toBe(false); + + await session.run( + "Delete every scheduled cron job with the CronDelete tool. Then reply with exactly: DONE", + ); + expect(await session.canStopRuntime!()).toBe(true); + } finally { + await session.close(); + } + }, 240_000); + + test("a turn interrupted after it creates a session-only cron keeps the runtime", async () => { + const logger = pino({ level: "silent" }); + const client = createRealProviderClient("claude", logger); + const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-session-cron-")); + const session = await client.createSession({ + cwd, + ...getRealProviderConfig("claude"), + }); + const cronCreated = new Promise((resolve) => { + session.subscribe((event) => { + if ( + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.name === "CronCreate" && + event.item.status === "completed" + ) + resolve(); + }); + }); + try { + await session.startTurn( + "Call the CronCreate tool exactly once with cron '0 */6 * * *', recurring true, durable false, prompt 'say hi'. Then run the Bash command 'sleep 120' in the foreground. Then reply with exactly: DONE", + ); + await cronCreated; + await session.interrupt(); + // The cancelled turn settles about a second after interrupt() resolves. + await new Promise((resolve) => setTimeout(resolve, 5_000)); + expect(await session.canStopRuntime!()).toBe(false); + } finally { + await session.close(); + } + }, 240_000); +}); diff --git a/packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts new file mode 100644 index 0000000000..85fc3547bf --- /dev/null +++ b/packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts @@ -0,0 +1,122 @@ +import { beforeAll, beforeEach, describe, expect, test } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; + +import { ClaudeAgentClient } from "../agent/providers/claude/agent.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { canRunRealProvider, getRealProviderConfig } from "./real-provider-test-config.js"; + +function tmpCwd(): string { + return mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-compaction-")); +} + +type TimelineItem = Awaited< + ReturnType +>["entries"][number]["item"]; + +// The steer must land while the compaction is still running, or it takes the idle path. +function isCompacting(items: TimelineItem[]): boolean { + const statuses = new Set( + items.flatMap((item) => (item.type === "compaction" ? [item.status] : [])), + ); + return statuses.has("loading") && !statuses.has("completed"); +} + +function hasAssistantText(items: TimelineItem[], text: string): boolean { + return items.some((item) => item.type === "assistant_message" && item.text.includes(text)); +} + +async function timelineItems(client: DaemonClient, agentId: string): Promise { + const timeline = await client.fetchAgentTimeline(agentId, { + direction: "tail", + limit: 200, + }); + return timeline.entries.map((entry) => entry.item); +} + +async function waitForTimeline( + client: DaemonClient, + agentId: string, + check: (items: TimelineItem[]) => boolean, + timeoutMs: number, + label: string, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const items = await timelineItems(client, agentId); + if (check(items)) return items; + if (Date.now() > deadline) { + throw new Error(`Timed out: ${label}: ${JSON.stringify(items.slice(-6)).slice(0, 2000)}`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +describe("daemon E2E (real claude) - steer during compaction", () => { + let canRun = false; + + beforeAll(async () => { + canRun = await canRunRealProvider("claude"); + }); + + beforeEach((context) => { + if (!canRun) context.skip(); + }); + + test("a steered message waits for a running /compact instead of cancelling it", async () => { + const logger = pino({ level: "silent" }); + const cwd = tmpCwd(); + const daemon = await createTestPaseoDaemon({ + agentClients: { claude: new ClaudeAgentClient({ logger }) }, + logger, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + }); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const agent = await client.createAgent({ + cwd, + title: "claude-steer-during-compaction", + ...getRealProviderConfig("claude"), + }); + await client.sendAgentMessage( + agent.id, + `Remember this list for later and reply exactly: NOTED. ${Array.from( + { length: 400 }, + (_, index) => `item-${index}`, + ).join(" ")}`, + ); + const firstFinish = await client.waitForFinish(agent.id, 120_000); + expect(firstFinish.status, firstFinish.error).toBe("idle"); + + await client.sendAgentMessage(agent.id, "/compact"); + await waitForTimeline(client, agent.id, isCompacting, 60_000, "Claude reports compacting"); + + await client.sendAgentMessage(agent.id, "Reply exactly: AFTER_COMPACT", { + activeTurnBehavior: "steer", + }); + await waitForTimeline( + client, + agent.id, + (items) => hasAssistantText(items, "AFTER_COMPACT"), + 180_000, + "Claude answers the steered message", + ); + await client.waitForFinish(agent.id, 120_000); + const finalItems = await timelineItems(client, agent.id); + expect( + finalItems.filter((item) => item.type === "compaction").map((item) => item.status), + ).toContain("completed"); + expect(hasAssistantText(finalItems, "Compaction canceled")).toBe(false); + } finally { + await client.close().catch(() => undefined); + await daemon.close().catch(() => undefined); + rmSync(cwd, { recursive: true, force: true }); + } + }, 420_000); +}); diff --git a/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts b/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts index 54ec1964c1..0a0da6f0e9 100644 --- a/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts @@ -9,7 +9,7 @@ import { symlinkSync, } from "fs"; import { once } from "node:events"; -import { get } from "node:http"; +import { get, type IncomingMessage } from "node:http"; import { tmpdir } from "os"; import path from "path"; import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js"; @@ -69,6 +69,29 @@ describe("daemon E2E", () => { }, 60000); describe("file download tokens", () => { + test("lets a page on a loopback alias of the request's host and port fetch a download", async () => { + const cwd = tmpCwd(); + writeFileSync(path.join(cwd, "download.bin"), "download bytes"); + try { + // The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at + // http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket + // accepts this origin, so the download must as well. + const token = await ctx.client.requestDownloadToken(cwd, "download.bin"); + const request = get({ + host: "127.0.0.1", + port: ctx.daemon.port, + path: `/api/files/download?token=${token.token}`, + headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" }, + }); + const [response] = (await once(request, "response")) as [IncomingMessage]; + response.resume(); + expect(response.statusCode).toBe(200); + expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080"); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + }); + test.skipIf(process.platform !== "linux")( "releases file descriptors after repeated HTTP download cancellations", async () => { diff --git a/packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts b/packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts new file mode 100644 index 0000000000..d8dbfe7eb8 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts @@ -0,0 +1,56 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js"; + +let ctx: DaemonTestContext; +let cwd: string; + +beforeEach(async () => { + ctx = await createDaemonTestContext(); + cwd = mkdtempSync(path.join(tmpdir(), "fork-background-work-")); +}); + +afterEach(async () => { + await ctx.cleanup(); + rmSync(cwd, { recursive: true, force: true }); +}, 30_000); + +test("forks from a reply that background work outlived", async () => { + const agent = await ctx.client.createAgent({ provider: "claude", cwd }); + await ctx.client.sendMessage(agent.id, "Start background work"); + expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle"); + await ctx.client.sendMessage(agent.id, "Any findings?"); + expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle"); + + const page = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 0 }); + const reply = page.entries.find( + (entry) => entry.item.type === "assistant_message" && entry.item.text === "Audit started.", + ); + if (reply?.item.type !== "assistant_message" || !reply.item.messageId) { + throw new Error("Expected the reply to carry a provider message id"); + } + const task = page.entries.find((entry) => entry.item.type === "tool_call"); + // The Task row started before the reply and completed after it. + expect(task?.item).toMatchObject({ name: "Task", status: "completed" }); + expect(task?.seqStart).toBeLessThan(reply.seqEnd); + expect(task?.seqEnd).toBeGreaterThan(reply.seqEnd); + + const byMessage = await ctx.client.buildAgentForkContext(agent.id, { + boundaryMessageId: reply.item.messageId, + }); + const byCursor = await ctx.client.buildAgentForkContext(agent.id, { + boundaryCursor: { epoch: page.epoch, seq: reply.seqEnd }, + }); + + for (const fork of [byMessage, byCursor]) { + expect(fork.itemCount).toBe(3); + expect(fork.attachment?.text).toContain( + "[User] Start background work\n[Explore] Audit the migrations\n[Assistant] Audit started.\n", + ); + expect(fork.attachment?.text).not.toContain("Any findings?"); + } + expect(byMessage.boundaryMessageId).toBe(reply.item.messageId); + expect(byCursor.boundaryCursor).toEqual({ epoch: page.epoch, seq: reply.seqEnd }); +}, 60_000); diff --git a/packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts new file mode 100644 index 0000000000..3a5594725b --- /dev/null +++ b/packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts @@ -0,0 +1,87 @@ +import { beforeAll, beforeEach, describe, test, expect } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; + +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { + canRunRealProvider, + createRealProviderClients, + getRealProviderConfig, +} from "./real-provider-test-config.js"; + +async function readStatusAndPendingIds( + client: DaemonClient, + agentId: string, +): Promise<{ status: string; pendingIds: string[] }> { + const fetched = await client.fetchAgent(agentId); + const snapshot = fetched!.agent; + const pendingIds = (snapshot.pendingPermissions ?? []).map((pending) => pending.id); + return { status: snapshot.status, pendingIds }; +} + +describe("daemon E2E (real opencode) - a message sent instead of answering a question", () => { + let canRun = false; + + beforeAll(async () => { + canRun = await canRunRealProvider("opencode"); + }); + + beforeEach((context) => { + if (!canRun) { + context.skip(); + } + }); + + test("removes the superseded question from the pending list", async () => { + const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-opencode-question-")); + const logger = pino({ level: "silent" }); + const daemon = await createTestPaseoDaemon({ + agentClients: createRealProviderClients(["opencode"], logger), + logger, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + + try { + const agent = await client.createAgent({ + ...getRealProviderConfig("opencode"), + cwd, + title: "OpenCode superseded question", + }); + + await client.sendMessage( + agent.id, + [ + "Use the question tool to ask me exactly one clarifying question:", + "What color should the button be?", + "Wait for my answer before doing anything else.", + ].join(" "), + ); + await client.waitForAgentUpsert( + agent.id, + (snapshot) => snapshot.pendingPermissions?.[0]?.kind === "question", + 120_000, + ); + + // The app sends with the default send setting, which steers the running turn. + await client.sendMessage(agent.id, "Never mind the question. Reply with the word done.", { + activeTurnBehavior: "steer", + }); + // OpenCode rejects the question and runs the steer message to completion. + await expect + .poll(() => readStatusAndPendingIds(client, agent.id), { + timeout: 120_000, + interval: 1_000, + }) + .toEqual({ status: "idle", pendingIds: [] }); + } finally { + await client.close().catch(() => undefined); + await daemon.close(); + rmSync(cwd, { recursive: true, force: true }); + } + }, 300_000); +}); diff --git a/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts b/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts index bc2803a65e..a8cc2c2379 100644 --- a/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts +++ b/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts @@ -95,7 +95,7 @@ test("an agent-sourced steer leaves the question pending and answerable", async await client.sendAgentMessage(recipient.id, "Peer status check", { sourceAgentId: sender.id, }); - // The public wait includes admitted message delivery before reporting permission status. + // Permission checkpoints are reported while the peer message waits for turn end. const waiting = await client.waitForFinish(recipient.id); expect(waiting.status).toBe("permission"); expect(waiting.final?.pendingPermissions).toMatchObject([ diff --git a/packages/server/src/server/dictation/dictation-stream-manager.ts b/packages/server/src/server/dictation/dictation-stream-manager.ts index b1b061501f..ac91fba00e 100644 --- a/packages/server/src/server/dictation/dictation-stream-manager.ts +++ b/packages/server/src/server/dictation/dictation-stream-manager.ts @@ -345,7 +345,7 @@ export class DictationStreamManager { }): Promise { const state = this.streams.get(params.dictationId); if (!state) { - this.failDictationStream(params.dictationId, "Dictation stream not started", true); + this.emitUnknownStreamError(params.dictationId); return; } @@ -528,7 +528,17 @@ export class DictationStreamManager { return path; } + // Chunks keep arriving for a stream the daemon already dropped, one error + // per chunk; the failure that dropped it is logged where it happened. + private emitUnknownStreamError(dictationId: string): void { + this.emit({ + type: "dictation_stream_error", + payload: { dictationId, error: "Dictation stream not started", retryable: true }, + }); + } + private failDictationStream(dictationId: string, error: string, retryable: boolean): void { + this.logger.warn({ dictationId, error, retryable }, "Dictation stream failed"); this.emit({ type: "dictation_stream_error", payload: { dictationId, error, retryable }, @@ -543,6 +553,10 @@ export class DictationStreamManager { const state = this.streams.get(dictationId); const debugRecordingPath = await this.maybePersistDictationStreamAudio(dictationId); if (!state || this.streams.get(dictationId) !== state) return; + this.logger.warn( + { dictationId, error, retryable, ackSeq: state.ackSeq }, + "Dictation stream failed", + ); this.emit({ type: "dictation_stream_error", payload: { diff --git a/packages/server/src/server/diff/git.test.ts b/packages/server/src/server/diff/git.test.ts index 5c77f80e45..d84214d7a2 100644 --- a/packages/server/src/server/diff/git.test.ts +++ b/packages/server/src/server/diff/git.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { mkdtemp, writeFile, rm, readFile, lstat } from "node:fs/promises"; +import { mkdtemp, writeFile, rm, readFile, lstat, utimes } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { expect, test } from "vitest"; @@ -107,6 +107,67 @@ test("supports empty trees, unborn HEAD, staged and unstaged comparisons", async } }); +test.each([ + { name: "index to working tree", base: { kind: "index" } as const }, + { + name: "commit to working tree with a file removed from the index", + base: { kind: "rev", rev: "HEAD" } as const, + }, +])("$name sees a same-size edit saved in the timestamp tick it was staged", async ({ base }) => { + const cwd = await mkdtemp(join(tmpdir(), "diff-racy-index-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const file = join(cwd, "x.ts"); + const indexPath = join(cwd, ".git", "index"); + const tick = new Date("2026-01-01T00:00:00Z"); + try { + git("init", "-b", "main"); + git("config", "user.email", "test@example.com"); + git("config", "user.name", "Test"); + // Only mtime, size, and inode tell this edit apart; ctime always moves. + git("config", "core.trustctime", "false"); + await writeFile(file, "const value = 1;\n"); + await writeFile(join(cwd, "y.ts"), "const kept = 1;\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(file, "const value = 2;\n"); + await utimes(file, tick, tick); + git("add", "x.ts"); + if (base.kind === "rev") { + git("-c", "commit.gpgsign=false", "commit", "-m", "staged"); + // A file on disk and in the base commit but absent from the index + // selects the private index for commit to working tree comparisons. + git("rm", "--cached", "y.ts"); + } + // The index is written in the tick the file was staged, and the file is + // saved again with the same size within that tick. + await utimes(indexPath, tick, tick); + await writeFile(file, "const value = 3;\n"); + await utimes(file, tick, tick); + expect(git("diff", "--name-only")).toBe("x.ts"); + const originalIndex = await readFile(indexPath); + const originalMtime = (await lstat(indexPath, { bigint: true })).mtimeNs; + + const comparison = await listComparison({ + cwd, + base, + head: { kind: "worktree" }, + highlight: false, + }); + expect(comparison.files.map((entry) => entry.entry.path)).toEqual(["x.ts"]); + const record = await readBody(comparison); + expect(record.body.hunks[0].lines).toEqual([ + { type: "header", content: "@@ -1 +1 @@" }, + { type: "remove", content: "const value = 2;" }, + { type: "add", content: "const value = 3;" }, + ]); + await comparison.close(); + expect(await readFile(indexPath)).toEqual(originalIndex); + expect((await lstat(indexPath, { bigint: true })).mtimeNs).toBe(originalMtime); + } finally { + await rm(cwd, { recursive: true, force: true }); + } +}); + test("lists oversized untracked files without treating their truncated contents as additions", async () => { const cwd = await mkdtemp(join(tmpdir(), "diff-large-file-")); const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); diff --git a/packages/server/src/server/diff/git.ts b/packages/server/src/server/diff/git.ts index c58c1de181..74e0f84057 100644 --- a/packages/server/src/server/diff/git.ts +++ b/packages/server/src/server/diff/git.ts @@ -12,7 +12,6 @@ import { type CheckoutDiffCompare, } from "../../utils/checkout-git.js"; import { lstat, readFile, readlink } from "node:fs/promises"; -import type { BigIntStats } from "node:fs"; import { resolve } from "node:path"; import type { DiffEndpoint, DiffSubscribeRequest } from "@getpaseo/protocol/messages"; import type { DiffEntry, DiffBody } from "@getpaseo/protocol/binary-frames/index"; @@ -27,6 +26,16 @@ export interface ListedFile { identity: string; source: { kind: "tracked" } | { kind: "untracked"; size: number }; } +interface WorktreeInput { + /** Comparison-side mode, or null when the file is added/untracked on this side. */ + oldMode: string | null; + /** Comparison-side blob, or null when the file is added/untracked on this side. */ + oldBlob: string | null; + /** A regular file whose bytes readGitInputs blob-hashes. */ + hashed: boolean; + /** Content Git cannot read as a regular file, such as a symlink target or submodule state. */ + literal: string | null; +} interface ResolvedComparison { baseSha: string; headSha: string; @@ -195,20 +204,47 @@ async function readComparisonList( ...(privateIndex ? { GIT_INDEX_FILE: privateIndex.indexFile } : {}), }, }; - const { files, worktreeFiles, interpretationPaths } = await readTrackedFiles( - compare, - args, - options, - ); - if (compare.head.kind === "worktree") files.push(...(await listUntrackedFiles(options))); + const tracked = await readTrackedFiles(compare, args, options); + const files = tracked.files; + const worktreeInputs = tracked.worktreeInputs; + if (compare.head.kind === "worktree") { + const untracked = await listUntrackedFiles(options); + files.push(...untracked.files); + for (const [path, input] of untracked.worktreeInputs) worktreeInputs.set(path, input); + } files.sort((a, b) => a.entry.path.localeCompare(b.entry.path)); - for (const file of files) interpretationPaths.add(file.entry.path); - const gitInputs = await readGitInputs([...interpretationPaths].sort(), worktreeFiles, options); - for (const file of files) + for (const file of files) tracked.interpretationPaths.add(file.entry.path); + const hashedPaths = new Set( + [...worktreeInputs].filter(([, input]) => input.hashed).map(([path]) => path), + ); + const literalContent = new Map( + [...worktreeInputs].flatMap(([path, input]) => + input.literal === null ? [] : [[path, input.literal] as const], + ), + ); + const gitInputs = await readGitInputs({ + paths: [...tracked.interpretationPaths].sort(), + hashedPaths, + options, + literalContent, + }); + for (const file of files) { + if (compare.head.kind === "worktree") { + const input = worktreeInputs.get(file.entry.path); + if (!input) throw new Error(`Missing worktree identity for ${file.entry.path}`); + file.identity = JSON.stringify([ + input.oldMode, + input.oldBlob, + gitInputs.identities.get(file.entry.path) ?? null, + gitInputs.identities.get(file.entry.oldPath ?? file.entry.path) ?? null, + ]); + continue; + } file.identity += JSON.stringify([ gitInputs.identities.get(file.entry.path), gitInputs.identities.get(file.entry.oldPath ?? file.entry.path), ]); + } const metrics = { highlightCalls: 0 }; const patches = new Patches(args, options, files); const sources = new HighlightSources({ @@ -237,7 +273,15 @@ async function readComparisonList( const result = file.source.kind === "untracked" ? await runGitCommand( - ["diff", "--no-index", ...GIT_PATCH_FORMAT_ARGS, "--", "/dev/null", file.entry.path], + [ + "diff", + "--no-index", + "--no-textconv", + ...GIT_PATCH_FORMAT_ARGS, + "--", + "/dev/null", + file.entry.path, + ], { ...options, acceptExitCodes: [0, 1], @@ -293,7 +337,11 @@ async function readTrackedFiles( compare: Compare, args: string[], options: GitCommandOptions, -): Promise<{ files: ListedFile[]; worktreeFiles: Set; interpretationPaths: Set }> { +): Promise<{ + files: ListedFile[]; + worktreeInputs: Map; + interpretationPaths: Set; +}> { const [raw, stat] = await Promise.all([ runGitCommand([...args.filter((arg) => arg !== "-w"), "--raw", "--no-abbrev", "-z"], options), runGitCommand([...args, "--numstat", "-z"], options), @@ -303,7 +351,7 @@ async function readTrackedFiles( const stats = parseStats(stat.stdout); const fields = raw.stdout.split("\0"); const files: ListedFile[] = []; - const worktreeFiles = new Set(); + const worktreeInputs = new Map(); const interpretationPaths = new Set(); for (let index = 0; index < fields.length - 1; index++) { const header = fields[index].split(" "); @@ -325,10 +373,25 @@ async function readTrackedFiles( else if (code === "D") change = "deleted"; else if (oldPath !== null) change = "renamed"; let identity = header.join(" "); - if (compare.head.kind === "worktree" && code !== "D") { - const worktree = await readWorktreeIdentity(path, header, options); - identity += `:${worktree.identity}`; - if (worktree.regular && !counts.binary) worktreeFiles.add(path); + if (compare.head.kind === "worktree") { + const input: WorktreeInput = { + oldMode: code === "A" ? null : header[0], + oldBlob: code === "A" ? null : absentBlob(header[2]), + hashed: false, + literal: null, + }; + if (code !== "D") { + const worktree = await readWorktreeContent({ + path, + header, + text: !counts.binary, + options, + }); + input.hashed = worktree.hashed; + input.literal = worktree.literal; + } + worktreeInputs.set(path, input); + identity = ""; } files.push({ @@ -345,24 +408,32 @@ async function readTrackedFiles( source: { kind: "tracked" }, }); } - return { files, worktreeFiles, interpretationPaths }; + return { files, worktreeInputs, interpretationPaths }; } -async function readWorktreeIdentity( - path: string, - header: string[], - options: GitCommandOptions, -): Promise<{ identity: string; regular: boolean }> { - const value = await lstat(resolve(options.cwd, path), { bigint: true }); - let identity = fileStatIdentity(value); +async function readWorktreeContent({ + path, + header, + text, + options, +}: { + path: string; + header: string[]; + text: boolean; + options: GitCommandOptions; +}): Promise<{ hashed: boolean; literal: string | null }> { + const absolutePath = resolve(options.cwd, path); + const value = await lstat(absolutePath, { bigint: true }); + if (value.isSymbolicLink()) + return { hashed: false, literal: `symlink:${await readlink(absolutePath)}` }; if (value.isDirectory() && (header[0] === ":160000" || header[1] === "160000")) { const submodule = await runGitCommand( ["status", "--porcelain=v2", "--branch", "--untracked-files=normal"], - { cwd: resolve(options.cwd, path), envOverlay: { GIT_OPTIONAL_LOCKS: "0" } }, + { cwd: absolutePath, envOverlay: { GIT_OPTIONAL_LOCKS: "0" } }, ); - identity += `:${submodule.stdout}`; + return { hashed: false, literal: `submodule:${submodule.stdout}` }; } - return { identity, regular: value.isFile() }; + return { hashed: value.isFile() && text, literal: null }; } function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] { @@ -385,9 +456,12 @@ async function readUntrackedText( return readFile(path); } -async function listUntrackedFiles(options: GitCommandOptions): Promise { +async function listUntrackedFiles( + options: GitCommandOptions, +): Promise<{ files: ListedFile[]; worktreeInputs: Map }> { const cwd = options.cwd; const files: ListedFile[] = []; + const worktreeInputs = new Map(); const untracked = await runGitCommand( ["ls-files", "--others", "--exclude-standard", "-z"], options, @@ -408,6 +482,12 @@ async function listUntrackedFiles(options: GitCommandOptions): Promise, - options: GitCommandOptions, -) { - const regular = paths.filter((path) => worktreeFiles.has(path)); +interface ReadGitInputsOptions { + paths: string[]; + hashedPaths: ReadonlySet; + options: GitCommandOptions; + literalContent?: ReadonlyMap; +} + +export async function readGitInputs({ + paths, + hashedPaths, + options, + literalContent = new Map(), +}: ReadGitInputsOptions) { + const regular = paths.filter((path) => hashedPaths.has(path)); const [interpretation, blobs] = await Promise.all([ readInterpretation(paths, options), regular.length @@ -34,7 +42,7 @@ export async function readGitInputs( fingerprint([ interpretation.config, interpretation.attributes.get(path) ?? [], - blobByPath.get(path) ?? null, + blobByPath.get(path) ?? literalContent.get(path) ?? null, ]), ]), ); diff --git a/packages/server/src/server/diff/subscriptions.test.ts b/packages/server/src/server/diff/subscriptions.test.ts index 6f792a3311..3fb0ca9509 100644 --- a/packages/server/src/server/diff/subscriptions.test.ts +++ b/packages/server/src/server/diff/subscriptions.test.ts @@ -530,6 +530,222 @@ test("submodule commits invalidate cached worktree gitlink bodies", async () => } }); +test("stat-only changes reuse cached bodies and send no body frames", async () => { + const { utimes } = await import("node:fs/promises"); + const cwd = await mkdtemp(join(tmpdir(), "diff-stat-only-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + const path = join(cwd, "file.txt"); + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, "README"), "base\n"); + await writeFile(path, "base\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(path, "changed\n"); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + expect( + frames.flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])), + ).toContainEqual(expect.objectContaining({ path: "file.txt" })); + frames.length = 0; + for (let index = 0; index < 3; index++) { + const ended = frames.filter((frame) => frame.opcode === DiffOpcode.End).length; + const timestamp = new Date(Date.now() + 1000 * (index + 1)); + await utimes(path, timestamp, timestamp); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.filter((frame) => frame.opcode === DiffOpcode.End).length, { + timeout: 5000, + }) + .toBeGreaterThanOrEqual(ended + 1); + await new Promise((resolve) => setTimeout(resolve, 300)); + } + expect(frames.filter((frame) => frame.opcode === DiffOpcode.Bodies)).toHaveLength(0); + const beginnings = frames.filter((frame) => frame.opcode === DiffOpcode.Begin); + expect(beginnings.length).toBeGreaterThanOrEqual(3); + for (const begin of beginnings) { + expect(begin.entries.find((entry) => entry.path === "file.txt")?.body).toBe(false); + } + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } +}); + +test("staging unchanged worktree content reuses its cached body", async () => { + const cwd = await mkdtemp(join(tmpdir(), "diff-staging-only-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, "README"), "base\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(join(cwd, "staged.ts"), "export const staged = true;\n"); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + expect( + frames.flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])), + ).toContainEqual(expect.objectContaining({ path: "staged.ts" })); + frames.length = 0; + git("add", "-A"); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + expect(frames.filter((frame) => frame.opcode === DiffOpcode.Bodies)).toHaveLength(0); + expect(frames.find((frame) => frame.opcode === DiffOpcode.Begin)).toMatchObject({ + entries: [{ path: "staged.ts", change: "added", body: false }], + }); + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } +}); + +test.skipIf(process.platform === "win32")( + "untracked bodies use the same patch conversion as tracked files", + async () => { + const cwd = await mkdtemp(join(tmpdir(), "diff-textconv-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, ".gitattributes"), "*.dat diff=upper\n"); + git("config", "diff.upper.textconv", "sed s/hello/HELLO/"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(join(cwd, "x.dat"), "hello\n"); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + const initial = frames + .flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])) + .find((file) => file.path === "x.dat"); + expect(initial?.hunks.flatMap((hunk) => hunk.lines)).toContainEqual({ + type: "add", + content: "hello", + }); + frames.length = 0; + git("add", "x.dat"); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + expect(frames.filter((frame) => frame.opcode === DiffOpcode.Bodies)).toHaveLength(0); + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } + }, +); + +test.skipIf(process.platform === "win32")( + "comparison-side file type changes refresh cached bodies", + async () => { + const { symlink } = await import("node:fs/promises"); + const cwd = await mkdtemp(join(tmpdir(), "diff-base-mode-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + const path = join(cwd, "x"); + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(path, "target"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "regular"); + git("branch", "compare"); + await rm(path); + await symlink("target", path); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "symlink"); + const moved = git("rev-parse", "HEAD"); + await rm(path); + await writeFile(path, "target\n"); + const compare = { + cwd, + base: { kind: "rev" as const, rev: "refs/heads/compare" }, + head: { kind: "worktree" as const }, + }; + const subscription = await streams.subscribe(compare, async (frame) => { + frames.push(frame); + }); + await subscription.start(); + expect( + frames.flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])), + ).toContainEqual(expect.objectContaining({ path: "x" })); + frames.length = 0; + git("update-ref", "refs/heads/compare", moved); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + const bodies = frames.flatMap((frame) => + frame.opcode === DiffOpcode.Bodies ? frame.files : [], + ); + expect(bodies).toContainEqual(expect.objectContaining({ path: "x" })); + const { listComparison } = await import("./git.js"); + const fresh = await listComparison(compare); + try { + const record = await fresh.read(fresh.files[0]); + if (record.kind !== "ready") throw new Error("Expected readable type change"); + expect(bodies).toContainEqual(record.body); + } finally { + await fresh.close(); + } + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } + }, +); + test.each([true, false])( "tracked=%s timestamp-preserving replacements refresh cached bodies", async (tracked) => { diff --git a/packages/server/src/server/file-observer/index.test.ts b/packages/server/src/server/file-observer/index.test.ts index c30e294817..cf481b6e0a 100644 --- a/packages/server/src/server/file-observer/index.test.ts +++ b/packages/server/src/server/file-observer/index.test.ts @@ -193,10 +193,11 @@ test("classifies a removed file as deleted", async () => { }); await rm(target); - // Native recursive delivery can be coalesced before the backend's deletion audit. - // Assert eventual classification without imposing Vitest's one-second default. + // macOS FSEvents can replay the write above as a create after the subscription starts, + // so the delete is the latest event for the path, not the first. Native recursive delivery + // can also be coalesced before the backend's deletion audit, hence the longer timeout. await expect - .poll(() => events.find((event) => event.path === target)?.type, { timeout: 10_000 }) + .poll(() => events.findLast((event) => event.path === target)?.type, { timeout: 10_000 }) .toBe("delete"); await subscription.unsubscribe(); }); @@ -327,6 +328,39 @@ test("unsubscribe cancels reconciliation queued by a write burst", async () => { expect(callback).toHaveBeenCalledTimes(callsAtClose); }, 20_000); +test("aborting a pending subscription stops its startup scan and rejects", async () => { + const root = await createRoot(); + // More directories than the Linux backend watches: a scan that keeps walking after the abort + // fails on the directory limit instead of rejecting with the abort reason. + await Promise.all( + Array.from({ length: 80 }, (_, outer) => + Promise.all( + Array.from({ length: 70 }, (__, inner) => + mkdir(join(root, `dir-${outer}`, `nested-${inner}`), { recursive: true }), + ), + ), + ), + ); + const observer = createObserver(); + const controller = new AbortController(); + const reason = new Error("setup deadline passed"); + const callback = vi.fn(); + + const subscription = observer.subscribe(root, callback, { signal: controller.signal }); + await new Promise((resolve) => setTimeout(resolve, 10)); + controller.abort(reason); + + await expect(subscription).rejects.toBe(reason); + expect(observer.getDiagnostics()).toMatchObject({ + activeObservationCount: 0, + nativeHandleCount: 0, + pendingReconciliationWorkCount: 0, + }); + await writeFile(join(root, "dir-0", "after-abort.txt"), "late"); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(callback).not.toHaveBeenCalled(); +}, 20_000); + test("aggregate diagnostics return to their lifecycle baseline", async () => { const root = await createRoot(); const observer = createObserver(); diff --git a/packages/server/src/server/file-observer/index.ts b/packages/server/src/server/file-observer/index.ts index 05c9fdac50..14c7af57d1 100644 --- a/packages/server/src/server/file-observer/index.ts +++ b/packages/server/src/server/file-observer/index.ts @@ -14,6 +14,8 @@ export interface FileChange { export interface FileObserverOptions { ignore?: string[]; + // Aborting before `subscribe()` resolves stops the startup scan and rejects with the reason. + signal?: AbortSignal; } export type FileObserverCallback = (error: Error | null, events: FileChange[]) => void; @@ -105,7 +107,19 @@ class FileObserverService implements FileObserver { createBackend: this.createBackend, onClosed: () => state.observations.delete(observation), }); - await observation.start(); + const { signal } = options; + signal?.throwIfAborted(); + const abort = () => void observation.close(); + signal?.addEventListener("abort", abort, { once: true }); + try { + await observation.start(); + } finally { + signal?.removeEventListener("abort", abort); + } + if (signal?.aborted) { + await observation.close(); + throw signal.reason; + } if (this.closePromise) { await observation.close(); throw new Error("File observer is closed"); diff --git a/packages/server/src/server/file-observer/internal/observation.test.ts b/packages/server/src/server/file-observer/internal/observation.test.ts new file mode 100644 index 0000000000..f27809e871 --- /dev/null +++ b/packages/server/src/server/file-observer/internal/observation.test.ts @@ -0,0 +1,46 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { createFileObserver } from "../index.js"; +import { createNativeRecursiveBackend } from "./native-recursive.js"; +import { createManagedObservation } from "./observation.js"; +import { createObserverPaths } from "./paths.js"; + +// Aborting a subscription closes its observation while start() may still be +// reading the root, before the backend has started. +test("closing an observation before its backend starts leaves no native watcher open", async () => { + const root = await mkdtemp(join(tmpdir(), "observation-close-")); + const paths = createObserverPaths(process.platform); + let openWatchers = 0; + const observation = createManagedObservation({ + root, + callback: () => {}, + options: {}, + paths, + metrics: createFileObserver().getDiagnostics(), + createBackend: (host) => + createNativeRecursiveBackend(host, paths, () => { + openWatchers += 1; + let open = true; + return { + close: () => { + if (open) openWatchers -= 1; + open = false; + }, + on: () => {}, + }; + }), + onClosed: () => {}, + }); + try { + const started = observation.start(); + const closed = observation.close(); + await started; + await closed; + + expect(openWatchers).toBe(0); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/file-observer/internal/observation.ts b/packages/server/src/server/file-observer/internal/observation.ts index f0c27a504a..ee91a7c67d 100644 --- a/packages/server/src/server/file-observer/internal/observation.ts +++ b/packages/server/src/server/file-observer/internal/observation.ts @@ -69,6 +69,9 @@ class Observation implements ManagedObservation, ObservationHost { if (!rootStats.isDirectory()) { throw new Error(`File observation requires a directory: ${this.root}`); } + // An aborted subscription can close the observation while the root is being read; the backend + // must not start after its close has already finished. + if (!this.isActive()) return; try { await this.backend.start(); } catch (error) { diff --git a/packages/server/src/server/file-observer/native-recursive.test.ts b/packages/server/src/server/file-observer/native-recursive.test.ts index cb442729fc..ce97e64fd7 100644 --- a/packages/server/src/server/file-observer/native-recursive.test.ts +++ b/packages/server/src/server/file-observer/native-recursive.test.ts @@ -47,7 +47,9 @@ test("the recursive watcher remembers newly announced files before reconciliatio const path = join(root, "new.txt"); await writeFile(path, "created"); await expect - .poll(() => changes.some((event) => event.path === path && event.type === "create")) + .poll(() => changes.some((event) => event.path === path && event.type === "create"), { + timeout: 10_000, + }) .toBe(true); // Consumers have seen this file. A later audit needs it in its comparison // inventory even if the native watcher coalesces the subsequent delete. @@ -55,7 +57,9 @@ test("the recursive watcher remembers newly announced files before reconciliatio await rm(path); await backend.updateIgnore(); await expect - .poll(() => changes.some((event) => event.path === path && event.type === "delete")) + .poll(() => changes.some((event) => event.path === path && event.type === "delete"), { + timeout: 10_000, + }) .toBe(true); } finally { active = false; diff --git a/packages/server/src/server/forge-web.ts b/packages/server/src/server/forge-web.ts new file mode 100644 index 0000000000..08aa3f3a0a --- /dev/null +++ b/packages/server/src/server/forge-web.ts @@ -0,0 +1,79 @@ +import { forgeWebHost } from "@getpaseo/protocol/git-remote"; +import type { ForgeWeb } from "@getpaseo/protocol/messages"; +import type { ForgeResolution } from "../services/forge-resolver.js"; + +// A failed reference-repository lookup (signed out, network down, rate limit) is retried after this long. +const REFERENCE_REPOSITORY_RETRY_MS = 60_000; + +/** + * Web location of a workspace's forge, remembered per origin remote. The host + * comes from the forge resolution; the reference repository needs the forge, so + * it is looked up once per remote, and again only after a failed lookup, once + * the retry delay has passed. + */ +export interface ForgeWebEntry { + remoteUrl: string; + remoteKey: string; + forgeWeb: ForgeWeb; + retryAtMs: number | null; +} + +/** + * The web location available without the forge lookup: a settled answer for this + * remote, or the host alone while its reference repository is due. Publish this + * with the snapshot immediately; a slow or signed-out forge CLI must not hold + * back the workspace's git state or pull request status. + */ +export function forgeWebForResolution(input: { + remoteUrl: string; + resolution: ForgeResolution; + previous: ForgeWebEntry | null; + nowMs: number; +}): ForgeWebEntry { + const remoteKey = `${input.resolution.forge}\0${input.remoteUrl}`; + const previous = input.previous?.remoteKey === remoteKey ? input.previous : null; + // A settled lookup stands for as long as the remote does, and a failed one keeps its retry + // time, however often forced refreshes (every push, fetch and branch switch) ask. + if (previous) { + return previous; + } + return { + remoteUrl: input.remoteUrl, + remoteKey, + forgeWeb: { host: forgeWebHost(input.resolution.forge, input.resolution.host) }, + // A lookup that has never run is due now; one that failed keeps its own retry time. + retryAtMs: input.resolution.service.getReferenceRepository ? input.nowMs : null, + }; +} + +/** + * Enriches an entry with the repository that owns issue and change-request + * numbers. The links still work without it, so a failed lookup is retried later + * rather than surfaced. + */ +export async function resolveForgeWebReference(input: { + cwd: string; + resolution: ForgeResolution; + entry: ForgeWebEntry; + nowMs: number; +}): Promise { + const host = input.entry.forgeWeb.host; + const lookup = input.resolution.service.getReferenceRepository; + if (!lookup) { + return input.entry.retryAtMs === null ? input.entry : { ...input.entry, retryAtMs: null }; + } + try { + const referenceRepository = await lookup.call(input.resolution.service, { cwd: input.cwd }); + return { + ...input.entry, + forgeWeb: referenceRepository ? { host, referenceRepository } : { host }, + retryAtMs: null, + }; + } catch { + return { + ...input.entry, + forgeWeb: { host }, + retryAtMs: input.nowMs + REFERENCE_REPOSITORY_RETRY_MS, + }; + } +} diff --git a/packages/server/src/server/hub/execution-session.websocket.test.ts b/packages/server/src/server/hub/execution-session.websocket.test.ts index 266c55e196..f9f9227f40 100644 --- a/packages/server/src/server/hub/execution-session.websocket.test.ts +++ b/packages/server/src/server/hub/execution-session.websocket.test.ts @@ -182,6 +182,46 @@ test("ordinary Hub create and message retries do not duplicate agents or prompts ).toMatchObject({ payload: { accepted: false } }); }); +test("Hub retries a message whose send failed before reaching the provider", async () => { + const hub = await launchRelationship(); + const agentId = await hub.createUnrelatedLocalAgent(); + const message = { + type: "send_agent_message_request", + agentId, + messageId: "mode-change-failed", + text: "retry me", + sessionMode: "full-access", + }; + hub.failNextProviderModeChange(); + expect(await hub.requestOrdinary({ ...message, requestId: "first-attempt" })).toMatchObject({ + payload: { accepted: false, error: expect.stringContaining("mode change failure") }, + }); + expect(hub.providerPromptTexts().filter((text) => text === "retry me")).toHaveLength(0); + + expect(await hub.requestOrdinary({ ...message, requestId: "retry" })).toMatchObject({ + payload: { accepted: true, error: null }, + }); + expect(hub.providerPromptTexts().filter((text) => text === "retry me")).toHaveLength(1); +}); + +test("Hub never resubmits a message whose send failed after reaching the provider", async () => { + const hub = await launchRelationship(); + const agentId = await hub.createUnrelatedLocalAgent(); + const message = { + type: "send_agent_message_request", + agentId, + messageId: "turn-start-failed", + text: "do not repeat me", + }; + hub.failProviderPromptStart("do not repeat me"); + await hub.requestOrdinary({ ...message, requestId: "first-attempt" }); + + expect(await hub.requestOrdinary({ ...message, requestId: "retry" })).toMatchObject({ + payload: { accepted: false, error: "agent_request_outcome_unknown" }, + }); + expect(hub.providerPromptTexts().filter((text) => text === "do not repeat me")).toHaveLength(0); +}); + test("ordinary Hub requests survive daemon restart and restore an archived workspace", async () => { const hub = await launchRelationship(); const create = { @@ -514,7 +554,7 @@ test("Hub resolves persisted execution ownership after daemon restart", async () expect(workspaceId).toEqual(expect.any(String)); expect(await hub.archivedWorkspaceAt(workspaceId!)).toEqual(expect.any(String)); expect(await hub.worktreeState(worktreeCwd)).toEqual({ exists: false, listed: false }); -}, 20_000); +}, 60_000); test("Hub treats missing and foreign executions as already controlled without exposing ownership", async () => { const hub = await launchRelationship(); diff --git a/packages/server/src/server/hub/test-utils/relationship-harness.ts b/packages/server/src/server/hub/test-utils/relationship-harness.ts index a0c02bbb12..f2e0e4dff6 100644 --- a/packages/server/src/server/hub/test-utils/relationship-harness.ts +++ b/packages/server/src/server/hub/test-utils/relationship-harness.ts @@ -458,6 +458,7 @@ export class HubRelationshipHarness { private readonly claimedCliSockets = new Set(); private readonly promptsToFail = new Set(); private failNextSessionClose = false; + private failNextModeChange = false; private observedEnrollments = 0; private observedSockets = 0; private readonly codex: ControlledAgentClient; @@ -474,6 +475,11 @@ export class HubRelationshipHarness { this.failNextSessionClose = false; throw new Error("Requested provider session close failure"); }, + beforeSetMode: async () => { + if (!this.failNextModeChange) return; + this.failNextModeChange = false; + throw new Error("Requested provider mode change failure"); + }, onStartTurn: (prompt) => { const promptText = typeof prompt === "string" ? prompt : JSON.stringify(prompt); if (this.promptsToFail.delete(promptText)) { @@ -674,6 +680,10 @@ export class HubRelationshipHarness { this.promptsToFail.add(prompt); } + failNextProviderModeChange(): void { + this.failNextModeChange = true; + } + failNextProviderSessionClose(): void { this.failNextSessionClose = true; } diff --git a/packages/server/src/server/message-receipts/index.test.ts b/packages/server/src/server/message-receipts/index.test.ts index 10c1615a6a..f77ced4d6e 100644 --- a/packages/server/src/server/message-receipts/index.test.ts +++ b/packages/server/src/server/message-receipts/index.test.ts @@ -23,7 +23,8 @@ test("message retries survive reconstruction without submitting twice", async () agentId: "agent", messageId: "arrival", request: { text: "hello" }, - send: async () => { + send: async (beforeDispatch: () => Promise) => { + await beforeDispatch(); deliveries++; }, }; @@ -41,7 +42,8 @@ test("ambiguous provider delivery is never blindly replayed after restart", asyn agentId: "agent", messageId: "arrival", request: {}, - send: async () => { + send: async (beforeDispatch: () => Promise) => { + await beforeDispatch(); deliveries++; throw new Error("connection lost"); }, @@ -53,7 +55,7 @@ test("ambiguous provider delivery is never blindly replayed after restart", asyn expect(deliveries).toBe(1); }); -test("failed local message preparation does not leave an ambiguous receipt", async () => { +test("a send that fails before beforeDispatch can be retried with the same message", async () => { const { requests, directory } = await fixture(); let available = false; let sends = 0; @@ -61,14 +63,13 @@ test("failed local message preparation does not leave an ambiguous receipt", asy agentId: "agent", messageId: "message", request: {}, - prepare: async () => { - if (!available) throw new Error("load failed"); - }, - send: async () => { + send: async (beforeDispatch: () => Promise) => { + if (!available) throw new Error("mode change failed"); + await beforeDispatch(); sends++; }, }; - await expect(requests.send(input)).rejects.toThrow("load failed"); + await expect(requests.send(input)).rejects.toThrow("mode change failed"); available = true; await new MessageReceipts(directory).send(input); available = false; diff --git a/packages/server/src/server/message-receipts/index.ts b/packages/server/src/server/message-receipts/index.ts index 6103160b12..f76d1381ec 100644 --- a/packages/server/src/server/message-receipts/index.ts +++ b/packages/server/src/server/message-receipts/index.ts @@ -13,8 +13,11 @@ interface SendMessageInput { agentId: string; messageId: string; request: unknown; - send: () => Promise; - prepare?: () => Promise; + /** + * Delivers the message. It awaits `beforeDispatch` immediately before the provider can receive + * the message; a failure before that call proves nothing was submitted and leaves no receipt. + */ + send: (beforeDispatch: () => Promise) => Promise; } /** Owns message delivery receipts; creation is owned by CreationService. */ @@ -48,10 +51,12 @@ export class MessageReceipts { // A provider may have accepted the message before its receipt was committed. throw new Error("agent_request_outcome_unknown"); } - await input.prepare?.(); const receipt = { fingerprint, agentId: input.agentId }; - await writeJsonFileAtomic(file, { ...receipt, state: "pending" }); - await input.send(); + let pending: Promise | null = null; + await input.send(() => { + pending ??= writeJsonFileAtomic(file, { ...receipt, state: "pending" }); + return pending; + }); await writeJsonFileAtomic(file, { ...receipt, state: "completed" }); } } diff --git a/packages/server/src/server/owned-subscriptions.e2e.test.ts b/packages/server/src/server/owned-subscriptions.e2e.test.ts index c210118f1f..75822ffeca 100644 --- a/packages/server/src/server/owned-subscriptions.e2e.test.ts +++ b/packages/server/src/server/owned-subscriptions.e2e.test.ts @@ -16,6 +16,7 @@ import { } from "@getpaseo/protocol/binary-frames/index"; import { DaemonClient } from "./test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js"; +import { withTimeout } from "../utils/promise-timeout.js"; import { SessionInboundMessageSchema, type SessionInboundMessage, @@ -1645,6 +1646,69 @@ test("request outcomes for import and attention reach only their requesting sock } }); +test("clearing a closed agent's attention does not resume its provider session", async () => { + const daemon = await createTestPaseoDaemon({ + mcpEnabled: false, + isDev: true, + agentClients: { mock: new MockLoadTestAgentClient() }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + const agent = await client.createAgent({ provider: "mock", cwd: daemon.staticDir }); + await daemon.daemon.agentManager.closeAgent(agent.id); + await daemon.daemon.agentManager.markAgentUnread(agent.id); + await client.clearAgentAttention(agent.id); + expect(daemon.daemon.agentManager.getAgent(agent.id)).toBeNull(); + const snapshot = await client.fetchAgent(agent.id); + expect(snapshot?.agent.requiresAttention).toBe(false); + expect(snapshot?.agent.status).toBe("closed"); + } finally { + await client.close(); + await daemon.close(); + } +}); + +class SessionGoneAgentClient extends MockLoadTestAgentClient { + resumeCalls = 0; + + override async resumeSession(): Promise { + this.resumeCalls += 1; + throw new Error("Session not found"); + } +} + +test("clearing a closed agent's attention succeeds when its provider session is gone", async () => { + const agentClient = new SessionGoneAgentClient(); + const daemon = await createTestPaseoDaemon({ + mcpEnabled: false, + isDev: true, + agentClients: { mock: agentClient }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + const agent = await client.createAgent({ provider: "mock", cwd: daemon.staticDir }); + await daemon.daemon.agentManager.closeAgent(agent.id); + await client.markWorkspaceUnread(agent.workspaceId!); + expect((await client.fetchAgent(agent.id))?.agent.requiresAttention).toBe(true); + + await withTimeout( + client.clearAgentAttention(agent.id), + 5_000, + "clear_agent_attention got no response", + ); + + const snapshot = await client.fetchAgent(agent.id); + expect(snapshot?.agent.requiresAttention).toBe(false); + expect(snapshot?.agent.status).toBe("closed"); + expect(agentClient.resumeCalls).toBe(0); + } finally { + await client.close(); + await daemon.close(); + } +}); + test("SDK import failure settles without waiting for the request timeout", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 4bc07bb0d6..11a851e434 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -401,6 +401,15 @@ export class PluginService { }); } + /** Reads the default registry's directory. Not queued: it touches no local state. */ + listRegistry() { + return this.requireManagedSources().listRegistry(); + } + + getRegistryPlugin(id: string) { + return this.requireManagedSources().getRegistryPlugin(id); + } + async statusSources(pluginId?: string): Promise { return this.enqueue(async () => { const sources = this.configStore.get().plugins ?? {}; diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index 92fb21443e..aab2a9bd15 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -163,8 +163,14 @@ export default function contribute(server) { server.addHook("agent.turn.before", async (event) => { console.log(JSON.stringify({ hook: "agent.turn.before", event })); }); - server.addHook("agent.turn.after", async (event) => { - console.log(JSON.stringify({ hook: "agent.turn.after", event })); + server.addHook("agent.turn.after", async (event, context) => { + const page = await context.paseo.agents + .ref(event.agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries + .filter((entry) => entry.turnId === event.turnId) + .map(({ item }) => item.type); + console.log(JSON.stringify({ hook: "agent.turn.after", event, turn })); }); server.addHook("agent.permission.before", async (event, context) => { console.log(JSON.stringify({ hook: "agent.permission.before", event })); @@ -220,6 +226,7 @@ export default function contribute(server) { { hook: "agent.turn.after", event: { outcome: { kind: "completed" }, timeline: [] }, + turn: ["user_message", "tool_call"], }, { hook: "agent.turn.before", event: { agent: { id: agent.id } } }, ]); @@ -520,13 +527,25 @@ test("agent creation hooks change the provider and environment before the sessio }); server.addHook("agent.open.before", async ({ request }) => { console.log(JSON.stringify({ hook: "agent.open.before", request })); - return { ...request, env: { ...request.env, HOOK_OPEN: "opened" } }; + return { ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Plugin instructions"], env: { ...request.env, HOOK_OPEN: "opened" } }; }); server.addHook("agent.create.after", async (event) => { console.log(JSON.stringify({ hook: "agent.create.after", event })); });`, reportOpen: true, }); + const extraPlugin = path.join(directory, "extra-plugin"); + await mkdir(extraPlugin); + await writeFile( + path.join(extraPlugin, "paseo-plugin.json"), + JSON.stringify({ id: "a-prompt", requirements: { paseo: ">=0.8.0" } }), + ); + const writePrompt = (prompt: string) => + writeFile( + path.join(extraPlugin, "index.server.ts"), + `export default function contribute(server) { server.addHook("agent.open.before", async ({ request }) => ({ ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), ${JSON.stringify(prompt)}] })); return () => {}; }`, + ); + await writePrompt("First plugin"); const daemon = await createTestPaseoDaemon(); const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); try { @@ -534,15 +553,17 @@ test("agent creation hooks change the provider and environment before the sessio await client.fetchAgents({ subscribe: {} }); await client.patchDaemonConfig({ pluginsEnabled: true }); await client.installDirectoryPlugin(pluginDirectory); + await client.installDirectoryPlugin(extraPlugin); const agent = await client.createAgent({ provider: "claude", cwd: directory, title: "Hook test", + systemPrompt: "Saved instructions", }); expect(agent.provider).toBe(PROVIDER_ID); expect(await daemon.daemon.agentStorage.get(agent.id)).toMatchObject({ provider: PROVIDER_ID, - config: { model: "shutdown-model" }, + config: { model: "shutdown-model", systemPrompt: "Saved instructions" }, }); await expect .poll(async () => { @@ -562,13 +583,32 @@ test("agent creation hooks change the provider and environment before the sessio }, { hook: "provider.open", - config: { env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" } }, + config: { + env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" }, + systemPrompt: "Saved instructions\n\nFirst plugin\n\nPlugin instructions", + }, }, { hook: "agent.create.after", event: { agent: { id: agent.id, provider: PROVIDER_ID } }, }, ]); + await writePrompt("Changed plugin"); + await client.reloadPlugin("a-prompt"); + await daemon.daemon.agentManager.reloadAgentSession(agent.id); + await client.disablePlugin("a-prompt"); + await daemon.daemon.agentManager.reloadAgentSession(agent.id); + const opens = (await client.getPluginLogs("shutdown-provider-plugin")) + .filter((entry) => entry.message.startsWith('{"hook":"provider.open"')) + .map((entry) => JSON.parse(entry.message).config.systemPrompt); + expect(opens).toEqual([ + "Saved instructions\n\nFirst plugin\n\nPlugin instructions", + "Saved instructions\n\nChanged plugin\n\nPlugin instructions", + "Saved instructions\n\nPlugin instructions", + ]); + expect((await daemon.daemon.agentStorage.get(agent.id))?.config?.systemPrompt).toBe( + "Saved instructions", + ); await client.archiveAgent(agent.id); } finally { await client.close(); diff --git a/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts index 40de1215d8..5223e547ec 100644 --- a/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts @@ -157,8 +157,7 @@ test.skipIf(process.platform !== "linux")( "This is a hook integration test. Reply exactly: out of credits. If the next user message is Try again., reply exactly RETRY_OK instead. Do not use tools.", ); await waitForTurns(client, agent.id, 2); - const retryTurns = await endedTurns(client, agent.id); - expect(assistantText(retryTurns[1].data.timeline)).toBe("RETRY_OK"); + expect(await latestReplyText(client, agent.id)).toBe("RETRY_OK"); proof.followup = "RETRY_OK"; await client.sendMessage( @@ -207,8 +206,7 @@ test.skipIf(process.platform !== "linux")( const envPermission = await waitForPermission(client, agent.id, envCommand); await client.respondToPermission(agent.id, envPermission, { behavior: "allow" }); await waitForTurns(client, agent.id, 5); - const envTurns = await endedTurns(client, agent.id); - expect(assistantText(envTurns[4].data.timeline)).toBe("created|opened"); + expect(await latestReplyText(client, agent.id)).toBe("created|opened"); proof.environmentOutput = "created|opened"; await client.refreshAgent(agent.id); @@ -332,6 +330,16 @@ test.skipIf(process.platform !== "linux")( 600_000, ); +// Turn hooks carry no history; read the reply the way plugins do. +async function latestReplyText(client: DaemonClient, agentId: string): Promise { + const page = await client.fetchAgentTimeline(agentId, { + direction: "tail", + limit: 1, + wholeTurns: true, + }); + return assistantText(page.entries.map((entry) => entry.item)); +} + function assistantText(timeline: readonly AgentTimelineItem[]): string { let text = ""; for (const item of timeline) { diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index bf7526ba1d..6ff3361f22 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -228,7 +228,9 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }, { background: }, paseo, ), - ).rejects.toThrow("agent.open.before hooks can only change env, tools, and mcpServers"); + ).rejects.toThrow( + "agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt", + ); }, ); @@ -357,3 +359,42 @@ test("checkout-branch hooks reject a branch-off baseRef", async () => { validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }), ).rejects.toThrow(/baseRef/); }); + +test("session-open instructions compose, survive old hooks, and are ignored for history", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "first"], + })); + hooks.addHook("agent.open.before", async ({ request }) => { + const { appendSystemPrompt: _ignored, ...oldRequest } = request; + return oldRequest; + }); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "second"], + })); + const input = { + agentId: "agent", + workspaceId: null, + provider: "codex", + cwd: "/project", + reason: "resume", + purpose: "interactive", + env: {}, + title: null, + labels: {}, + metadata: {}, + tools: [], + mcpServers: {}, + }; + const interactive = await hooks.invoke("interactive", "agent.open.before", input, paseo); + expect(interactive).toMatchObject({ appendSystemPrompt: ["first", "second"] }); + const history = await hooks.invoke( + "history", + "agent.open.before", + { ...input, purpose: "history" }, + paseo, + ); + expect(history).not.toHaveProperty("appendSystemPrompt"); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 5e552c0111..46e2a87d66 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -108,6 +108,7 @@ const beforeSchemas = { labels: z.record(z.string(), z.string()), // Optional so a plugin that returns its own object keeps working; omitted means unchanged. metadata: z.record(z.string(), z.custom()).optional(), + appendSystemPrompt: z.array(z.string()).optional(), tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(), @@ -195,21 +196,18 @@ export function publishAgentStream( lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, - timeline: [], outcome: { kind: "completed" }, }); } else if (event.type === "turn_failed") { lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, - timeline: [], outcome: { kind: "failed", error: { message: event.error, code: event.code } }, }); } else if (event.type === "turn_canceled") { lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, - timeline: [], outcome: { kind: "canceled", reason: event.reason }, }); } else if (event.type === "permission_requested") { @@ -251,9 +249,18 @@ export async function validateBeforeResult { }); }); +it("reads the registry directory and a listing with the registry's credentials, without install intent", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-browse-home-")); + roots.push(home); + const listing = { + id: "acme/example", + name: "Example", + description: "Test", + categories: ["tools"], + author: { github: "acme" }, + repository: { url: "https://github.com/acme/example" }, + artifact: { + kind: "git", + remote: "https://github.com/acme/example.git", + commit: "a".repeat(40), + }, + media: [], + submittedAt: "2026-10-03", + reviewedAt: "2026-10-03", + updatedAt: "2026-10-03", + publishedAt: "2026-10-03", + }; + const documents: Record = { + "/internal/index.json": { + schemaVersion: 1, + registry: { name: "Internal", url: "http://registry.test" }, + categories: [{ slug: "tools", label: "Tools" }], + // A listing this host cannot read is left out; the rest stay browsable. + plugins: [listing, { ...listing, id: "acme/future", artifact: { kind: "oci" } }], + featured: ["acme/example"], + generatedAt: "2026-10-03", + }, + "/internal/plugins/acme/example.json": { ...listing, readme: "# Example" }, + "/internal/plugins/acme/other.json": { ...listing, readme: "# Example" }, + }; + const requests: Array<{ path?: string; intent?: string | string[]; authorization?: string }> = []; + const server = createServer((req, res) => { + requests.push({ + path: req.url, + intent: req.headers["x-paseo-install"], + authorization: req.headers.authorization, + }); + const document = req.url ? documents[req.url] : undefined; + if (!document) { + res.writeHead(404).end(); + return; + } + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify(document)); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing registry address"); + const host = `127.0.0.1:${address.port}`; + try { + const sources = new ManagedPluginSources(home, { + defaultUrl: `http://${host}/internal/`, + registries: { [host]: { authorization: "Bearer test" } }, + }); + const index = await sources.listRegistry(); + expect(index.plugins.map((plugin) => plugin.id)).toEqual(["acme/example"]); + expect(index.featured).toEqual(["acme/example"]); + expect((await sources.getRegistryPlugin("acme/example")).readme).toBe("# Example"); + await expect(sources.getRegistryPlugin("acme/other")).rejects.toThrow( + "Registry returned a different plugin ID", + ); + await expect(sources.getRegistryPlugin("acme/missing")).rejects.toThrow( + "Plugin registry returned 404 for plugins/acme/missing.json", + ); + await expect(sources.getRegistryPlugin("../index")).rejects.toThrow(); + expect(requests).toEqual([ + { path: "/internal/index.json", intent: undefined, authorization: "Bearer test" }, + { + path: "/internal/plugins/acme/example.json", + intent: undefined, + authorization: "Bearer test", + }, + { + path: "/internal/plugins/acme/other.json", + intent: undefined, + authorization: "Bearer test", + }, + { + path: "/internal/plugins/acme/missing.json", + intent: undefined, + authorization: "Bearer test", + }, + ]); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +it("reports a misconfigured registry instead of asking the user to retry", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-browse-config-")); + roots.push(home); + const sources = new ManagedPluginSources(home, { + defaultUrl: "http://registry.example", + registries: { "registry.example": { authorization: "Bearer test" } }, + }); + await expect(sources.listRegistry()).rejects.toThrow("Registry credentials require HTTPS"); + await expect(sources.getRegistryPlugin("acme/example")).rejects.toThrow( + "Registry credentials require HTTPS", + ); +}); + it("installs and updates only the npm artifacts pinned by the plugin registry", async () => { const { startNpmRegistry, npmPluginPackages } = await import("../../../../../scripts/test-support/npm-registry.mjs"); diff --git a/packages/server/src/server/plugins/managed-source.ts b/packages/server/src/server/plugins/managed-source.ts index a20be890b3..636ffd8161 100644 --- a/packages/server/src/server/plugins/managed-source.ts +++ b/packages/server/src/server/plugins/managed-source.ts @@ -2,7 +2,12 @@ import { PluginRegistryIdentitySchema, parsePluginRegistryReference, } from "@getpaseo/protocol/plugin-registry"; -import { resolveRegistryPlugin, type RegistryOptions } from "./managed-source/registry.js"; +import { + getRegistryPlugin, + listRegistryPlugins, + resolveRegistryPlugin, + type RegistryOptions, +} from "./managed-source/registry.js"; import { randomUUID } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; import { mkdir, realpath, rename, rm } from "node:fs/promises"; @@ -357,6 +362,14 @@ export class ManagedPluginSources { } } + listRegistry() { + return listRegistryPlugins(this.registryOptions); + } + + getRegistryPlugin(id: string) { + return getRegistryPlugin(id, this.registryOptions); + } + async status(pluginId: string, configuredPath: string): Promise { const preview = await this.preview(pluginId, configuredPath); const installation = preview.current!; diff --git a/packages/server/src/server/plugins/managed-source/registry.ts b/packages/server/src/server/plugins/managed-source/registry.ts index 009cac5a68..2225b9f983 100644 --- a/packages/server/src/server/plugins/managed-source/registry.ts +++ b/packages/server/src/server/plugins/managed-source/registry.ts @@ -1,7 +1,12 @@ import { + DEFAULT_PLUGIN_REGISTRY_URL, PluginRegistryArtifactSchema, PluginRegistryIdSchema, + PluginRegistryIndexSchema, + PublishedPluginDetailSchema, + PublishedPluginSchema, type PluginRegistries, + type PluginRegistryIndex, type PluginRegistryIdentity, } from "@getpaseo/protocol/plugin-registry"; import type { PluginUpdateTarget } from "@getpaseo/protocol/messages"; @@ -17,12 +22,9 @@ export interface RegistryOptions { defaultUrl?: string; registries?: PluginRegistries; } -export async function resolveRegistryPlugin( - identity: PluginRegistryIdentity, - options: RegistryOptions, - install: boolean, -) { - const base = new URL(identity.url); +/** Request headers for a registry, with its configured credentials. Rejects unsafe bases. */ +function registryHeaders(url: string, options: RegistryOptions): Record { + const base = new URL(url); if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("Registry base must be an HTTP(S) URL without credentials"); const authorization = options.registries?.[base.host]?.authorization; @@ -32,8 +34,67 @@ export async function resolveRegistryPlugin( !["localhost", "127.0.0.1", "[::1]"].includes(base.hostname) ) throw new Error("Registry credentials require HTTPS"); - const headers: Record = {}; - if (authorization) headers.Authorization = authorization; + return authorization ? { Authorization: authorization } : {}; +} + +function defaultRegistryUrl(options: RegistryOptions): string { + return (options.defaultUrl ?? DEFAULT_PLUGIN_REGISTRY_URL).replace(/\/+$/, ""); +} + +/** Reads a display document from the default registry; never used to choose what installs. */ +async function readRegistryDocument(options: RegistryOptions, path: string): Promise { + const base = defaultRegistryUrl(options); + const url = `${base}/${path}`; + // Built before the request, so a registry setup error reaches the user instead of "Retry later". + const headers = registryHeaders(base, options); + let response: Response; + try { + response = await fetch(url, { + headers, + redirect: "error", + signal: AbortSignal.timeout(30000), + }); + } catch (cause) { + throw new Error(`Could not reach plugin registry ${url}. Retry later.`, { cause }); + } + if (!response.ok) throw new Error(`Plugin registry returned ${response.status} for ${path}`); + return response.json(); +} + +// Listings are read one by one, so a listing this host cannot read leaves the rest browsable. +const RegistryIndexDocumentSchema = PluginRegistryIndexSchema.extend({ + plugins: z.array(z.unknown()), +}); + +/** The default registry's plugin directory, for browsing, without listings this host cannot read. */ +export async function listRegistryPlugins(options: RegistryOptions): Promise { + const index = RegistryIndexDocumentSchema.parse( + await readRegistryDocument(options, "index.json"), + ); + const plugins = index.plugins.flatMap((listing) => { + const parsed = PublishedPluginSchema.safeParse(listing); + return parsed.success ? [parsed.data] : []; + }); + return { ...index, plugins }; +} + +/** One listing with its overview, for the plugin's page. */ +export async function getRegistryPlugin(id: string, options: RegistryOptions) { + const pluginId = PluginRegistryIdSchema.parse(id); + const plugin = PublishedPluginDetailSchema.parse( + await readRegistryDocument(options, `plugins/${pluginId}.json`), + ); + if (plugin.id !== pluginId) throw new Error("Registry returned a different plugin ID"); + return plugin; +} + +export async function resolveRegistryPlugin( + identity: PluginRegistryIdentity, + options: RegistryOptions, + install: boolean, +) { + const base = new URL(identity.url); + const headers = registryHeaders(identity.url, options); if (install) headers["X-Paseo-Install"] = "1"; const url = `${identity.url.replace(/\/+$/, "")}/plugins/${identity.id}.json`; let response: Response; diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index 2e9c52ef4f..81860e67b0 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -568,7 +568,7 @@ export class PluginRuntime { type: "hook", requestId: randomUUID(), name, - input: event, + input: wireEvent(name, event), }) .then(() => undefined) .catch((error) => { @@ -1526,3 +1526,11 @@ function readConnectionId(value: unknown): string | null { const connectionId = Reflect.get(value, "connectionId"); return typeof connectionId === "string" ? connectionId : null; } + +// COMPAT(pluginTurnTimeline): added in v0.16.0-beta.3; plugins built before the field left the SDK type read `timeline`; remove after 2027-05-31 +function wireEvent( + name: Name, + event: PluginHookEvents[Name], +): PluginHookEvents[Name] { + return name === "agent.turn.after" ? { ...event, timeline: [] } : event; +} diff --git a/packages/server/src/server/resolve-worktree-creation-intent.ts b/packages/server/src/server/resolve-worktree-creation-intent.ts index 5eddc0ef7b..34d587da03 100644 --- a/packages/server/src/server/resolve-worktree-creation-intent.ts +++ b/packages/server/src/server/resolve-worktree-creation-intent.ts @@ -3,7 +3,7 @@ import type { WorktreeSource } from "../utils/worktree.js"; export type WorktreeCreationIntent = Exclude< WorktreeSource, - { kind: "restore" | "restore-from-base" } + { kind: "restore" | "restore-from-base" | "restore-commit" } >; export interface ResolveWorktreeCreationIntentInput { diff --git a/packages/server/src/server/schedule/service.test.ts b/packages/server/src/server/schedule/service.test.ts index 26c4d0a62c..9c17720833 100644 --- a/packages/server/src/server/schedule/service.test.ts +++ b/packages/server/src/server/schedule/service.test.ts @@ -38,6 +38,7 @@ import { type ScheduleServiceOptions, } from "./service.js"; import { ScheduleStore } from "./store.js"; +import { ForegroundPromptStart } from "../agent/agent-run-state.js"; import type { ScheduleExecutionResult, StoredSchedule } from "@getpaseo/protocol/schedule/types"; interface ScheduleServiceInternals { @@ -648,6 +649,157 @@ describe("ScheduleService", () => { expect(resumed.nextRunAt).toBe("2026-01-01T00:04:00.000Z"); }); + test("shows an active heartbeat and stops it through agent background work", async () => { + const logger = createTestLogger(); + const manager = new AgentManager({ + logger, + clients: createTestAgentClients(), + registry: agentStorage, + }); + const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, { + workspaceId: undefined, + }); + const service = createScheduleService({ + paseoHome: tempDir, + logger, + agentManager: manager, + agentStorage, + providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, + now: () => now, + }); + const input = { + prompt: "Private heartbeat instruction", + cadence: { type: "every", everyMs: 60_000 }, + target: { type: "agent", agentId: agent.id }, + } as const; + const created = await service.create(input); + + const items = manager.listAgentBackgroundWork(agent.id); + expect(items).toEqual([ + expect.objectContaining({ + kind: "heartbeat", + description: null, + canStop: true, + startedAt: created.createdAt, + }), + ]); + expect(JSON.stringify(items)).not.toContain(created.prompt); + await service.update({ id: created.id, name: "Status check" }); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([ + expect.objectContaining({ description: "Status check", startedAt: created.createdAt }), + ]); + const replacement = await service.createOrReplace({ ...input, name: "Status check" }); + expect(replacement.id).toBe(created.id); + expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(1); + await service.pause(created.id); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + await service.resume(created.id); + const [firstResume] = manager.listAgentBackgroundWork(agent.id); + const pausing = service.pause(created.id); + const resuming = service.resume(created.id); + const staleStop = expect( + manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: firstResume.id, + stopToken: firstResume.stopToken!, + canManageAutomation: true, + }), + ).rejects.toThrow("Background work is no longer available to stop"); + await Promise.all([pausing, resuming, staleStop]); + const [resumed] = manager.listAgentBackgroundWork(agent.id); + await manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: resumed.id, + stopToken: resumed.stopToken!, + canManageAutomation: true, + }); + await expect(service.inspect(created.id)).rejects.toThrow(`Schedule not found: ${created.id}`); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + + const deleted = await service.createOrReplace({ ...input, name: "Another check" }); + expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(1); + await service.delete(deleted.id); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + }); + + test("removes heartbeats when they expire or finish their last run", async () => { + const logger = createTestLogger(); + const manager = new AgentManager({ logger, clients: createTestAgentClients() }); + const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, { + workspaceId: undefined, + }); + const service = createScheduleService({ + paseoHome: tempDir, + logger, + agentManager: manager, + agentStorage, + providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, + now: () => now, + runner: async () => ({ agentId: agent.id, output: "done" }), + }); + const input = { + prompt: "Check", + cadence: { type: "every", everyMs: 60_000 }, + target: { type: "agent", agentId: agent.id }, + } as const; + const expiring = await service.create({ + ...input, + expiresAt: "2026-01-01T00:00:30.000Z", + runOnCreate: false, + }); + const finite = await service.create({ ...input, maxRuns: 1 }); + expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(2); + + now = new Date("2026-01-01T00:00:30.000Z"); + await service.tick(); + + expect(await service.inspect(expiring.id)).toMatchObject({ status: "completed", runs: [] }); + expect(await service.inspect(finite.id)).toMatchObject({ + status: "completed", + runs: [{ status: "succeeded" }], + }); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + }); + + test("lets an already launched heartbeat turn finish after Stop deletes its schedule", async () => { + const logger = createTestLogger(); + const manager = new AgentManager({ logger, clients: createTestAgentClients() }); + const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, { + workspaceId: undefined, + }); + const runner = new OverlappingTickRunner(); + const service = createScheduleService({ + paseoHome: tempDir, + logger, + agentManager: manager, + agentStorage, + providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, + now: () => now, + runner: (schedule) => runner.run(schedule), + }); + const created = await service.create({ + prompt: "block the first tick", + cadence: { type: "every", everyMs: 60_000 }, + target: { type: "agent", agentId: agent.id }, + }); + const tick = service.tick(); + await runner.firstRunStarted; + try { + const [item] = manager.listAgentBackgroundWork(agent.id); + await manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: item.id, + stopToken: item.stopToken!, + canManageAutomation: true, + }); + } finally { + runner.unblockFirstRun(); + await tick; + } + await expect(service.inspect(created.id)).rejects.toThrow(`Schedule not found: ${created.id}`); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + }); + test("completes schedules when max runs is reached", async () => { const service = createScheduleService({ paseoHome: tempDir, @@ -754,6 +906,7 @@ describe("ScheduleService", () => { agent.id, expect.stringContaining(`Schedule fired (id=${schedule.id}, run=`), undefined, + expect.any(ForegroundPromptStart), ]); }); @@ -3091,12 +3244,19 @@ describe("ScheduleService", () => { target: { type: "agent", agentId: liveAgentId }, }); await service1.pause(pausedLive.id); + const expired = await service1.create({ + prompt: "Expired check", + cadence: { type: "every", everyMs: 60_000 }, + expiresAt: "2026-01-01T00:01:00.000Z", + target: { type: "agent", agentId: liveAgentId }, + }); now = new Date("2026-01-01T00:10:00.000Z"); + const replacementManager = new AgentManager({ logger: createTestLogger() }); const service2 = createScheduleService({ paseoHome: tempDir, logger: createTestLogger(), - agentManager: new AgentManager({ logger: createTestLogger() }), + agentManager: replacementManager, agentStorage, providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, now: () => now, @@ -3110,6 +3270,12 @@ describe("ScheduleService", () => { expect((await service2.inspect(archived.id)).status).toBe("completed"); expect((await service2.inspect(live.id)).status).toBe("active"); expect((await service2.inspect(newAgent.id)).status).toBe("active"); + expect((await service2.inspect(expired.id)).status).toBe("completed"); + expect(replacementManager.getAgentBackgroundWorkSummary(missingAgentId)).toBeUndefined(); + expect(replacementManager.getAgentBackgroundWorkSummary(archivedAgentId)).toBeUndefined(); + expect(replacementManager.listAgentBackgroundWork(liveAgentId)).toEqual([ + expect.objectContaining({ id: `heartbeat:${live.id}`, startedAt: live.createdAt }), + ]); // Paused schedules are swept too when their agent is gone, but survive when it lives. expect((await service2.inspect(pausedMissing.id)).status).toBe("completed"); expect((await service2.inspect(pausedLive.id)).status).toBe("paused"); diff --git a/packages/server/src/server/schedule/service.ts b/packages/server/src/server/schedule/service.ts index 6e6ad6e7c2..8434d80ef7 100644 --- a/packages/server/src/server/schedule/service.ts +++ b/packages/server/src/server/schedule/service.ts @@ -243,6 +243,8 @@ type ScheduleAgentManager = Pick< | "runAgent" | "waitForAgentEvent" | "waitForAgentClose" + | "setHeartbeatBackgroundWork" + | "removeHeartbeatBackgroundWork" >; interface ScheduleWorkspaceCreateInput { @@ -286,12 +288,18 @@ export class ScheduleService { runId: string, ) => Promise; private readonly runningScheduleIds = new Set(); + private readonly heartbeatStops = new Map Promise>(); + private recovering = false; private tickTimer: ReturnType | null = null; constructor(options: ScheduleServiceOptions) { this.logger = options.logger.child({ module: "schedule-service" }); - this.store = new ScheduleStore(join(options.paseoHome, "schedules"), this.logger); this.agentManager = options.agentManager; + this.store = new ScheduleStore( + join(options.paseoHome, "schedules"), + this.logger, + (schedule, change) => this.syncHeartbeat(schedule, change), + ); this.agentStorage = options.agentStorage; this.createAgent = options.createAgent; this.createDirectoryWorkspace = options.createDirectoryWorkspace; @@ -302,11 +310,19 @@ export class ScheduleService { } async start(): Promise { - await this.recoverInterruptedRuns(); - await this.sweepOrphanedSchedules(); if (this.tickTimer) { return; } + this.recovering = true; + try { + await this.recoverInterruptedRuns(); + await this.sweepOrphanedSchedules(); + } finally { + this.recovering = false; + } + for (const schedule of await this.store.list()) { + this.syncHeartbeat(schedule, "write"); + } const timer = setInterval(() => { void this.tick().catch((error) => { this.logger.error({ err: error }, "Failed to process schedule tick"); @@ -505,6 +521,46 @@ export class ScheduleService { await this.store.delete(id); } + private syncHeartbeat(schedule: StoredSchedule, change: "write" | "delete"): void { + if (schedule.target.type !== "agent") { + return; + } + const { agentId } = schedule.target; + const { id, name, createdAt } = schedule; + if (change === "delete" || schedule.status !== "active") { + this.heartbeatStops.delete(id); + this.agentManager.removeHeartbeatBackgroundWork(agentId, id); + return; + } + if (this.recovering) { + return; + } + let stop = this.heartbeatStops.get(id); + if (!stop) { + const stopHeartbeat = () => + this.store.delete(id, (current) => { + // A queued Stop can reach the store after a pause and resume replaced its row. + if ( + current?.status !== "active" || + current.target.type !== "agent" || + current.target.agentId !== agentId || + this.heartbeatStops.get(id) !== stopHeartbeat + ) { + throw new ScheduleStateConflictError("Background work is no longer available to stop"); + } + }); + this.heartbeatStops.set(id, stopHeartbeat); + stop = stopHeartbeat; + } + this.agentManager.setHeartbeatBackgroundWork({ + agentId, + scheduleId: id, + name, + createdAt, + stop, + }); + } + async completeForAgent(agentId: string): Promise { const now = this.now(); const schedules = await this.store.list(); @@ -590,7 +646,7 @@ export class ScheduleService { } private async completeScheduleIfDue(scheduleId: string, now: Date): Promise { - const updated = await this.store.update(scheduleId, (schedule) => { + await this.store.update(scheduleId, (schedule) => { if ( schedule.status !== "active" || !schedule.nextRunAt || @@ -600,7 +656,6 @@ export class ScheduleService { } return completeSchedule(schedule, now); }); - requireSchedule(updated, scheduleId); } private async recoverInterruptedRuns(): Promise { @@ -646,12 +701,16 @@ export class ScheduleService { error: "Daemon restarted before the scheduled run completed", }; updated = { ...updated, runs }; - if (shouldCompleteSchedule(updated, now)) { - updated = completeSchedule(updated, now); - } dirty = true; } + if ( + (updated.status === "active" || runningIndex !== -1) && + shouldCompleteSchedule(updated, now) + ) { + return completeSchedule(updated, now); + } + if ( updated.status === "active" && updated.nextRunAt && @@ -778,7 +837,7 @@ export class ScheduleService { now: Date, ): Promise<{ schedule: StoredSchedule; runId: string } | null> { let claimed: { schedule: StoredSchedule; runId: string } | null = null; - const updatedSchedule = await this.store.update(scheduleId, (schedule) => { + await this.store.update(scheduleId, (schedule) => { if ( schedule.status !== "active" || !schedule.nextRunAt || @@ -821,7 +880,6 @@ export class ScheduleService { claimed = { schedule: updated, runId }; return updated; }); - requireSchedule(updatedSchedule, scheduleId); return claimed; } @@ -847,7 +905,8 @@ export class ScheduleService { targetGone: boolean; manual: boolean; }): Promise { - const updatedSchedule = await this.store.update(params.scheduleId, (schedule) => { + // A Stop can delete the schedule while its already launched turn is still running. + await this.store.update(params.scheduleId, (schedule) => { const now = this.now(); const completedRuns = schedule.runs.map((run) => run.id === params.runId @@ -900,7 +959,6 @@ export class ScheduleService { return updated; }); - requireSchedule(updatedSchedule, params.scheduleId); } private async recordRunWorkspace(params: { diff --git a/packages/server/src/server/schedule/store.ts b/packages/server/src/server/schedule/store.ts index 6feee5bc85..964adfeb93 100644 --- a/packages/server/src/server/schedule/store.ts +++ b/packages/server/src/server/schedule/store.ts @@ -100,6 +100,17 @@ function parseStoredSchedule( return StoredScheduleSchema.safeParse(json); } +async function readScheduleFile(filePath: string): Promise { + try { + return await readFile(filePath, "utf-8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; + } +} + export class ScheduleStore { private readonly scheduleMutations = new Map>(); private readonly identityMutations = new Map>(); @@ -108,6 +119,7 @@ export class ScheduleStore { constructor( private readonly dir: string, private readonly logger: Logger, + private readonly onChange?: (schedule: StoredSchedule, change: "write" | "delete") => void, ) {} private filePath(id: string): string { @@ -128,12 +140,17 @@ export class ScheduleStore { .filter((entry) => entry.isFile() && entry.name.endsWith(".json")) .map(async (entry) => { const filePath = join(this.dir, entry.name); - return { filePath, parsed: parseStoredSchedule(await readFile(filePath, "utf-8")) }; + const content = await readScheduleFile(filePath); + return content === null ? null : { filePath, parsed: parseStoredSchedule(content) }; }), ); const schedules: StoredSchedule[] = []; const invalidFiles = new Set(); - for (const { filePath, parsed } of files) { + for (const file of files) { + if (!file) { + continue; + } + const { filePath, parsed } = file; if (parsed.success) { schedules.push(parsed.data); continue; @@ -149,21 +166,16 @@ export class ScheduleStore { async get(id: string): Promise { await this.ensureDir(); - try { - const content = await readFile(this.filePath(id), "utf-8"); - return StoredScheduleSchema.parse(JSON.parse(content)); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return null; - } - throw error; - } + const content = await readScheduleFile(this.filePath(id)); + return content === null ? null : StoredScheduleSchema.parse(JSON.parse(content)); } async create(schedule: Omit): Promise { const created = StoredScheduleSchema.parse({ ...schedule, id: generateScheduleId() }); - await this.write(created); - return created; + return this.serializeScheduleMutation(created.id, async () => { + await this.write(created); + return created; + }); } async update(id: string, updater: ScheduleUpdater): Promise { @@ -204,8 +216,10 @@ export class ScheduleStore { if (!matchesNameAndTarget(created, name, target)) { throw new Error("Created schedule does not match requested identity"); } - await this.write(created); - return created; + return this.serializeScheduleMutation(created.id, async () => { + await this.write(created); + return created; + }); } const updated = await this.updateMatchedSchedule(existing.id, name, target, options.update); @@ -219,12 +233,22 @@ export class ScheduleStore { private async write(schedule: StoredSchedule): Promise { await this.ensureDir(); await writeJsonFileAtomic(this.filePath(schedule.id), schedule); + this.onChange?.(schedule, "write"); } - async delete(id: string): Promise { + async delete( + id: string, + assertDeletable?: (schedule: StoredSchedule | null) => void, + ): Promise { await this.serializeScheduleMutation(id, async () => { - await this.ensureDir(); + const content = await readScheduleFile(this.filePath(id)); + const parsed = content === null ? null : parseStoredSchedule(content); + const schedule = parsed?.success ? parsed.data : null; + assertDeletable?.(schedule); await rm(this.filePath(id), { force: true }); + if (schedule) { + this.onChange?.(schedule, "delete"); + } }); } diff --git a/packages/server/src/server/script-status-projection.test.ts b/packages/server/src/server/script-status-projection.test.ts index b6ef6e18f5..7032ba0d5c 100644 --- a/packages/server/src/server/script-status-projection.test.ts +++ b/packages/server/src/server/script-status-projection.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { tmpdir } from "node:os"; @@ -13,6 +13,7 @@ import { WorkspaceScriptPayloadSchema } from "@getpaseo/protocol/messages"; import type { ScriptHealthState } from "./script-health-monitor.js"; import { WorkspaceScriptRuntimeStore } from "./workspace-script-runtime-store.js"; import { readPaseoConfig } from "../utils/worktree.js"; +import { readPaseoConfigForEdit, writePaseoConfigForEdit } from "../utils/paseo-config-file.js"; import type { PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; import { createTestLogger } from "../test-utils/test-logger.js"; @@ -471,6 +472,84 @@ describe("script-status-projection", () => { } }); + it("keeps every workspace's scripts when a listing's paseo.json checks do not finish in time", async () => { + // More workspaces than the daemon kept snapshots for before, each with a config it has read. + const tempDir = realpathSync(mkdtempSync(path.join(tmpdir(), "script-projection-many-"))); + const workspaces = Array.from({ length: 300 }, (_, index) => { + const directory = path.join(tempDir, `workspace-${index}`); + mkdirSync(directory); + writeFileSync( + path.join(directory, "paseo.json"), + JSON.stringify({ scripts: { api: { type: "service", command: "npm run dev" } } }), + ); + return directory; + }); + const logger = createTestLogger(); + try { + await Promise.all( + workspaces.map((directory) => readPaseoConfigForProjection(directory, logger)), + ); + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const listing = Promise.all( + workspaces.map((directory) => readPaseoConfigForProjection(directory, logger)), + ); + // The filesystem has not answered any check when the 5 s budget runs out. + vi.advanceTimersByTime(5_000); + const configs = await listing; + + expect(configs.filter((config) => config?.scripts?.api === undefined)).toEqual([]); + } finally { + vi.useRealTimers(); + rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it("keeps the saved scripts when the first check after an in-app save is late", async () => { + const workspace = createWorkspaceRepo({ + paseoConfig: { scripts: { api: { type: "service", command: "npm run dev" } } }, + }); + const logger = createTestLogger(); + try { + const current = await readPaseoConfigForEdit(workspace.repoDir); + if (!current.ok) throw new Error("expected a readable paseo.json"); + const saved = await writePaseoConfigForEdit({ + repoRoot: workspace.repoDir, + config: { scripts: { web: { type: "service", command: "npm run web" } } }, + expectedRevision: current.revision, + }); + expect(saved.ok).toBe(true); + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const listing = readPaseoConfigForProjection(workspace.repoDir, logger); + vi.advanceTimersByTime(5_000); + + expect(Object.keys((await listing)?.scripts ?? {})).toEqual(["web"]); + } finally { + vi.useRealTimers(); + workspace.cleanup(); + } + }); + + it("shows an external paseo.json edit on the next listing", async () => { + const workspace = createWorkspaceRepo({ + paseoConfig: { scripts: { api: { type: "service", command: "npm run dev" } } }, + }); + try { + await readPaseoConfigForProjection(workspace.repoDir, createTestLogger()); + writeFileSync( + path.join(workspace.repoDir, "paseo.json"), + JSON.stringify({ scripts: { web: { type: "service", command: "npm run web" } } }), + ); + + const config = await readPaseoConfigForProjection(workspace.repoDir, createTestLogger()); + + expect(Object.keys(config?.scripts ?? {})).toEqual(["web"]); + } finally { + workspace.cleanup(); + } + }); + it("buildWorkspaceScriptPayloads given paseoConfig=null still surfaces orphaned runtime scripts", async () => { const workspaceId = "workspace-null-config"; const workspace = createWorkspaceRepo(); diff --git a/packages/server/src/server/script-status-projection.ts b/packages/server/src/server/script-status-projection.ts index a66f5fb073..25922ee2bc 100644 --- a/packages/server/src/server/script-status-projection.ts +++ b/packages/server/src/server/script-status-projection.ts @@ -5,7 +5,8 @@ import type { WorkspaceScriptPayload, } from "@getpaseo/protocol/messages"; import type { PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; -import { getScriptConfigs, isServiceScript, readPaseoConfig } from "../utils/worktree.js"; +import { readPaseoConfigOrLastKnown } from "../utils/paseo-config-file.js"; +import { getScriptConfigs, isServiceScript } from "../utils/worktree.js"; import { deriveProjectSlug } from "./workspace-git-metadata.js"; import type { ScriptHealthEntry, ScriptHealthState } from "./script-health-monitor.js"; import type { @@ -37,7 +38,7 @@ export async function readPaseoConfigForProjection( workspaceDirectory: string, logger: Logger, ): Promise { - const result = await readPaseoConfig(workspaceDirectory); + const result = await readPaseoConfigOrLastKnown(workspaceDirectory); if (result.ok) { return result.config; } diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index b2f8932b90..adafdc7eb4 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -48,7 +48,10 @@ import type { StoredAgentRecord } from "./agent/agent-storage.js"; import type { AgentManagerEvent } from "./agent/agent-manager.js"; import type { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js"; import { WorkspaceLabelError, type WorkspaceLabelService } from "./workspace-labels/index.js"; -import { createPersistedProjectRecord } from "./workspace-registry.js"; +import { + createPersistedProjectRecord, + createPersistedWorkspaceRecord, +} from "./workspace-registry.js"; import { deriveProjectKey } from "./project-key.js"; import type { SessionOptions } from "./session.js"; import type { SessionInboundMessage, SessionOutboundMessage } from "./messages.js"; @@ -1660,6 +1663,37 @@ describe("plugin timeline append RPC", () => { }), ); }); + + test.each(["repro.card", "Review", "review_card", "1review", ""])( + "rejects the kind %j that no client renderer can register", + async (kind) => { + const messages: SessionOutboundMessage[] = []; + const appendTimelineItem = vi.fn(); + const session = createSessionForTest({ + clientId: "plugin:review", + messages, + agentManager: { appendTimelineItem }, + }); + + await session.handleMessage({ + type: "agent.timeline.append.request", + requestId: "append-kind", + agentId: "agent-1", + item: { type: "plugin", id: "review-1", kind, version: 1, data: {} }, + }); + + expect(appendTimelineItem).not.toHaveBeenCalled(); + expect(messages).toContainEqual({ + type: "rpc_error", + payload: { + requestId: "append-kind", + requestType: "agent.timeline.append.request", + error: `Request failed: Plugin timeline item kind must start with a lowercase letter and contain only lowercase letters, digits, and dashes: ${JSON.stringify(kind)}`, + code: "handler_error", + }, + }); + }, + ); }); describe("agent detach RPC", () => { @@ -6111,6 +6145,7 @@ test("answers an agent background work list request", async () => { const messages: SessionOutboundMessage[] = []; const session = createSessionForTest({ messages, + permissions: ["workspace.read", "workspace.write"], agentManager: { waitForAgentClose: vi.fn().mockResolvedValue(undefined), getAgent: vi.fn(() => ({ id: "agent-a" })), @@ -6120,6 +6155,8 @@ test("answers an agent background work list request", async () => { id: "bash-1", kind: "shell", description: "sleep 20", + canStop: true, + stopToken: "provider-token", startedAt: "2026-10-06T10:00:00.000Z", }, ]), @@ -6142,6 +6179,8 @@ test("answers an agent background work list request", async () => { id: "bash-1", kind: "shell", description: "sleep 20", + canStop: true, + stopToken: "provider-token", startedAt: "2026-10-06T10:00:00.000Z", }, ], @@ -6150,6 +6189,228 @@ test("answers an agent background work list request", async () => { }); }); +const heartbeatBackgroundWork = { + id: "heartbeat:heartbeat-a", + kind: "heartbeat", + description: "Check progress", + startedAt: "2026-10-06T10:00:00.000Z", + canStop: true, + stopToken: "heartbeat-token", +}; + +test.each([ + { permissions: ["workspace.read"], canStop: false }, + { permissions: ["workspace.read", "automation.manage"], canStop: false }, + { permissions: ["workspace.read", "workspace.write"], canStop: false }, + { permissions: ["workspace.read", "hub.execute", "automation.manage"], canStop: true }, +] satisfies Array<{ permissions: DaemonPermission[]; canStop: boolean }>)( + "filters dormant heartbeat controls for $permissions on list and update", + async ({ permissions, canStop }) => { + const messages: SessionOutboundMessage[] = []; + let listener: ((event: AgentManagerEvent) => void) | undefined; + const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }); + const session = createSessionForTest({ + messages, + permissions, + agentManager: { + getAgent: () => undefined, + getAgentBackgroundWorkSummary: () => ({ count: 1 }), + listAgentBackgroundWork: () => [heartbeatBackgroundWork], + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, + }, + agentStorage: { get: async () => record }, + }); + await session.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "subscribe-heartbeat", + events: ["agent.background_work.update"], + }); + await session.handleMessage({ + type: "agent.background_work.list.request", + requestId: "list-heartbeat", + agentId: record.id, + }); + if (!listener) throw new Error("Agent event listener was not installed"); + listener({ + type: "background_work", + agentId: record.id, + items: [heartbeatBackgroundWork], + }); + + const { canStop: _canStop, stopToken: _token, ...readOnly } = heartbeatBackgroundWork; + const items = [canStop ? heartbeatBackgroundWork : readOnly]; + expect(findByType(messages, "agent.background_work.list.response")?.payload).toEqual({ + requestId: "list-heartbeat", + agentId: record.id, + items, + error: null, + }); + await expect + .poll(() => findByType(messages, "agent.background_work.update")?.payload) + .toEqual({ agentId: record.id, items }); + + await session.cleanup(); + }, +); + +test("publishes the current dormant inventory when an older update waits on storage", async () => { + const messages: SessionOutboundMessage[] = []; + const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }); + const pendingRecord = deferred(); + let firstRead = true; + let listener: ((event: AgentManagerEvent) => void) | undefined; + let items = [heartbeatBackgroundWork]; + const session = createSessionForTest({ + messages, + agentManager: { + getAgent: () => null, + getAgentBackgroundWorkSummary: () => (items.length ? { count: items.length } : undefined), + listAgentBackgroundWork: () => items, + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, + }, + agentStorage: { + get: async () => { + if (!firstRead) return record; + firstRead = false; + return pendingRecord.promise; + }, + }, + }); + await session.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "subscribe-delayed-inventory", + events: ["agent.background_work.update"], + }); + + if (!listener) throw new Error("Agent event listener was not installed"); + listener({ type: "background_work", agentId: record.id, items }); + items = []; + listener({ type: "background_work", agentId: record.id, items }); + await expect + .poll(() => findByType(messages, "agent.background_work.update")?.payload.items) + .toEqual([]); + + pendingRecord.resolve(record); + await new Promise((resolve) => setImmediate(resolve)); + const updates = messages.filter((message) => message.type === "agent.background_work.update"); + expect(updates.every((message) => message.payload.items.length === 0)).toBe(true); + await session.cleanup(); +}); + +test("passes the automation grant to the dormant background work stop operation", async () => { + const messages: SessionOutboundMessage[] = []; + const stops: Parameters[0][] = []; + const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }); + const session = createSessionForTest({ + messages, + permissions: ["workspace.read", "automation.manage"], + agentManager: { + getAgent: () => undefined, + stopAgentBackgroundWork: async ( + request: Parameters[0], + ) => { + stops.push(request); + }, + }, + agentStorage: { get: async () => record }, + }); + const request = { + type: "agent.background_work.stop.request", + requestId: "stop-heartbeat", + agentId: record.id, + itemId: heartbeatBackgroundWork.id, + stopToken: heartbeatBackgroundWork.stopToken, + } as const; + await session.handleMessage({ ...request, requestId: "stop-heartbeat-read-only" }); + expect(findByType(messages, "rpc_error")?.payload.code).toBe("access_denied"); + session.setPermissions(["workspace.read", "workspace.write"]); + await session.handleMessage(request); + session.setPermissions(["workspace.read", "workspace.write", "automation.manage"]); + await session.handleMessage({ ...request, requestId: "stop-heartbeat-owner" }); + + const { agentId, itemId, stopToken } = request; + expect(stops).toEqual([ + { agentId, itemId, stopToken, canManageAutomation: false }, + { agentId, itemId, stopToken, canManageAutomation: true }, + ]); + expect(findByType(messages, "agent.background_work.stop.response")?.payload.error).toBeNull(); + await session.cleanup(); +}); + +test("projects dormant heartbeat counts in directory snapshots and live updates", async () => { + const messages: SessionOutboundMessage[] = []; + let listener: ((event: AgentManagerEvent) => void) | undefined; + let count = 1; + const record = createStoredAgentRecord({ + id: "agent-a", + workspaceId: "workspace-a", + cwd: "/tmp/repo", + }); + const workspace = createPersistedWorkspaceRecord({ + workspaceId: "workspace-a", + projectId: "project-a", + cwd: record.cwd, + kind: "directory", + displayName: "Workspace", + createdAt: record.createdAt, + updatedAt: record.updatedAt, + }); + const project = createPersistedProjectRecord({ + projectId: workspace.projectId, + rootPath: workspace.cwd, + kind: "non_git", + displayName: "Project", + createdAt: record.createdAt, + updatedAt: record.updatedAt, + }); + const providers = createProviderSnapshotManagerStub(); + providers.listRegisteredProviderIds.mockReturnValue([record.provider]); + const session = createSessionForTest({ + messages, + providerSnapshotManager: providers.manager, + permissions: ["workspace.read"], + agentManager: { + getAgent: () => undefined, + getAgentBackgroundWorkSummary: () => (count ? { count } : undefined), + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, + }, + agentStorage: { get: async () => record, listAll: async () => [record] }, + workspaceRegistry: { get: vi.fn(async () => workspace) }, + projectRegistry: { get: async () => project }, + }); + + await session.handleMessage({ + type: "fetch_agents_request", + requestId: "list-heartbeat-agents", + subscribe: { subscriptionId: "heartbeat-agents" }, + }); + expect(findByType(messages, "fetch_agents_response")?.payload.entries).toMatchObject([ + { agent: { id: record.id, backgroundWork: { count: 1 } } }, + ]); + + if (!listener) throw new Error("Agent event listener was not installed"); + count = 0; + listener({ type: "background_work", agentId: record.id, items: [] }); + await expect + .poll(() => findByType(messages, "agent_update")?.payload) + .toMatchObject({ + kind: "upsert", + agent: { id: record.id }, + }); + const update = findByType(messages, "agent_update")?.payload; + expect(update?.kind === "upsert" && update.agent.backgroundWork).toBeUndefined(); + await session.cleanup(); +}); + test("reports an unavailable inventory for a stored agent without loading it", async () => { const messages: SessionOutboundMessage[] = []; const resumeAgentFromPersistence = vi.fn(); @@ -6213,8 +6474,9 @@ test.each([ record: createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo", internal: true }), error: "Unknown agent 'agent-a'", }, -])("rejects a background work list request for $name that is not loaded", async (scenario) => { +])("rejects background work control and updates for $name that is not loaded", async (scenario) => { const messages: SessionOutboundMessage[] = []; + let listener: ((event: AgentManagerEvent) => void) | undefined; const session = createSessionForTest({ messages, agentManager: { @@ -6223,20 +6485,45 @@ test.each([ getRegisteredProviderIds: vi.fn(() => ["codex"]), resumeAgentFromPersistence: vi.fn(), createAgent: vi.fn(), + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, }, agentStorage: { get: vi.fn().mockResolvedValue(scenario.record) }, }); + await session.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "subscribe-background-work", + events: ["agent.background_work.update"], + }); await session.handleMessage({ type: "agent.background_work.list.request", agentId: "agent-a", requestId: "list-rejected", }); + await session.handleMessage({ + type: "agent.background_work.stop.request", + requestId: "stop-rejected", + agentId: "agent-a", + itemId: heartbeatBackgroundWork.id, + stopToken: heartbeatBackgroundWork.stopToken, + }); + if (!listener) throw new Error("Agent event listener was not installed"); + listener({ type: "background_work", agentId: "agent-a", items: [heartbeatBackgroundWork] }); + await new Promise((resolve) => setImmediate(resolve)); + expect(messages).toContainEqual({ type: "agent.background_work.list.response", payload: { requestId: "list-rejected", agentId: "agent-a", items: [], error: scenario.error }, }); + expect(findByType(messages, "agent.background_work.stop.response")?.payload.error).toBe( + scenario.error, + ); + expect(findByType(messages, "agent.background_work.update")).toBeUndefined(); + await session.cleanup(); }); test("never pushes background work to an old app", async () => { @@ -6253,6 +6540,7 @@ test("never pushes background work to an old app", async () => { return () => {}; }), }, + agentStorage: { get: async () => createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }) }, }); // provider_subagents makes subagent updates flow to this legacy socket, so the // manager listener is installed for it. @@ -6269,6 +6557,7 @@ test("never pushes background work to an old app", async () => { ], }); + await new Promise((resolve) => setImmediate(resolve)); const pushed = [...messages, ...targetedMessages.map((entry) => entry.message)]; expect(pushed.some((message) => message.type === "agent.background_work.update")).toBe(false); }); @@ -6276,19 +6565,6 @@ test("never pushes background work to an old app", async () => { test("pushes background work only to clients that subscribed to it", async () => { const messages: SessionOutboundMessage[] = []; const agentEventListeners: Array<(event: AgentManagerEvent) => void> = []; - const session = createSessionForTest({ - messages, - agentManager: { - getAgent: vi.fn(() => undefined), - subscribe: vi.fn((listener: (event: AgentManagerEvent) => void) => { - agentEventListeners.push(listener); - return () => {}; - }), - }, - }); - const forward = (event: AgentManagerEvent) => { - for (const listener of agentEventListeners) listener(event); - }; const event: AgentManagerEvent = { type: "background_work", agentId: "agent-a", @@ -6296,6 +6572,22 @@ test("pushes background work only to clients that subscribed to it", async () => { id: "bash-1", kind: "shell", description: null, startedAt: "2026-10-06T10:00:00.000Z" }, ], }; + const session = createSessionForTest({ + messages, + agentManager: { + getAgent: vi.fn(() => undefined), + getAgentBackgroundWorkSummary: () => ({ count: event.items.length }), + listAgentBackgroundWork: () => event.items, + subscribe: vi.fn((listener: (event: AgentManagerEvent) => void) => { + agentEventListeners.push(listener); + return () => {}; + }), + }, + agentStorage: { get: async () => createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }) }, + }); + const forward = () => { + for (const listener of agentEventListeners) listener(event); + }; // Subscribe to an unrelated event so the manager listener is installed, then prove // a client that did not ask for background work never receives it. @@ -6305,7 +6597,8 @@ test("pushes background work only to clients that subscribed to it", async () => events: ["agent.provider_subagents.update"], }); if (agentEventListeners.length === 0) throw new Error("Agent event listener was not installed"); - forward(event); + forward(); + await new Promise((resolve) => setImmediate(resolve)); expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false); await session.handleMessage({ @@ -6315,14 +6608,16 @@ test("pushes background work only to clients that subscribed to it", async () => }); messages.length = 0; - forward(event); + forward(); - expect(messages).toContainEqual( - expect.objectContaining({ - type: "agent.background_work.update", - payload: expect.objectContaining({ agentId: "agent-a", items: event.items }), - }), - ); + await expect + .poll(() => messages) + .toContainEqual( + expect.objectContaining({ + type: "agent.background_work.update", + payload: expect.objectContaining({ agentId: "agent-a", items: event.items }), + }), + ); }); test("does not publish internal agents' background work to subscribed clients", async () => { @@ -6332,7 +6627,7 @@ test("does not publish internal agents' background work to subscribed clients", messages, agentManager: { getAgent: () => ({ id: "internal-agent", internal: true }) as never, - subscribe: (callback) => { + subscribe: (callback: (event: AgentManagerEvent) => void) => { listener = callback; return () => {}; }, @@ -6352,5 +6647,6 @@ test("does not publish internal agents' background work to subscribed clients", { id: "work", kind: "shell", description: "private", startedAt: "2026-10-06T10:00:00.000Z" }, ], }); + await new Promise((resolve) => setImmediate(resolve)); expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false); }); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 2192c699ad..2bdad76ba3 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -23,7 +23,10 @@ import { isAbsolute } from "node:path"; import { CreationService, type CreatedAgent } from "./creation/index.js"; import type { CreationSnapshot, AgentCreateRequest } from "@getpaseo/protocol/messages"; import type { MessageReceipts } from "./message-receipts/index.js"; -import type { AgentBackgroundWorkItem } from "./agent/background-work/index.js"; +import { + isHeartbeatBackgroundWorkItem, + type AgentBackgroundWorkItem, +} from "./agent/background-work/index.js"; import equal from "fast-deep-equal"; import { WorkspaceSetupObservation } from "./workspace-setup-observation.js"; import { SessionDelivery, type OwnedSubscription } from "./session/owned-subscriptions/index.js"; @@ -144,7 +147,10 @@ import { updateAgentCommand, } from "./agent/lifecycle-command.js"; import { buildStoredAgentPayload, toAgentPayload } from "./agent/agent-projections.js"; -import { assertPluginTimelineDataSize } from "./agent/agent-timeline-content.js"; +import { + assertPluginTimelineDataSize, + assertPluginTimelineKind, +} from "./agent/agent-timeline-content.js"; import { parsePluginClientId } from "./plugins/plugin-session-identity.js"; import { buildAgentForkContextAttachment } from "./agent/activity-curator.js"; import { buildAgentPrompt } from "./agent/prompt-attachments.js"; @@ -319,6 +325,7 @@ type ProviderSubagentManagerEvent = Extract< // Clients before 0.1.45 validate providers with z.enum(["claude", "codex", "opencode"]) and reject // the entire session message if they encounter an unknown provider. const LEGACY_PROVIDER_IDS = new Set(["claude", "codex", "opencode"]); +const FULL_AGENT_ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i; const MIN_VERSION_ALL_PROVIDERS = "0.1.45"; const MIN_VERSION_EXPLICIT_WORKSPACE_RECOVERY = "0.1.105"; function errorToFriendlyMessage(error: unknown): string { @@ -537,6 +544,10 @@ export interface SessionOptions { statusSources( pluginId?: string, ): Promise; + listRegistry(): Promise; + getRegistryPlugin( + id: string, + ): Promise; previewUpdates(input: { pluginId?: string; target?: import("@getpaseo/protocol/messages").PluginUpdateSelection; @@ -2172,7 +2183,12 @@ export class Session { } if (event.type === "background_work") { - this.forwardBackgroundWork(event); + void this.forwardBackgroundWork(event.agentId).catch((error) => + this.sessionLogger.error( + { err: error, agentId: event.agentId }, + "Failed to emit background work update", + ), + ); return; } @@ -2255,16 +2271,34 @@ export class Session { this.forwardProviderSubagentUpdate(event); } - private forwardBackgroundWork( - event: Extract, - ): void { - const agent = this.agentManager.getAgent(event.agentId); - if (agent?.internal) return; + private async forwardBackgroundWork(agentId: string): Promise { + const target = await this.resolveBackgroundWorkAgent(agentId); + if ("error" in target) return; + const { agent, record } = target; + // The inventory may have changed while resolving a dormant agent. + const items = this.agentManager.getAgentBackgroundWorkSummary(agentId) + ? this.agentManager.listAgentBackgroundWork(agentId) + : []; this.emit({ type: "agent.background_work.update", - payload: { agentId: event.agentId, items: event.items }, + payload: { agentId, items: this.projectBackgroundWorkItems(items) }, + }); + if (agent) await this.agentUpdates.forwardLiveAgent(agent); + else if (record) await this.agentUpdates.forwardStoredAgent(record); + } + + private projectBackgroundWorkItems(items: AgentBackgroundWorkItem[]): AgentBackgroundWorkItem[] { + if ( + this.authorization.allowsPermission("automation.manage") && + this.authorization.allowsInbound({ type: "agent.background_work.stop.request" }) + ) { + return items; + } + return items.map((item) => { + if (!isHeartbeatBackgroundWorkItem(item)) return item; + const { canStop: _canStop, stopToken: _stopToken, ...visible } = item; + return visible; }); - if (agent) void this.agentUpdates.forwardLiveAgent(agent); } private emitProviderSubagentWorkspaceUpdate(event: ProviderSubagentManagerEvent): void { @@ -2299,10 +2333,12 @@ export class Session { } private async enrichAgentPayload(payload: AgentSnapshotPayload): Promise { - payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id); const storedRecord = await this.agentStorage.get(payload.id); payload.title = storedRecord?.title ?? null; payload.archivedAt = storedRecord?.archivedAt ?? null; + if (!payload.internal && !storedRecord?.internal && !payload.archivedAt) { + payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id); + } return payload; } @@ -2314,8 +2350,11 @@ export class Session { record: StoredAgentRecord, registeredProviderIds = new Set(this.providerSnapshotManager.listRegisteredProviderIds()), ): AgentSnapshotPayload { - return buildStoredAgentPayload(record, registeredProviderIds, (provider, own) => - this.agentManager.effectiveOptionsFor(provider, own), + return buildStoredAgentPayload( + record, + registeredProviderIds, + (provider, own) => this.agentManager.effectiveOptionsFor(provider, own), + this.agentManager.getAgentBackgroundWorkSummary(record.id), ); } @@ -2900,6 +2939,30 @@ export class Session { }); } + private dispatchPluginRegistryMessage(msg: SessionInboundMessage): Promise | undefined { + if (msg.type === "plugin.registry.list.request") { + if (!this.pluginRuntime) throw new Error("Plugin service is unavailable"); + return this.pluginRuntime.listRegistry().then((index) => { + this.emit({ + type: "plugin.registry.list.response", + payload: { requestId: msg.requestId, index }, + }); + return undefined; + }); + } + if (msg.type === "plugin.registry.get.request") { + if (!this.pluginRuntime) throw new Error("Plugin service is unavailable"); + return this.pluginRuntime.getRegistryPlugin(msg.id).then((plugin) => { + this.emit({ + type: "plugin.registry.get.response", + payload: { requestId: msg.requestId, plugin }, + }); + return undefined; + }); + } + return undefined; + } + private dispatchPluginDirectoryMessage(msg: SessionInboundMessage): Promise | undefined { if (msg.type === "plugin.source.install.request") { if (!this.pluginRuntime) throw new Error("Plugin service is unavailable"); @@ -2980,7 +3043,7 @@ export class Session { return undefined; }); } - return undefined; + return this.dispatchPluginRegistryMessage(msg); } private subscribeToPluginChanges( @@ -5393,15 +5456,11 @@ export class Session { const agentIds = Array.isArray(agentId) ? agentId : [agentId]; try { - await Promise.all( - agentIds.map((id) => - ensureAgentLoaded(id, { - agentManager: this.agentManager, - agentStorage: this.agentStorage, - logger: this.sessionLogger, - }), - ), - ); + for (const id of agentIds) { + if (!this.agentManager.getAgent(id) && !(await this.agentStorage.get(id))) { + throw new Error(`Agent not found: ${id}`); + } + } await Promise.all(agentIds.map((id) => this.agentManager.clearAgentAttention(id))); if (requestId) { const agents = ( @@ -5767,6 +5826,12 @@ export class Session { return { ok: true, agentId: trimmed }; } + // A complete agent ID names one agent. When none has it, no prefix or + // title answers for it, so a command never acts on a different agent. + if (FULL_AGENT_ID_PATTERN.test(trimmed)) { + return { ok: false, notFound: true, error: `Agent not found: ${trimmed}` }; + } + const prefixMatches = Array.from(knownIds).filter((id) => id.startsWith(trimmed)); if (prefixMatches.length === 1) { return { ok: true, agentId: prefixMatches[0] }; @@ -6184,6 +6249,7 @@ export class Session { // resolves to "github") so the sidebar/hover-card brand mark matches the // status projection without a second resolve. forge: snapshot.forge.forge, + forgeWeb: snapshot.forgeWeb, }; } @@ -8500,6 +8566,7 @@ export class Session { ): Promise { const pluginId = parsePluginClientId(this.clientId); if (!pluginId) throw new Error("Only plugin sessions can append plugin timeline items"); + assertPluginTimelineKind(msg.item.kind); assertPluginTimelineDataSize(msg.item.data); const { seq, epoch } = await this.agentManager.appendTimelineItem(msg.agentId, { ...msg.item, @@ -8649,10 +8716,13 @@ export class Session { ): Promise { let error: string | null = null; try { + const target = await this.resolveBackgroundWorkAgent(msg.agentId); + if ("error" in target) throw new Error(target.error); await this.agentManager.stopAgentBackgroundWork({ agentId: msg.agentId, itemId: msg.itemId, stopToken: msg.stopToken, + canManageAutomation: this.authorization.allowsPermission("automation.manage"), }); } catch (cause) { error = cause instanceof Error ? cause.message : String(cause); @@ -8694,23 +8764,27 @@ export class Session { } } - // Background work lives only in memory, so an agent that is not loaded has none. - // Answering from storage keeps a read from resuming a dormant agent. private async readAgentBackgroundWork(agentId: string): Promise { - if (this.agentManager.getAgent(agentId)) { - if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) { - throw new Error("Background work inventory is unavailable"); - } - return this.agentManager.listAgentBackgroundWork(agentId); + const target = await this.resolveBackgroundWorkAgent(agentId); + if ("error" in target) throw new Error(target.error); + if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) { + throw new Error("Background work inventory is unavailable"); } + return this.projectBackgroundWorkItems(this.agentManager.listAgentBackgroundWork(agentId)); + } + + private async resolveBackgroundWorkAgent( + agentId: string, + ): Promise<{ agent: ManagedAgent | null; record: StoredAgentRecord | null } | { error: string }> { const record = await this.agentStorage.get(agentId); - if (!record || record.internal) { - throw new Error(`Unknown agent '${agentId}'`); + const agent = this.agentManager.getAgent(agentId); + if ((!agent && !record) || agent?.internal || record?.internal) { + return { error: `Unknown agent '${agentId}'` }; } - if (record.archivedAt) { - throw new Error(`Agent is archived: ${agentId}`); + if (record?.archivedAt) { + return { error: `Agent is archived: ${agentId}` }; } - throw new Error("Background work inventory is unavailable"); + return { agent, record }; } private async handleProviderSubagentTimelineRequest( @@ -8917,8 +8991,9 @@ export class Session { queued = acceptAdmission; }); let deliveryStatus: "queued" | undefined; - const send = async () => { + const send = async (beforeDispatch: () => Promise) => { if (msg.sourceAgentId) { + await beforeDispatch(); const receipt = this.agentMessages.enqueue({ recipientId: agentId, messageId: msg.messageId, @@ -8949,12 +9024,14 @@ export class Session { activeTurnBehavior: msg.activeTurnBehavior ?? "interrupt", sessionMode: msg.sessionMode, clearPendingPermissions: true, + beforeDispatch, logger: this.sessionLogger, }); if (result.disposition === "turn_started") { await waitForAgentRunStartWithTimeout( this.agentManager, agentId, + result.started, this.delivery.requestSignal, ); } @@ -8971,12 +9048,12 @@ export class Session { activeTurnBehavior: msg.activeTurnBehavior ?? (msg.sourceAgentId ? "steer" : "interrupt"), }, - prepare: async () => { + send: async (beforeDispatch) => { if (!msg.sourceAgentId) await this.prepareAgentMessage(agentId, msg.text); + await send(beforeDispatch); }, - send, }) - : send(); + : send(async () => {}); void sent.catch((error) => { if (deliveryStatus === "queued") { this.handleAgentRunError(agentId, error, "Failed to dispatch queued agent message"); diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index b3ededb352..f14a6e94dc 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -6619,6 +6619,45 @@ test("lists Git runtime for a checkout explicitly owned by a non-Git project", a }); }); +test("lists where the workspace's forge is on the web so every client builds the same links", async () => { + const session = createSessionForWorkspaceTests(); + const project = createPersistedProjectRecord({ + projectId: "proj-forge-web", + rootPath: REPO_CWD, + kind: "git", + displayName: "repo", + createdAt: "2026-03-01T12:00:00.000Z", + updatedAt: "2026-03-01T12:00:00.000Z", + }); + const workspace = createPersistedWorkspaceRecord({ + workspaceId: "ws-forge-web", + projectId: project.projectId, + cwd: REPO_CWD, + kind: "local_checkout", + displayName: "main", + createdAt: "2026-03-01T12:00:00.000Z", + updatedAt: "2026-03-01T12:00:00.000Z", + }); + session.listAgentPayloads = async () => []; + session.projectRegistry.list = async () => [project]; + session.workspaceRegistry.listAll = session.workspaceRegistry.listActive = async () => [ + workspace, + ]; + session.workspaceRuntimeStore.get = () => ({ + ...createWorkspaceRuntimeSnapshot(REPO_CWD), + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }); + + const [descriptor] = ( + await session.buildWorkspaceDescriptorMap({ includeGitData: true }) + ).values(); + + expect(descriptor?.forgeWeb).toEqual({ + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}); + test("buildWorkspaceDescriptorMap computes statusEnteredAt from runtime agent fields", async () => { const setupSession = () => { const session = createSessionForWorkspaceTests(); diff --git a/packages/server/src/server/session/agent-updates/agent-updates-service.ts b/packages/server/src/server/session/agent-updates/agent-updates-service.ts index 789dcbe5c3..08cfb03582 100644 --- a/packages/server/src/server/session/agent-updates/agent-updates-service.ts +++ b/packages/server/src/server/session/agent-updates/agent-updates-service.ts @@ -44,6 +44,7 @@ export interface AgentUpdatesService { hasSubscription(): boolean; includesLiveAgent(agent: ManagedAgent, subscriptionIds?: ReadonlySet): Promise; forwardLiveAgent(agent: ManagedAgent): Promise; + forwardStoredAgent(record: StoredAgentRecord): Promise; emitStoredRecord(record: StoredAgentRecord): Promise; removeAgent(agentId: string): Promise; dispose(): void; @@ -302,10 +303,13 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU return payload; } - async function emitLiveAgentUpdate(payload: AgentSnapshotPayload): Promise { + async function emitAgentUpdate( + workspaceId: string | undefined, + projectPayload?: () => AgentSnapshotPayload | Promise, + ): Promise { try { - if (hasSubscription()) await publishPayload(await deps.enrichAgentPayload(payload)); - if (payload.workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(payload.workspaceId); + if (projectPayload && hasSubscription()) await publishPayload(await projectPayload()); + if (workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId); } catch (error) { deps.logger.error({ err: error }, "Failed to emit agent update"); } @@ -330,17 +334,20 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU if (!hasSubscription()) { const workspaceId = agent.workspaceId; return workspaceId - ? enqueueAgentUpdate(agent.id, async () => { - try { - await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId); - } catch (error) { - deps.logger.error({ err: error }, "Failed to emit workspace update"); - } - }) + ? enqueueAgentUpdate(agent.id, () => emitAgentUpdate(workspaceId)) : Promise.resolve(); } const payload = toAgentPayload(agent); - return enqueueAgentUpdate(payload.id, () => emitLiveAgentUpdate(payload)); + return enqueueAgentUpdate(payload.id, () => + emitAgentUpdate(payload.workspaceId, () => deps.enrichAgentPayload(payload)), + ); + } + + function forwardStoredAgent(record: StoredAgentRecord): Promise { + if (!hasSubscription() && !record.workspaceId) return Promise.resolve(); + return enqueueAgentUpdate(record.id, () => + emitAgentUpdate(record.workspaceId, () => deps.buildStoredAgentPayload(record)), + ); } function removeAgent(agentId: string): Promise { @@ -362,6 +369,7 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU hasSubscription, includesLiveAgent, forwardLiveAgent, + forwardStoredAgent, emitStoredRecord, removeAgent, dispose, diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts index 5526166d05..16a59dcd62 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts @@ -335,11 +335,15 @@ async function createBaseRecoveryFixture(baseBranch: string | null) { await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null })); }, }); - async function archiveAndRemove() { - await archivePersistedWorkspaceRecord({ - workspaceId: workspace.workspaceId, - workspaceRegistry: registry, - }); + async function archiveAndRemove(legacy = false) { + if (legacy) { + await registry.archive(workspace.workspaceId, new Date().toISOString()); + } else { + await archivePersistedWorkspaceRecord({ + workspaceId: workspace.workspaceId, + workspaceRegistry: registry, + }); + } await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome }); expect(existsSync(workspace.cwd)).toBe(false); } @@ -357,6 +361,134 @@ test("preserves ordinary checkout behavior when no separate base was recorded", ).toMatchObject({ currentBranch: "feature", baseRef: "feature" }); }); +test("records the full HEAD ref of an archived checkout", async () => { + const fixture = await createBaseRecoveryFixture(null); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: "refs/heads/feature", + }); +}); + +test("archives a workspace whose worktree Git administration is missing", async () => { + const fixture = await createBaseRecoveryFixture(null); + const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + rmSync(gitDir, { recursive: true, force: true }); + await archivePersistedWorkspaceRecord({ + workspaceId: fixture.workspace.workspaceId, + workspaceRegistry: fixture.registry, + }); + expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeTruthy(); +}); + +test("restores a branch that shares its name with a tag", async () => { + const fixture = await createBaseRecoveryFixture("main"); + execFileSync("git", ["tag", "feature"], { cwd: fixture.repoDir }); + await fixture.archiveAndRemove(); + expect((await fixture.registry.get(fixture.workspace.workspaceId))?.head).toBe( + "refs/heads/feature", + ); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature"); +}); + +test("restores detached HEAD even when the stored branch is stale", async () => { + const fixture = await createBaseRecoveryFixture("main"); + execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: commit, + }); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: null, + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("HEAD"); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); +}); + +test.each(["manual", "reconciliation"] as const)( + "a later %s archive without a readable HEAD restores the latest recorded branch", + async (route) => { + const fixture = await createBaseRecoveryFixture("main"); + await fixture.archiveAndRemove(); + await fixture.service.restore(fixture.workspace.workspaceId); + execFileSync("git", ["switch", "-c", "feature-b"], { cwd: fixture.workspace.cwd }); + writeFileSync(join(fixture.workspace.cwd, "newer.txt"), "newer\n"); + execFileSync("git", ["add", "newer.txt"], { cwd: fixture.workspace.cwd }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "newer"], { + cwd: fixture.workspace.cwd, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + // Placement reconciliation records the branch observed while the workspace is active. + await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({ + ...workspace, + branch: "feature-b", + })); + execFileSync("git", ["worktree", "remove", "--force", fixture.workspace.cwd], { + cwd: fixture.repoDir, + }); + if (route === "manual") { + await archivePersistedWorkspaceRecord({ + workspaceId: fixture.workspace.workspaceId, + workspaceRegistry: fixture.registry, + }); + } else { + await fixture.registry.archive(fixture.workspace.workspaceId, new Date().toISOString()); + } + + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature-b", + head: undefined, + }); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature-b", + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature-b"); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); + }, +); + test("restores a branchless workspace from its recorded base so work can continue", async () => { const fixture = await createBaseRecoveryFixture("refs/heads/release"); execFileSync("git", ["switch", "-c", "release"], { cwd: fixture.repoDir, stdio: "pipe" }); @@ -368,7 +500,7 @@ test("restores a branchless workspace from its recorded base so work can continu ...workspace, branch: null, })); - await fixture.archiveAndRemove(); + await fixture.archiveAndRemove(true); await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({ kind: "recoverable", @@ -402,7 +534,7 @@ test("restores a branchless workspace from the repository default when its base ...workspace, branch: null, })); - await fixture.archiveAndRemove(); + await fixture.archiveAndRemove(true); await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({ workspaceId: fixture.workspace.workspaceId, @@ -418,6 +550,44 @@ test("restores a branchless workspace from the repository default when its base ); }); +test("restores the archived detached checkout at its recorded commit", async () => { + const fixture = await createBaseRecoveryFixture("refs/heads/main"); + execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd }); + writeFileSync(join(fixture.workspace.cwd, "detached.txt"), "detached\n"); + execFileSync("git", ["add", "detached.txt"], { cwd: fixture.workspace.cwd }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], { + cwd: fixture.workspace.cwd, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: commit, + }); + execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir }); + execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({ + baseRefName: "main", + baseRef: "refs/heads/main", + }); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); + expect( + execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("HEAD"); +}); + test("restores the branch HEAD with a base name when the exact base is missing", async () => { const fixture = await createBaseRecoveryFixture("refs/remotes/upstream/main"); const headBeforeArchive = execFileSync("git", ["rev-parse", "HEAD"], { diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts index a683a07744..38c95cb421 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts @@ -151,13 +151,27 @@ export function createWorkspaceRecoveryService(deps: { workspace: PersistedWorkspaceRecord, sourceRepoRoot: string, ): Promise { - const source: WorktreeSource = workspace.branch - ? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch } - : { - kind: "restore-from-base", - branchName: `restored/${randomUUID().slice(0, 8)}`, - baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), - }; + let source: WorktreeSource; + const checkout = parseWorkspaceHead(workspace); + if (checkout.kind === "branch") { + source = { + kind: "restore", + branchName: checkout.branch, + baseRef: workspace.baseBranch, + }; + } else if (checkout.kind === "commit") { + source = { + kind: "restore-commit", + commit: checkout.commit, + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } else { + source = { + kind: "restore-from-base", + branchName: `restored/${randomUUID().slice(0, 8)}`, + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } try { await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 }); @@ -251,16 +265,29 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null return defaultBranch; } +function parseWorkspaceHead( + workspace: PersistedWorkspaceRecord, +): { kind: "branch"; branch: string } | { kind: "commit"; commit: string } | { kind: "missing" } { + if (workspace.head) { + const prefix = "refs/heads/"; + return workspace.head.startsWith(prefix) + ? { kind: "branch", branch: workspace.head.slice(prefix.length) } + : { kind: "commit", commit: workspace.head }; + } + return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" }; +} + function createRecoveryPlan( input: | { action: "unarchive"; workspace: PersistedWorkspaceRecord } | { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string }, ): RecoveryPlan { + const checkout = parseWorkspaceHead(input.workspace); const state = { kind: "recoverable" as const, workspaceId: input.workspace.workspaceId, workspaceName: resolveWorkspaceDisplayName(input.workspace), - branch: input.workspace.branch, + branch: checkout.kind === "branch" ? checkout.branch : null, }; if (input.action === "restore") { return { diff --git a/packages/server/src/server/speech/providers/local/config.ts b/packages/server/src/server/speech/providers/local/config.ts index dd52537796..5f504addea 100644 --- a/packages/server/src/server/speech/providers/local/config.ts +++ b/packages/server/src/server/speech/providers/local/config.ts @@ -87,7 +87,12 @@ function shouldIncludeLocalProviderConfig(params: { params.providers.dictationStt.provider === "local") || (params.providers.voiceStt.enabled !== false && params.providers.voiceStt.provider === "local") || - (params.providers.voiceTts.enabled !== false && params.providers.voiceTts.provider === "local"); + (params.providers.voiceTts.enabled !== false && + params.providers.voiceTts.provider === "local") || + // Turn detection is always local, so an enabled local turn detector + // needs the local provider config even when no speech site uses it. + (params.providers.voiceTurnDetection.enabled !== false && + params.providers.voiceTurnDetection.provider === "local"); return ( localRequestedByFeature || diff --git a/packages/server/src/server/speech/speech-config-resolver.test.ts b/packages/server/src/server/speech/speech-config-resolver.test.ts index c83d2c45fa..bca1b85d18 100644 --- a/packages/server/src/server/speech/speech-config-resolver.test.ts +++ b/packages/server/src/server/speech/speech-config-resolver.test.ts @@ -168,6 +168,122 @@ describe("resolveSpeechConfig", () => { }, ); + test("includes local provider config for local turn detection with OpenAI voice STT/TTS", () => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { enabled: false }, + voiceMode: { + enabled: true, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + tts: { provider: "openai", apiKey: "test-key", model: "gpt-4o-mini-tts", voice: "alloy" }, + }, + }, + }); + + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: {} as NodeJS.ProcessEnv, + persisted, + }); + + expect(result.speech.providers.voiceTurnDetection).toEqual({ + provider: "local", + explicit: false, + enabled: true, + }); + expect(result.speech.providers.voiceStt).toEqual({ + provider: "openai", + explicit: true, + enabled: true, + }); + expect(result.speech.providers.voiceTts).toEqual({ + provider: "openai", + explicit: true, + enabled: true, + }); + expect(result.speech.providers.dictationStt).toEqual({ + provider: "local", + explicit: false, + enabled: false, + }); + // Turn detection is always local, so the local provider config must be + // present even when no speech site uses the local provider and no + // models directory is configured; otherwise voice mode reports + // turn_detection_unavailable. + expect(result.speech.local).toEqual({ + modelsDir: path.join("/tmp/paseo-home", "models", "local-speech"), + models: { + dictationStt: "parakeet-tdt-0.6b-v2-int8", + voiceStt: "parakeet-tdt-0.6b-v2-int8", + voiceTts: "kokoro-en-v0_19", + voiceTtsSpeakerId: 0, + }, + }); + }); + + test("includes local provider config for local turn detection with dictation on OpenAI", () => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { + enabled: true, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + }, + voiceMode: { + enabled: true, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + tts: { provider: "openai", apiKey: "test-key", model: "gpt-4o-mini-tts", voice: "alloy" }, + }, + }, + }); + + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: {} as NodeJS.ProcessEnv, + persisted, + }); + + expect(result.speech.providers.voiceTurnDetection).toEqual({ + provider: "local", + explicit: false, + enabled: true, + }); + expect(result.speech.local).toEqual({ + modelsDir: path.join("/tmp/paseo-home", "models", "local-speech"), + models: { + dictationStt: "parakeet-tdt-0.6b-v2-int8", + voiceStt: "parakeet-tdt-0.6b-v2-int8", + voiceTts: "kokoro-en-v0_19", + voiceTtsSpeakerId: 0, + }, + }); + }); + + test("omits local provider config when voice mode is off and no speech site is local", () => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { enabled: false }, + voiceMode: { + enabled: false, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + tts: { provider: "openai", apiKey: "test-key", model: "gpt-4o-mini-tts", voice: "alloy" }, + }, + }, + }); + + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: {} as NodeJS.ProcessEnv, + persisted, + }); + + expect(result.speech.providers.voiceTurnDetection).toEqual({ + provider: "local", + explicit: false, + enabled: false, + }); + expect(result.speech.local).toBeUndefined(); + }); + test("respects disabled dictation and voice mode feature flags", () => { const persisted = PersistedConfigSchema.parse({ features: { diff --git a/packages/server/src/server/test-utils/agent-messages.ts b/packages/server/src/server/test-utils/agent-messages.ts index b69da1f1c8..55cc698aab 100644 --- a/packages/server/src/server/test-utils/agent-messages.ts +++ b/packages/server/src/server/test-utils/agent-messages.ts @@ -12,12 +12,31 @@ export function createTestAgentMessages(params: { agentManager: AgentManager; agentStorage: AgentStorage; logger: Logger; + schedule?: (delayMs: number, callback: () => void) => () => void; }) { return createAgentMessageDelivery({ - schedule: (_delay, callback) => { - const timer = setTimeout(callback, 0); - return () => clearTimeout(timer); - }, + tryRunOutOfBand: (request, onAccepted) => + params.agentManager.tryRunOutOfBand( + request.recipientId, + request.prompt, + { clientMessageId: request.messageIds[0] }, + onAccepted, + ), + isRunning: (agentId) => params.agentManager.hasInFlightRun(agentId), + hasPendingPermission: (agentId) => params.agentManager.hasPendingPermissions(agentId), + subscribe: (notify) => + params.agentManager.subscribe( + (event) => { + if (event.type === "agent_state") notify(event.agent.id); + }, + { replayState: false }, + ), + schedule: + params.schedule ?? + ((_delay, callback) => { + const timer = setTimeout(callback, 0); + return () => clearTimeout(timer); + }), dispatch: async (request) => { const result = await sendPreparedPromptToAgent({ ...params, @@ -26,12 +45,16 @@ export function createTestAgentMessages(params: { sessionMode: request.sessionMode, unarchive: request.unarchive, activeTurnBehavior: request.activeTurnBehavior, + idleOnly: request.idleOnly, clearPendingPermissions: request.clearPendingPermissions, - onDispatch: request.onDispatch, runOptions: { clientMessageId: request.messageIds[0] }, }); if (result.disposition === "turn_started") - await waitForAgentRunStartWithTimeout(params.agentManager, request.recipientId); + await waitForAgentRunStartWithTimeout( + params.agentManager, + request.recipientId, + result.started, + ); return result.disposition; }, onError: (error, request) => diff --git a/packages/server/src/server/test-utils/fake-agent-client.ts b/packages/server/src/server/test-utils/fake-agent-client.ts index a7a237b9de..e9a0d9828e 100644 --- a/packages/server/src/server/test-utils/fake-agent-client.ts +++ b/packages/server/src/server/test-utils/fake-agent-client.ts @@ -84,6 +84,7 @@ interface FakeAgentSessionOptions { beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; steerActiveTurn?: AgentSession["steerActiveTurn"]; onInterrupt?: () => void; + beforeSetMode?: (modeId: string) => Promise; historyEvents?: readonly AgentStreamEvent[]; } @@ -95,6 +96,7 @@ export interface TestAgentClientOptions { beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; steerActiveTurn?: AgentSession["steerActiveTurn"]; onInterrupt?: () => void; + beforeSetMode?: (modeId: string) => Promise; supportsMcpServers?: boolean; historyEvents?: readonly AgentStreamEvent[]; } @@ -369,6 +371,7 @@ class FakeAgentSession implements AgentSession { readonly steerActiveTurn: AgentSession["steerActiveTurn"]; private readonly onInterrupt: (() => void) | undefined; + private readonly beforeSetMode: ((modeId: string) => Promise) | undefined; private readonly closeSession: (() => Promise) | undefined; private readonly onStartTurn: TestAgentClientOptions["onStartTurn"]; private readonly beforeTurnComplete: ((prompt: AgentPromptInput) => Promise) | undefined; @@ -385,6 +388,7 @@ class FakeAgentSession implements AgentSession { this.memoryMarker = options.memoryMarker ?? null; this.steerActiveTurn = options.steerActiveTurn; this.onInterrupt = options.onInterrupt; + this.beforeSetMode = options.beforeSetMode; this.closeSession = options.closeSession; this.onStartTurn = options.onStartTurn; this.beforeTurnComplete = options.beforeTurnComplete; @@ -543,6 +547,48 @@ class FakeAgentSession implements AgentSession { this.notifySubscribers(completed); } + private async emitEvent(event: AgentStreamEvent): Promise { + await this.appendHistoryEvent(event); + this.notifySubscribers(event); + } + + /** + * A background Task that outlives the turn's reply: the Task starts, the assistant replies, + * then the Task completes. + */ + private async emitBackgroundWorkTurn(): Promise { + const callId = randomUUID(); + const task = (status: "running" | "completed", log: string): AgentStreamEvent => ({ + type: "timeline", + provider: this.providerName, + item: { + type: "tool_call", + name: "Task", + callId, + status, + error: null, + detail: { + type: "sub_agent", + subAgentType: "Explore", + description: "Audit the migrations", + log, + }, + }, + }); + await this.emitEvent(task("running", "")); + await this.emitEvent({ + type: "timeline", + provider: this.providerName, + item: { type: "assistant_message", text: "Audit started.", messageId: randomUUID() }, + }); + await this.emitEvent(task("completed", "Found 2 unsafe migrations.")); + await this.emitEvent({ + type: "turn_completed", + provider: this.providerName, + usage: { inputTokens: 1, outputTokens: 1 }, + }); + } + private async emitStressTurn(stress: { count: number; coalesced: boolean }): Promise { for (let index = 0; index < stress.count; index += 1) { const stressUpdate: AgentStreamEvent = { @@ -786,6 +832,11 @@ class FakeAgentSession implements AgentSession { this.notifySubscribers(child); } + if (textPrompt === "Start background work") { + await this.emitBackgroundWorkTurn(); + return; + } + if (textPrompt.toLowerCase().includes("emit a turn failure")) { const failed: AgentStreamEvent = { type: "turn_failed", @@ -891,6 +942,7 @@ class FakeAgentSession implements AgentSession { } async setMode(modeId: string): Promise { + await this.beforeSetMode?.(modeId); this.config.modeId = modeId; } @@ -1264,6 +1316,7 @@ class FakeAgentClient implements AgentClient { beforeTurnComplete: this.options.beforeTurnComplete, steerActiveTurn: this.options.steerActiveTurn, onInterrupt: this.options.onInterrupt, + beforeSetMode: this.options.beforeSetMode, historyEvents: this.options.historyEvents, }); } @@ -1294,6 +1347,7 @@ class FakeAgentClient implements AgentClient { beforeTurnComplete: this.options.beforeTurnComplete, steerActiveTurn: this.options.steerActiveTurn, onInterrupt: this.options.onInterrupt, + beforeSetMode: this.options.beforeSetMode, historyEvents: this.options.historyEvents, }); } diff --git a/packages/server/src/server/test-utils/paseo-daemon.ts b/packages/server/src/server/test-utils/paseo-daemon.ts index 766fd49919..17f47df629 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.ts @@ -55,6 +55,7 @@ interface TestPaseoDaemonOptions { resumeOnStartup?: boolean; resumePrompt?: string; pluginsEnabled?: PaseoDaemonConfig["pluginsEnabled"]; + pluginRegistryUrl?: PaseoDaemonConfig["pluginRegistryUrl"]; builtinPlugins?: BuiltinPluginLoader; plugins?: PaseoDaemonConfig["plugins"]; } @@ -232,6 +233,7 @@ async function prepareTestDaemonConfig( resumePrompt: options.resumePrompt, pluginsEnabled: options.pluginsEnabled, plugins: options.plugins, + pluginRegistryUrl: options.pluginRegistryUrl, }; return { config, paseoHomeRoot, paseoHome, staticDir, createdDirs }; } diff --git a/packages/server/src/server/test-utils/session-stubs.ts b/packages/server/src/server/test-utils/session-stubs.ts index 0c156ae5d9..7546da1427 100644 --- a/packages/server/src/server/test-utils/session-stubs.ts +++ b/packages/server/src/server/test-utils/session-stubs.ts @@ -306,7 +306,7 @@ export function createProviderSnapshotManagerStub(): { export function createMessageReceiptsStub(): SessionOptions["messageReceipts"] { return { - send: (input) => input.send(), + send: (input) => input.send(async () => {}), }; } diff --git a/packages/server/src/server/test-utils/versioned-daemon.ts b/packages/server/src/server/test-utils/versioned-daemon.ts index f8763e0d6f..ac46db8c8f 100644 --- a/packages/server/src/server/test-utils/versioned-daemon.ts +++ b/packages/server/src/server/test-utils/versioned-daemon.ts @@ -1,6 +1,7 @@ // Browser compatibility tests run a real daemon in a separate Node runtime. // // argv: [port] [paseoHomeRoot] +// env: PASEO_PLUGIN_REGISTRY, read as the real daemon reads it. // A fixed port and a caller-owned home let a test stop this daemon and start a // replacement under the same endpoint and serverId. import path from "node:path"; @@ -24,6 +25,7 @@ const daemon = await createTestPaseoDaemon({ } : {}), pluginsEnabled: true, + pluginRegistryUrl: process.env.PASEO_PLUGIN_REGISTRY, mcpEnabled: false, corsAllowedOrigins: ["*"], }); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 50c5edac99..2e6e299837 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -728,23 +728,39 @@ export class VoiceAssistantWebSocketServer { this.agentManager = agentManager; this.agentStorage = agentStorage; this.agentMessages = createAgentMessageDelivery({ + tryRunOutOfBand: (request, onAccepted) => + agentManager.tryRunOutOfBand( + request.recipientId, + request.prompt, + { clientMessageId: request.messageIds[0] }, + onAccepted, + ), + isRunning: (agentId) => agentManager.hasInFlightRun(agentId), + hasPendingPermission: (agentId) => agentManager.hasPendingPermissions(agentId), + subscribe: (notify) => + agentManager.subscribe( + (event) => { + if (event.type === "agent_state") notify(event.agent.id); + }, + { replayState: false }, + ), dispatch: async (batch) => { - const { disposition } = await sendPreparedPromptToAgent({ + const dispatch = await sendPreparedPromptToAgent({ agentManager, agentStorage, agentId: batch.recipientId, prompt: batch.prompt, activeTurnBehavior: batch.activeTurnBehavior, + idleOnly: batch.idleOnly, sessionMode: batch.sessionMode, clearPendingPermissions: batch.clearPendingPermissions, unarchive: batch.unarchive, runOptions: { clientMessageId: batch.messageIds[0] }, - onDispatch: batch.onDispatch, logger: this.logger, }); - if (disposition === "turn_started") - await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId); - return disposition; + if (dispatch.disposition === "turn_started") + await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId, dispatch.started); + return dispatch.disposition; }, onError: (err, batch) => this.logger.error( @@ -982,9 +998,7 @@ export class VoiceAssistantWebSocketServer { callback(false, 403, "Host not allowed"); return; } - const sameOrigin = isWebSocketSameOrigin(origin, requestHost); - - if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) { + if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) { callback(true); } else { this.incrementRuntimeCounter("originRejected"); @@ -2092,6 +2106,8 @@ export class VoiceAssistantWebSocketServer { pluginGitManagement: true, pluginSourceInstallation: true, pluginSourceUpdates: true, + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + pluginRegistry: true, pluginLogs: true, // COMPAT(pluginThemes): added in v0.5.0, remove gate after 2027-08-20. pluginThemes: true, @@ -3249,6 +3265,22 @@ function isLoopbackAlias(hostname: string): boolean { return /^127(?:\.\d{1,3}){3}$/.test(normalized); } +/** + * Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket + * upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch. + */ +export function isDaemonOriginAllowed( + origin: string, + requestHost: string | null, + allowedOrigins: Set, +): boolean { + return ( + allowedOrigins.has("*") || + allowedOrigins.has(origin) || + isWebSocketSameOrigin(origin, requestHost) + ); +} + export function isWebSocketSameOrigin( origin: string | undefined, requestHost: string | null, diff --git a/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts b/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts index d10a098d79..bd243ced8e 100644 --- a/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts @@ -1,5 +1,13 @@ -import { execFile, execFileSync, spawn } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { execFile, execFileSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -569,7 +577,130 @@ test.skipIf(process.platform === "win32")( 60000, ); +async function createWorktreeWithTeardown( + slug: string, + worktreeConfig: { teardown: string; teardownTimeoutMs?: number }, +): Promise<{ workspaceId: string; worktreePath: string }> { + const repoDir = createGitRepo(); + writeFileSync(path.join(repoDir, "paseo.json"), JSON.stringify({ worktree: worktreeConfig })); + execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add teardown"], { + cwd: repoDir, + stdio: "pipe", + }); + const result = await ctx.client.createWorkspace({ + source: { kind: "worktree", cwd: repoDir, worktreeSlug: slug, baseBranch: "main" }, + }); + const workspace = result.workspace; + if (!workspace?.workspaceDirectory) { + throw new Error(result.error ?? "Failed to create worktree workspace"); + } + return { workspaceId: workspace.id, worktreePath: workspace.workspaceDirectory }; +} + +function isProcessRunning(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + test.skipIf(process.platform === "win32")( + "a paseo.json teardown that never exits is stopped and the archive answers", + async () => { + const pidFile = path.join(makeTempDir("hanging-teardown-"), "sleep.pid"); + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("hanging-teardown", { + teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`, + teardownTimeoutMs: 2000, + }); + + try { + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true }); + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + await expect.poll(() => isProcessRunning(sleepPid), { timeout: 5000 }).toBe(false); + } finally { + if (existsSync(pidFile)) { + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL"); + } + } + }, + 30000, +); + +test.skipIf(process.platform === "win32")( + "a paseo.json teardown that prints more than 1 MiB still removes the worktree", + async () => { + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("chatty-teardown", { + teardown: `node -e "process.stdout.write('x'.repeat(2 * 1024 * 1024))"`, + }); + + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: false }); + }, + 60000, +); + +test.skipIf(process.platform === "win32")( + "a teardown that handles SIGTERM and exits zero still leaves the worktree", + async () => { + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-trap", { + teardown: `trap 'exit 0' TERM; sleep 5 & wait`, + teardownTimeoutMs: 2000, + }); + + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true }); + }, + 15000, +); + +test.skipIf(process.platform === "win32")( + "the archive answers when an exited teardown shell's child holds its output open", + async () => { + const pidFile = path.join(makeTempDir("teardown-open-output-"), "sleep.pid"); + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-open-output", { + teardown: `sleep 12 & echo $! > ${JSON.stringify(pidFile)}`, + teardownTimeoutMs: 2000, + }); + + try { + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true }); + } finally { + if (existsSync(pidFile)) { + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL"); + } + } + }, + 10000, +); + +test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( "repeating archive removes a residual worktree for an already-archived workspace", async () => { const repoDir = createGitRepo(); @@ -586,42 +717,24 @@ test.skipIf(process.platform === "win32")( throw new Error(result.error ?? "Failed to create worktree workspace"); } - const writerStartedPath = path.join(repoDir, "writer-started"); - const stopWriterPath = path.join(repoDir, "stop-writer"); - const target = path.join( - workspace.workspaceDirectory, - "node_modules/react-native-svg/lib/typescript", - ); - const writer = spawn( - process.execPath, - [ - "-e", - `const fs=require('fs'),path=require('path');const target=${JSON.stringify(target)};const started=${JSON.stringify(writerStartedPath)};const stop=${JSON.stringify(stopWriterPath)};fs.writeFileSync(started,'started');while(!fs.existsSync(stop)){try{fs.mkdirSync(target,{recursive:true});fs.writeFileSync(path.join(target,'active'),String(Date.now()))}catch{}}`, - ], - { stdio: "ignore" }, - ); - const writerExit = new Promise((resolve) => writer.once("exit", () => resolve())); - + const directory = workspace.workspaceDirectory; + const originalMode = statSync(directory).mode & 0o777; + // Deny removal of entries such as .git until the second archive request. + chmodSync(directory, originalMode & ~0o222); try { - await expect.poll(() => existsSync(writerStartedPath), { timeout: 10000 }).toBe(true); - const firstArchive = await ctx.client.archiveWorkspace(workspace.id); expect(firstArchive.error).toBeNull(); expect((await activeWorkspaceIds()).has(workspace.id)).toBe(false); - expect(existsSync(workspace.workspaceDirectory)).toBe(true); - - writeFileSync(stopWriterPath, "stop\n"); - await writerExit; - - const retry = await ctx.client.archiveWorkspace(workspace.id); - - expect(retry.error).toBeNull(); - expect(existsSync(workspace.workspaceDirectory)).toBe(false); + expect(existsSync(directory)).toBe(true); } finally { - writeFileSync(stopWriterPath, "stop\n"); - await writerExit; + if (existsSync(directory)) chmodSync(directory, originalMode); } + + const retry = await ctx.client.archiveWorkspace(workspace.id); + + expect(retry.error).toBeNull(); + expect(existsSync(directory)).toBe(false); }, 60000, ); diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index 7a71b4682b..5f6fb473e7 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -8,6 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js"; import type { ForgeService } from "../services/forge-service.js"; import { deletePaseoWorktree, + readWorktreeHeadReference, isPaseoOwnedWorktreeCwd, runWorktreeTeardownCommands, WorktreeTeardownError, @@ -707,7 +708,15 @@ export async function archivePersistedWorkspaceRecord(input: { } const archivedAt = input.archivedAt ?? new Date().toISOString(); - await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context); + let head: string | null = null; + if (existingWorkspace.kind === "worktree") { + const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd; + head = await readWorktreeHeadReference(cwd); + } + await input.workspaceRegistry.archive(input.workspaceId, archivedAt, { + ...input.context, + ...(head ? { head } : {}), + }); return existingWorkspace; } diff --git a/packages/server/src/server/workspace-archive-undo.e2e.test.ts b/packages/server/src/server/workspace-archive-undo.e2e.test.ts index a509cb2b6a..1d65afc307 100644 --- a/packages/server/src/server/workspace-archive-undo.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-undo.e2e.test.ts @@ -1,6 +1,14 @@ import { DaemonClient } from "./test-utils/daemon-client.js"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync, writeFileSync, renameSync, mkdirSync } from "node:fs"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + renameSync, + mkdirSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, expect, test } from "vitest"; @@ -125,6 +133,55 @@ test.skipIf(process.platform === "win32")( 60000, ); +test.skipIf(process.platform === "win32")( + "an undo during a teardown that never exits returns once the deadline stops it", + async () => { + const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-hang-")); + tempRoots.push(tempRoot); + const repoDir = path.join(tempRoot, "repo"); + const pidFile = path.join(tempRoot, "sleep.pid"); + execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" }); + git(repoDir, ["config", "user.email", "test@getpaseo.local"]); + git(repoDir, ["config", "user.name", "Paseo Test"]); + writeFileSync( + path.join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`, + teardownTimeoutMs: 2000, + }, + }), + ); + git(repoDir, ["add", "paseo.json"]); + git(repoDir, ["-c", "commit.gpgsign=false", "commit", "-m", "hanging teardown"]); + const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent( + repoDir, + "undo-during-hanging-teardown", + ); + try { + const archive = ctx.client.archiveWorkspace(workspaceId); + await expect.poll(() => existsSync(pidFile), { timeout: 15000 }).toBe(true); + await Promise.all([archive, ctx.client.undoWorkspaceArchive(workspaceId)]); + + expect({ + workspaceActive: await isWorkspaceActive(workspaceId), + directoryExists: existsSync(directory), + agentArchived: await isAgentArchived(agentId), + }).toEqual({ workspaceActive: true, directoryExists: true, agentArchived: false }); + } finally { + if (existsSync(pidFile)) { + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + try { + process.kill(sleepPid, "SIGKILL"); + } catch { + // Already stopped by the teardown deadline. + } + } + } + }, + 30000, +); + test.skipIf(process.platform === "win32")( "an undo after the archive finished recreates the worktree and its agents", async () => { @@ -151,6 +208,40 @@ test.skipIf(process.platform === "win32")( 60000, ); +test.skipIf(process.platform === "win32").each([ + ["branch", "restore"], + ["branch", "undo"], + ["detached", "restore"], + ["detached", "undo"], +] as const)( + "%s checkout survives archive and %s", + async (checkout, action) => { + const repo = createRepoWithGatedTeardown(); + repo.releaseTeardown(); + const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent( + repo.repoDir, + `keep-${checkout}-${action}`, + ); + if (checkout === "detached") git(directory, ["switch", "--detach"]); + writeFileSync(path.join(directory, "change.txt"), `${checkout}\n`); + git(directory, ["add", "change.txt"]); + git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "workspace commit"]); + const readHead = (args: string[]) => + execFileSync("git", args, { cwd: directory, encoding: "utf8" }).trim(); + const commit = readHead(["rev-parse", "HEAD"]); + const branch = readHead(["rev-parse", "--abbrev-ref", "HEAD"]); + expect((await ctx.client.archiveWorkspace(workspaceId)).error).toBeNull(); + expect(existsSync(directory)).toBe(false); + git(repo.repoDir, ["reflog", "expire", "--expire=now", "--all"]); + git(repo.repoDir, ["gc", "--prune=now"]); + if (action === "undo") await ctx.client.undoWorkspaceArchive(workspaceId); + else await ctx.client.restoreWorkspace(workspaceId); + expect(readHead(["rev-parse", "HEAD"])).toBe(commit); + expect(readHead(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(branch); + }, + 60000, +); + test.skipIf(process.platform === "win32")( "archive, undo, archive leaves the workspace archived", async () => { diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index 8480d0604d..cbed2c8e58 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -17,6 +17,7 @@ import { type CheckoutSnapshotFacts, type CheckoutStatusGit, } from "../utils/checkout-git.js"; +import { createGitHubService, GitHubCommandError } from "../services/github-service.js"; import { createFileObserver } from "./file-observer/index.js"; import { WorkspaceGitServiceImpl } from "./workspace-git-service.js"; import type { FileChange, FileObserver, SubscribeToFileChanges } from "./file-observer/index.js"; @@ -1019,3 +1020,559 @@ test("a branch switch made before the Git metadata watcher starts still reaches ) .toBe("feature"); }, 30_000); + +function createCheckoutWithOrigin(origin: string): string { + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-forge-web-"))); + const repo = path.join(root, "repo"); + mkdirSync(repo); + const git = (...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: repo, stdio: "pipe" }); + git("init", "-b", "main"); + git("config", "user.email", "test@example.com"); + git("config", "user.name", "Test"); + writeFileSync(path.join(repo, "README.md"), "base\n"); + git("add", "."); + git("commit", "-m", "base"); + git("remote", "add", "origin", origin); + cleanup.push(async () => + rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }), + ); + return repo; +} + +// The GitHub adapter runs for real; only the `gh` binary it spawns is scripted. +function createGitHubWithRepositoryView(repositoryView: object) { + return createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view") { + return { stdout: JSON.stringify(repositoryView), stderr: "" }; + } + return { stdout: "", stderr: "" }; + }, + }); +} + +async function snapshotOf( + repo: string, + deps: ConstructorParameters[0]["deps"], +) { + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps, + }); + cleanup.push(() => service.dispose()); + return { + service, + snapshot: await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }), + }; +} + +async function expectForgeWebEventually( + service: WorkspaceGitServiceImpl, + repo: string, + expected: { host: string; referenceRepository?: string }, +) { + await expect + .poll(async () => (await service.getSnapshot(repo, { includeForge: false })).forgeWeb, { + timeout: 10_000, + }) + .toEqual(expected); +} + +test("an SSH config alias remote publishes the web host the alias resolves to", async () => { + const repo = createCheckoutWithOrigin("git@github.com-work:acme/repo.git"); + + const { snapshot } = await snapshotOf(repo, { + resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), + forgeOverrides: { github: createGitHubWithRepositoryView({}) }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); +}); + +test("a cloud SSH host publishes the forge's web host", async () => { + const repo = createCheckoutWithOrigin("ssh://git@ssh.github.com/acme/repo.git"); + + const { snapshot } = await snapshotOf(repo, { + forgeOverrides: { github: createGitHubWithRepositoryView({}) }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); +}); + +test("a fork checkout publishes its parent as the repository that owns issue and pull request numbers", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + + const { service, snapshot } = await snapshotOf(repo, { + forgeOverrides: { + github: createGitHubWithRepositoryView({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + }, + }); + + // The host is available with the first snapshot; the parent follows in a background update. + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}); + +test("a plain remote publishes no separate reference repository", async () => { + const repo = createCheckoutWithOrigin("https://github.com/acme/repo.git"); + + const { service, snapshot } = await snapshotOf(repo, { + forgeOverrides: { + github: createGitHubWithRepositoryView({ owner: { login: "acme" }, name: "repo" }), + }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); + await expectForgeWebEventually(service, repo, { host: "github.com" }); +}); + +test("a remote on no forge publishes no web location", async () => { + const repo = createCheckoutWithOrigin("git@bitbucket.org:acme/repo.git"); + + const { snapshot } = await snapshotOf(repo, { resolveSshHostname: async () => null }); + + expect(snapshot.forgeWeb).toBeUndefined(); +}); + +test("changing the origin remote publishes the new remote's web location, not the previous one", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view") { + const isFork = args[2] === "fork-owner/repo"; + return { + stdout: JSON.stringify( + isFork + ? { + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + } + : { owner: { login: "acme" }, name: "other" }, + ), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + const before = await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + + execFileSync("git", ["remote", "set-url", "origin", "git@github.com-work:acme/other.git"], { + cwd: repo, + }); + // The refresh a `.git/config` change schedules does not ask for forge data. + const after = await service.getSnapshot(repo, { + force: true, + includeForge: false, + reason: "forge-web-test", + }); + + expect(after.git.remoteUrl).toBe("git@github.com-work:acme/other.git"); + expect(after.forgeWeb).toEqual({ host: "github.com" }); + expect(before.forgeWeb).toEqual({ host: "github.com" }); +}, 30_000); + +test("a failed parent lookup is retried by the pull request status poll, keeping the host an SSH alias resolves to", async () => { + const repo = createCheckoutWithOrigin("git@github.com-work:fork-owner/repo.git"); + let nowMs = Date.parse("2026-01-01T00:00:00Z"); + let ghAnswers = false; + let lookups = 0; + let pollStatus: ((status: null) => void) | undefined; + const github = createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + // The reference lookup names the origin repository; the PR status load asks for the cwd repo. + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookups += 1; + if (!ghAnswers) { + throw new GitHubCommandError({ + args, + cwd: repo, + exitCode: 1, + stderr: "error connecting to api.github.com", + }); + } + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + now: () => new Date(nowMs), + // Observing the workspace starts a background fetch of origin. A real one would run ssh + // against the alias host in the checkout, and can outlive disposal and hold the folder. + runGitFetch: async () => ({ changes: [], error: null }), + resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), + forgeOverrides: { + // The adapter is real; only the poll is driven by the test instead of a timer. + github: Object.assign(Object.create(github), { + retainCurrentPullRequestStatusPoll: (options: { onStatus?: (status: null) => void }) => { + pollStatus = options.onStatus; + return { unsubscribe: () => {} }; + }, + }), + }, + }, + }); + const subscription = service.registerWorkspace({ cwd: repo }, () => {}); + cleanup.push(async () => { + subscription.unsubscribe(); + await service.dispose(); + }); + + const failed = await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + expect(failed.forgeWeb).toEqual({ host: "github.com" }); + await expect.poll(() => pollStatus, { timeout: 10_000 }).toBeDefined(); + await expect.poll(() => lookups, { timeout: 10_000 }).toBe(1); + // Let the failed lookup record its retry time before advancing the clock. + await new Promise((resolve) => setTimeout(resolve, 0)); + + ghAnswers = true; + nowMs += 61_000; + pollStatus?.(null); + + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + const forced = await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + expect(forced.forgeWeb).toEqual({ host: "github.com", referenceRepository: "main-owner/repo" }); +}, 30_000); + +test("a successful parent lookup is reused across forced refreshes of the same remote", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + let repositoryViews = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view") { + // The parent lookup is the one that names the origin repository. + if (args[2] === "fork-owner/repo") repositoryViews += 1; + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + expect(repositoryViews).toBe(1); +}); + +test("a fork checked out at a detached HEAD still publishes its parent", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + execFileSync("git", ["checkout", "--detach"], { cwd: repo, stdio: "pipe" }); + + const { service, snapshot } = await snapshotOf(repo, { + forgeOverrides: { + github: createGitHubWithRepositoryView({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}); + +test("a parent lookup that finishes during a refresh keeps its answer", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + const lookupStarted = Promise.withResolvers(); + const releaseLookup = Promise.withResolvers(); + const statusLoadStarted = Promise.withResolvers(); + const releaseStatusLoad = Promise.withResolvers(); + let holdNextStatusLoad = false; + let repositoryViews = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "auth" && args[1] === "status" && holdNextStatusLoad) { + holdNextStatusLoad = false; + statusLoadStarted.resolve(); + await releaseStatusLoad.promise; + } + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + repositoryViews += 1; + if (repositoryViews === 1) { + lookupStarted.resolve(); + await releaseLookup.promise; + } + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await lookupStarted.promise; + + holdNextStatusLoad = true; + const second = service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await statusLoadStarted.promise; + + // The first refresh's lookup finishes while the second refresh is still loading the PR status. + releaseLookup.resolve(); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + releaseStatusLoad.resolve(); + + const snapshot = await second; + expect(snapshot.forgeWeb).toEqual({ + host: "github.com", + referenceRepository: "main-owner/repo", + }); + expect(repositoryViews).toBe(1); +}, 30_000); + +test("disposal waits for a background parent lookup", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + const lookupStarted = Promise.withResolvers(); + const releaseLookup = Promise.withResolvers(); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookupStarted.resolve(); + await releaseLookup.promise; + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + + try { + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await lookupStarted.promise; + + let disposed = false; + const disposal = service.dispose().then(() => { + disposed = true; + return undefined; + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(disposed).toBe(false); + + releaseLookup.resolve(); + await disposal; + expect(disposed).toBe(true); + } finally { + releaseLookup.resolve(); + await service.dispose(); + } +}, 30_000); + +test("the first snapshot publishes git state and pull request status without waiting for the parent lookup", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + writeFileSync(path.join(repo, "changed.txt"), "dirty\n"); + const lookupStarted = Promise.withResolvers(); + const releaseLookup = Promise.withResolvers(); + const pullRequestStatusLoaded = Promise.withResolvers(); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookupStarted.resolve(); + await releaseLookup.promise; + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + if (args[0] === "pr" && args[1] === "view") { + pullRequestStatusLoaded.resolve(); + return { + stdout: JSON.stringify({ + number: 42, + url: "https://github.com/fork-owner/repo/pull/42", + title: "Already known pull request", + state: "OPEN", + baseRefName: "main", + headRefName: "main", + mergedAt: null, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + let snapshot: Awaited> | null = null; + const pending = service + .getSnapshot(repo, { force: true, reason: "forge-web-test" }) + .then((value) => { + snapshot = value; + return value; + }); + + await pullRequestStatusLoaded.promise; + // The forge lookup is still held here; the snapshot must not wait for it. + await expect.poll(() => snapshot !== null, { timeout: 5_000 }).toBe(true); + expect(snapshot).not.toBeNull(); + expect(snapshot!.git.currentBranch).toBe("main"); + expect(snapshot!.git.isDirty).toBe(true); + expect(snapshot!.forge.pullRequest?.number).toBe(42); + expect(snapshot!.forgeWeb).toEqual({ host: "github.com" }); + + await lookupStarted.promise; + releaseLookup.resolve(); + await pending; + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}, 30_000); + +test("a failed parent lookup is not repeated by forced refreshes before the retry delay", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + let lookups = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookups += 1; + throw new GitHubCommandError({ + args, + cwd: repo, + exitCode: 1, + stderr: "error connecting to api.github.com", + }); + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await expect.poll(() => lookups, { timeout: 10_000 }).toBe(1); + // Let the failed lookup record its retry time. + await new Promise((resolve) => setTimeout(resolve, 0)); + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + + expect(lookups).toBe(1); +}, 30_000); diff --git a/packages/server/src/server/workspace-git-service.primitive.test.ts b/packages/server/src/server/workspace-git-service.primitive.test.ts index f9d4af8a9d..b969c7315c 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -264,6 +264,8 @@ function createSnapshot(cwd: string, overrides?: SnapshotOverrides): WorkspaceGi pullRequest: resolveSnapshotPullRequest(base, overrides), error: resolveSnapshotError(base, overrides), }, + // Every remote these fixtures use is on github.com. + ...(forge ? { forgeWeb: { host: "github.com" } } : {}), }; } @@ -704,8 +706,9 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => { refreshStatus.resolve(createCheckoutStatus(REPO_CWD, { currentBranch: "feature" })); await refresh; - expect(await service.getSnapshot(REPO_CWD)).toEqual( - createSnapshot(REPO_CWD, { + // A branch change resets the PR status but not where the same remote lives on the web. + expect(await service.getSnapshot(REPO_CWD)).toEqual({ + ...createSnapshot(REPO_CWD, { git: { currentBranch: "feature", diffStat: { additions: 4, deletions: 2 }, @@ -716,7 +719,8 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => { error: null, }, }), - ); + forgeWeb: { host: "github.com" }, + }); expect(getCheckoutStatus).toHaveBeenCalledTimes(2); expect(getCheckoutShortstat).toHaveBeenCalledTimes(2); @@ -2191,6 +2195,7 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => { expect(subscribe).toHaveBeenCalledTimes(1); expect(subscribe).toHaveBeenCalledWith(repoDir, expect.any(Function), { ignore: [join(repoDir, ".git"), ignoredRoot], + signal: expect.any(AbortSignal), }); subscription.unsubscribe(); diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index 9d91610cd8..8349977f92 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -93,6 +93,8 @@ function createSnapshot( pullRequest: resolveSnapshotPullRequest(base, overrides), error: resolveSnapshotError(base, overrides), }, + // Every remote these fixtures use is on github.com. + ...(forgeName ? { forgeWeb: { host: "github.com" } } : {}), }; } @@ -475,6 +477,56 @@ async function advanceThroughWorkingTreeRecoveryAttempts( } } +// Stalls every subscription for `watchPath` the way a CPU-starved startup scan does, until the +// service aborts it at the subscribe deadline. Other paths subscribe immediately. +function createStallingWatchSetup(watchPath: string) { + const signals: AbortSignal[] = []; + let acceptNext = false; + let acceptedCallback: WatchCallback | null = null; + const subscribe = vi.fn( + async (directory: string, callback: WatchCallback, options?: { signal?: AbortSignal }) => { + if (directory !== watchPath) { + return createAsyncSubscription(); + } + const signal = options?.signal ?? new AbortController().signal; + signals.push(signal); + if (acceptNext) { + acceptNext = false; + acceptedCallback = callback; + return createAsyncSubscription(); + } + return new Promise>((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }, + ); + return { + subscribe, + signals, + acceptNextAttempt() { + acceptNext = true; + }, + failAcceptedWatcher() { + acceptedCallback?.(new Error("accepted watcher stopped"), []); + }, + async expectAttemptAbortedAtDeadline() { + const signal = signals.at(-1); + expect(signal?.aborted).toBe(false); + await vi.advanceTimersByTimeAsync(WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS); + expect(signal?.aborted).toBe(true); + expect(signal?.reason).toMatchObject({ name: "WorkspaceGitWatcherSubscriptionTimeoutError" }); + }, + async expectNextAttemptAfter(delayMs: number, service: WorkspaceGitServiceImpl) { + const attempts = signals.length; + await vi.advanceTimersByTimeAsync(delayMs - 1); + await waitForRefreshesToSettle(service); + expect(signals).toHaveLength(attempts); + await vi.advanceTimersByTimeAsync(1); + await settle(() => expect(signals).toHaveLength(attempts + 1)); + }, + }; +} + describe("WorkspaceGitServiceImpl", () => { beforeEach(() => { vi.useFakeTimers(); @@ -1571,6 +1623,7 @@ describe("WorkspaceGitServiceImpl", () => { expect(subscribe).toHaveBeenCalledTimes(1); expect(subscribe).toHaveBeenCalledWith(REPO_CWD, expect.any(Function), { ignore: [join(REPO_CWD, ".git")], + signal: expect.any(AbortSignal), }); subscription.unsubscribe(); @@ -1646,6 +1699,67 @@ describe("WorkspaceGitServiceImpl", () => { 15_000, ); + test.each(["repository metadata", "working tree"])( + "aborts each timed-out %s watcher setup and backs retries off toward an hour", + async (kind) => { + const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD; + const setup = createStallingWatchSetup(watchPath); + const getCheckoutStatus = vi.fn(async (cwd: string) => createCheckoutStatus(cwd)); + const service = createService({ subscribe: setup.subscribe, getCheckoutStatus }); + const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn()); + try { + await settle(() => expect(setup.signals).toHaveLength(1)); + await setup.expectAttemptAbortedAtDeadline(); + await waitForObservationToSettle(service, 1); + for (const delayMs of [ + 30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_920_000, 3_600_000, + ]) { + await setup.expectNextAttemptAfter(delayMs, service); + await setup.expectAttemptAbortedAtDeadline(); + } + // Degraded polling keeps the checkout fresh while the watcher waits out an hour. + const readsBeforeCappedWait = getCheckoutStatus.mock.calls.length; + await setup.expectNextAttemptAfter(3_600_000, service); + expect(getCheckoutStatus.mock.calls.length).toBeGreaterThanOrEqual( + readsBeforeCappedWait + 59, + ); + } finally { + subscription.unsubscribe(); + await service.dispose(); + } + }, + 30_000, + ); + + test.each(["repository metadata", "working tree"])( + "an accepted %s watcher subscription resets the setup-timeout backoff", + async (kind) => { + const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD; + const setup = createStallingWatchSetup(watchPath); + const service = createService({ subscribe: setup.subscribe }); + const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn()); + try { + await settle(() => expect(setup.signals).toHaveLength(1)); + await setup.expectAttemptAbortedAtDeadline(); + for (const delayMs of [30_000, 60_000, 120_000, 240_000, 480_000]) { + await setup.expectNextAttemptAfter(delayMs, service); + await setup.expectAttemptAbortedAtDeadline(); + } + setup.acceptNextAttempt(); + await setup.expectNextAttemptAfter(960_000, service); + setup.failAcceptedWatcher(); + // The ordinary recovery ladder's ceiling applies again, not the 32-minute timeout step. + await setup.expectNextAttemptAfter(300_000, service); + await setup.expectAttemptAbortedAtDeadline(); + await setup.expectNextAttemptAfter(300_000, service); + } finally { + subscription.unsubscribe(); + await service.dispose(); + } + }, + 30_000, + ); + test.each(["repository metadata", "working tree"])( "ignores expired %s watcher callbacks after recovery", async (kind) => { @@ -1871,6 +1985,7 @@ describe("WorkspaceGitServiceImpl", () => { expect(subscription.repoRoot).toBeNull(); expect(subscribe).toHaveBeenCalledWith(plainCwd, expect.any(Function), { ignore: [join(plainCwd, ".git")], + signal: expect.any(AbortSignal), }); expect(vi.getTimerCount()).toBe(1); diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index c086fa41be..cdafbdd507 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -5,7 +5,7 @@ import { LRUCache } from "lru-cache"; import { CheckoutDiffCache } from "./checkout-diff-cache.js"; import pLimit from "p-limit"; import type pino from "pino"; -import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; +import type { ForgeWeb, ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; import type { CheckoutContext } from "../utils/checkout-git.js"; import { @@ -71,6 +71,12 @@ import { type SubscribeToFileChanges, createFileObserver, } from "./file-observer/index.js"; +import { + forgeWebForResolution, + resolveForgeWebReference, + type ForgeWebEntry, +} from "./forge-web.js"; +import type { SshHostnameResolver } from "../utils/ssh-hostname.js"; import { checkoutLiteFromGitSnapshot } from "./workspace-registry-model.js"; import { createWatcherLivenessCanary } from "./watcher-liveness-canary.js"; @@ -117,6 +123,11 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30_000; // restart, which kills running agents. Back off, but keep trying. const WATCH_RECOVERY_MAX_DELAY_MS = 300_000; const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4; +// A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the +// next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore +// keep doubling the recovery delay past the ladder cap, up to an hour. +const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3_600_000; +const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7; // Auxiliary reads may reuse cached values within this window; snapshots do not expire on read. const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15_000; // Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it. @@ -200,6 +211,8 @@ export interface WorkspaceGitRuntimeSnapshot { } | null; error: { message: string } | null; }; + /** Absent when the remote resolves to no forge. */ + forgeWeb?: ForgeWeb; } export interface WorkspaceGitService { @@ -406,6 +419,8 @@ interface WorkspaceGitServiceDependencies { * fakes. Any forge not listed here is built (and cached once) by the registry. */ forgeOverrides?: Record; + /** Resolves an SSH config alias to its HostName; defaults to `ssh -G`. */ + resolveSshHostname?: SshHostnameResolver; resolveAbsoluteGitDir: (cwd: string) => Promise; hasOriginRemote: (cwd: string) => Promise; runGitFetch: ( @@ -459,6 +474,11 @@ interface WorkspaceGitTarget { latestGitLoadedAtMs: number | null; latestForge: WorkspaceGitRuntimeSnapshot["forge"] | null; latestForgeLoadedAtMs: number | null; + latestForgeWeb: ForgeWebEntry | null; + /** The entry whose reference repository is being looked up, so one remote costs one call. */ + forgeWebLookupEntry: ForgeWebEntry | null; + /** The remote the forge snapshot was last refreshed for; null until the first forge refresh. */ + forgeRefreshedForRemote: { remoteUrl: string | null } | null; latestSnapshot: WorkspaceGitRuntimeSnapshot | null; latestSnapshotLoadedAtMs: number | null; latestFacts: CheckoutSnapshotFacts | null; @@ -559,6 +579,10 @@ interface WatchRecoveryState { // use (SMB/NFS, Docker virtiofs, some FUSE) resets the ladder on every // attempt and the backoff never engages. establishedAt: number | null; + // Setup attempts that hit WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS since the last accepted + // subscription. Reset on acceptance: finishing the startup scan in time is the proof that + // the next attempt is affordable. + setupTimeoutCount: number; } function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { @@ -580,6 +604,7 @@ interface WorkspaceGitAuxiliaryReadCacheEntry { interface WorkspaceForgePrStatusPollTarget { headRef: string; + currentBranch?: string; headSha?: string; headRepositoryOwner?: string; } @@ -647,6 +672,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private disposed = false; private disposePromise: Promise | null = null; private readonly pendingRefreshes = new Set>(); + private readonly pendingForgeWebLookups = new Set>(); private readonly snapshotUpdatedListeners = new Set(); private readonly workspaceTargets = new Map(); private readonly repoTargets = new Map(); @@ -691,6 +717,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { ); this.forgeResolver = createForgeResolver({ createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge), + resolveSshHostname: this.deps.resolveSshHostname, }); } @@ -1140,11 +1167,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { this.workingTreeWatchAliases.clear(); this.snapshotUpdatedListeners.clear(); // Unsubscribing can remove a target while its Git command still owns the cwd. - // Stop admission first, then drain those refreshes before releasing the service. - this.disposePromise = Promise.all([ - this.fileObserver.close(), - Promise.allSettled(this.pendingRefreshes), - ]).then(() => undefined); + // Stop admission first, then drain those refreshes and the parent lookups they start. + this.disposePromise = (async () => { + await Promise.all([this.fileObserver.close(), Promise.allSettled(this.pendingRefreshes)]); + await Promise.allSettled(this.pendingForgeWebLookups); + })(); return this.disposePromise; } @@ -1301,6 +1328,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { latestGit: null, latestGitLoadedAtMs: null, latestForge: null, + latestForgeWeb: null, + forgeWebLookupEntry: null, + forgeRefreshedForRemote: null, latestForgeLoadedAtMs: null, latestSnapshot: null, latestSnapshotLoadedAtMs: null, @@ -1499,7 +1529,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { fallbackPolling: false, fallbackPollTimer: null, fallbackPollQuietTickCount: 0, - recovery: { attemptCount: 0, timer: null, establishedAt: null }, + recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 }, listeners: new Set(), closed: false, }; @@ -1529,9 +1559,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { let removeAbortListener = () => {}; let unsubscribePromise: Promise | null = null; let subscriptionPromise: Promise; + // Abandoning the race is not enough: the observer's startup scan would keep walking the + // tree after the deadline. Abort it so a timed-out attempt stops costing CPU. + const setupController = new AbortController(); try { subscriptionPromise = this.deps - .subscribe(watchPath, callback, options) + .subscribe(watchPath, callback, { ...options, signal: setupController.signal }) .finally(onSubscribeSettled); } catch (error) { onSubscribeSettled(); @@ -1550,12 +1583,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const timeoutPromise = new Promise((_resolve, reject) => { timeout = setTimeout(() => { outcome = "expired"; - reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath)); + const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath); + setupController.abort(error); + reject(error); }, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS); }); const disposalPromise = new Promise((_resolve, reject) => { const rejectForDisposal = () => { outcome = "expired"; + setupController.abort(signal.reason); reject(signal.reason); }; if (signal.aborted) { @@ -1690,6 +1726,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { // `scheduleWorkingTreeWatchRecovery` only resets the ladder once this // one has survived long enough to prove itself durable. target.recovery.establishedAt = this.deps.now().getTime(); + target.recovery.setupTimeoutCount = 0; if (options?.replaceFallback && target.repoRoot !== null) { target.fallbackPolling = false; if (target.fallbackPollTimer) { @@ -1710,6 +1747,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { { err: error, cwd: target.cwd }, "Failed to start working tree watcher; using degraded polling", ); + this.noteWatchSetupFailure(target.recovery, error); if (!options?.replaceFallback) { this.startWorkingTreeWatchFallback(target, "watcher_setup_failed"); } @@ -1932,11 +1970,26 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } recovery.establishedAt = null; recovery.attemptCount += 1; - return Math.min( + const ladderDelayMs = Math.min( WATCH_RECOVERY_BASE_DELAY_MS * 2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS), WATCH_RECOVERY_MAX_DELAY_MS, ); + if (recovery.setupTimeoutCount === 0) { + return ladderDelayMs; + } + const setupTimeoutDelayMs = Math.min( + WATCH_RECOVERY_BASE_DELAY_MS * + 2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS), + WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS, + ); + return Math.max(ladderDelayMs, setupTimeoutDelayMs); + } + + private noteWatchSetupFailure(recovery: WatchRecoveryState, error: unknown): void { + if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) { + recovery.setupTimeoutCount += 1; + } } private scheduleWorkingTreeWatchRecovery(target: WorkingTreeWatchTarget): void { @@ -2410,7 +2463,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { fallbackPolling: false, fallbackPollTimer: null, fallbackPollQuietTickCount: 0, - recovery: { attemptCount: 0, timer: null, establishedAt: null }, + recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 }, intervalId: null, fetchInFlight: false, bufferedFetchMetadataEvents: [], @@ -2560,6 +2613,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { // subscribe success alone, only record when this subscription was // established. target.recovery.establishedAt = this.deps.now().getTime(); + target.recovery.setupTimeoutCount = 0; if (options?.replaceFallback) { target.fallbackPolling = false; if (target.fallbackPollTimer) { @@ -2583,6 +2637,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { { err: error, repoGitRoot: target.repoGitRoot }, "Failed to start repository metadata watcher; using degraded polling", ); + this.noteWatchSetupFailure(target.recovery, error); if (!options?.replaceFallback) { this.startRepoMetadataFallback(target); } @@ -3096,11 +3151,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { if (resolution.service.retainCurrentPullRequestStatusPoll) { target.forgePrStatusPollSubscription = resolution.service.retainCurrentPullRequestStatusPoll({ cwd: target.cwd, - headRef: pollTarget.headRef, - ...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}), - ...(pollTarget.headRepositoryOwner - ? { headRepositoryOwner: pollTarget.headRepositoryOwner } - : {}), + ...pollTarget, onStatus: (status) => { if (!this.isActiveObservedWorkspaceTarget(target)) { return; @@ -3172,11 +3223,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { try { const status = await service.getCurrentPullRequestStatus({ cwd: target.cwd, - headRef: pollTarget.headRef, - ...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}), - ...(pollTarget.headRepositoryOwner - ? { headRepositoryOwner: pollTarget.headRepositoryOwner } - : {}), + ...pollTarget, reason: "self-heal-forge-pr-status", }); if (!closed && this.isActiveObservedWorkspaceTarget(target)) { @@ -3231,13 +3278,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { target.latestFacts?.isGit && target.latestFacts.currentBranch === git.currentBranch ? target.latestFacts.pullRequestLookupTarget : null; - if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) { - return lookupTarget; - } if (lookupTarget) { - return lookupTarget; + return git.currentBranch === lookupTarget.headRef + ? lookupTarget + : { ...lookupTarget, currentBranch: git.currentBranch }; + } + if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) { + return null; } - return { headRef: git.currentBranch }; } @@ -3568,6 +3616,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } if (request.includeForge) { await this.refreshForgeSnapshot(target, request, facts, runRefreshGitCommand); + } else if (this.hasRemoteChangedSinceForgeRefresh(target)) { + // `git remote set-url` reaches here as a git-only refresh. The forge, its host and the + // fork's parent all belong to the old remote, so resolve the new one now. + await this.refreshForgeSnapshot( + target, + { ...request, includeForge: true, force: true }, + facts, + runRefreshGitCommand, + ); } const snapshot = this.combineSnapshot(target); @@ -3669,6 +3726,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const loadedAtMs = this.deps.now().getTime(); target.latestGitLoadedAtMs = loadedAtMs; target.latestForge = buildForgeUnavailableSnapshot(); + target.latestForgeWeb = null; target.latestForgeLoadedAtMs = target.latestGitLoadedAtMs; return facts; } @@ -3713,6 +3771,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { return facts; } + private hasRemoteChangedSinceForgeRefresh(target: WorkspaceGitTarget): boolean { + const refreshedFor = target.forgeRefreshedForRemote; + return ( + refreshedFor !== null && + target.latestGit?.isGit === true && + refreshedFor.remoteUrl !== target.latestGit.remoteUrl + ); + } + private async refreshForgeSnapshot( target: WorkspaceGitTarget, request: WorkspaceGitRefreshRequest, @@ -3720,13 +3787,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { runRefreshGitCommand: RunGitCommand, ): Promise { const remoteUrl = target.latestGit?.remoteUrl ?? null; + target.forgeRefreshedForRemote = { remoteUrl }; const resolution = await this.forgeResolver.resolveFromRemoteUrlAsync(remoteUrl); // Every forge gates on the resolver alone: a cloud host matches synchronously // and a self-hosted/Enterprise host is recognized by the adapter probe (which // this async resolution populates), so GitHub Enterprise is no longer gated // out by a cloud-only identity check. - if (!resolution) { + if (!resolution || !remoteUrl) { target.latestForge = buildUnresolvedRemoteForgeSnapshot(remoteUrl); + target.latestForgeWeb = null; target.latestForgeLoadedAtMs = this.deps.now().getTime(); return; } @@ -3749,7 +3818,16 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { // Carry the resolved forge (probe-aware) so the wire projection labels // self-managed GitLab hosts correctly instead of falling back to "github". target.latestForge = { ...forgeSnapshot, forge: resolution.forge }; + // Publish the host with the snapshot; the parent lookup finishes in the background. Read the + // previous entry after the wait: a lookup for the old entry may have completed meanwhile. + target.latestForgeWeb = forgeWebForResolution({ + remoteUrl, + resolution, + previous: target.latestForgeWeb, + nowMs: this.deps.now().getTime(), + }); target.latestForgeLoadedAtMs = this.deps.now().getTime(); + this.queueForgeWebReferenceLookup(target); } private combineSnapshot(target: WorkspaceGitTarget): WorkspaceGitRuntimeSnapshot { @@ -3761,6 +3839,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { cwd: target.cwd, git: target.latestGit, forge: target.latestForge ?? buildForgeUnavailableSnapshot(), + // Only the remote it was resolved for: after `git remote set-url` the old host and + // parent are wrong until the next forge refresh resolves the new remote. + ...(target.latestForgeWeb?.remoteUrl === target.latestGit.remoteUrl + ? { forgeWeb: target.latestForgeWeb.forgeWeb } + : {}), }; } @@ -3800,6 +3883,68 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { this.rememberSnapshot(target, this.combineSnapshot(target), { forceEmit: false, }); + this.queueForgeWebReferenceLookup(target); + } + + private queueForgeWebReferenceLookup(target: WorkspaceGitTarget): void { + const lookup = this.resolveForgeWebReferenceIfDue(target) + .catch((error) => { + if (!this.disposed) { + this.logger.warn( + { err: error, cwd: target.cwd }, + "Failed to resolve the forge reference repository", + ); + } + }) + .finally(() => { + this.pendingForgeWebLookups.delete(lookup); + }); + this.pendingForgeWebLookups.add(lookup); + } + + // The status poll is the only periodic work an idle workspace has, so it also + // retries a parent lookup that failed or ran before the forge CLI was signed in. + private async resolveForgeWebReferenceIfDue(target: WorkspaceGitTarget): Promise { + const entry = target.latestForgeWeb; + const remoteUrl = target.latestGit?.remoteUrl ?? null; + const nowMs = this.deps.now().getTime(); + if ( + !entry || + !remoteUrl || + entry.remoteUrl !== remoteUrl || + entry.retryAtMs === null || + nowMs < entry.retryAtMs || + target.forgeWebLookupEntry === entry + ) { + return; + } + target.forgeWebLookupEntry = entry; + try { + // The async resolver, like the forge refresh: only it reports the `ssh -G` host for an alias. + const resolution = await this.forgeResolver.resolveFromRemoteUrlAsync(remoteUrl); + if (!resolution) { + return; + } + const next = await resolveForgeWebReference({ + cwd: target.cwd, + resolution, + entry, + nowMs, + }); + if (target.closed || this.workspaceTargets.get(target.cwd) !== target) { + return; + } + // The origin can change while the lookup runs; the old remote's answer is not ours to publish. + if (target.latestForgeWeb !== entry || target.latestGit?.remoteUrl !== entry.remoteUrl) { + return; + } + target.latestForgeWeb = next; + this.rememberSnapshot(target, this.combineSnapshot(target), { forceEmit: false }); + } finally { + if (target.forgeWebLookupEntry === entry) { + target.forgeWebLookupEntry = null; + } + } } private rememberSnapshot( @@ -4273,6 +4418,7 @@ function buildWorkspaceForgePrStatusPollKey({ forge, remoteUrl, target.headRef, + target.currentBranch ?? null, target.headSha ?? null, target.headRepositoryOwner ?? null, ]); diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index 3d0057bcae..6f34b69853 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -641,7 +641,83 @@ describe("WorkspaceReconciliationService", () => { expect(workspaces.get("w1")).toMatchObject({ archivedAt, - branch: "new-branch", + branch: "old-branch", + }); + }); + + test("keeps a worktree restorable when it is archived while its checkout read is in flight", async () => { + const projectRoot = "/reconcile/archive-worktree/root"; + const worktreeCwd = "/reconcile/archive-worktree/worktrees/feature"; + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath: projectRoot, + projectKey: deriveProjectKey({ + rootPath: projectRoot, + remoteUrl: null, + worktreeRoot: projectRoot, + mainRepoRoot: null, + }), + kind: "git", + displayName: "archive-worktree", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + workspaces.set( + "w1", + createPersistedWorkspaceRecord({ + workspaceId: "w1", + projectId: "p1", + cwd: worktreeCwd, + kind: "worktree", + displayName: "feature", + branch: "feature", + worktreeRoot: worktreeCwd, + isPaseoOwnedWorktree: true, + mainRepoRoot: projectRoot, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const worktreeReadStarted = deferred(); + const allowWorktreeRead = deferred(); + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), + inspectDirectory: async () => "directory", + workspaceGitService: { + getCheckout: async (cwd) => { + if (cwd === projectRoot) { + return createCheckout(cwd, { isGit: true, currentBranch: "main", worktreeRoot: cwd }); + } + worktreeReadStarted.resolve(); + await allowWorktreeRead.promise; + // Archive deletes the worktree after archiving its record, so a read that + // lands mid-deletion no longer sees a Git checkout there. + return createCheckout(cwd); + }, + }, + }); + + const reconciliation = service.runOnce(); + await worktreeReadStarted.promise; + const archivedAt = "2025-01-02T00:00:00.000Z"; + await workspaceRegistry.archive("w1", archivedAt); + allowWorktreeRead.resolve(); + const result = await reconciliation; + + expect(result.changesApplied).toEqual([]); + expect(workspaces.get("w1")).toMatchObject({ + archivedAt, + kind: "worktree", + branch: "feature", + worktreeRoot: worktreeCwd, + isPaseoOwnedWorktree: true, + mainRepoRoot: projectRoot, }); }); diff --git a/packages/server/src/server/workspace-reconciliation-service.ts b/packages/server/src/server/workspace-reconciliation-service.ts index f1fe5c9444..84a0221a7f 100644 --- a/packages/server/src/server/workspace-reconciliation-service.ts +++ b/packages/server/src/server/workspace-reconciliation-service.ts @@ -396,8 +396,7 @@ export class WorkspaceReconciliationService { const workspaceCheckouts = await Promise.all( siblings.map(async (workspace) => { const current = await this.workspaceRegistry.get(workspace.workspaceId); - if (!current || current.cwd !== workspace.cwd || current.projectId !== workspace.projectId) - return null; + if (!current || !isStillReconcilable(current, workspace)) return null; return { workspace: current, checkout: await readCheckout(current.cwd) }; }), ); @@ -446,8 +445,9 @@ export class WorkspaceReconciliationService { return; let fields: Partial | null = null; await this.workspaceRegistry.update(workspace.workspaceId, (current) => { - if (current.cwd !== workspace.cwd || current.projectId !== workspace.projectId) - return current; + // Archive removes a worktree only after archiving its record, so a read + // that raced the archive may have seen the directory mid-deletion. + if (!isStillReconcilable(current, workspace)) return current; const update = reconcileWorkspacePlacement({ workspace: current, checkout: wsGit, @@ -685,3 +685,13 @@ async function mapBounded(items: T[], visit: (item: T) => Promise): Pro ); return results; } + +/** An archived record keeps the placement its restore depends on. */ +function isStillReconcilable( + current: PersistedWorkspaceRecord, + scanned: PersistedWorkspaceRecord, +): boolean { + return ( + !current.archivedAt && current.cwd === scanned.cwd && current.projectId === scanned.projectId + ); +} diff --git a/packages/server/src/server/workspace-registry.ts b/packages/server/src/server/workspace-registry.ts index fd376cc14c..04265da0c2 100644 --- a/packages/server/src/server/workspace-registry.ts +++ b/packages/server/src/server/workspace-registry.ts @@ -72,6 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({ .nullable() .optional() .transform((value) => value ?? null), + head: z.string().optional(), // Exact checkout/worktree root backing cwd. This differs from cwd when the // selected project is a subdirectory inside a repository. Persist it so // archive and recovery do not need the directory to still exist in order to @@ -126,6 +127,7 @@ export interface WorkspaceMutationContext { export interface WorkspaceArchiveContext { autoArchivedChangeRequestUrl?: string; + head?: string; } export interface ProjectMutation { @@ -586,6 +588,7 @@ export class FileBackedWorkspaceRegistry ...existing, updatedAt: archivedAt, archivedAt, + head: context?.head, ...(context?.autoArchivedChangeRequestUrl ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl } : {}), diff --git a/packages/server/src/services/forge-service.ts b/packages/server/src/services/forge-service.ts index d676304f79..264ed7acd6 100644 --- a/packages/server/src/services/forge-service.ts +++ b/packages/server/src/services/forge-service.ts @@ -436,6 +436,22 @@ export interface CreatePullRequestOptions { body?: string; } +export interface CurrentPullRequestLookup { + cwd: string; + headRef: string; + headSha?: string; + headRepositoryOwner?: string; + /** Local branch name when it differs from the PR source ref. */ + currentBranch?: string; +} + +export function isOnDefaultBranch( + lookup: Pick, + defaultBranch: string | null | undefined, +): boolean { + return (lookup.currentBranch ?? lookup.headRef) === defaultBranch; +} + export interface ForgeService { listPullRequests(options: ListPullRequestsOptions): Promise; listIssues(options: ListIssuesOptions): Promise; @@ -467,13 +483,15 @@ export interface ForgeService { * Others reject a cross-repo checkout that carries no refs. */ supportsCrossRepoCheckoutWithoutRefs?: boolean; + /** + * Repository path that owns the issue and change-request numbers of the + * checkout's origin repository when that is a different repository, such as a + * fork's parent. Null when the origin owns its numbers. Adapters whose forge + * has no fork model omit it. + */ + getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise; getCurrentPullRequestStatus( - options: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - } & ForgeReadOptions, + options: CurrentPullRequestLookup & ForgeReadOptions, ): Promise; getPullRequestTimeline(options: GetPullRequestTimelineOptions): Promise; getCheckDetails(options: GetCheckDetailsOptions): Promise; @@ -509,14 +527,12 @@ export interface ForgeService { * cannot change the outcome and is pure overhead. */ authProbeCanThrow?: boolean; - retainCurrentPullRequestStatusPoll?(options: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - onStatus?: (status: CurrentPullRequestStatus | null) => void; - onError?: (error: unknown) => void; - }): { unsubscribe: () => void }; + retainCurrentPullRequestStatusPoll?( + options: CurrentPullRequestLookup & { + onStatus?: (status: CurrentPullRequestStatus | null) => void; + onError?: (error: unknown) => void; + }, + ): { unsubscribe: () => void }; invalidate(options: { cwd: string }): void; dispose?(): void; } diff --git a/packages/server/src/services/gitea-service.test.ts b/packages/server/src/services/gitea-service.test.ts index 44d263791f..b4aca78bd4 100644 --- a/packages/server/src/services/gitea-service.test.ts +++ b/packages/server/src/services/gitea-service.test.ts @@ -429,6 +429,41 @@ function giteaMergeStatus( }; } +describe("createGiteaService getReferenceRepository", () => { + it("names the repository a fork was forked from, asking about the origin repository explicitly", async () => { + const { service, calls } = makeService(() => + ok( + JSON.stringify({ + full_name: "example-user/sample-repo", + fork: true, + parent: { full_name: "upstream-org/sample-repo" }, + }), + ), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBe( + "upstream-org/sample-repo", + ); + expect(calls).toEqual([["api", "repos/example-user/sample-repo"]]); + }); + + it("rejects when tea api answers with an error body, since tea exits 0 on HTTP errors", async () => { + const { service } = makeService(() => + ok(JSON.stringify({ message: "user does not exist [uid: 0, name: ]" })), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).rejects.toThrow(); + }); + + it("is null for a repository that is not a fork", async () => { + const { service } = makeService(() => + ok(JSON.stringify({ full_name: "example-user/sample-repo", fork: false, parent: null })), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBeNull(); + }); +}); + describe("createGiteaService", () => { it("maps a tea pr list item to the neutral current PR status by head branch", async () => { const { service, calls } = makeService((args) => { @@ -2001,6 +2036,33 @@ describe("createGiteaService", () => { ]); }); + it("hides a historical PR on the repository's default branch", async () => { + const historical = currentPullRequestApi({ + number: 8, + state: "closed", + headRef: "trunk", + headSha: "8888888888888888888888888888888888888888", + }); + const { service } = makeService((args) => { + if (args[0] === "pr" && args[1] === "list") return ok("[]"); + if (args[0] === "api" && args[1].includes("/pulls?state=all")) { + return ok(JSON.stringify([historical])); + } + if (args[0] === "api" && args[1] === "repos/example-user/sample-repo") { + return ok( + JSON.stringify({ + full_name: "example-user/sample-repo", + default_branch: "trunk", + }), + ); + } + throw new Error(`unexpected call: ${args.join(" ")}`); + }); + await expect( + service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }), + ).resolves.toBeNull(); + }); + it("falls back to the recent all-state PR window for a recently closed current branch PR", async () => { const headSha = "8888888888888888888888888888888888888888"; const closedPr = currentPullRequestApi({ diff --git a/packages/server/src/services/gitea-service.ts b/packages/server/src/services/gitea-service.ts index ef1df9f888..f974d05693 100644 --- a/packages/server/src/services/gitea-service.ts +++ b/packages/server/src/services/gitea-service.ts @@ -26,11 +26,13 @@ import { compareTimelineItems, createUnavailableSearchResult, normalizeForgeSearchKinds, + isOnDefaultBranch, parseOptionalTime, } from "./forge-service.js"; import type { CheckDetails, CreatePullRequestOptions, + CurrentPullRequestLookup, CurrentPullRequestStatus, DisablePullRequestAutoMergeOptions, EnablePullRequestAutoMergeOptions, @@ -247,6 +249,15 @@ const GiteaPullRequestApiSchema = z }) .passthrough(); +// `full_name` is required so an HTTP error body, which `tea api` returns with exit code 0, fails the parse. +const GiteaRepositoryApiSchema = z + .object({ + full_name: z.string(), + default_branch: z.string().nullish(), + parent: z.object({ full_name: z.string().optional() }).nullable().optional(), + }) + .passthrough(); + const GiteaCurrentPullRequestApiSchema = z .object({ number: z.number(), @@ -1577,11 +1588,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For return { items, truncated: true }; } - async function loadCurrentPullRequestStatus(input: { - cwd: string; - headRef: string; - headSha?: string; - }): Promise { + async function loadCurrentPullRequestStatus( + input: CurrentPullRequestLookup, + ): Promise { const match = await findCurrentPullRequestForHeadRef(input); if (!match) { return null; @@ -1605,11 +1614,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For return identity ? { owner: identity.owner, name: identity.name } : null; } - async function findCurrentPullRequestForHeadRef(input: { - cwd: string; - headRef: string; - headSha?: string; - }): Promise { + function readRepository(cwd: string, repoPath: string) { + return runJson(["api", repoPath], { cwd }, GiteaRepositoryApiSchema); + } + + function repositoryApiPath(repo: { owner: string; name: string } | null): string { + return repo + ? `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}` + : "repos/{owner}/{repo}"; + } + + async function findCurrentPullRequestForHeadRef( + input: CurrentPullRequestLookup, + ): Promise { const repoIdentity = await resolveCurrentRepoIdentity(input.cwd); const expectedHeadOwner = repoIdentity?.owner ?? null; const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner); @@ -1620,9 +1637,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For // tea discovers repository context from any configured git remote, while // the default remote resolver reads origin only. Preserve that broader // discovery for repositories whose primary remote has another name. - const repoPath = repoIdentity - ? `repos/${encodeURIComponent(repoIdentity.owner)}/${encodeURIComponent(repoIdentity.name)}` - : "repos/{owner}/{repo}"; + const repoPath = repositoryApiPath(repoIdentity); const recentItems = await runJsonArray( [ "api", @@ -1658,6 +1673,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For ) ?? candidates[0] ?? null; + if (match && mapGiteaState(match.state) !== "open") { + const repository = await readRepository(input.cwd, repoPath).catch(() => null); + if (isOnDefaultBranch(input, repository?.default_branch)) { + return null; + } + } return match ? currentPullRequestApiToListItem(match) : null; } @@ -2007,12 +2028,17 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For } }, + async getReferenceRepository(input): Promise { + const repo = await resolveCurrentRepoIdentity(input.cwd); + if (!repo) { + return null; + } + const repository = await readRepository(input.cwd, repositoryApiPath(repo)); + return repository.parent?.full_name ?? null; + }, + getCurrentPullRequestStatus(input): Promise { - return loadCurrentPullRequestStatus({ - cwd: input.cwd, - headRef: input.headRef, - headSha: input.headSha, - }); + return loadCurrentPullRequestStatus(input); }, async getPullRequest(input: GetPullRequestOptions): Promise { diff --git a/packages/server/src/services/github-service.test.ts b/packages/server/src/services/github-service.test.ts index 0b97f551bb..910a40c3b9 100644 --- a/packages/server/src/services/github-service.test.ts +++ b/packages/server/src/services/github-service.test.ts @@ -528,6 +528,65 @@ describe("ForgeService", () => { vi.useFakeTimers(); }); + describe("getReferenceRepository", () => { + const forkView = JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }); + + it("names the parent of a fork checkout, asking about the origin repository explicitly", async () => { + const runner = createRunner([forkView]); + const service = createGitHubService({ + runner: runner.runner, + resolveRepoHost: async () => null, + resolveOriginRepository: async () => "fork-owner/repo", + }); + + await expect(service.getReferenceRepository?.({ cwd: "/tmp/repo" })).resolves.toBe( + "main-owner/repo", + ); + expect(runner.calls).toHaveLength(1); + expect(runner.calls[0].args).toEqual([ + "repo", + "view", + "fork-owner/repo", + "--json", + "owner,name,parent,defaultBranchRef", + ]); + }); + + it("rejects when gh cannot answer, so a failed lookup is not mistaken for a repository without a parent", async () => { + const service = createGitHubService({ + runner: async () => { + throw new GitHubCommandError({ + args: ["repo", "view"], + cwd: "/tmp/repo", + exitCode: 1, + stderr: "error connecting to api.github.com", + }); + }, + resolveRepoHost: async () => null, + resolveOriginRepository: async () => "fork-owner/repo", + }); + + await expect(service.getReferenceRepository?.({ cwd: "/tmp/repo" })).rejects.toBeInstanceOf( + GitHubCommandError, + ); + }); + + it("is null for a repository that is not a fork", async () => { + const runner = createRunner([JSON.stringify({ owner: { login: "acme" }, name: "repo" })]); + const service = createGitHubService({ + runner: runner.runner, + resolveRepoHost: async () => null, + resolveOriginRepository: async () => "acme/repo", + }); + + await expect(service.getReferenceRepository?.({ cwd: "/tmp/repo" })).resolves.toBeNull(); + }); + }); + afterEach(() => { vi.useRealTimers(); }); @@ -803,7 +862,7 @@ describe("ForgeService", () => { expect(runner.calls).toHaveLength(2); expect(runner.calls[0]).toEqual({ cwd: "/repo", - args: ["repo", "view", "--json", "owner,name,parent"], + args: ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], }); expect(runner.calls[1]?.cwd).toBe("/repo"); expect(runner.calls[1]?.args.slice(0, 3)).toEqual(["api", "graphql", "-f"]); @@ -1052,6 +1111,56 @@ describe("ForgeService", () => { expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1); }); + it.each([ + { currentBranch: undefined, state: "MERGED", expected: null, calls: 1 }, + { currentBranch: undefined, state: "OPEN", expected: "open", calls: 2 }, + { currentBranch: "fork/trunk", state: "MERGED", expected: "merged", calls: 2 }, + ])( + "polls a $state PR with source trunk from checkout $currentBranch", + async ({ currentBranch, state, expected, calls }) => { + const runner = createScriptedRunner([ + batchPollStatusJson({ + t0: batchPollRepositoryJson( + [ + batchPollPrNodeJson({ + headRefName: "trunk", + state, + ...(state === "OPEN" ? { mergedAt: null } : {}), + }), + ], + { + defaultBranchRef: { name: "trunk" }, + }, + ), + }), + batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }), + ]); + const service = createGitHubService({ + runner: runner.runner, + resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => "acme/widgets", + now: () => 0, + }); + const statuses: Array = []; + try { + service.retainCurrentPullRequestStatusPoll?.({ + cwd: "/repo", + headRef: "trunk", + currentBranch, + onStatus: (status) => statuses.push(status), + }); + await vi.advanceTimersByTimeAsync(0); + await flushMicrotasks(); + + expect(statuses.map((status) => status?.state ?? null)).toEqual([expected]); + expect(runner.calls).toHaveLength(calls); + } finally { + service.dispose?.(); + } + }, + ); + it("batches PR status polls across workspaces into one GraphQL request", async () => { let now = 0; const runner = createScriptedRunner([ @@ -1431,13 +1540,19 @@ describe("ForgeService", () => { batchPollStatusJson({ t0: batchPollRepositoryJson([], { isFork: true, parent }), }), - batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }), + batchPollStatusJson({ + t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }), + origin0: { defaultBranchRef: { name: "main" } }, + }), batchPollStatusJson({ t0: batchPollChecksAliasJson([ { __typename: "StatusContext", context: "ci", state: "SUCCESS" }, ]), }), - batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }), + batchPollStatusJson({ + t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }), + origin0: { defaultBranchRef: { name: "main" } }, + }), ]); const service = createGitHubService({ ttlMs: 0, @@ -1465,6 +1580,9 @@ describe("ForgeService", () => { expect(runner.calls[1]?.args[3]).toContain( 't0: repository(owner: "upstream", name: "widgets")', ); + expect(runner.calls[1]?.args[3]).toContain( + 'origin0: repository(owner: "forkowner", name: "widgets")', + ); expect(statuses).toEqual([ expect.objectContaining({ number: 42, repoOwner: "upstream", checksStatus: "success" }), ]); @@ -3219,6 +3337,30 @@ describe("ForgeService", () => { }); }); + it.each([ + ["main", "CLOSED"], + ["master", "MERGED"], + ])("hides a %s PR on the default branch in a direct read (state %s)", async (headRef, state) => { + const historical = currentPullRequestJson({ + headRefName: headRef, + headRepositoryOwner: { login: "acme" }, + state, + }); + const runner = createScriptedRunner([ + historical, + JSON.stringify({ owner: { login: "acme" }, defaultBranchRef: { name: headRef } }), + JSON.stringify([JSON.parse(historical)]), + ]); + const service = createGitHubService({ + runner: runner.runner, + resolveGhPath: async () => "/usr/bin/gh", + }); + + await expect( + service.getCurrentPullRequestStatus({ cwd: "/repo", headRef }), + ).resolves.toBeNull(); + }); + it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => { const headSha = "2222222222222222222222222222222222222222"; const runner = createRunner([ @@ -3546,7 +3688,7 @@ describe("ForgeService", () => { }); expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([ ["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS], - ["repo", "view", "--json", "owner,name,parent"], + ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], ["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`], ["pr", "view", "41", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS], ["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS], @@ -3778,7 +3920,7 @@ describe("ForgeService", () => { }); expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([ ["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS], - ["repo", "view", "--json", "owner,name,parent"], + ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], ["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`], ["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS], [ @@ -3843,7 +3985,7 @@ describe("ForgeService", () => { ).resolves.toBeNull(); expect(calls.map((call) => call.args)).toEqual([ ["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS], - ["repo", "view", "--json", "owner,name,parent"], + ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], [ "pr", "list", @@ -4691,7 +4833,12 @@ describe("ForgeService", () => { }), ).resolves.toEqual({ url: "https://github.com/acme/repo/pull/7", number: 7 }); - expect(runner.calls[0]?.args).toEqual(["repo", "view", "--json", "owner,name,parent"]); + expect(runner.calls[0]?.args).toEqual([ + "repo", + "view", + "--json", + "owner,name,parent,defaultBranchRef", + ]); expect(runner.calls[1]?.args).toEqual([ "api", "-X", @@ -4765,7 +4912,7 @@ describe("ForgeService", () => { expect(readFakeGitHubCliLog(fixture.logPath)).toEqual( expect.arrayContaining([ "auth status --hostname github.acme.internal|", - "repo view --json owner,name,parent|github.acme.internal", + "repo view --json owner,name,parent,defaultBranchRef|github.acme.internal", "api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal", ]), ); @@ -4810,7 +4957,7 @@ describe("ForgeService", () => { ).toHaveLength(2); expect(log).toEqual( expect.arrayContaining([ - "repo view --json owner,name,parent|github.acme.internal", + "repo view --json owner,name,parent,defaultBranchRef|github.acme.internal", "api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal", ]), ); diff --git a/packages/server/src/services/github-service.ts b/packages/server/src/services/github-service.ts index 04731b63d2..cdb701ffb3 100644 --- a/packages/server/src/services/github-service.ts +++ b/packages/server/src/services/github-service.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { isGitHubHost, + parseGitHubRemoteIdentity, parseGitHubRemoteUrl, parseGitRemoteLocation, } from "@getpaseo/protocol/git-remote"; @@ -26,6 +27,7 @@ import { computeChecksStatus, compareTimelineItems, createUnavailableSearchResult, + isOnDefaultBranch, normalizeForgeSearchKinds, parseOptionalTime, } from "./forge-service.js"; @@ -33,6 +35,7 @@ import type { CheckAnnotation, CheckDetails, CheckFailedJob, + CurrentPullRequestLookup, CurrentPullRequestStatus, DisablePullRequestAutoMergeOptions, EnablePullRequestAutoMergeOptions, @@ -445,7 +448,11 @@ const PullRequestTimelineGraphqlSchema = z.object({ .optional(), }); -const GitHubRepoViewSchema = z.object({ +const GitHubDefaultBranchSchema = z.object({ + defaultBranchRef: z.object({ name: z.string() }).nullish(), +}); + +const GitHubRepoViewSchema = GitHubDefaultBranchSchema.extend({ owner: z .object({ login: z.string().optional(), @@ -656,7 +663,7 @@ const BatchPollPrNodeSchema = z.object({ isInMergeQueue: z.boolean().optional().catch(false), }); -const BatchPollRepositorySchema = z.object({ +const BatchPollRepositorySchema = GitHubDefaultBranchSchema.extend({ owner: z.object({ login: z.string().optional() }).nullable().optional().catch(null), isFork: z.boolean().optional().catch(false), parent: z @@ -778,9 +785,7 @@ function graphqlString(value: string): string { return JSON.stringify(value); } -function buildBatchPullRequestStatusQuery( - entries: Array<{ owner: string; name: string; headRef: string }>, -): string { +function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): string { const aliases = entries.map( (entry, index) => ` ${batchAlias(index)}: repository(owner: ${graphqlString( entry.owner, @@ -788,6 +793,9 @@ function buildBatchPullRequestStatusQuery( owner { login } + defaultBranchRef { + name + } isFork parent { owner { @@ -801,7 +809,7 @@ function buildBatchPullRequestStatusQuery( rebaseMergeAllowed viewerDefaultMergeMethod pullRequests(headRefName: ${graphqlString( - entry.headRef, + entry.target.headRef, )}, first: ${BATCH_PR_CANDIDATE_LIMIT}, orderBy: {field: CREATED_AT, direction: DESC}) { nodes { ...PaseoPollPullRequest @@ -809,13 +817,26 @@ function buildBatchPullRequestStatusQuery( } }`, ); + const originAliases = entries.flatMap((entry, index) => + entry.owner === entry.originOwner && entry.name === entry.originName + ? [] + : [ + ` origin${index}: repository(owner: ${graphqlString( + entry.originOwner, + )}, name: ${graphqlString(entry.originName)}) { + defaultBranchRef { + name + } + }`, + ], + ); return `query PaseoBatchPullRequestStatus { rateLimit { limit remaining resetAt } -${aliases.join("\n")} +${[...aliases, ...originAliases].join("\n")} }\n${BATCH_PR_STATUS_FRAGMENT}`; } @@ -959,6 +980,11 @@ interface GitHubServiceDependencies { * per invocation. */ resolveRepoSlug: (cwd: string) => Promise; + /** + * owner/name of the origin remote on any host: an SSH alias or Enterprise + * host included, which `resolveRepoSlug` leaves to `gh`. + */ + resolveOriginRepository: (cwd: string) => Promise; } export interface GitHubCommandRunnerOptions { @@ -1050,6 +1076,7 @@ interface CreateGitHubServiceOptions { now?: () => number; resolveRepoHost?: (cwd: string) => Promise; resolveRepoSlug?: (cwd: string) => Promise; + resolveOriginRepository?: (cwd: string) => Promise; } type PullRequestCheckRunNode = z.infer; @@ -1069,11 +1096,7 @@ interface InFlightCacheEntry { force: boolean; } -interface GitHubPollTarget { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; +interface GitHubPollTarget extends CurrentPullRequestLookup { retainCount: number; /** Absolute due time on the shared poll grid; null while a poll is in flight. */ nextDueAt: number | null; @@ -1132,6 +1155,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G now: options.now ?? Date.now, resolveRepoHost: options.resolveRepoHost ?? resolveGitHubEnterpriseHost, resolveRepoSlug: options.resolveRepoSlug ?? resolveGitHubSlugFromOrigin, + resolveOriginRepository: options.resolveOriginRepository ?? resolveOriginRepositoryPath, }; // A resolved enterprise host is cached permanently; a null resolution (no // host, or the auth probe said no) expires so `gh auth login --hostname` @@ -1356,12 +1380,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G }); } - function getPollTargetKey(target: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - }): string { + function getPollTargetKey(target: CurrentPullRequestLookup): string { return buildCacheKey({ cwd: target.cwd, method: "getCurrentPullRequestStatus", @@ -1369,18 +1388,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: target.headRef, headSha: target.headSha, headRepositoryOwner: target.headRepositoryOwner, + currentBranch: target.currentBranch, }, }); } - function updatePollTargetAfterSuccess(update: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - status: CurrentPullRequestStatus | null; - notify: boolean; - }): void { + function updatePollTargetAfterSuccess( + update: CurrentPullRequestLookup & { + status: CurrentPullRequestStatus | null; + notify: boolean; + }, + ): void { const target = pollTargets.get(getPollTargetKey(update)); if (!target) { return; @@ -1630,13 +1648,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G if (!firstEntry) { return; } - const query = buildBatchPullRequestStatusQuery( - addressedEntries.map((entry) => ({ - owner: entry.owner, - name: entry.name, - headRef: entry.target.headRef, - })), - ); + const query = buildBatchPullRequestStatusQuery(addressedEntries); const args = ["api", "graphql", "-f", `query=${query}`]; const response = await loadGitHubPollBatchResponse({ entries: addressedEntries, @@ -1752,6 +1764,18 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G } continue; } + if ( + isTerminalOnDefaultBranch(entry, node, repository.data, input.aliases[`origin${index}`]) + ) { + finalizeBatchPollTarget({ + entry, + node: null, + repository: repository.data, + rollup: null, + startedAt: input.startedAt, + }); + continue; + } const frozenKey = node.state !== "OPEN" && node.headRefOid.length > 0 ? `${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}` @@ -1778,6 +1802,22 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return distribution; } + function isTerminalOnDefaultBranch( + entry: GitHubBatchPollEntry, + node: BatchPollPrNode, + repository: BatchPollRepository, + originAlias: unknown, + ): boolean { + if (node.state === "OPEN") { + return false; + } + const origin = + entry.owner === entry.originOwner && entry.name === entry.originName + ? repository + : GitHubDefaultBranchSchema.safeParse(originAlias).data; + return isOnDefaultBranch(entry.target, origin?.defaultBranchRef?.name); + } + function addressGitHubBatchEntry(entry: GitHubBatchPollEntry): GitHubBatchPollEntry { const redirect = pollRepositoryRedirects.get(batchRepositoryRedirectKey(entry)); return redirect @@ -1955,25 +1995,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G ); status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null; } - const cacheKey = buildCacheKey({ - cwd: entry.target.cwd, - method: "getCurrentPullRequestStatus", - args: { - headRef: entry.target.headRef, - headSha: entry.target.headSha, - headRepositoryOwner: entry.target.headRepositoryOwner, - }, - }); + const cacheKey = getPollTargetKey(entry.target); // A direct or forced read can finish between this batch becoming due and // its checks query returning. Its cache write is newer than this cycle, so // converge on it instead of overwriting fresher data with the batch's. const existing = cache.get(cacheKey); if (existing && existing.expiresAt - ttlMs > input.startedAt) { updatePollTargetAfterSuccess({ - cwd: entry.target.cwd, - headRef: entry.target.headRef, - headSha: entry.target.headSha, - headRepositoryOwner: entry.target.headRepositoryOwner, + ...entry.target, status: existing.value as CurrentPullRequestStatus | null, notify: true, }); @@ -1983,10 +2012,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G // between polls reuse the batch result instead of spawning gh again. cache.set(cacheKey, { value: status, cwd: entry.target.cwd, expiresAt: deps.now() + ttlMs }); updatePollTargetAfterSuccess({ - cwd: entry.target.cwd, - headRef: entry.target.headRef, - headSha: entry.target.headSha, - headRepositoryOwner: entry.target.headRepositoryOwner, + ...entry.target, status, notify: true, }); @@ -1999,6 +2025,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: target.headRef, headSha: target.headSha, headRepositoryOwner: target.headRepositoryOwner, + currentBranch: target.currentBranch, reason: "self-heal-github", }); } catch (error) { @@ -2165,14 +2192,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, }, readOptions: input, load: async () => { - const status = await resolveCurrentPullRequestView({ + const status = await loadCurrentPullRequestView({ cwd: input.cwd, headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, + resolveOriginRepo: () => resolveRepoSlugCached(input.cwd), run, }); return addCurrentPullRequestGithubFacts({ cwd: input.cwd, status, run }); @@ -2183,6 +2213,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, status, notify: input.reason === "self-heal-github", }); @@ -2543,6 +2574,26 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return { success: true }; }, + getReferenceRepository(input) { + return cached({ + cwd: input.cwd, + method: "getReferenceRepository", + args: {}, + readOptions: input, + load: async () => { + const repo = await deps.resolveOriginRepository(input.cwd); + if (!repo) { + return null; + } + // A failed lookup must reject: "no parent" is cached as a final answer. + const view = await readGitHubRepoView({ cwd: input.cwd, repo, run }); + const parentOwner = view.parent?.owner?.login; + const parentName = view.parent?.name; + return parentOwner && parentName ? `${parentOwner}/${parentName}` : null; + }, + }); + }, + isAuthenticated(input) { return cached({ cwd: input.cwd, @@ -2575,6 +2626,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, retainCount: 0, nextDueAt: null, pollCycleStartedAt: null, @@ -2956,13 +3008,35 @@ function isGitHubRateLimitError(error: unknown): boolean { ); } -async function resolveCurrentPullRequestView(options: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; -}): Promise { +async function loadCurrentPullRequestView( + options: CurrentPullRequestLookup & { + resolveOriginRepo(): Promise; + run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; + }, +): Promise { + let repoRead: ReturnType | undefined; + const readRepo = () => (repoRead ??= getGitHubRepoView(options)); + const status = await resolveCurrentPullRequestView({ ...options, readRepo }); + if (!status || status.state === "open") { + return status; + } + + const originRepo = await options.resolveOriginRepo(); + const repo = await repoRead; + const repoName = repo?.owner?.login && repo.name ? `${repo.owner.login}/${repo.name}` : null; + const origin = + originRepo && originRepo.toLowerCase() !== repoName?.toLowerCase() + ? await getGitHubRepoView({ ...options, repo: originRepo }) + : await readRepo(); + return isOnDefaultBranch(options, origin?.defaultBranchRef?.name) ? null : status; +} + +async function resolveCurrentPullRequestView( + options: CurrentPullRequestLookup & { + readRepo(): Promise | null>; + run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; + }, +): Promise { const viewCandidate = await tryCurrentPullRequestView(options); const viewMatch = viewCandidate ? pickPullRequestCandidate({ @@ -2979,7 +3053,7 @@ async function resolveCurrentPullRequestView(options: { let headRepositoryOwner = options.headRepositoryOwner; if (!headRepositoryOwner) { - const repo = await getGitHubRepoView(options); + const repo = await options.readRepo(); const forkOwner = repo?.owner?.login; const parentOwner = repo?.parent?.owner?.login; const parentName = repo?.parent?.name; @@ -3224,20 +3298,53 @@ async function resolveGitHubSlugFromOrigin(cwd: string): Promise return parseGitHubRemoteUrl(stdout.trim())?.repo ?? null; } -async function getGitHubRepoView(options: { - cwd: string; - run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; -}): Promise | null> { - const args = ["repo", "view", "--json", "owner,name,parent"]; +async function resolveOriginRepositoryPath(cwd: string): Promise { + let stdout: string; try { - const stdout = await options.run(args, { - cwd: options.cwd, - }); - return parseGitHubJsonOutput(stdout, GitHubRepoViewSchema, { - args, - cwd: options.cwd, - emptyFallback: "{}", - }); + ({ stdout } = await runGitCommand(["config", "--get", "remote.origin.url"], { + cwd, + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, + timeout: GIT_ORIGIN_URL_READ_TIMEOUT_MS, + })); + } catch { + return null; + } + const location = parseGitRemoteLocation(stdout.trim()); + return location ? (parseGitHubRemoteIdentity(location.path)?.repo ?? null) : null; +} + +interface GitHubRepoViewOptions { + cwd: string; + /** owner/name to ask about; `gh` picks the default repository for the directory when absent. */ + repo?: string; + run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; +} + +async function readGitHubRepoView( + options: GitHubRepoViewOptions, +): Promise> { + const args = [ + "repo", + "view", + ...(options.repo ? [options.repo] : []), + "--json", + "owner,name,parent,defaultBranchRef", + ]; + const stdout = await options.run(args, { + cwd: options.cwd, + }); + return parseGitHubJsonOutput(stdout, GitHubRepoViewSchema, { + args, + cwd: options.cwd, + emptyFallback: "{}", + }); +} + +async function getGitHubRepoView( + options: GitHubRepoViewOptions, +): Promise | null> { + try { + return await readGitHubRepoView(options); } catch (error) { // A missing CLI or an auth failure must surface as its typed class so the // caller reports the real problem; only a genuine "not a resolvable repo" diff --git a/packages/server/src/services/gitlab-service.test.ts b/packages/server/src/services/gitlab-service.test.ts index 81e8bc966d..cb2034a2c9 100644 --- a/packages/server/src/services/gitlab-service.test.ts +++ b/packages/server/src/services/gitlab-service.test.ts @@ -260,6 +260,38 @@ const DISCUSSIONS = [ }, ]; +describe("createGitLabService getReferenceRepository", () => { + it("names the project a fork was forked from, asking about the origin project explicitly", async () => { + const { service, calls } = makeService(() => + ok( + JSON.stringify({ + path_with_namespace: "example-group/example-project", + forked_from_project: { path_with_namespace: "upstream-group/sub/example-project" }, + }), + ), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBe( + "upstream-group/sub/example-project", + ); + expect(calls).toEqual([["api", "projects/example-group%2Fexample-project"]]); + }); + + it("rejects when glab api answers with an error body", async () => { + const { service } = makeService(() => ok(JSON.stringify({ message: "404 Project Not Found" }))); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).rejects.toThrow(); + }); + + it("is null for a project that is not a fork", async () => { + const { service } = makeService(() => + ok(JSON.stringify({ path_with_namespace: "example-group/example-project" })), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBeNull(); + }); +}); + describe("createGitLabService", () => { it("maps a glab merge request view to the neutral current PR status", async () => { const { service, calls } = makeService((args) => @@ -357,6 +389,26 @@ describe("createGitLabService", () => { expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]); }); + it("hides a historical MR on the project's default branch", async () => { + const historical = { ...OPEN_MR, state: "merged", source_branch: "trunk" }; + const { service } = makeService((args) => { + if (args[1] === "list") return ok(JSON.stringify([historical])); + if (args[1] === "view") return ok(JSON.stringify(historical)); + if (args[0] === "api" && args[1] === "projects/example-group%2Fexample-project") { + return ok( + JSON.stringify({ + path_with_namespace: "example-group/example-project", + default_branch: "trunk", + }), + ); + } + return ok("{}"); + }); + await expect( + service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }), + ).resolves.toBeNull(); + }); + it("keeps a merged MR when its remote head advances beyond the checkout", async () => { const stale = { ...OPEN_MR, diff --git a/packages/server/src/services/gitlab-service.ts b/packages/server/src/services/gitlab-service.ts index 4fde7173f9..25737e321e 100644 --- a/packages/server/src/services/gitlab-service.ts +++ b/packages/server/src/services/gitlab-service.ts @@ -16,6 +16,7 @@ import { compareTimelineItems, createUnavailableSearchResult, normalizeForgeSearchKinds, + isOnDefaultBranch, parseOptionalTime, } from "./forge-service.js"; import type { @@ -249,6 +250,17 @@ const GitLabApprovalsSchema = z }) .passthrough(); +const GitLabProjectSchema = z + .object({ + path_with_namespace: z.string(), + default_branch: z.string().nullish(), + forked_from_project: z + .object({ path_with_namespace: z.string().optional() }) + .nullable() + .optional(), + }) + .passthrough(); + type GitLabMergeRequest = z.infer; type GitLabIssue = z.infer; type GitLabNote = z.infer; @@ -1132,6 +1144,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F return issues.map(toIssueSummary); } + async function readOriginProject(cwd: string) { + const remoteUrl = await resolveRemoteUrl(cwd); + const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null; + if (!projectPath) { + return null; + } + return runJson( + ["api", `projects/${encodeURIComponent(projectPath)}`], + { cwd: cwd }, + GitLabProjectSchema, + ); + } + return { async isAuthenticated(input: { cwd: string } & ForgeReadOptions): Promise { const glabPath = await resolveGlab(); @@ -1151,12 +1176,23 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F } }, + async getReferenceRepository(input): Promise { + const project = await readOriginProject(input.cwd); + return project?.forked_from_project?.path_with_namespace ?? null; + }, + async getCurrentPullRequestStatus(input): Promise { try { const mr = await resolveCurrentMergeRequest(input.cwd, input.headRef, input.headSha); if (!mr) { return null; } + if (mapMergeRequestState(mr.state) !== "open") { + const project = await readOriginProject(input.cwd).catch(() => null); + if (isOnDefaultBranch(input, project?.default_branch)) { + return null; + } + } const [approvals, pipelineChecks] = await Promise.all([ fetchApprovals(input.cwd, mr), fetchPipelineChecks(input.cwd, mr), diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index c61ead0628..7e548552b0 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -19,7 +19,7 @@ import { type TerminalWorkerRecord, } from "./terminal-worker-record.js"; import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js"; -import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js"; +import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js"; import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, TERMINAL_WORKER_PROTOCOL_VERSION, @@ -700,23 +700,25 @@ function runWorker(argv: string[]): void { } async function start(): Promise { - const socketPath = resolveTerminalWorkerSocketPath({ + const { socketPath, listener } = await listenOnTerminalWorkerSocket({ paseoHome: args.paseoHome, workerPid: process.pid, recordId: args.recordId, + listen: (candidatePath) => { + if (process.platform !== "win32") { + rmSync(candidatePath, { force: true }); + } + const listening = createServer(handleConnection); + return new Promise((resolve, reject) => { + listening.once("error", reject); + listening.listen(candidatePath, () => { + listening.off("error", reject); + resolve(listening); + }); + }); + }, }); - if (process.platform !== "win32") { - rmSync(socketPath, { force: true }); - } - const listening = createServer(handleConnection); - await new Promise((resolve, reject) => { - listening.once("error", reject); - listening.listen(socketPath, () => { - listening.off("error", reject); - resolve(); - }); - }); - server = listening; + server = listener; if (process.platform !== "win32") { chmodSync(socketPath, PRIVATE_FILE_MODE); } diff --git a/packages/server/src/terminal/terminal-worker-reaper.test.ts b/packages/server/src/terminal/terminal-worker-reaper.test.ts index ef8d4fe487..753db72e0a 100644 --- a/packages/server/src/terminal/terminal-worker-reaper.test.ts +++ b/packages/server/src/terminal/terminal-worker-reaper.test.ts @@ -577,20 +577,27 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { // chmod cannot make a file unreadable to root. describe.skipIf(process.getuid?.() === 0)("a record that cannot be opened for a moment", () => { - it("still ends a live worker it names, then retires the record", async () => { - const home = makeHome(); + // The reaper signals a worker only once its socket accepts, so wait for the listen. + async function spawnListeningWorker(socketPath: string): Promise { const worker = spawn( process.execPath, [ "-e", - `require("node:net").createServer(() => {}).listen(${JSON.stringify(path.join(home, "live-record-under-test.sock"))});setInterval(() => {}, 1e9)`, + `require("node:net").createServer(() => {}).listen(${JSON.stringify(socketPath)}, () => process.stdout.write("listening\\n"));setInterval(() => {}, 1e9)`, "--", "--paseo-terminal-worker", "record-under-test", ], - { detached: true, stdio: "ignore" }, + { detached: true, stdio: ["ignore", "pipe", "ignore"] }, ); children.push(worker); + await new Promise((resolve) => worker.stdout!.once("data", resolve)); + return worker; + } + + it("still ends a live worker it names, then retires the record", async () => { + const home = makeHome(); + const worker = await spawnListeningWorker(path.join(home, "live-record-under-test.sock")); const recordPath = writeRecord(home, { pid: worker.pid!, socketPath: path.join(home, "live-record-under-test.sock"), @@ -632,18 +639,7 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { it("still reports a record that stays unreadable, and signals nothing it names", async () => { const home = makeHome(); - const worker = spawn( - process.execPath, - [ - "-e", - `require("node:net").createServer(() => {}).listen(${JSON.stringify(path.join(home, "live-record-under-test.sock"))});setInterval(() => {}, 1e9)`, - "--", - "--paseo-terminal-worker", - "record-under-test", - ], - { detached: true, stdio: "ignore" }, - ); - children.push(worker); + const worker = await spawnListeningWorker(path.join(home, "live-record-under-test.sock")); const recordPath = writeRecord(home, { pid: worker.pid!, socketPath: path.join(home, "live-record-under-test.sock"), diff --git a/packages/server/src/terminal/terminal-worker-runtime.ts b/packages/server/src/terminal/terminal-worker-runtime.ts index 7ee0696478..1f24e73b0d 100644 --- a/packages/server/src/terminal/terminal-worker-runtime.ts +++ b/packages/server/src/terminal/terminal-worker-runtime.ts @@ -13,6 +13,7 @@ import { import { createRequire } from "node:module"; import { access, readdir, rm } from "node:fs/promises"; import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import { ensurePrivateDirectory } from "../server/private-files.js"; import { listTerminalWorkerRecords, terminalWorkerDirectory } from "./terminal-worker-record.js"; @@ -193,6 +194,28 @@ export function prepareTerminalWorkerRuntime(input: { return entry; } +// Windows keeps a just-exited worker's files open for a moment, so a delete that fails with one +// of these codes is retried for a short window. Each attempt is a single rm: rm's own maxRetries +// repeats at every directory level, so a file that stays locked deep in node-pty would hold +// daemon start and stop far past any window. +const TRANSIENT_REMOVE_ERRORS = new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]); +const TRANSIENT_REMOVE_WINDOW_MS = 3_000; +const TRANSIENT_REMOVE_PAUSE_MS = 100; + +async function removeCopy(directory: string): Promise { + const deadline = Date.now() + TRANSIENT_REMOVE_WINDOW_MS; + for (;;) { + try { + await rm(directory, { recursive: true, force: true }); + return; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!code || !TRANSIENT_REMOVE_ERRORS.has(code) || Date.now() >= deadline) throw error; + await delay(TRANSIENT_REMOVE_PAUSE_MS); + } + } +} + export interface PruneTerminalWorkerRuntimesResult { removed: string[]; /** Copies that could not be deleted (a worker that just exited can still hold files on Windows). */ @@ -236,7 +259,7 @@ export async function pruneTerminalWorkerRuntimes( ) continue; try { - await rm(directory, { recursive: true, force: true }); + await removeCopy(directory); result.removed.push(directory); } catch (error) { result.failed.push({ diff --git a/packages/server/src/terminal/terminal-worker-socket-path.test.ts b/packages/server/src/terminal/terminal-worker-socket-path.test.ts index 6017177fcf..786f095886 100644 --- a/packages/server/src/terminal/terminal-worker-socket-path.test.ts +++ b/packages/server/src/terminal/terminal-worker-socket-path.test.ts @@ -1,10 +1,11 @@ import { afterEach, describe, expect, it } from "vitest"; import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"; -import { createServer } from "node:net"; +import { createServer, type Server } from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; import { isPlatform } from "../test-utils/platform.js"; import { + listenOnTerminalWorkerSocket, resolveTerminalWorkerSocketPath, TerminalWorkerSocketPathError, } from "./terminal-worker-socket-path.js"; @@ -25,7 +26,36 @@ function longHome(root: string): string { return home; } -afterEach(() => { +const openServers: Server[] = []; + +function listenFor(socketPath: string): Promise { + const server = createServer(); + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => { + openServers.push(server); + resolve(server); + }); + }); +} + +// Stands in for a filesystem that passes the directory checks but refuses AF_UNIX bind, as AFS +// does with EPERM. +function refuseBindUnder(directory: string, code: string) { + return (socketPath: string): Promise => { + if (socketPath.startsWith(directory + path.sep)) { + return Promise.reject( + Object.assign(new Error(`listen ${code}: ${socketPath}`), { code, syscall: "listen" }), + ); + } + return listenFor(socketPath); + }; +} + +afterEach(async () => { + await Promise.all( + openServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))), + ); for (const dir of temporaryDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } @@ -142,6 +172,66 @@ describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => { }); }); +describe.skipIf(isPlatform("win32"))("terminal worker socket listen", () => { + it("falls back to the next directory when the home's filesystem refuses the bind", async () => { + const home = makeDir("tw-b-", "/tmp"); + const tmpDir = makeDir("tw-t-", "/tmp"); + const homeSocketDirectory = path.join(home, "terminal-worker", "sock"); + const { socketPath, listener } = await listenOnTerminalWorkerSocket({ + paseoHome: home, + recordId: "test", + workerPid: 11, + tmpDir, + listen: refuseBindUnder(homeSocketDirectory, "EPERM"), + }); + expect(path.dirname(socketPath)).toBe(path.join(tmpDir, `paseo-${process.getuid!()}`)); + expect(listener.address()).toBe(socketPath); + }); + + it("throws a listen error that does not mean the filesystem refuses sockets", async () => { + const home = makeDir("tw-u-", "/tmp"); + const homeSocketDirectory = path.join(home, "terminal-worker", "sock"); + await expect( + listenOnTerminalWorkerSocket({ + paseoHome: home, + recordId: "test", + workerPid: 12, + tmpDir: makeDir("tw-t-", "/tmp"), + listen: refuseBindUnder(homeSocketDirectory, "EADDRINUSE"), + }), + ).rejects.toMatchObject({ code: "EADDRINUSE" }); + }); + + it("names every candidate's bind error when no directory accepts a socket", async () => { + const home = makeDir("tw-n-", "/tmp"); + const tmpDir = makeDir("tw-t-", "/tmp"); + let caught: unknown; + try { + await listenOnTerminalWorkerSocket({ + paseoHome: home, + recordId: "test", + workerPid: 13, + tmpDir, + listen: refuseBindUnder("", "EPERM"), + }); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError); + const rejected = (caught as TerminalWorkerSocketPathError).rejected; + expect(rejected.slice(0, 2)).toEqual([ + expect.objectContaining({ + path: expect.stringContaining(path.join(home, "terminal-worker", "sock")), + reason: "cannot bind a socket here (EPERM)", + }), + expect.objectContaining({ + path: expect.stringContaining(path.join(tmpDir, `paseo-${process.getuid!()}`)), + reason: "cannot bind a socket here (EPERM)", + }), + ]); + }); +}); + it("uses a separate socket for each record even when its pid is reused", () => { const paseoHome = makeDir("tw-id-"); const first = resolveTerminalWorkerSocketPath({ paseoHome, workerPid: 42, recordId: "old" }); diff --git a/packages/server/src/terminal/terminal-worker-socket-path.ts b/packages/server/src/terminal/terminal-worker-socket-path.ts index d9a153c598..0ad94a1ced 100644 --- a/packages/server/src/terminal/terminal-worker-socket-path.ts +++ b/packages/server/src/terminal/terminal-worker-socket-path.ts @@ -14,6 +14,9 @@ const SOCKET_PATH_BYTE_BUDGET: Partial> = { }; const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103; const OWNER_ONLY_MODE = 0o700; +// Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other +// network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM. +const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]); export interface TerminalWorkerSocketPathInput { paseoHome: string; @@ -24,6 +27,16 @@ export interface TerminalWorkerSocketPathInput { uid?: number; } +export interface TerminalWorkerSocketListenInput extends TerminalWorkerSocketPathInput { + /** Binds a fresh listener at the path, removing any stale socket there first. */ + listen: (socketPath: string) => Promise; +} + +export interface TerminalWorkerSocketListener { + socketPath: string; + listener: T; +} + export interface RejectedSocketCandidate { path: string; byteLength: number; @@ -36,7 +49,7 @@ export class TerminalWorkerSocketPathError extends Error { constructor(rejected: RejectedSocketCandidate[], budget: number) { super( [ - `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`, + `No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`, ...rejected.map( (candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`, ), @@ -57,18 +70,73 @@ export function terminalWorkerSocketId(paseoHome: string, workerPid: number): st * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX * tries $PASEO_HOME/terminal-worker/sock, then /paseo-, then /tmp/paseo-. * A shared root is never chmodded: an existing directory there is used only when it is a real - * directory owned by this user with mode 0700. + * directory owned by this user with mode 0700. It does not bind; the worker listens through + * `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket. */ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string { const platform = input.platform ?? process.platform; - const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId; if (platform === "win32") { - return `\\\\.\\pipe\\paseo-tw-${id}`; + return windowsPipePath(input); } + const budget = socketPathByteBudget(platform); + const rejected: RejectedSocketCandidate[] = []; + for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) { + return candidate.path; + } + throw new TerminalWorkerSocketPathError(rejected, budget); +} +/** + * Listens on the first candidate path that accepts a socket. A bind refused by the filesystem + * moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is. + */ +export async function listenOnTerminalWorkerSocket( + input: TerminalWorkerSocketListenInput, +): Promise> { + const { listen } = input; + const platform = input.platform ?? process.platform; + if (platform === "win32") { + const socketPath = windowsPipePath(input); + return { socketPath, listener: await listen(socketPath) }; + } + const budget = socketPathByteBudget(platform); + const rejected: RejectedSocketCandidate[] = []; + for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) { + try { + return { socketPath: candidate.path, listener: await listen(candidate.path) }; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error; + rejected.push({ + path: candidate.path, + byteLength: candidate.byteLength, + reason: `cannot bind a socket here (${code})`, + }); + } + } + throw new TerminalWorkerSocketPathError(rejected, budget); +} + +function windowsPipePath(input: TerminalWorkerSocketPathInput): string { + return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`; +} + +function socketFileId(input: TerminalWorkerSocketPathInput): string { + return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId; +} + +function socketPathByteBudget(platform: NodeJS.Platform): number { + return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET; +} + +/** Yields each candidate that fits the budget in an owner-only directory, in order. */ +function* eligibleUnixSocketPaths( + input: TerminalWorkerSocketPathInput, + budget: number, + rejected: RejectedSocketCandidate[], +): Generator<{ path: string; byteLength: number }> { const uid = input.uid ?? process.getuid?.() ?? 0; - const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET; - const fileName = `tw-${id}.sock`; + const fileName = `tw-${socketFileId(input)}.sock`; const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock"); const candidates: Array<{ directory: string; prepare: () => string | null }> = [ { @@ -87,7 +155,6 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI }), ]; - const rejected: RejectedSocketCandidate[] = []; const seen = new Set(); for (const candidate of candidates) { const socketPath = path.join(candidate.directory, fileName); @@ -108,9 +175,8 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI rejected.push({ path: socketPath, byteLength, reason: problem }); continue; } - return socketPath; + yield { path: socketPath, byteLength }; } - throw new TerminalWorkerSocketPathError(rejected, budget); } function prepareSharedRootDirectory(directory: string, uid: number): string | null { diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index e57e413b4c..6864c76152 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1690,8 +1690,10 @@ it("leaves a worker from a newer Paseo running, reports it incompatible, and clo await manager.closeTerminals(); - expect(isProcessAlive(newer.workerPid)).toBe(false); expect(isProcessAlive(newer.programPid)).toBe(false); + // Cleanup counts the worker gone once its socket refuses connections, which happens before + // its process exits. + await waitForCondition(() => !isProcessAlive(newer.workerPid), 5000); expect(await workerRecords(paseoHome)).toEqual([]); }); diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index 075f7ebda1..ef240fa63c 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -30,6 +30,7 @@ import { getCheckoutShortstat, getPullRequestStatus, getCheckoutStatus, + getCheckoutWorktreeState, checkoutResolvedBranch, listBranchSuggestions, setCheckoutBaseBranch, @@ -177,6 +178,7 @@ function createPullRequestStatus(overrides?: Partial) interface RequestedPullRequestTarget { headRef: string; + currentBranch?: string; headSha?: string; headRepositoryOwner?: string; } @@ -193,6 +195,7 @@ function createGitHubServiceRecordingPullRequestTargets( github.getCurrentPullRequestStatus = async (request) => { options.requestedTargets.push({ headRef: request.headRef, + ...(request.currentBranch ? { currentBranch: request.currentBranch } : {}), ...(request.headSha ? { headSha: request.headSha } : {}), ...(request.headRepositoryOwner ? { headRepositoryOwner: request.headRepositoryOwner } : {}), }); @@ -572,6 +575,15 @@ describe("checkout git utilities", () => { expect(message).toBe("update file"); }); + it("counts untracked files as dirty when the repository hides them from status", async () => { + execFileSync("git", ["config", "status.showUntrackedFiles", "no"], { cwd: repoDir }); + writeFileSync(join(repoDir, "new-file.txt"), "not yet added\n"); + expect(execFileSync("git", ["status", "--porcelain"], { cwd: repoDir }).toString()).toBe(""); + + expect((await getCheckoutStatus(repoDir)).isDirty).toBe(true); + expect((await getCheckoutWorktreeState(repoDir, {})).isDirty).toBe(true); + }); + it("honors commit signing configuration", async () => { execFileSync("git", ["config", "commit.gpgsign", "true"], { cwd: repoDir }); execFileSync("git", ["config", "gpg.format", "openpgp"], { cwd: repoDir }); @@ -3450,7 +3462,7 @@ const x = 1; { paseoHome }, ); - expect(requestedTargets).toEqual([factsTarget]); + expect(requestedTargets).toEqual([{ ...factsTarget, currentBranch: "tender-parrot" }]); }); it("uses the tracked fork branch for PR worktree status lookup", async () => { @@ -3480,7 +3492,11 @@ const x = 1; const status = await getPullRequestStatus(repoDir, github); expect(requestedTargets).toEqual([ - expect.objectContaining({ headRef: "main", headRepositoryOwner: "chethanuk" }), + expect.objectContaining({ + headRef: "main", + currentBranch: "chethanuk/main", + headRepositoryOwner: "chethanuk", + }), ]); expect(status.status?.number).toBe(345); expect(status.status?.headRefName).toBe("main"); @@ -3511,6 +3527,20 @@ const x = 1; expect(status.status?.state).toBe("closed"); }); + it("looks up PR status again when switching branches at the same commit", async () => { + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); + const requestedTargets: RequestedPullRequestTarget[] = []; + const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets }); + + const feature = await getPullRequestStatus(repoDir, forge); + execFileSync("git", ["checkout", "main"], { cwd: repoDir }); + const main = await getPullRequestStatus(repoDir, forge); + + expect(feature.status?.headRefName).toBe("feature"); + expect(main.status?.headRefName).toBe("main"); + expect(requestedTargets.map(({ headRef }) => headRef)).toEqual(["feature", "main"]); + }); + it("caches PR status results for duplicate lookups", async () => { execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], { diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index 2bb295b371..f465edadb4 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -6,6 +6,7 @@ import { stat as statFile, mkdtemp, copyFile, + utimes, realpath, access, rm, @@ -152,8 +153,12 @@ function createShortstatCache(ttlMs: number) { }); } -function getPullRequestStatusCacheKey(cwd: string, headSha: string | null): string { - return `${resolve(cwd)}\u0000${headSha ?? ""}`; +function getPullRequestStatusCacheKey( + cwd: string, + currentBranch: string | null, + headSha: string | null, +): string { + return `${resolve(cwd)}\u0000${currentBranch ?? ""}\u0000${headSha ?? ""}`; } function rememberPullRequestStatus(cacheKey: string, status: PullRequestStatusResult): void { @@ -1413,12 +1418,17 @@ function resolveOperationBaseRef(input: { return input.storedBaseRef ?? input.requestedBaseRef ?? input.resolvedBaseRef; } +// Untracked files count whatever `status.showUntrackedFiles` says: archive warns from this before +// it removes a worktree, and a file nobody added yet is still work to lose. async function isWorkingTreeDirty(cwd: string, context?: CheckoutContext): Promise { - const { stdout } = await getRunGitCommand(context)(["status", "--porcelain"], { - cwd, - envOverlay: READ_ONLY_GIT_ENV, - logger: context?.logger, - }); + const { stdout } = await getRunGitCommand(context)( + ["status", "--porcelain", "--untracked-files=normal"], + { + cwd, + envOverlay: READ_ONLY_GIT_ENV, + logger: context?.logger, + }, + ); return stdout.trim().length > 0; } @@ -3660,6 +3670,12 @@ export async function prepareAllChangesIndex(cwd: string, baseRef: string) { // write-tree rewrites its index. A private snapshot prevents an index read from // invalidating the observation that requested it. +// +// Git re-reads a file whose stat matches its index entry only when the entry is +// not older than the index file ("racy git"). A fresh copy would be newer than +// every entry, so a same-size edit made in the tick the index was written would +// read as unchanged. The copy takes the source's mtime, read before copying and +// rounded down to the second, so it is never later than the source. export async function snapshotComparisonIndex(cwd: string) { const directory = await mkdtemp(resolve(tmpdir(), "paseo-comparison-index-")); const indexFile = resolve(directory, "index"); @@ -3671,7 +3687,9 @@ export async function snapshotComparisonIndex(cwd: string) { const source = resolveGitRevParsePath(cwd, index.stdout); if (!source) throw new Error("Git did not return an index path"); try { + const { atime, mtimeMs } = await statFile(source); await copyFile(source, indexFile); + await utimes(indexFile, atime, Math.floor(mtimeMs / 1000)); } catch (error) { if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error; await runGitCommand(["read-tree", "--empty"], { @@ -4423,8 +4441,11 @@ export async function getPullRequestStatus( options?: CheckoutReadCacheOptions, context?: CheckoutContext, ): Promise { - const headSha = await getCurrentHeadSha(cwd, context); - const cacheKey = getPullRequestStatusCacheKey(cwd, headSha); + const [headSha, head] = await Promise.all([ + getCurrentHeadSha(cwd, context), + context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context), + ]); + const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha); if (!options?.force) { const cached = pullRequestStatusCache.get(cacheKey); if (cached) { @@ -4437,7 +4458,7 @@ export async function getPullRequestStatus( } } - const lookup = getPullRequestStatusUncached(cwd, forgeService, options, context, headSha) + const lookup = getPullRequestStatusUncached(cwd, forgeService, head, options, context, headSha) .then((status) => { pullRequestStatusCache.set(cacheKey, status); rememberPullRequestStatus(cacheKey, status); @@ -4463,6 +4484,7 @@ export async function getPullRequestStatus( async function getPullRequestStatusUncached( cwd: string, forgeService: ForgeService, + head: string | null, options?: CheckoutReadCacheOptions, context?: CheckoutContext, headSha?: string | null, @@ -4472,18 +4494,16 @@ async function getPullRequestStatusUncached( if (!context?.facts?.isGit) { await requireGitRepo(cwd, context); } - const head = context?.facts?.isGit - ? context.facts.currentBranch - : await getCurrentBranch(cwd, context); if (!head) { return buildPullRequestStatusResult(null, "no_remote"); } try { const resolvedLookupTarget = await resolvePullRequestStatusLookupTarget(cwd, head, context); - const lookupTarget = - headSha && !resolvedLookupTarget.headSha - ? { ...resolvedLookupTarget, headSha } - : resolvedLookupTarget; + const lookupTarget = { + ...resolvedLookupTarget, + ...(headSha && !resolvedLookupTarget.headSha ? { headSha } : {}), + ...(head !== resolvedLookupTarget.headRef ? { currentBranch: head } : {}), + }; let status: CurrentPullRequestStatus | null; if (options?.force) { const reason = options.reason; diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 6a7e43c757..ff77f44bce 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -14,6 +14,7 @@ import { PaseoConfigRawSchema, getWorktreeSetupCommands, getWorktreeTeardownCommands, + getWorktreeTeardownTimeoutMs, } from "./worktree.js"; import { readPaseoConfigForEdit, @@ -295,6 +296,34 @@ describe("paseo config file substrate", () => { expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean", "npm run reset"]); }); + it("reads the teardown time limit and defaults to one minute", async () => { + expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000); + + for (const teardownTimeoutMs of [1, 300_000, 2_147_483_647]) { + writeFileSync( + join(tempDir, "paseo.json"), + JSON.stringify({ worktree: { teardownTimeoutMs } }), + ); + expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(teardownTimeoutMs); + } + }); + + it.each([0, -1000, 1500.5, 2_147_483_648, "90000", null, true, { ms: 90_000 }])( + "falls back to the default teardown time limit for %j and keeps the commands", + async (teardownTimeoutMs) => { + const config = { worktree: { teardown: "npm run clean", teardownTimeoutMs } }; + writeFileSync(join(tempDir, "paseo.json"), JSON.stringify(config)); + + expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000); + expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean"]); + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ + ok: true, + config, + revision: await statPaseoConfigPath(tempDir), + }); + }, + ); + it("writes pretty JSON with a trailing newline when revision matches", async () => { writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "old" } })); const expectedRevision = await statPaseoConfigPath(tempDir); diff --git a/packages/server/src/utils/paseo-config-file.ts b/packages/server/src/utils/paseo-config-file.ts index b8152c4f22..909c7d3dad 100644 --- a/packages/server/src/utils/paseo-config-file.ts +++ b/packages/server/src/utils/paseo-config-file.ts @@ -114,6 +114,12 @@ interface Snapshot { runtime: ReadPaseoConfigResult; } +// How long a caller waits for the filesystem, including time queued behind other roots. +const READ_BUDGET_MS = 5_000; +// Above the roots a busy daemon lists: a listing that visits more roots than this evicts the next one it needs. +const MAX_SNAPSHOTS = 1_024; +const UNAVAILABLE = Symbol("project config unavailable"); + /** Owns config admission, snapshots and daemon read/modify/write ordering for every consumer. */ class ProjectConfigOwner { // A stalled mount retains its slot until the OS returns; never consume the whole fs pool. @@ -166,17 +172,39 @@ class ProjectConfigOwner { this.snapshots.delete(root); this.snapshots.set(root, snapshot); // Worktrees come and go; retain only a bounded set of reusable snapshots. - if (this.snapshots.size > 256) this.snapshots.delete(this.snapshots.keys().next().value!); + if (this.snapshots.size > MAX_SNAPSHOTS) + this.snapshots.delete(this.snapshots.keys().next().value!); return snapshot; } async read(repoRoot: string): Promise { + const checked = await this.check(resolve(repoRoot)); + if (checked === UNAVAILABLE) throw new Error("Project config unavailable"); + return checked; + } + + /** A check the filesystem does not answer in time answers the last config read for that root. */ + async readOrLastKnown(repoRoot: string): Promise { const root = resolve(repoRoot); - return withTimeout( - this.serialized(root, "read", () => this.load(root)), - 5_000, - "Project config unavailable", - ); + const checked = await this.check(root); + if (checked !== UNAVAILABLE) return checked; + const known = this.snapshots.get(root); + if (!known) throw new Error("Project config unavailable"); + return known; + } + + private async check(root: string): Promise { + let budget: ReturnType | undefined; + try { + return await Promise.race([ + this.serialized(root, "read", () => this.load(root)), + new Promise((settle) => { + budget = setTimeout(settle, READ_BUDGET_MS, UNAVAILABLE); + }), + ]); + } finally { + clearTimeout(budget); + } } private async load(root: string): Promise { @@ -242,7 +270,7 @@ class ProjectConfigOwner { async write(input: WritePaseoConfigForEditInput): Promise { const root = resolve(input.repoRoot); return this.serialized(root, "write", async () => { - const { edit: parsed } = await validateConfig(input.config); + const { edit: parsed, runtime } = await validateConfig(input.config); if (!parsed.success) return { ok: false, error: { code: "invalid_project_config" } }; const content = `${JSON.stringify(parsed.data, null, 2)}\n`; if (Buffer.byteLength(content) > MAX_PASEO_CONFIG_BYTES) { @@ -251,7 +279,8 @@ class ProjectConfigOwner { const tempPath = join(root, `.${PASEO_CONFIG_FILE_NAME}.${process.pid}.${randomUUID()}.tmp`); try { await writeFile(tempPath, content, { flag: "wx" }); - const savedRevision = revision(await stat(tempPath)); + const savedStats = await stat(tempPath); + const savedRevision = revision(savedStats); const currentStats = await inspect(root); if (currentStats) admit(currentStats); const currentRevision = currentStats ? revision(currentStats) : null; @@ -261,7 +290,13 @@ class ProjectConfigOwner { // Serialized against daemon edits. External writers still have the existing // optimistic stat/rename race; revision tokens remain mtime + size. await rename(tempPath, resolvePaseoConfigPath(root)); - this.snapshots.delete(root); + // Remember what was saved without another read, so a late check right after the save + // still has a config to show. A rename that changes ctime only costs the next check a reload. + this.remember(root, { + fingerprint: fingerprint(savedStats), + edit: { ok: true, config: parsed.data, revision: savedRevision }, + runtime: { ok: true, config: runtime }, + }); return { ok: true, config: parsed.data, revision: savedRevision }; } catch { return { ok: false, error: { code: "write_failed" } }; @@ -289,6 +324,18 @@ export async function readPaseoConfig(repoRoot: string): Promise { + try { + return (await projectConfig.readOrLastKnown(repoRoot)).runtime; + } catch (error) { + return { ok: false, configPath: resolvePaseoConfigPath(repoRoot), error }; + } +} + export async function readPaseoConfigForEdit( repoRoot: string, ): Promise { diff --git a/packages/server/src/utils/worktree-shell-selection.test.ts b/packages/server/src/utils/worktree-shell-selection.test.ts index a17d6cd498..62f34174e4 100644 --- a/packages/server/src/utils/worktree-shell-selection.test.ts +++ b/packages/server/src/utils/worktree-shell-selection.test.ts @@ -5,17 +5,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const execFileMock = vi.hoisted(() => vi.fn()); const spawnProcessMock = vi.hoisted(() => vi.fn()); -vi.mock("child_process", async () => { - const actual = await vi.importActual("child_process"); - return { - ...actual, - execFile: execFileMock, - }; -}); - vi.mock("./spawn.js", async () => { const actual = await vi.importActual("./spawn.js"); return { @@ -42,19 +33,7 @@ describe("worktree shell selection", () => { const originalPlatform = process.platform; beforeEach(() => { - execFileMock.mockReset(); spawnProcessMock.mockReset(); - execFileMock.mockImplementation( - ( - _file: string, - _args: string[], - _options: unknown, - callback?: (error: Error | null, stdout: string, stderr: string) => void, - ) => { - callback?.(null, "", ""); - return {}; - }, - ); spawnProcessMock.mockImplementation(createSpawnChildStub); }); @@ -94,8 +73,8 @@ describe("worktree shell selection", () => { branchName: "main", }); - expect(execFileMock).toHaveBeenCalledTimes(1); - expect(execFileMock).toHaveBeenCalledWith( + expect(spawnProcessMock).toHaveBeenCalledTimes(1); + expect(spawnProcessMock).toHaveBeenCalledWith( "powershell", [ "-NoProfile", @@ -105,11 +84,10 @@ describe("worktree shell selection", () => { "-Command", "Write-Output 'teardown'", ], - expect.objectContaining({ cwd: worktreePath }), - expect.any(Function), + expect.objectContaining({ cwd: worktreePath, shell: false }), ); - const execOptions = execFileMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv }; - expect(execOptions.env?.BASH_ENV).toBeUndefined(); + const spawnOptions = spawnProcessMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv }; + expect(spawnOptions.env?.BASH_ENV).toBeUndefined(); } finally { if (originalBashEnv === undefined) { delete process.env.BASH_ENV; diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 35d59cce3f..5ee2ec5b1a 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -1406,6 +1406,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { rmSync(tempDir, { recursive: true, force: true }); }); + it("keeps an otherwise unreachable detached commit after deleting the worktree", async () => { + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "keep-commit", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/keep-commit" }, + paseoHome, + }); + execFileSync("git", ["checkout", "--detach"], { cwd: result.worktreePath }); + writeFileSync(join(result.worktreePath, "file.txt"), "detached change\n"); + execFileSync("git", ["add", "file.txt"], { cwd: result.worktreePath }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], { + cwd: result.worktreePath, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: result.worktreePath, + encoding: "utf8", + }).trim(); + + await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome }); + execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: repoDir }); + execFileSync("git", ["gc", "--prune=now"], { cwd: repoDir }); + expect( + execFileSync("git", ["cat-file", "-t", commit], { cwd: repoDir, encoding: "utf8" }).trim(), + ).toBe("commit"); + }); + it("places, owns, lists, and deletes a worktree outside the legacy root", async () => { // Sibling layout: /wt- diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index f549b461f8..4f0a1d5ef3 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -3,6 +3,7 @@ import { createWorktree as createWorktreePrimitive, deriveWorktreeProjectHash, deletePaseoWorktree, + readWorktreeHead, isPaseoOwnedWorktreeCwd, mapWorkspaceCwdToWorktree, runWorktreeTeardownCommands, @@ -189,6 +190,30 @@ describe("paseo worktree manager", () => { }); }); + it("retains bounded diagnostic text per teardown output stream", async () => { + const limit = 1024 * 1024; + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + teardown: `node -e "process.stdout.write('x'.repeat(${2 * limit})); process.stderr.write('y'.repeat(${2 * limit}))"`, + }, + }), + ); + + const [result] = await runWorktreeTeardownCommands({ + worktreePath: repoDir, + repoRootPath: repoDir, + branchName: "main", + }); + + expect({ + exitCode: result.exitCode, + stdoutLength: result.stdout.length, + stderrLength: result.stderr.length, + }).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit }); + }); + it("rejects paths that are not under the paseo worktrees root", async () => { const outsidePath = join(tempDir, "outside-paseo-home"); mkdirSync(outsidePath, { recursive: true }); @@ -302,6 +327,29 @@ describe("paseo worktree manager", () => { expect(existsSync(created.worktreePath)).toBe(false); }); + it("does not read a parent repository's HEAD when the worktree has no .git", async () => { + const directory = join(repoDir, "missing-worktree"); + mkdirSync(directory); + await expect(readWorktreeHead(directory)).resolves.toBeNull(); + }); + + it("keeps a worktree when writing its retention ref fails", async () => { + const created = await createLegacyWorktreeForTest({ + branchName: "ref-write-failure", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "ref-write-failure", + paseoHome, + }); + mkdirSync(join(repoDir, ".git", "refs", "paseo"), { recursive: true }); + writeFileSync(join(repoDir, ".git", "refs", "paseo", "kept-commits"), "blocked\n"); + + await expect( + deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }), + ).rejects.toThrow(); + expect(existsSync(created.worktreePath)).toBe(true); + }); + it("deletes a worktree when Git reports its source through native and long path spellings", async () => { const created = await createLegacyWorktreeForTest({ branchName: "identity-delete", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 2fc8bc05db..98c48e460c 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -146,6 +146,13 @@ export class WorktreeSetupError extends Error { export type WorktreeTeardownCommandResult = WorktreeSetupCommandResult; +// paseo.json can change this with worktree.teardownTimeoutMs. Archive waits for teardown before it +// answers, and the app stops waiting for an archive answer after 60 seconds +// (DEFAULT_SESSION_RPC_TIMEOUT_MS in the client). A teardown that runs to this limit, or to a longer +// one, answers after the app has reported the archive as failed. +const DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS = 60_000; +const MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM = 1024 * 1024; + export class WorktreeTeardownError extends Error { readonly results: WorktreeTeardownCommandResult[]; @@ -188,6 +195,7 @@ export type WorktreeSource = | { kind: "branch-off"; baseBranch: string; branchName: string } | { kind: "checkout-branch"; branchName: string } | { kind: "restore"; branchName: string; baseRef: string | null } + | { kind: "restore-commit"; commit: string; baseRef: string } | { kind: "restore-from-base"; baseRef: string; branchName: string } | { kind: "checkout-change-request"; @@ -280,6 +288,13 @@ export async function getWorktreeTeardownCommands(repoRoot: string): Promise { + return ( + (await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardownTimeoutMs ?? + DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS + ); +} + export async function getWorktreeTerminalSpecs( repoRoot: string, ): Promise { @@ -448,12 +463,14 @@ async function execSetupCommandStreamed(options: { index: number; total: number; signal?: AbortSignal; + maxOutputCharsPerStream?: number; onEvent?: (event: WorktreeSetupCommandProgressEvent) => void; }): Promise { return new Promise((resolvePromise) => { const startedAt = Date.now(); - const stdoutChunks: string[] = []; - const stderrChunks: string[] = []; + const outputChunks: Record<"stdout" | "stderr", string[]> = { stdout: [], stderr: [] }; + const outputLimit = options.maxOutputCharsPerStream ?? Infinity; + const remainingOutputChars = { stdout: outputLimit, stderr: outputLimit }; let settled = false; let termination: Promise | null = null; @@ -462,10 +479,10 @@ async function execSetupCommandStreamed(options: { if (!text) { return; } - if (stream === "stdout") { - stdoutChunks.push(text); - } else { - stderrChunks.push(text); + const retainedText = text.slice(0, remainingOutputChars[stream]); + if (retainedText) { + outputChunks[stream].push(retainedText); + remainingOutputChars[stream] -= retainedText.length; } options.onEvent?.({ type: "output", @@ -484,12 +501,17 @@ async function execSetupCommandStreamed(options: { } settled = true; options.signal?.removeEventListener("abort", abort); - await termination; + if (termination) { + await termination; + // A descendant can keep these pipes open after the shell exits. + child.stdout?.destroy(); + child.stderr?.destroy(); + } const result: WorktreeSetupCommandResult = { command: options.command, cwd: options.cwd, - stdout: stdoutChunks.join(""), - stderr: stderrChunks.join(""), + stdout: outputChunks.stdout.join(""), + stderr: outputChunks.stderr.join(""), exitCode, durationMs: Date.now() - startedAt, }; @@ -528,6 +550,7 @@ async function execSetupCommandStreamed(options: { gracefulTimeoutMs: 1000, forceTimeoutMs: 1000, }); + void finish(null); }; if (options.signal?.aborted) { abort(); @@ -767,17 +790,26 @@ export async function runWorktreeTeardownCommands(options: { }), ); + // One deadline covers every command. Reaching it counts as failure and keeps the worktree. + const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd); + const deadline = AbortSignal.timeout(timeoutMs); const results: WorktreeTeardownCommandResult[] = []; - for (const cmd of teardownCommands) { - const result = await execSetupCommand(cmd, { + for (const [index, cmd] of teardownCommands.entries()) { + const result = await execSetupCommandStreamed({ + command: cmd, cwd: teardownCwd, env: teardownEnv, + index: index + 1, + total: teardownCommands.length, + signal: deadline, + maxOutputCharsPerStream: MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM, }); results.push(result); if (result.exitCode !== 0) { + const reason = deadline.aborted ? `Timed out after ${timeoutMs / 1000}s` : result.stderr; throw new WorktreeTeardownError( - `Worktree teardown command failed: ${cmd}\n${result.stderr}`.trim(), + `Worktree teardown command failed: ${cmd}\n${reason}`.trim(), results, ); } @@ -1153,6 +1185,32 @@ async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): P } } +export async function readWorktreeHead(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) return null; + try { + const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], { + cwd: worktreePath, + }); + return stdout.trim(); + } catch { + return null; + } +} + +export async function readWorktreeHeadReference(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) return null; + try { + const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], { + cwd: worktreePath, + acceptExitCodes: [0, 1], + }); + if (result.exitCode === 0) return result.stdout.trim(); + return readWorktreeHead(worktreePath); + } catch { + return null; + } +} + export async function deletePaseoWorktree({ cwd, worktreePath, @@ -1208,6 +1266,12 @@ export async function deletePaseoWorktree({ teardownCwd, }); } + const commit = await readWorktreeHead(resolvedWorktree); + if (commit) { + await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], { + cwd: resolvedWorktree, + }); + } } if (cwd) { @@ -1361,14 +1425,22 @@ export async function resolveDefaultWorktreePath( /** * Create a git worktree with proper naming conventions */ -export const createWorktree = async ({ +export function createWorktree( + options: CreateWorktreeOptions & { source: Exclude }, +): Promise; +export function createWorktree( + options: CreateWorktreeOptions, +): Promise & { branchName: string | null }>; +export async function createWorktree({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, -}: CreateWorktreeOptions): Promise => { +}: CreateWorktreeOptions): Promise< + Omit & { branchName: string | null } +> { const branchesBefore = source.kind === "checkout-branch" || source.kind === "checkout-change-request" || @@ -1394,14 +1466,14 @@ export const createWorktree = async ({ }); worktreePath = await normalizePathForOwnership(worktreePath); - if (sourcePlan.pushRemote) { + if (sourcePlan.pushRemote && sourcePlan.branchName) { await configureWorktreePushRemote({ cwd, branchName: sourcePlan.branchName, remote: sourcePlan.pushRemote, }); } - if (sourcePlan.trackingRemote) { + if (sourcePlan.trackingRemote && sourcePlan.branchName) { await configureWorktreeTrackingRemote({ cwd, branchName: sourcePlan.branchName, @@ -1434,7 +1506,7 @@ export const createWorktree = async ({ } throw error; } -}; +} interface ResolveWorktreeSourcePlanOptions { cwd: string; @@ -1443,7 +1515,7 @@ interface ResolveWorktreeSourcePlanOptions { } interface WorktreeSourcePlan { - branchName: string; + branchName: string | null; // Display name and exact ref are two different facts. The name cannot round-trip to a // commit — "main" resolves local-first even when the worktree was cut from a fork's // upstream — so comparisons and actions read the ref and the UI reads the name. @@ -1492,6 +1564,26 @@ async function resolveRestoredWorktreeSourcePlan( }; } +async function resolveRestoredCommitSourcePlan( + cwd: string, + source: Extract, +): Promise { + let exactBase: string | undefined; + if (isQualifiedRef(source.baseRef)) { + try { + exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef); + } catch { + // Restore the saved commit even when its comparison ref no longer exists. + } + } + return { + branchName: null, + metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef), + ...(exactBase ? { metadataBaseRef: exactBase } : {}), + addArguments: ["--detach", source.commit], + }; +} + async function resolveRestoredWorktreeFromBasePlan( cwd: string, source: Extract, @@ -1544,6 +1636,8 @@ async function resolveWorktreeSourcePlan({ return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug); case "restore": return resolveRestoredWorktreeSourcePlan(cwd, source); + case "restore-commit": + return resolveRestoredCommitSourcePlan(cwd, source); case "restore-from-base": return resolveRestoredWorktreeFromBasePlan(cwd, source); case "checkout-branch": { diff --git a/packages/website/e2e/changelog.spec.ts b/packages/website/e2e/changelog.spec.ts index c95b389544..2e50ff5da4 100644 --- a/packages/website/e2e/changelog.spec.ts +++ b/packages/website/e2e/changelog.spec.ts @@ -1,4 +1,4 @@ -import { expect, test, type Locator, type Page } from "./fixtures"; +import { expect, test, waitForHydration, type Locator, type Page } from "./fixtures"; // The page renders the repository's CHANGELOG.md, so releases are found by shape, never by version: // a release with highlights has the toggle, a release without them does not. @@ -6,12 +6,9 @@ function releases(page: Page): Locator { return page.getByRole("region"); } -// The router resets the scroll position when the page hydrates. A click sent before that is aimed -// at where the control was, so wait for the page to be interactive: the language button is enabled -// once it has hydrated. async function openChangelog(page: Page): Promise { await page.goto("/changelog"); - await expect(page.getByRole("button", { name: /^Language/ }).first()).toBeEnabled(); + await waitForHydration(page); } function releaseWithHighlights(page: Page): Locator { diff --git a/packages/website/e2e/fixtures.ts b/packages/website/e2e/fixtures.ts index a0d0ed2e8f..16ed1a3bb0 100644 --- a/packages/website/e2e/fixtures.ts +++ b/packages/website/e2e/fixtures.ts @@ -1,8 +1,17 @@ -import { test as base } from "playwright/test"; +import { expect, test as base, type Page } from "playwright/test"; export { expect } from "playwright/test"; export type { Locator, Page } from "playwright/test"; +/** + * Waits until the page has hydrated. Server-rendered content shows before that, but it has no + * click handlers yet, and the router scrolls the window back to the top when it hydrates. + * The language button stays disabled until the render after that reset. + */ +export async function waitForHydration(page: Page) { + await expect(page.getByRole("button", { name: /^(Language|语言)/ }).first()).toBeEnabled(); +} + export const test = base.extend({ page: async ({ page, baseURL }, run) => { page.on("response", async (response) => { diff --git a/packages/website/e2e/mockups.spec.ts b/packages/website/e2e/mockups.spec.ts index 82a440fa1c..174f17781a 100644 --- a/packages/website/e2e/mockups.spec.ts +++ b/packages/website/e2e/mockups.spec.ts @@ -1,12 +1,13 @@ -import { expect, test, type Locator, type Page } from "./fixtures"; +import { expect, test, waitForHydration, type Locator, type Page } from "./fixtures"; const desktopName = "Paseo desktop app with coding agents, a conversation, and a code diff open side by side"; -async function openHomepage(page: Page) { - await page.setViewportSize({ width: 1512, height: 930 }); +/** Opens the homepage once it has hydrated, so the router's scroll reset cannot undo a later scroll. */ +async function openHomepage(page: Page, window = { width: 1512, height: 930 }) { + await page.setViewportSize(window); await page.goto("/"); - await expect(page.getByRole("button", { name: "Parallel agents", exact: true })).toBeVisible(); + await waitForHydration(page); } async function viewPhones(page: Page) { @@ -60,6 +61,225 @@ test("desktop mockup corners shrink in proportion on a phone", async ({ page }) await expect.poll(() => cornerProportion(mockup)).toBeCloseTo(desktopCorner, 3); }); +/** Each hero pill and one thing only its finished scene draws. */ +const HERO_SCENES = [ + { pill: "Orchestration", shows: "Pi · GLM-5.2" }, + { pill: "Remote", shows: "Tailscale" }, + { pill: "Code review", shows: "Feedback sent to Codex" }, + { pill: "Pull requests", shows: "https://github.com/getpaseo/paseo/pull/3981" }, + { pill: "Plugins", shows: "app-tests (macos)" }, +]; + +/** Clicks a hero pill until its scene starts. A click before hydration selects nothing. */ +async function playScene(page: Page, pill: string, opensWith: Locator) { + await expect(async () => { + await page.getByRole("button", { name: pill, exact: true }).click(); + await expect(opensWith).toBeVisible({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); +} + +test("each hero pill shows its finished scene when motion is reduced", async ({ page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await mockup.scrollIntoViewIfNeeded(); + // Last to first, so the opening scene is also reached by a click. + for (const scene of HERO_SCENES.toReversed()) { + await playScene(page, scene.pill, mockup.getByText(scene.shows, { exact: true }).first()); + } +}); + +test("the hero opens on orchestration across providers and machines", async ({ page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(page.getByRole("button", { name: "Orchestration", exact: true })).toHaveAttribute( + "aria-pressed", + "true", + ); + for (const agent of ["Codex · GPT-5.6-Sol", "OpenCode · Kimi K3", "Pi · GLM-5.2"]) { + await expect(mockup.getByText(agent, { exact: true })).toBeVisible(); + } + // The task on another machine carries that host's badge in its tool call and its subagent row. + for (const remoteTask of ["OpenCode · fix/menu-bar-icon", "OpenCode · Kimi K3"]) { + const row = mockup.getByText(remoteTask, { exact: true }).locator("xpath=.."); + await expect(row.getByText("mac-mini", { exact: true })).toBeVisible(); + } +}); + +test("the orchestration scene plays from an empty chat to the open roster of subagents", async ({ + page, +}) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const composer = mockup.getByText("Message the agent, tag @files, or use /commands and /skills"); + await playScene(page, "Orchestration", composer); + await expect(mockup.getByText("Create agent", { exact: true })).toHaveCount(0); + await expect(mockup.getByText("3 subagents", { exact: true })).toHaveCount(0); + + // The orchestrator lists the issues and the agent profiles, launches three agents and says so, + // then the pointer clicks the pill and the roster opens. + await expect(mockup.getByText("3 subagents", { exact: true })).toBeVisible({ timeout: 20_000 }); + await expect(mockup.getByText("gh issue list --label ready", { exact: true })).toBeVisible(); + await expect(mockup.getByText("List agent profiles", { exact: true })).toBeVisible(); + await expect( + mockup.getByText( + "I will launch the UI agent on your mac-mini, because that issue is specific to macOS.", + ), + ).toBeVisible(); + await expect(mockup.getByText("Create agent", { exact: true })).toHaveCount(3); + await expect( + mockup.getByText("All three are launched. Paseo will notify me when each one finishes."), + ).toBeVisible(); + await expect(mockup.getByText("Pi · GLM-5.2", { exact: true })).toBeVisible({ timeout: 10_000 }); +}); + +test("the opening scene waits until most of the mockup is on screen", async ({ page }) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); + await expect(mockup).not.toBeInViewport({ ratio: 0.6 }); + + // A scene that started at load sends the request within three seconds. + await page.waitForTimeout(4500); + await expect(request).toHaveCount(0); + + await mockup.scrollIntoViewIfNeeded(); + await expect(request).toBeVisible({ timeout: 10_000 }); +}); + +test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => { + await openHomepage(page, { width: 1400, height: 400 }); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); + await mockup.scrollIntoViewIfNeeded(); + await expect(mockup).not.toBeInViewport({ ratio: 0.6 }); + await expect(request).toBeVisible({ timeout: 10_000 }); +}); + +test("the plugins scene installs the panel, then changes it on request", async ({ page }) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const changesPanel = mockup.getByText("Uncommitted", { exact: true }); + const pluginPanel = mockup.getByText("Recently merged", { exact: true }); + const failingCheck = mockup.getByText("app-tests (macos)", { exact: true }); + await playScene(page, "Plugins", page.getByRole("button", { name: "Plugins", pressed: true })); + await expect(changesPanel).toBeVisible(); + await expect(pluginPanel).toHaveCount(0); + + // Installing the plugin swaps the docked panel for the one the agent built. + await expect(pluginPanel).toBeVisible({ timeout: 20_000 }); + await expect(changesPanel).toHaveCount(0); + await expect(failingCheck).toHaveCount(0); + + // The second request reloads the plugin and the open panel lists the failing check. + await expect(failingCheck).toBeVisible({ timeout: 15_000 }); + await expect( + mockup.getByText("paseo plugin reload release-radar", { exact: true }), + ).toBeVisible(); +}); + +test("the code review scene comments on a line and sends the feedback to an agent", async ({ + page, +}) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const comment = mockup.getByText("Add “write”. The agent edits files too.", { exact: true }); + const sendFeedback = mockup.getByText("Send feedback (1)", { exact: true }); + await playScene( + page, + "Code review", + page.getByRole("button", { name: "Code review", pressed: true }), + ); + await expect(comment).toHaveCount(0); + + // The pointer opens the editor on a line, and the typed comment is saved under that line. + await expect(sendFeedback).toBeVisible({ timeout: 10_000 }); + await expect(comment).toBeVisible(); + + // Send feedback asks which agent, and the sent comment leaves the diff. + await expect(mockup.getByText("Claude Code", { exact: true })).toHaveCount(2, { + timeout: 10_000, + }); + await expect(mockup.getByText("Feedback sent to Codex", { exact: true })).toBeVisible({ + timeout: 10_000, + }); + await expect(sendFeedback).toHaveCount(0); + await expect(comment).toHaveCount(0); +}); + +test("picking a scene brings the pills and the whole mockup on screen", async ({ page }) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(mockup).not.toBeInViewport({ ratio: 0.9 }); + + await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); + await expect(mockup).toBeInViewport({ ratio: 0.99 }); + await expect(page.getByRole("button", { name: "Remote", exact: true })).toBeInViewport({ + ratio: 1, + }); +}); + +test("picking a scene in a window too short for the mockup keeps the pills on screen", async ({ + page, +}) => { + await openHomepage(page); + await page.setViewportSize({ width: 1280, height: 600 }); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(mockup).not.toBeInViewport(); + + await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); + await expect(mockup).toBeInViewport({ ratio: 0.7 }); + await expect(page.getByRole("button", { name: "Remote", exact: true })).toBeInViewport({ + ratio: 1, + }); +}); + +test("picking a scene while the hero is still sliding in keeps the pills on screen", async ({ + page, +}) => { + // Reduced motion makes the scroll instant, so the test does not wait for one to settle. + await page.emulateMedia({ reducedMotion: "reduce" }); + await openHomepage(page, { width: 1280, height: 700 }); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); + + // The hero slides up 40px as it enters. The test waits for that to end, puts the same 40px back + // on the container, picks a scene, and lets the slide end again. A click during a real slide + // does the same, but only inside the first second after load. + const sliding = page + .getByRole("button", { name: "Remote", exact: true }) + .locator("xpath=../../../.."); + await expect(sliding).toHaveCSS("transform", "none"); + await page.evaluate(() => window.scrollTo(0, 0)); + await expect(mockup).not.toBeInViewport({ ratio: 0.99 }); + const slideBy = (pixels: number) => + sliding.evaluate((container, y) => { + container.style.transform = y === 0 ? "none" : `translateY(${y}px)`; + }, pixels); + + const codeReview = page.getByRole("button", { name: "Code review", exact: true }); + await slideBy(40); + await codeReview.click(); + await slideBy(0); + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0); + await expect(codeReview).toBeInViewport({ ratio: 1 }); +}); + +test("the remote scene lists hosts with how each connects and its round trip time", async ({ + page, +}) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(async () => { + await page.getByRole("button", { name: "Remote", exact: true }).click(); + await expect(mockup.getByText("Hosts", { exact: true })).toBeVisible({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + for (const fact of ["Local", "Relay", "Tailscale", "SSH", "38ms", "mo@workstation"]) { + await expect(mockup.getByText(fact, { exact: true })).toBeVisible(); + } +}); + /** Opacity as rendered: the element's own times every ancestor's. */ async function renderedOpacity(locator: Locator) { return locator.evaluate((element) => { diff --git a/packages/website/e2e/plugins.spec.ts b/packages/website/e2e/plugins.spec.ts index 26e1ccfd94..7d02e9d7d5 100644 --- a/packages/website/e2e/plugins.spec.ts +++ b/packages/website/e2e/plugins.spec.ts @@ -1,5 +1,5 @@ import securityPlugin from "./overview.fixture.json" with { type: "json" }; -import { expect, test, type Page, type Locator } from "./fixtures"; +import { expect, test, waitForHydration, type Page, type Locator } from "./fixtures"; import registry from "./registry.fixture.json" with { type: "json" }; import { CATEGORIES } from "../src/plugins/categories"; import copy from "../src/i18n/resources/en.json" with { type: "json" }; @@ -9,12 +9,6 @@ async function openPlugins(page: Page) { await expect(page.getByRole("heading", { level: 1, name: /^Plugins/ })).toBeVisible(); } -async function waitForInteractivePage(page: Page) { - // Server-rendered content is visible before hydration attaches its click handlers. - // The language selector stays disabled until that page has hydrated. - await expect(page.getByRole("button", { name: "Language: English" }).first()).toBeEnabled(); -} - function pluginCards(page: Page, section: string): Locator { return page .getByRole("region", { name: section }) @@ -84,18 +78,18 @@ test("browses from the directory into a category, a plugin, and its author", asy }); }); await openPlugins(page); - await waitForInteractivePage(page); + await waitForHydration(page); await page.getByRole("region", { name: "Categories" }).getByRole("link", { name: /Git/ }).click(); await expect(page).toHaveURL(/\/plugins\/category\/git$/); await expect(page.getByRole("heading", { level: 1, name: /^Git/ })).toBeVisible(); - await waitForInteractivePage(page); + await waitForHydration(page); await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0); await page.getByRole("link", { name: /Fresh Worktrees/ }).click(); await expect(page).toHaveURL(/\/plugins\/omercnet\/fresh-worktrees$/); await expect(page.getByRole("heading", { name: "Fresh Worktrees" })).toHaveCount(1); - await waitForInteractivePage(page); + await waitForHydration(page); await expect(page.getByText("paseo plugin add omercnet/fresh-worktrees")).toHaveCount(1); await expect( page.getByRole("heading", { level: 2, name: "Behavior", exact: true }), @@ -192,7 +186,7 @@ test("keeps the directory's ranking window when searching", async ({ page }) => test("submits the visible search term when its input event was missed", async ({ page }) => { await page.goto("/plugins?window=month"); - await expect(page.getByRole("button", { name: "Language: English" }).first()).toBeEnabled(); + await waitForHydration(page); await fillSearchWithMissedInputEvent(page, "graphite"); await page.keyboard.press("Enter"); diff --git a/packages/website/package.json b/packages/website/package.json index 93e801ed2d..0e5a5f5003 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.16.0-beta.1", + "version": "0.16.1", "private": true, "type": "module", "scripts": { diff --git a/packages/website/src/components/hero-mockup.tsx b/packages/website/src/components/hero-mockup.tsx index 1249d5c3d5..6a3e0a219b 100644 --- a/packages/website/src/components/hero-mockup.tsx +++ b/packages/website/src/components/hero-mockup.tsx @@ -1,24 +1,57 @@ -import { motion } from "framer-motion"; -import { useCallback, useState } from "react"; +import { motion, useInView, useReducedMotion } from "framer-motion"; +import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { - DEFAULT_MOCKUP_STATE, + createMockupPlayer, DESIGN_HEIGHT, DESIGN_WIDTH, MOCKUP_STATES, type MockupStateId, MockupWindow, ScaledMockup, + useMockupScene, } from "~/components/mockup"; +const IN_VIEW = { once: true }; +/** How far down the mockup its start line sits. */ +const START_LINE = "60%"; +/** The space left between the top or bottom of the window and the pills or the mockup. */ +const PAGE_MARGIN = 16; +const START_LINE_STYLE = { top: START_LINE }; const PILL_TRANSITION = { duration: 0.34, ease: [0.22, 0.61, 0.36, 1] as const }; export function HeroMockup() { const { t } = useTranslation(); - const [state, setState] = useState(DEFAULT_MOCKUP_STATE); + const [player] = useState(createMockupPlayer); + const state = useMockupScene(player); + + // The opening scene plays once most of the mockup is on screen, so a visitor who scrolls to it + // sees it from the start. "Most" is a line 60% of the way down the mockup. A window shorter than + // 60% of the mockup still reaches the line, which a share of the mockup on screen would not. + // With reduced motion there is nothing to miss, so the finished scene shows at once. + const frame = useRef(null); + const startLine = useRef(null); + const reduceMotion = useReducedMotion(); + const onScreen = useInView(startLine, IN_VIEW); + const ready = onScreen || reduceMotion === true; + useEffect(() => { + if (ready) player.start(); + }, [ready, player]); + useEffect(() => player.stop, [player]); + + // The pills can sit above a mockup that is partly below the fold, most of all on a phone. + // Picking a scene brings the pills and the mockup on screen together. A window too short for + // both keeps the pills at its top edge, so the next pill is still in reach. + const select = useCallback( + (scene: MockupStateId) => { + player.select(scene); + if (frame.current) scrollOnScreen(frame.current, reduceMotion ? "auto" : "smooth"); + }, + [player, reduceMotion], + ); return ( -
+
{MOCKUP_STATES.map((option) => ( ))}
- - - +
+
); } +/** Where an element sits in the window, from layout alone. A slide-in that is still running does not count. */ +function layoutRect(element: HTMLElement) { + let top = -window.scrollY; + for (let node: Element | null = element; node instanceof HTMLElement; node = node.offsetParent) { + top += node.offsetTop; + } + return { top, bottom: top + element.offsetHeight }; +} + +/** + * Scrolls the least that shows all of an element, and never past the point where its top edge is + * at the top of the window. The element is measured where it settles, because the hero slides up + * as it enters and a click can come before it stops. + */ +function scrollOnScreen(element: HTMLElement, behavior: ScrollBehavior) { + const { top, bottom } = layoutRect(element); + const aboveWindow = top - PAGE_MARGIN; + const belowWindow = bottom + PAGE_MARGIN - window.innerHeight; + const distance = aboveWindow < 0 ? aboveWindow : Math.min(Math.max(belowWindow, 0), aboveWindow); + if (distance !== 0) window.scrollBy({ top: distance, behavior }); +} + function StatePill({ id, label, diff --git a/packages/website/src/components/landing-page.tsx b/packages/website/src/components/landing-page.tsx index 77869e7379..d6fa15f3d9 100644 --- a/packages/website/src/components/landing-page.tsx +++ b/packages/website/src/components/landing-page.tsx @@ -714,8 +714,8 @@ function AutomationDetail({ kind }: { kind: AutomationKind }) { } const MCP_AGENT_CALLS: ToolCall[] = [ - { kind: "paseo", label: "Create agent", detail: "Fix #412: retry flaky relay handshake" }, - { kind: "paseo", label: "Create agent", detail: "Fix #417: group schedules by project" }, + { kind: "paseo", label: "Create agent", detail: "Fix #412: relay handshake race" }, + { kind: "paseo", label: "Create agent", detail: "Fix #417: menu bar icon on macOS" }, ]; function McpAutomationTranscript() { diff --git a/packages/website/src/components/mockup/atoms.tsx b/packages/website/src/components/mockup/atoms.tsx index c90310be79..02f060b336 100644 --- a/packages/website/src/components/mockup/atoms.tsx +++ b/packages/website/src/components/mockup/atoms.tsx @@ -18,6 +18,13 @@ export function DiffStat({ add, remove }: { add: string; remove: string }) { ); } +/** The text caret of an input that has focus. */ +export function Caret({ className }: { className: string }) { + return ( + + ); +} + export type DotTone = "success" | "danger" | "warning" | "running" | "idle"; const DOT_TONE: Record = { diff --git a/packages/website/src/components/mockup/chat.tsx b/packages/website/src/components/mockup/chat.tsx index dc951a8517..167d55acb6 100644 --- a/packages/website/src/components/mockup/chat.tsx +++ b/packages/website/src/components/mockup/chat.tsx @@ -15,15 +15,19 @@ import { SquareTerminal, Zap, } from "lucide-react"; +import { motion } from "framer-motion"; import type * as React from "react"; import { useTranslation } from "react-i18next"; -import { DiffStat } from "./atoms"; -import { CodexIcon, PaseoMark } from "./icons"; - -// Icons passed as props are hoisted so they are not rebuilt on every render. -const MODEL_ICON = ; -const EFFORT_ICON = ; -const ACCESS_ICON = ; +import { Caret, DiffStat } from "./atoms"; +import { HostBadge } from "./hosts"; +import { PaseoMark } from "./icons"; +import { FADE_IN, FADE_OUT } from "./motion"; +import { DELEGATED_TASKS, SUBAGENTS_CLICK, tasksDelegated } from "./orchestration"; +import { useSceneClock } from "./player"; +import { Pointer } from "./pointer"; +import { PROVIDERS, type ProviderId } from "./providers"; +import { COMPOSER, type SceneScript, type ToolCall, type TranscriptEntry } from "./script"; +import type { MockupStateId } from "./states"; // --- transcript ------------------------------------------------------------- @@ -62,6 +66,38 @@ function TurnFooter({ duration }: { duration: string }) { ); } +const BUILT_IN_LABELS = { read: "Read", write: "Write", shell: "Shell" } as const; + +function toolCallLabel(call: ToolCall): string { + return call.kind === "paseo" ? call.label : BUILT_IN_LABELS[call.kind]; +} + +function ToolCallIcon({ kind }: { kind: ToolCall["kind"] }) { + if (kind === "read") return ; + if (kind === "write") return ; + if (kind === "paseo") return ; + return ; +} + +/** + * One tool call row, drawn like the app's collapsed timeline item + * (`packages/app/src/components/message.tsx`): icon, label, then the summary, + * all muted and in the UI font. A Paseo call that targets another machine ends + * with that host's badge, which the app's row does not draw. + */ +export function ToolCallRow({ call }: { call: ToolCall }) { + return ( +
+ + + + {toolCallLabel(call)} + {call.detail ? {call.detail} : null} + {call.kind === "paseo" && call.host ? : null} +
+ ); +} + export function AgentTranscript() { return (
@@ -88,161 +124,273 @@ export function AgentTranscript() { Includes responsive mobile proof and the supporting homepage story. Formatting, typecheck, and lint are clean.
- Ready for review.
); } -/** - * A collapsed tool call as the app's timeline shows it. Built-in tools carry a - * fixed label; Paseo MCP tools name their action, such as "Create agent". - */ -export type ToolCall = - | { kind: "read" | "write" | "shell"; detail: string } - | { kind: "paseo"; label: string; detail: string }; - -const BUILT_IN_LABELS = { read: "Read", write: "Write", shell: "Shell" } as const; - -function toolCallLabel(call: ToolCall): string { - return call.kind === "paseo" ? call.label : BUILT_IN_LABELS[call.kind]; -} - -const PLUGIN_TOOL_CALLS: ToolCall[] = [ - { kind: "read", detail: "paseo-plugin/SKILL.md" }, - { kind: "shell", detail: "paseo plugin init ~/dev/release-radar" }, - { kind: "write", detail: "~/dev/release-radar/index.ts" }, - { kind: "write", detail: "~/dev/release-radar/release-radar.client.tsx" }, - { kind: "shell", detail: "npm install && npm run typecheck" }, - { kind: "shell", detail: "paseo plugin install ~/dev/release-radar" }, -]; - -const PLUGIN_DISCOVERY_CALLS = PLUGIN_TOOL_CALLS.slice(0, 1); -const PLUGIN_BUILD_CALLS = PLUGIN_TOOL_CALLS.slice(1, 4); -const PLUGIN_INSTALL_CALLS = PLUGIN_TOOL_CALLS.slice(4); - -function ToolCallIcon({ kind }: { kind: ToolCall["kind"] }) { - if (kind === "read") return ; - if (kind === "write") return ; - if (kind === "paseo") return ; - return ; -} - -/** - * One tool call row, drawn like the app's collapsed timeline item - * (`packages/app/src/components/message.tsx`): icon, label, then the summary, - * all muted and in the UI font. - */ -export function ToolCallRow({ call }: { call: ToolCall }) { +/** Something that fades in when the script reaches it. */ +function Entering({ children }: { children: React.ReactNode }) { return ( -
- - - - {toolCallLabel(call)} - {call.detail} -
+ + {children} + ); } -function PluginToolGroup({ calls }: { calls: ToolCall[] }) { +interface ScriptedProps { + scene: MockupStateId; + script: SceneScript; +} + +function StreamedText({ scene, script, entry }: ScriptedProps & { entry: TranscriptEntry }) { + const text = useSceneClock(scene, (ms) => script.streamed(entry, ms)); + return {text}; +} + +function LandedTools({ + scene, + script, + entry, + calls, +}: ScriptedProps & { entry: TranscriptEntry; calls: ToolCall[] }) { + const landed = useSceneClock(scene, (ms) => script.landed(entry, ms)); return (
- {calls.map((call) => ( - + {calls.slice(0, landed).map((call) => ( + + + ))}
); } -export function PluginBuildTranscript() { +function TranscriptEntryView({ scene, script, entry }: ScriptedProps & { entry: TranscriptEntry }) { + const { beat } = entry; + if (beat.kind === "agent") return ; + if (beat.kind === "tools") { + return ; + } + if (beat.kind === "user") { + return ( + + {beat.text} + + ); + } + return ( + + + + ); +} + +/** The transcript of a scripted scene, as far as its script has played. */ +export function ScriptedTranscript({ scene, script }: ScriptedProps) { + const entered = useSceneClock(scene, script.entered); return (
- - Build me a release radar for Paseo. I want an explorer panel showing merged PRs, changes in - review, failing checks, and seven-day activity, accessible from the sidebar. - - - I’ll scaffold a local plugin, add the explorer surface, and wire it into the sidebar. - - - - The plugin API exposes Paseo’s live project and workspace state, so the radar - doesn’t need a separate service. - - - The surface is wired. I’m checking the project and installing it now. - - Release Radar is live. It should now be visible in the right sidebar. - + {script.entries.slice(0, entered).map((entry) => ( + + ))}
); } // --- composer --------------------------------------------------------------- -function ControlPill({ icon, label }: { icon: React.ReactNode; label: string }) { +/** One composer control: its icon as the child, then the current value. */ +function ControlPill({ label, children }: { label: string; children: React.ReactNode }) { return ( - - {icon} + + {children} {label} ); } -/** A rounded pill that floats above the composer — task tracker, subagents, diff. */ -function ComposerPill({ children }: { children: React.ReactNode }) { +/** + * A rounded pill that floats above the composer — task tracker, subagents, diff. An open pill is + * the one whose panel is showing. + */ +function ComposerPill({ children, open = false }: { children: React.ReactNode; open?: boolean }) { return ( - + {children} ); } +function SubagentsPill({ count, open = false }: { count: number; open?: boolean }) { + const { t } = useTranslation(); + return ( + + + {t("landing.mockup.app.subagents", { count })} + + ); +} + +/** The row of pills above the composer input. */ +function ComposerTrack({ children }: { children: React.ReactNode }) { + return
{children}
; +} + +/** The trackers of a turn in progress: tasks, subagents, and the diff so far. */ +export function ProgressTrack() { + const { t } = useTranslation(); + return ( + +
+ + {t("landing.mockup.app.tasksProgress", { completed: 6, total: 6 })} + + + + + +
+
+ ); +} + +function SubagentRow({ task }: { task: (typeof DELEGATED_TASKS)[number] }) { + const provider = PROVIDERS[task.provider]; + return ( +
+ + + + + + {task.title} + + + {provider.name} · {provider.model} + + {task.host ? ( + <> + · + + + ) : null} + + +
+ ); +} + +// Where the pointer sets off from, in design pixels from the spot it clicks. +const POINTER_TO_PILL = { x: 236, y: -128 }; +const POINTER_TO_COMPOSER = { x: 230, y: -140 }; + +const ROSTER_CLOSED = { opacity: 0, scale: 0.97, y: 6 }; +const ROSTER_OPEN = { opacity: 1, scale: 1, y: 0 }; + +/** + * The Subagents track of the orchestration scene. Its pill appears with the first subagent and + * counts each one the orchestrator launches. When the pointer clicks the pill, the roster opens: + * one row per agent, drawn like the app's track rows (`packages/app/src/subagents/track.tsx`). + * The title is the task and the line under it names the provider and model. An agent on another + * machine ends that line with the host's badge, where the app writes the host's name in plain text. + */ +export function SubagentsTrack() { + const launched = useSceneClock("orchestrate", tasksDelegated); + const pressed = useSceneClock("orchestrate", SUBAGENTS_CLICK.pressed); + const open = useSceneClock("orchestrate", SUBAGENTS_CLICK.done); + if (launched === 0) return null; + return ( + + {open ? ( + + {DELEGATED_TASKS.map((task) => ( + + ))} + + ) : null} + + + + + + + + ); +} + /** The amber ring the app shows while a turn is streaming. */ function BusyRing() { return ; } export function Composer({ - showProgress = true, - busy = true, + track, + agent = "codex", + busy = false, + draft = "", + focused = false, + children, }: { - showProgress?: boolean; + /** The composer track shown above the input, such as `ProgressTrack`. It brings its own spacing. */ + track?: React.ReactNode; + /** Which provider's agent this composer talks to. */ + agent?: ProviderId; busy?: boolean; + /** What the user has typed and not yet sent. Empty shows the placeholder. */ + draft?: string; + /** Whether the caret is in the input. */ + focused?: boolean; + /** Something drawn over the input box, such as the pointer that clicks it. */ + children?: React.ReactNode; }) { const { t } = useTranslation(); + const provider = PROVIDERS[agent]; return (
-
- {showProgress ? ( -
- - {t("landing.mockup.app.tasksProgress", { completed: 6, total: 6 })} - - - - {t("landing.mockup.app.subagents", { count: 3 })} - - - - -
- ) : null} -
-
+ {track} +
+ {children}
- - {t("landing.mockup.app.composerPlaceholder")} - + {draft ? ( + + {draft} + + + ) : ( + + {/* The caret takes no room, so the placeholder does not move when it appears. */} + {focused ? : null} + {t("landing.mockup.app.composerPlaceholder")} + + )}
- - - + + + + + + + + + @@ -255,3 +403,29 @@ export function Composer({
); } + +/** + * The composer of a scripted scene. The pointer clicks it, which puts the caret in it. Then the + * script types into it and says when a turn is running. + */ +export function ScriptedComposer({ + scene, + script, + agent, + track, +}: ScriptedProps & { agent: ProviderId; track?: React.ReactNode }) { + const click = script.click(COMPOSER); + const draft = useSceneClock(scene, script.draft); + const busy = useSceneClock(scene, script.busy); + const focused = useSceneClock(scene, (ms) => click.pressed(ms) || click.done(ms)); + return ( + + + + ); +} diff --git a/packages/website/src/components/mockup/diff.tsx b/packages/website/src/components/mockup/diff.tsx index 9a0d3a5f25..abc32d4d31 100644 --- a/packages/website/src/components/mockup/diff.tsx +++ b/packages/website/src/components/mockup/diff.tsx @@ -9,6 +9,8 @@ import { RefreshCw, Rows3, } from "lucide-react"; +import { Fragment } from "react"; +import type * as React from "react"; import { useTranslation } from "react-i18next"; import { Code, DiffStat } from "./atoms"; import { TABBAR_H } from "./geometry"; @@ -29,7 +31,7 @@ const SUBHEADER_STYLE = { height: TABBAR_H }; export type DiffRow = | { kind: "file"; name: string; path?: string; add: string; remove: string } | { kind: "hunk"; label: string } - | { kind: "line"; n: string; text: string; mark?: DiffMark } + | { kind: "line"; n: string; text: string; mark?: DiffMark; reviewed?: boolean } | { kind: "scrollbar" } | { kind: "gap" }; @@ -47,16 +49,35 @@ const NUMBER_COLOR: Record = { remove: "text-mock-danger", }; -function DiffLine({ n, text, mark }: { n: string; text: string; mark?: DiffMark }) { +/** What a review adds to the line it comments on. Rows mark that line with `reviewed`. */ +export interface LineReview { + /** Drawn on the line's gutter, such as the button that adds a comment. */ + action: React.ReactNode; + /** Drawn under the line: the thread of comments. */ + thread: React.ReactNode; +} + +function DiffLine({ + n, + text, + mark, + action, +}: { + n: string; + text: string; + mark?: DiffMark; + action?: React.ReactNode; +}) { const fill = mark ? ROW_FILL[mark] : ""; const number = mark ? NUMBER_COLOR[mark] : "text-mock-fg-muted"; return (
{n} + {action} @@ -88,7 +109,15 @@ function FileRow({ ); } -export function DiffRows({ rows, flush }: { rows: DiffRow[]; flush?: boolean }) { +export function DiffRows({ + rows, + flush, + review, +}: { + rows: DiffRow[]; + flush?: boolean; + review?: LineReview; +}) { return (
{rows.map((row, index) => { @@ -110,6 +139,14 @@ export function DiffRows({ rows, flush }: { rows: DiffRow[]; flush?: boolean })
); + if (row.reviewed && review) { + return ( + + + {review.thread} + + ); + } return ; })} {!flush ? ( @@ -333,6 +370,7 @@ export const REVIEW_DIFF_ROWS: DiffRow[] = [ n: "23", text: 'type ToolKind = "read" | "shell";', mark: "add", + reviewed: true, }, { kind: "line", n: "24", text: "" }, { diff --git a/packages/website/src/components/mockup/geometry.ts b/packages/website/src/components/mockup/geometry.ts index be8e6c43bb..6485fe077a 100644 --- a/packages/website/src/components/mockup/geometry.ts +++ b/packages/website/src/components/mockup/geometry.ts @@ -4,14 +4,17 @@ * plain px number you can reason about directly, and nothing has to change when * the hero column gets wider or narrower. * - * The numbers come from measuring public/homepage-hero.png (a 2x capture of a - * 2249x1289 window region) and dividing by 1.5617 so the window lands at 1440 - * wide — the widest the hero column ever renders it. + * The window is 1280 wide, the widest the hero column ever renders it, so on a + * wide screen one design pixel is one CSS pixel and the text is as large as the + * app's. The type and control sizes come from measuring public/homepage-hero.png + * (a 2x capture of a 2249x1289 window region) and dividing by 1.5617. */ -export const DESIGN_WIDTH = 1440; -export const DESIGN_HEIGHT = 826; +export const DESIGN_WIDTH = 1280; +export const DESIGN_HEIGHT = 734; export const TITLEBAR_H = 39; export const TABBAR_H = 31; export const SIDEBAR_W = 262; -export const RIGHT_PANEL_W = 424; +// The docked panel is as wide as the file tree needs. A pull request or a plugin panel gets more room. +export const RIGHT_PANEL_W = 300; +export const RIGHT_PANEL_WIDE_W = 424; diff --git a/packages/website/src/components/mockup/hosts.tsx b/packages/website/src/components/mockup/hosts.tsx new file mode 100644 index 0000000000..2fefb7a204 --- /dev/null +++ b/packages/website/src/components/mockup/hosts.tsx @@ -0,0 +1,157 @@ +import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal, X } from "lucide-react"; +import type * as React from "react"; +import { useTranslation } from "react-i18next"; +import { TailscaleMark } from "./icons"; + +/** + * The machines the mockup's workspaces live on. A host's name is the label its owner gave it, and + * its color is the identity color they picked for its badge. The local machine draws no badge, as + * a host set to hide its badge does in the app. + */ +export type RemoteHostId = "devbox" | "mac-mini"; + +/** Badge ink per host, as the app's `HostBadge` paints glyph and label in one identity color. */ +const HOST_TONE: Record = { + devbox: "text-mock-host-teal", + "mac-mini": "text-mock-host-violet", +}; + +/** + * The mark that says which machine something runs on: the server glyph and the host's name in its + * identity color. It inherits its text size, so it sits in a sidebar row, a tool call, or a + * subagent row alike. + */ +export function HostBadge({ host, glyph = 12 }: { host: RemoteHostId; glyph?: number }) { + return ( + + + {host} + + ); +} + +// --- hosts modal -------------------------------------------------------------- + +type IconComponent = React.ComponentType<{ size?: number; className?: string }>; + +/** How the app reaches a host. Tailscale is a direct TCP connection to a tailnet name. */ +type HostLink = "local" | "relay" | "tailscale" | "ssh"; + +const LINK_ICON: Record = { + local: Monitor, + relay: Globe, + tailscale: TailscaleMark, + ssh: Terminal, +}; + +interface ConnectedHost { + name: string; + device: IconComponent; + tone: string; + link: HostLink; + /** The address in use. The local daemon has none worth showing. */ + endpoint?: string; + /** Round trip time, formatted as the app's `formatLatency` prints it. */ + latency: string; + agents: number; +} + +const CONNECTED_HOSTS: ConnectedHost[] = [ + { + name: "MacBook Pro", + device: Laptop, + tone: "text-mock-fg-muted", + link: "local", + latency: "1ms", + agents: 4, + }, + { + name: "devbox", + device: Server, + tone: HOST_TONE.devbox, + link: "relay", + endpoint: "relay.paseo.sh", + latency: "38ms", + agents: 6, + }, + { + name: "mac-mini", + device: Computer, + tone: HOST_TONE["mac-mini"], + link: "tailscale", + endpoint: "mac-mini:6767", + latency: "12ms", + agents: 3, + }, + { + name: "workstation", + device: PcCase, + tone: "text-mock-host-orange", + link: "ssh", + endpoint: "mo@workstation", + latency: "24ms", + agents: 2, + }, +]; + +function HostRow({ host }: { host: ConnectedHost }) { + const { t } = useTranslation(); + const Device = host.device; + const LinkIcon = LINK_ICON[host.link]; + return ( +
+ + + + + + + {host.name} + + + + {t(`landing.mockup.app.hostLinks.${host.link}`)} + {host.endpoint ? {host.endpoint} : null} + + + + + {host.latency} + + + {t("landing.mockup.app.agentCount", { count: host.agents })} + + +
+ ); +} + +/** + * Every machine this window is connected to: what kind of machine it is, how the app reaches it, + * the round trip time, and how many agents it runs. + */ +export function HostsModal() { + const { t } = useTranslation(); + return ( +
+
+ + {t("landing.mockup.app.hosts")} + + +
+ {CONNECTED_HOSTS.map((host) => ( + + ))} +
+ {/* The plus sits on the center line of the device tiles above it. */} + + + + {t("landing.mockup.app.addHost")} +
+
+ ); +} diff --git a/packages/website/src/components/mockup/icons.tsx b/packages/website/src/components/mockup/icons.tsx index 9b4cd39e08..260aeefd09 100644 --- a/packages/website/src/components/mockup/icons.tsx +++ b/packages/website/src/components/mockup/icons.tsx @@ -1,5 +1,7 @@ // Exact SVG paths from packages/app/src/components/icons/ +import { OpenCodeIcon as OpenCodeBrandIcon, PiIcon as PiBrandIcon } from "../agent-icons"; + /** The Paseo brand swirl — public/logo.svg, drawn as a small sidebar avatar mark. */ export function PaseoMark({ size = 13, className }: { size?: number; className?: string }) { return ( @@ -112,3 +114,65 @@ export function SourceControlIcon({ size = 14, className }: { size?: number; cla ); } + +export function OpenCodeIcon({ size = 13, className }: { size?: number; className?: string }) { + return ; +} + +export function PiIcon({ size = 13, className }: { size?: number; className?: string }) { + return ; +} + +const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) => + [3, 12, 21].map((cx, column) => ({ + cx, + cy, + // The mark is a T: the middle row and the dot under its center are solid. + solid: row === 1 || (row === 2 && column === 1), + })), +); + +/** The Tailscale mark: a three by three dot grid with a solid T. */ +export function TailscaleMark({ size = 12, className }: { size?: number; className?: string }) { + return ( + + ); +} + +/** A mouse pointer. Its tip is the top left corner of the glyph. */ +export function PointerArrow({ size = 24, className }: { size?: number; className?: string }) { + return ( + + ); +} diff --git a/packages/website/src/components/mockup/index.ts b/packages/website/src/components/mockup/index.ts index d07c4d1f56..8b624ff1fd 100644 --- a/packages/website/src/components/mockup/index.ts +++ b/packages/website/src/components/mockup/index.ts @@ -1,10 +1,11 @@ export { ClaudeIcon, CodexIcon, SourceControlIcon } from "./icons"; -export { type ToolCall, ToolCallRow } from "./chat"; +export { ToolCallRow } from "./chat"; +export type { ToolCall } from "./script"; export { DESIGN_HEIGHT, DESIGN_WIDTH } from "./geometry"; export { PhoneFrame } from "./mobile/frame"; export { MobileChat } from "./mobile/chat"; export { MobileDiff } from "./mobile/diff"; export { MobileSidebar } from "./mobile/sidebar"; -export { DEFAULT_MOCKUP_STATE, MOCKUP_STATES, type MockupStateId } from "./states"; -export { MockupWindow } from "./window"; +export { MOCKUP_STATES, type MockupStateId } from "./states"; +export { createMockupPlayer, MockupWindow, useMockupScene } from "./window"; export { ScaledMockup } from "./scaled-mockup"; diff --git a/packages/website/src/components/mockup/orchestration.ts b/packages/website/src/components/mockup/orchestration.ts new file mode 100644 index 0000000000..0d913527ff --- /dev/null +++ b/packages/website/src/components/mockup/orchestration.ts @@ -0,0 +1,102 @@ +import type { RemoteHostId } from "./hosts"; +import { PROVIDERS, type ProviderId } from "./providers"; +import { COMPOSER, script, type ToolCall } from "./script"; + +/** + * The work the orchestrating agent hands out in the orchestration scene. The sidebar draws one + * workspace per task and the chat draws the tool calls and the subagent rows from the same list. + */ +export const DELEGATED_TASKS: { + id: string; + title: string; + branch: string; + provider: Exclude; + host?: RemoteHostId; +}[] = [ + { + id: "issue-412", + title: "Fix #412: relay handshake race", + branch: "fix/relay-handshake-race", + provider: "codex", + }, + { + id: "issue-417", + title: "Fix #417: menu bar icon on macOS", + branch: "fix/menu-bar-icon", + provider: "opencode", + host: "mac-mini", + }, + { + id: "issue-421", + title: "Fix #421: stale Docker setup docs", + branch: "docs/docker-setup", + provider: "pi", + }, +]; + +/** + * The orchestrator's Paseo tool calls, one per delegated task. One call creates the worktree + * workspace and starts the agent in it. + */ +const DELEGATION_CALLS: ToolCall[] = DELEGATED_TASKS.map((task) => ({ + kind: "paseo", + label: "Create agent", + detail: `${PROVIDERS[task.provider].name} · ${task.branch}`, + host: task.host, +})); + +/** + * What the orchestrator looks up before it delegates: the issues to fix, and the agent profiles + * the user set up, which say which model takes which kind of work. + */ +const LOOKUP_CALLS: ToolCall[] = [ + { kind: "shell", detail: "gh issue list --label ready" }, + { kind: "paseo", label: "List agent profiles" }, +]; + +const REQUEST = "Fix the issues labeled ready, one worktree each."; + +/** + * The orchestration scene: the user asks Claude to fix the ready issues, each in a worktree. Claude + * lists the issues and the user's agent profiles, picks a model for each issue, and puts the one + * that needs macOS on another machine. It says that Paseo will notify it when the agents finish. + * Then the pointer opens the subagents roster. + */ +export const ORCHESTRATION = script([ + { kind: "wait", ms: 200 }, + { kind: "click", target: COMPOSER }, + { kind: "wait", ms: 250 }, + { kind: "type", text: REQUEST }, + { kind: "user", text: REQUEST }, + { kind: "tools", calls: LOOKUP_CALLS }, + { + kind: "agent", + text: `I loaded your orchestration preferences: ${PROVIDERS.codex.model} for the hard bug, ${PROVIDERS.opencode.model} for UI, ${PROVIDERS.pi.model} for docs.`, + }, + { + kind: "agent", + text: "I will launch the UI agent on your mac-mini, because that issue is specific to macOS.", + }, + { kind: "tools", calls: DELEGATION_CALLS }, + { + kind: "agent", + text: "All three are launched. Paseo will notify me when each one finishes.", + }, + // No footer: with it, the transcript and the open roster do not both fit in the pane. + { kind: "turnEnd" }, + { kind: "click", target: "subagents" }, +]); + +/** The pointer's click on the subagents pill. It opens the roster of subagents. */ +export const SUBAGENTS_CLICK = ORCHESTRATION.click("subagents"); + +/** + * How many tasks the orchestrator delegated so far. Each one adds a workspace to the sidebar and a + * subagent to the composer's pill. + */ +export function tasksDelegated(ms: number): number { + const delegation = ORCHESTRATION.entries.find( + (entry) => entry.beat.kind === "tools" && entry.beat.calls === DELEGATION_CALLS, + ); + return delegation ? ORCHESTRATION.landed(delegation, ms) : 0; +} diff --git a/packages/website/src/components/mockup/panes.tsx b/packages/website/src/components/mockup/panes.tsx index 3f0554f403..32831b582a 100644 --- a/packages/website/src/components/mockup/panes.tsx +++ b/packages/website/src/components/mockup/panes.tsx @@ -1,15 +1,86 @@ -import { DiffRows, REVIEW_DIFF_ROWS, ScopeRow } from "./diff"; +import { DiffRows, type LineReview, REVIEW_DIFF_ROWS, ScopeRow } from "./diff"; +import { AddCommentAction, ReviewFeedback, ReviewThread } from "./review-thread"; import { useTranslation } from "react-i18next"; // --- review ----------------------------------------------------------------- -/** The selected Changes-tree file, open in its own workspace tab. */ +const LINE_REVIEW: LineReview = { action: , thread: }; + +/** + * The selected Changes-tree file, open in its own workspace tab. The review scene comments on one + * of its lines and sends that feedback to an agent. + */ export function DiffReviewPane() { const { t } = useTranslation(); return ( -
+
- + + +
+ ); +} + +// --- remote ----------------------------------------------------------------- + +function ShellPrompt() { + return ( + <> + mo@devbox: + ~/dev/paseo${" "} + + ); +} + +function ViteArrow() { + return {" ➜ "}; +} + +function HmrLine({ time, file }: { time: string; file: string }) { + return ( +
+ {time}{" "} + [vite]{" "} + hmr update{" "} + {file} +
+ ); +} + +/** + * The workspace's terminal tab. The workspace lives on devbox, so the shell does too: the prompt + * names the remote machine while the pane sits in the same window as every local workspace. + */ +export function RemoteTerminalPane() { + return ( +
+
+ + npm run dev +
+
+
> @getpaseo/website dev
+
> vite
+
+
+ {" "} + VITE v7.3.3 + {" ready in "}412 ms +
+
+
+ + {"Local: "} + http://localhost:3000/ +
+
+ + press h + enter to show help +
+
+ + +
); } diff --git a/packages/website/src/components/mockup/player.test.ts b/packages/website/src/components/mockup/player.test.ts new file mode 100644 index 0000000000..73732638f0 --- /dev/null +++ b/packages/website/src/components/mockup/player.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { createScenePlayer, type Frames } from "./player"; + +/** A page clock that moves only when the test turns it. */ +function handClock() { + let time = 0; + let nextId = 0; + const waiting = new Map void>(); + const frames: Frames = { + now: () => time, + request(callback) { + nextId += 1; + waiting.set(nextId, callback); + return nextId; + }, + cancel: (id) => waiting.delete(id), + reducedMotion: () => false, + }; + return { + frames, + /** Moves the clock on and runs the frames that were waiting for it. */ + advance(ms: number) { + time += ms; + const due = [...waiting.values()]; + waiting.clear(); + for (const callback of due) callback(time); + }, + framesWaiting: () => waiting.size, + }; +} + +function setUp() { + const clock = handClock(); + const player = createScenePlayer("orchestrate", { orchestrate: 1000, review: 500 }, clock.frames); + return { clock, player }; +} + +describe("scene player", () => { + it("plays the opening scene from the start when the page starts it", () => { + const { clock, player } = setUp(); + player.start(); + clock.advance(16); + clock.advance(16); + expect(player.elapsed("orchestrate")).toBe(32); + }); + + it("keeps the place of a scene that a pill click started before the page did", () => { + const { clock, player } = setUp(); + player.select("review"); + clock.advance(16); + clock.advance(16); + expect(player.elapsed("review")).toBe(32); + + player.start(); + expect(player.scene()).toBe("review"); + expect(player.elapsed("review")).toBe(32); + expect(player.elapsed("orchestrate")).toBe(0); + }); + + it("stops the clock", () => { + const { clock, player } = setUp(); + player.start(); + clock.advance(16); + expect(clock.framesWaiting()).toBe(1); + + player.stop(); + expect(clock.framesWaiting()).toBe(0); + clock.advance(16); + expect(player.elapsed("orchestrate")).toBe(16); + }); +}); diff --git a/packages/website/src/components/mockup/player.ts b/packages/website/src/components/mockup/player.ts new file mode 100644 index 0000000000..30828d0155 --- /dev/null +++ b/packages/website/src/components/mockup/player.ts @@ -0,0 +1,130 @@ +import { createContext, useContext, useSyncExternalStore } from "react"; +import type { MockupStateId } from "./states"; + +/** + * Which scene the mockup shows and how far into its script each scene is. The player owns the + * clock. Components read the time through `useSceneClock` and never keep time themselves. + */ +export interface ScenePlayer { + scene(): MockupStateId; + /** Milliseconds into a scene's script. Each scene keeps its own, so a scene that is fading out holds its last frame. */ + elapsed(scene: MockupStateId): number; + /** Shows a scene and plays its script from the start. */ + select(scene: MockupStateId): void; + /** + * Plays the opening scene from the start, unless a scene has played already. A pill click can + * come before the page decides to start, and that scene keeps its place. + */ + start(): void; + /** Stops the clock. A scene that is playing holds its last frame. */ + stop(): void; + subscribe(listener: () => void): () => void; +} + +// A background tab stops animation frames. On return the script resumes where it paused. +const LONGEST_FRAME_MS = 64; + +/** What the player needs from the page to keep time. Tests pass a clock they turn by hand. */ +export interface Frames { + now(): number; + request(callback: (now: number) => void): number; + cancel(id: number): void; + reducedMotion(): boolean; +} + +const browserFrames: Frames = { + now: () => performance.now(), + request: (callback) => requestAnimationFrame(callback), + cancel: (id) => cancelAnimationFrame(id), + // Visitors who ask for reduced motion get the finished scene. + reducedMotion: () => window.matchMedia("(prefers-reduced-motion: reduce)").matches, +}; + +/** + * @param durations How long each scene's script runs. A scene without a script has no entry and is + * always at its finished state. + */ +export function createScenePlayer( + initial: MockupStateId, + durations: Partial>, + frames: Frames = browserFrames, +): ScenePlayer { + let scene = initial; + const times = new Map(); + const listeners = new Set<() => void>(); + let frame = 0; + let lastFrameAt = 0; + let played = false; + + function emit() { + for (const listener of listeners) listener(); + } + + function stop() { + if (frame) frames.cancel(frame); + frame = 0; + } + + function tick(now: number) { + const end = durations[scene] ?? 0; + const next = Math.min( + end, + (times.get(scene) ?? 0) + Math.min(now - lastFrameAt, LONGEST_FRAME_MS), + ); + lastFrameAt = now; + times.set(scene, next); + frame = next < end ? frames.request(tick) : 0; + emit(); + } + + function play() { + played = true; + stop(); + const end = durations[scene] ?? 0; + const animated = end > 0 && !frames.reducedMotion(); + times.set(scene, animated ? 0 : end); + if (animated) { + lastFrameAt = frames.now(); + frame = frames.request(tick); + } + emit(); + } + + return { + scene: () => scene, + elapsed: (of) => times.get(of) ?? 0, + select(next) { + scene = next; + play(); + }, + start() { + if (!played) play(); + }, + stop, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }; +} + +export const ScenePlayerContext = createContext(null); + +/** The scene a player shows. */ +export function usePlayerScene(player: ScenePlayer): MockupStateId { + return useSyncExternalStore(player.subscribe, player.scene, player.scene); +} + +/** + * Reads one fact about a scene at its current time, such as how many tool calls have landed. + * The component renders again only when that fact changes, so `select` must return a primitive. + */ +export function useSceneClock( + scene: MockupStateId, + select: (ms: number) => Fact, +): Fact { + const player = useContext(ScenePlayerContext); + if (!player) throw new Error("useSceneClock needs a ScenePlayerContext"); + const read = () => select(player.elapsed(scene)); + return useSyncExternalStore(player.subscribe, read, read); +} diff --git a/packages/website/src/components/mockup/plugin-build.ts b/packages/website/src/components/mockup/plugin-build.ts new file mode 100644 index 0000000000..99a6c747eb --- /dev/null +++ b/packages/website/src/components/mockup/plugin-build.ts @@ -0,0 +1,55 @@ +import { COMPOSER, script } from "./script"; + +const BUILD_REQUEST = "Build a release radar panel for merged PRs and failing checks."; +const CHANGE_REQUEST = "Show which check is failing."; + +/** + * The plugins scene: the user asks for a panel, the agent builds and installs a plugin, and the + * panel opens. Then the user asks for a change and the open panel shows it. + */ +export const PLUGIN_BUILD = script([ + { kind: "wait", ms: 200 }, + { kind: "click", target: COMPOSER }, + { kind: "wait", ms: 250 }, + { kind: "type", text: BUILD_REQUEST }, + { kind: "user", text: BUILD_REQUEST }, + { + kind: "agent", + text: "I’ll scaffold a local plugin, add the explorer surface, and wire it into the sidebar.", + }, + { + kind: "tools", + calls: [ + { kind: "read", detail: "paseo-plugin/SKILL.md" }, + { kind: "shell", detail: "paseo plugin init ~/dev/release-radar" }, + { kind: "write", detail: "~/dev/release-radar/release-radar.client.tsx" }, + { kind: "shell", detail: "paseo plugin install ~/dev/release-radar" }, + ], + }, + { kind: "mark", name: "installed", ms: 500 }, + { kind: "agent", text: "Release Radar is live. It should now be visible in the right sidebar." }, + { kind: "turnEnd", worked: "2m 14s" }, + { kind: "wait", ms: 900 }, + { kind: "type", text: CHANGE_REQUEST }, + { kind: "user", text: CHANGE_REQUEST }, + { + kind: "tools", + calls: [ + { kind: "write", detail: "~/dev/release-radar/release-radar.client.tsx" }, + { kind: "shell", detail: "paseo plugin reload release-radar" }, + ], + }, + { kind: "mark", name: "revised", ms: 500 }, + { kind: "agent", text: "Reloaded. The radar now lists the failing check under the tiles." }, + { kind: "turnEnd", worked: "19s" }, +]); + +/** Whether the plugin is installed: its panel is open and its item is in the sidebar. */ +export function pluginInstalled(ms: number): boolean { + return PLUGIN_BUILD.reached("installed", ms); +} + +/** Whether the reloaded plugin lists the failing check. */ +export function failingCheckListed(ms: number): boolean { + return PLUGIN_BUILD.reached("revised", ms); +} diff --git a/packages/website/src/components/mockup/pointer.tsx b/packages/website/src/components/mockup/pointer.tsx new file mode 100644 index 0000000000..23086c0239 --- /dev/null +++ b/packages/website/src/components/mockup/pointer.tsx @@ -0,0 +1,45 @@ +import { useMemo } from "react"; +import { PointerArrow } from "./icons"; +import { useSceneClock } from "./player"; +import type { PointerClick } from "./script"; +import type { MockupStateId } from "./states"; + +/** + * The visitor's stand-in: a mouse pointer that glides to a spot and clicks it. The spot is where + * `className` places the pointer in its nearest positioned ancestor. + */ +export function Pointer({ + scene, + click, + from, + className, +}: { + scene: MockupStateId; + click: PointerClick; + /** Where the pointer sets off from, in design pixels from the spot it clicks. */ + from: { x: number; y: number }; + className: string; +}) { + const opacity = useSceneClock(scene, click.opacity); + const approach = useSceneClock(scene, click.approach); + const pressed = useSceneClock(scene, click.pressed); + const style = useMemo( + () => ({ + opacity, + transform: `translate(${(1 - approach) * from.x}px, ${(1 - approach) * from.y}px)`, + }), + [opacity, approach, from], + ); + if (opacity === 0) return null; + return ( + + + + ); +} diff --git a/packages/website/src/components/mockup/providers.ts b/packages/website/src/components/mockup/providers.ts new file mode 100644 index 0000000000..167438ff7b --- /dev/null +++ b/packages/website/src/components/mockup/providers.ts @@ -0,0 +1,11 @@ +import { ClaudeIcon, CodexIcon, OpenCodeIcon, PiIcon } from "./icons"; + +/** Each agent provider the mockup shows: its name, its mark, and the model it runs. */ +export const PROVIDERS = { + claude: { name: "Claude Code", Icon: ClaudeIcon, model: "Opus 5.5" }, + codex: { name: "Codex", Icon: CodexIcon, model: "GPT-5.6-Sol" }, + opencode: { name: "OpenCode", Icon: OpenCodeIcon, model: "Kimi K3" }, + pi: { name: "Pi", Icon: PiIcon, model: "GLM-5.2" }, +}; + +export type ProviderId = keyof typeof PROVIDERS; diff --git a/packages/website/src/components/mockup/review-thread.tsx b/packages/website/src/components/mockup/review-thread.tsx new file mode 100644 index 0000000000..dffb3993ab --- /dev/null +++ b/packages/website/src/components/mockup/review-thread.tsx @@ -0,0 +1,231 @@ +import { AnimatePresence, motion } from "framer-motion"; +import { CircleCheck, Pencil, Plus, Send, Trash2 } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Caret } from "./atoms"; +import { FADE_IN, FADE_OUT, MOCKUP_TRANSITION } from "./motion"; +import { useSceneClock } from "./player"; +import { Pointer } from "./pointer"; +import { PROVIDERS, type ProviderId } from "./providers"; +import { + ADD_COMMENT_CLICK, + lineHovered, + RECIPIENT_CLICK, + recipientHovered, + REVIEW, + REVIEW_COMMENT, + reviewPhase, + SEND_FEEDBACK_CLICK, +} from "./review"; + +// The review scene, drawn like the app's review module (`packages/app/src/review`): the add +// button of a hovered line, the inline editor, the saved comment, and Send feedback. + +// --- on the line ------------------------------------------------------------ + +const POINTER_TO_LINE = { x: 240, y: 150 }; + +/** + * The add button a hovered line shows across its gutter's edge, and the pointer that clicks it. + * Goes in the line's gutter. + */ +export function AddCommentAction() { + const hovered = useSceneClock("review", lineHovered); + const pressed = useSceneClock("review", ADD_COMMENT_CLICK.pressed); + return ( + + {hovered ? ( + + + + ) : null} + + + ); +} + +function CommentEditor() { + const { t } = useTranslation(); + const body = useSceneClock("review", REVIEW.draft); + return ( +
+
+ {body ? ( + + {body} + + + ) : ( + + + {t("landing.mockup.app.reviewCommentPlaceholder")} + + )} +
+
+ + {t("landing.mockup.app.reviewCancel")} + + + {t("landing.mockup.app.reviewSave")} + +
+
+ ); +} + +function SavedComment() { + return ( +
+ {REVIEW_COMMENT} + + +
+ ); +} + +// The thread is as tall as what it holds plus 8 of padding above and below. +const THREAD_CLOSED = { height: 0, opacity: 0 }; +const THREAD_WRITING = { height: 110, opacity: 1 }; +const THREAD_COMMENTED = { height: 58, opacity: 1 }; + +/** The comment thread under the line: the editor first, then the saved comment until it is sent. */ +export function ReviewThread() { + const phase = useSceneClock("review", reviewPhase); + const writing = phase === "writing"; + const open = writing || phase === "commented" || phase === "choosing"; + return ( + + {open ? ( + +
{writing ? : }
+
+ ) : null} +
+ ); +} + +// --- over the diff ---------------------------------------------------------- + +function RecipientRow({ agent, lit = false }: { agent: ProviderId; lit?: boolean }) { + const provider = PROVIDERS[agent]; + return ( + + + + + {provider.name} + + ); +} + +/** Who gets the feedback. The workspace has two agent tabs, so Send feedback asks which one. */ +const RECIPIENT: ProviderId = "codex"; + +// Where the pointer sets off for Send feedback, and how far the picked agent's row is from there. +// The button is 32 high. The list floats 6 above it, with 4 of padding around two rows of 30. +const POINTER_TO_SEND = { x: -190, y: -170 }; +const POINTER_TO_RECIPIENT = { x: -6, y: 73 }; + +const FLOATING = "pointer-events-none absolute inset-x-0 bottom-[16px] flex justify-center"; +const FLOATING_SHADOW = "shadow-[0_8px_24px_rgba(0,0,0,0.4)]"; + +/** + * What floats over the bottom of the diff: Send feedback while a comment waits, the list of + * agents it opens, and the toast that says who got the feedback. + */ +export function ReviewFeedback() { + const { t } = useTranslation(); + const phase = useSceneClock("review", reviewPhase); + const pressed = useSceneClock("review", SEND_FEEDBACK_CLICK.pressed); + const recipientLit = useSceneClock("review", recipientHovered); + return ( + <> + + {phase === "commented" || phase === "choosing" ? ( + + + {phase === "choosing" ? ( + + + + + ) : null} + + + {t("landing.mockup.app.sendFeedback", { count: 1 })} + + + + ) : null} + {phase === "sent" ? ( + + + + {t("landing.mockup.app.feedbackSent", { recipient: PROVIDERS[RECIPIENT].name })} + + + ) : null} + + {/* Both spots are measured from the middle of the button's bottom edge. */} + + + + + + ); +} diff --git a/packages/website/src/components/mockup/review.ts b/packages/website/src/components/mockup/review.ts new file mode 100644 index 0000000000..858d633e28 --- /dev/null +++ b/packages/website/src/components/mockup/review.ts @@ -0,0 +1,54 @@ +import { script } from "./script"; + +/** What the reviewer writes on the line. */ +export const REVIEW_COMMENT = "Add “write”. The agent edits files too."; + +/** + * The code review scene: the pointer adds a comment on a line of the diff and the user types it. + * Then the pointer sends the feedback and picks the agent that gets it. + */ +export const REVIEW = script([ + { kind: "wait", ms: 300 }, + { kind: "click", target: "addComment" }, + { kind: "wait", ms: 250 }, + { kind: "type", text: REVIEW_COMMENT }, + { kind: "mark", name: "saved", ms: 450 }, + { kind: "click", target: "sendFeedback" }, + { kind: "click", target: "recipient" }, +]); + +/** The click on the add button of the line. It opens the comment editor. */ +export const ADD_COMMENT_CLICK = REVIEW.click("addComment"); +/** The click on Send feedback. It opens the list of agents. */ +export const SEND_FEEDBACK_CLICK = REVIEW.click("sendFeedback"); +/** The click on the agent that gets the feedback. */ +export const RECIPIENT_CLICK = REVIEW.click("recipient"); + +/** + * Where the review stands. + * + * - `reading`: no comment yet. + * - `writing`: the comment editor is open. + * - `commented`: the comment is saved and waits to be sent. + * - `choosing`: the list of agents is open. + * - `sent`: an agent has the feedback, and the saved comment is gone. + */ +export type ReviewPhase = "reading" | "writing" | "commented" | "choosing" | "sent"; + +export function reviewPhase(ms: number): ReviewPhase { + if (RECIPIENT_CLICK.done(ms)) return "sent"; + if (SEND_FEEDBACK_CLICK.done(ms)) return "choosing"; + if (REVIEW.reached("saved", ms)) return "commented"; + if (ADD_COMMENT_CLICK.done(ms)) return "writing"; + return "reading"; +} + +/** Whether the pointer is over the line. A hovered line shows its add button. */ +export function lineHovered(ms: number): boolean { + return ADD_COMMENT_CLICK.approach(ms) > 0.93 && !ADD_COMMENT_CLICK.done(ms); +} + +/** Whether the pointer is over the agent it is about to pick. */ +export function recipientHovered(ms: number): boolean { + return RECIPIENT_CLICK.approach(ms) > 0.8; +} diff --git a/packages/website/src/components/mockup/right-panel.tsx b/packages/website/src/components/mockup/right-panel.tsx index dc4e300683..32997a3fb2 100644 --- a/packages/website/src/components/mockup/right-panel.tsx +++ b/packages/website/src/components/mockup/right-panel.tsx @@ -1,5 +1,6 @@ import { CircleCheck, + CircleX, ChevronDown, ExternalLink, FileDiff, @@ -14,12 +15,26 @@ import type { TFunction } from "i18next"; import type * as React from "react"; import { useTranslation } from "react-i18next"; import { ChangesBranchRow, ChangesCommitsRow, ChangesScopeRow, ExplorerChangesTree } from "./diff"; -import { RIGHT_PANEL_W, TABBAR_H, TITLEBAR_H } from "./geometry"; -import type { MockupStateId } from "./states"; +import { RIGHT_PANEL_W, RIGHT_PANEL_WIDE_W, TABBAR_H, TITLEBAR_H } from "./geometry"; +import { AnimatePresence, motion } from "framer-motion"; +import { useSceneClock } from "./player"; +import { failingCheckListed } from "./plugin-build"; const TABBAR_STYLE = { height: TITLEBAR_H }; const SUBHEADER_STYLE = { height: TABBAR_H }; -const PANEL_STYLE = { width: RIGHT_PANEL_W }; + +export type PanelId = "changes" | "ship" | "plugin"; + +/** How wide the docked panel is for what it shows. Only the file tree fits the narrow width. */ +export function panelWidth(panel: PanelId): number { + return panel === "changes" ? RIGHT_PANEL_W : RIGHT_PANEL_WIDE_W; +} + +const PANEL_STYLES: Record = { + changes: { width: panelWidth("changes") }, + ship: { width: panelWidth("ship") }, + plugin: { width: panelWidth("plugin") }, +}; interface PanelTab { label: string; @@ -52,10 +67,12 @@ function PanelTabs({ tabs, active }: { tabs: PanelTab[]; active: number }) { } function PanelShell({ + panel, tabs, active, children, }: { + panel: PanelId; tabs: PanelTab[]; active: number; children: React.ReactNode; @@ -63,7 +80,7 @@ function PanelShell({ return (
{children} @@ -88,7 +105,7 @@ function changesTabs(t: TFunction): PanelTab[] { function ChangesPanel({ selectedFile }: { selectedFile?: string }) { const { t } = useTranslation(); return ( - + @@ -118,7 +135,7 @@ function CheckGlyph() { function ShipPanel() { const { t } = useTranslation(); return ( - +
+ +
+ {t("landing.mockup.app.failing")} +
+
+ + + + app-tests (macos) + + + #3976 · Honor configured commit signing + + + 5m 02s +
+
+ ); +} + +function PluginDashboard() { + const { t } = useTranslation(); + const listsFailingCheck = useSceneClock("extend", failingCheckListed); + return ( +
+ + {listsFailingCheck ? : null} + +
{t("landing.mockup.app.mergesWeek")} @@ -307,8 +356,8 @@ function PluginDashboard() { ); } -export function RightPanel({ state }: { state: MockupStateId }) { - if (state === "ship") return ; - if (state === "extend") return ; +export function RightPanel({ panel }: { panel: PanelId }) { + if (panel === "ship") return ; + if (panel === "plugin") return ; return ; } diff --git a/packages/website/src/components/mockup/script.test.ts b/packages/website/src/components/mockup/script.test.ts new file mode 100644 index 0000000000..10d27775d5 --- /dev/null +++ b/packages/website/src/components/mockup/script.test.ts @@ -0,0 +1,177 @@ +import { describe, expect, it } from "vitest"; +import { script } from "./script"; + +const REQUEST = "Rename the panel."; +const REPLY = "Renamed. The panel is now called Radar."; + +const scene = script([ + { kind: "wait", ms: 500 }, + { kind: "type", text: REQUEST }, + { kind: "user", text: REQUEST }, + { + kind: "tools", + calls: [ + { kind: "read", detail: "panel.tsx" }, + { kind: "write", detail: "panel.tsx" }, + ], + }, + { kind: "mark", name: "renamed", ms: 400 }, + { kind: "agent", text: REPLY }, + { kind: "turnEnd", worked: "8s" }, +]); + +const [sent, tools, reply, turnEnd] = scene.entries; + +function midway(entry: { start: number; end: number }): number { + return (entry.start + entry.end) / 2; +} + +const POINTER_ENTERS = 200; +const PAUSE_BEFORE_TYPING = 100; + +const pointed = script([ + { kind: "wait", ms: POINTER_ENTERS }, + { kind: "click", target: "composer" }, + { kind: "wait", ms: PAUSE_BEFORE_TYPING }, + { kind: "type", text: REQUEST }, + { kind: "user", text: REQUEST }, + { kind: "click", target: "pill" }, + { kind: "click", target: "menu" }, +]); +const composerClick = pointed.click("composer"); +const pillClick = pointed.click("pill"); +const menuClick = pointed.click("menu"); + +/** The first millisecond of the pointed scene at which something is true. */ +function firstMs(holds: (ms: number) => boolean): number { + for (let ms = 0; ms <= pointed.duration; ms += 1) { + if (holds(ms)) return ms; + } + throw new Error("It never holds"); +} + +describe("script", () => { + it("starts with an empty composer, an empty transcript, and no turn running", () => { + expect(scene.draft(0)).toBe(""); + expect(scene.entered(0)).toBe(0); + expect(scene.busy(0)).toBe(false); + }); + + it("types the request into the composer, then clears it when the message is sent", () => { + const typing = { start: 500, end: sent.start }; + const partial = scene.draft(typing.start + 200); + expect(partial.length).toBeGreaterThan(0); + expect(partial.length).toBeLessThan(REQUEST.length); + expect(REQUEST.startsWith(partial)).toBe(true); + + expect(scene.draft(typing.end - 1)).toBe(REQUEST); + expect(scene.draft(sent.start)).toBe(""); + expect(scene.entered(midway(sent))).toBe(1); + }); + + it("runs the turn from the sent message until the turn ends", () => { + expect(scene.busy(sent.start - 1)).toBe(false); + expect(scene.busy(sent.start)).toBe(true); + expect(scene.busy(midway(reply))).toBe(true); + expect(scene.busy(turnEnd.start)).toBe(false); + }); + + it("lands tool calls one at a time", () => { + expect(scene.landed(tools, tools.start)).toBe(0); + expect(scene.landed(tools, tools.start + 1)).toBe(1); + expect(scene.landed(tools, tools.end)).toBe(2); + }); + + it("streams the agent's text", () => { + expect(scene.streamed(reply, reply.start)).toBe(""); + const partial = scene.streamed(reply, midway(reply)); + expect(partial.length).toBeGreaterThan(0); + expect(partial.length).toBeLessThan(REPLY.length); + expect(REPLY.startsWith(partial)).toBe(true); + expect(scene.streamed(reply, reply.end)).toBe(REPLY); + }); + + it("reaches a mark after the beats before it and reports progress through it", () => { + expect(scene.reached("renamed", tools.end)).toBe(false); + expect(scene.reached("renamed", tools.end + 1)).toBe(true); + expect(scene.progress("renamed", tools.end + 100)).toBeCloseTo(0.25); + expect(scene.progress("renamed", reply.start)).toBe(1); + }); + + it("glides the pointer to its target, presses, and lets go", () => { + const pressedAt = firstMs(composerClick.pressed); + const doneAt = firstMs(composerClick.done); + + expect(composerClick.opacity(POINTER_ENTERS)).toBe(0); + expect(composerClick.approach(POINTER_ENTERS)).toBe(0); + + const gliding = (POINTER_ENTERS + pressedAt) / 2; + expect(composerClick.opacity(gliding)).toBe(1); + expect(composerClick.approach(gliding)).toBeGreaterThan(0); + expect(composerClick.approach(gliding)).toBeLessThan(1); + expect(composerClick.pressed(gliding)).toBe(false); + + expect(composerClick.approach(pressedAt)).toBe(1); + expect(composerClick.done(pressedAt)).toBe(false); + + expect(doneAt).toBeGreaterThan(pressedAt); + expect(composerClick.pressed(doneAt)).toBe(false); + }); + + it("keeps the pointer where it clicked until the user types", () => { + const typingAt = firstMs(composerClick.done) + PAUSE_BEFORE_TYPING; + expect(composerClick.opacity(typingAt - 1)).toBe(1); + expect(pointed.draft(typingAt - 1)).toBe(""); + + // The pointer fades away while the first characters land. + expect(pointed.draft(typingAt + 1)).not.toBe(""); + expect(composerClick.opacity(typingAt + 1)).toBeLessThan(1); + expect(composerClick.opacity(typingAt + 500)).toBe(0); + expect(composerClick.done(typingAt + 500)).toBe(true); + }); + + it("fades the pointer in when it comes back after typing", () => { + const setsOffAt = firstMs((ms) => pillClick.approach(ms) > 0); + expect(pillClick.opacity(setsOffAt)).toBeGreaterThan(0); + expect(pillClick.opacity(setsOffAt)).toBeLessThan(1); + }); + + it("moves one pointer from a click to the click after it", () => { + const handoffAt = firstMs(pillClick.done); + expect(pillClick.opacity(handoffAt - 1)).toBe(1); + expect(menuClick.opacity(handoffAt - 1)).toBe(0); + + expect(pillClick.opacity(handoffAt)).toBe(0); + expect(menuClick.opacity(handoffAt)).toBe(1); + expect(menuClick.approach(handoffAt)).toBe(0); + }); + + it("leaves the pointer on the last thing it clicked", () => { + expect(menuClick.opacity(pointed.duration)).toBe(1); + expect(menuClick.approach(pointed.duration)).toBe(1); + expect(menuClick.done(pointed.duration)).toBe(true); + expect(composerClick.opacity(pointed.duration)).toBe(0); + expect(composerClick.done(pointed.duration)).toBe(true); + }); + + it("ends a turn without a footer when the beat gives no time worked", () => { + const quiet = script([ + { kind: "user", text: REQUEST }, + { kind: "agent", text: REPLY }, + { kind: "turnEnd" }, + { kind: "wait", ms: 300 }, + ]); + const [, quietReply] = quiet.entries; + expect(quiet.entries.map((entry) => entry.beat.kind)).toEqual(["user", "agent"]); + expect(quiet.busy(quietReply.end - 1)).toBe(true); + expect(quiet.busy(quietReply.end)).toBe(false); + }); + + it("shows the finished scene at its duration", () => { + expect(scene.duration).toBe(turnEnd.end); + expect(scene.entered(scene.duration)).toBe(scene.entries.length); + expect(scene.draft(scene.duration)).toBe(""); + expect(scene.busy(scene.duration)).toBe(false); + expect(scene.reached("renamed", scene.duration)).toBe(true); + }); +}); diff --git a/packages/website/src/components/mockup/script.ts b/packages/website/src/components/mockup/script.ts new file mode 100644 index 0000000000..7079a587f0 --- /dev/null +++ b/packages/website/src/components/mockup/script.ts @@ -0,0 +1,267 @@ +import type { RemoteHostId } from "./hosts"; + +/** + * A collapsed tool call as the app's timeline shows it. Built-in tools carry a + * fixed label; Paseo MCP tools name their action, such as "Create agent". + */ +export type ToolCall = + | { kind: "read" | "write" | "shell"; detail: string } + | { kind: "paseo"; label: string; detail?: string; host?: RemoteHostId }; + +/** + * One step of a scripted scene. Beats play in order, each after the one before it ends. + * + * - `wait`: nothing happens. + * - `click`: the pointer glides to a named target and clicks it. + * - `type`: the user types into the composer. + * - `user`: the typed message is sent and joins the transcript. + * - `agent`: the agent's text streams into the transcript. + * - `tools`: the agent's tool calls land one at a time. + * - `turnEnd`: the turn finishes. With `worked`, its footer joins the transcript. + * - `mark`: a named moment the rest of the window reacts to, such as a panel opening. + */ +export type Beat = + | { kind: "wait"; ms: number } + | { kind: "click"; target: Target } + | { kind: "type"; text: string } + | { kind: "user"; text: string } + | { kind: "agent"; text: string } + | { kind: "tools"; calls: ToolCall[] } + | { kind: "turnEnd"; worked?: string } + | { kind: "mark"; name: Mark; ms: number }; + +type TranscriptBeat = + | Extract + | { kind: "turnEnd"; worked: string }; + +/** A beat that leaves something in the transcript, with the span of time it plays over. */ +export interface TranscriptEntry { + id: string; + start: number; + end: number; + beat: TranscriptBeat; +} + +/** One click of the pointer: it glides to its target, presses the button, and lets go. */ +export interface PointerClick { + /** + * How visible the pointer is for this click, from 0 to 1. It fades in on its way, and fades out + * when the user types. A click right after another one takes the same pointer over, with no fade. + */ + opacity(ms: number): number; + /** How far the pointer has come on its way to the target, from 0 to 1. */ + approach(ms: number): number; + /** Whether the pointer's button is down on the target. */ + pressed(ms: number): boolean; + /** Whether the click has happened: the button went down and came back up. */ + done(ms: number): boolean; +} + +/** The click target every scripted chat has. Clicking it puts the caret in the composer. */ +export const COMPOSER = "composer"; + +/** What a chat pane reads from a script: the composer and the transcript at a point in time. */ +export interface SceneScript { + /** The length of the whole script. At this time the scene shows its finished state. */ + duration: number; + entries: TranscriptEntry[]; + /** What the user is typing: the text so far, until it is sent. */ + draft(ms: number): string; + /** Whether a turn is running: from the user's message until the turn ends. */ + busy(ms: number): boolean; + /** How many transcript entries have started. */ + entered(ms: number): number; + /** How much of an agent entry's text has streamed in. */ + streamed(entry: TranscriptEntry, ms: number): string; + /** How many of a tools entry's calls have landed. */ + landed(entry: TranscriptEntry, ms: number): number; + /** The script's click on a target. */ + click(target: string): PointerClick; +} + +export interface Script extends SceneScript { + click(target: Target): PointerClick; + /** Whether a mark has started. */ + reached(mark: Mark, ms: number): boolean; + /** How far through a mark the scene is, from 0 to 1. */ + progress(mark: Mark, ms: number): number; +} + +// A demo types and streams faster than a person or a model does, and still reads as both. +const TYPING_MS_PER_CHARACTER = 14; +const SHORTEST_TYPING_MS = 700; +const PAUSE_BEFORE_SEND_MS = 320; +const SEND_MS = 420; +const STREAM_MS_PER_CHARACTER = 8; +const TOOL_CALL_MS = 320; +const TURN_END_MS = 420; +const POINTER_APPROACH_MS = 900; +const POINTER_PRESS_MS = 240; +const POINTER_FADE_MS = 150; + +function typingMs(text: string): number { + return Math.max(SHORTEST_TYPING_MS, text.length * TYPING_MS_PER_CHARACTER); +} + +function beatMs(beat: Beat): number { + switch (beat.kind) { + case "wait": + case "mark": + return beat.ms; + case "click": + return POINTER_APPROACH_MS + POINTER_PRESS_MS; + case "type": + return typingMs(beat.text) + PAUSE_BEFORE_SEND_MS; + case "user": + return SEND_MS; + case "agent": + return beat.text.length * STREAM_MS_PER_CHARACTER; + case "tools": + return beat.calls.length * TOOL_CALL_MS; + case "turnEnd": + return TURN_END_MS; + } +} + +function isTranscriptBeat(beat: Beat): beat is TranscriptBeat { + if (beat.kind === "turnEnd") return beat.worked !== undefined; + return beat.kind === "user" || beat.kind === "agent" || beat.kind === "tools"; +} + +function fraction(start: number, end: number, ms: number): number { + if (ms <= start) return 0; + if (ms >= end) return 1; + return (ms - start) / (end - start); +} + +// A hand speeds a mouse up and slows it down again. +function easeInOut(linear: number): number { + return linear < 0.5 ? 2 * linear * linear : 1 - (-2 * linear + 2) ** 2 / 2; +} + +function hundredths(value: number): number { + return Math.round(value * 100) / 100; +} + +/** How a click's pointer comes and goes. */ +interface PointerPresence { + /** When the pointer sets off. */ + start: number; + /** Whether the pointer is already on screen, at the click before this one. */ + continues: boolean; + /** When the pointer goes away, or `Infinity` when it stays to the end of the scene. */ + leaves: number; + /** Whether the next click takes the pointer over. Otherwise typing fades it out. */ + handsOver: boolean; +} + +function pointerClick({ start, continues, leaves, handsOver }: PointerPresence): PointerClick { + const pressStart = start + POINTER_APPROACH_MS; + const pressEnd = pressStart + POINTER_PRESS_MS; + return { + opacity(ms) { + if (ms >= leaves) { + return handsOver ? 0 : hundredths(1 - fraction(leaves, leaves + POINTER_FADE_MS, ms)); + } + if (continues) return ms >= start ? 1 : 0; + return hundredths(fraction(start, start + POINTER_FADE_MS, ms)); + }, + approach: (ms) => Math.round(easeInOut(fraction(start, pressStart, ms)) * 1000) / 1000, + pressed: (ms) => ms >= pressStart && ms < pressEnd, + done: (ms) => ms >= pressEnd, + }; +} + +/** Lays beats end to end and answers what the scene shows at any time. */ +export function script( + beats: Beat[], +): Script { + let clock = 0; + const timed = beats.map((beat, index) => { + const start = clock; + clock += beatMs(beat); + return { id: `${index}:${beat.kind}`, start, end: clock, beat }; + }); + const duration = clock; + + const entries: TranscriptEntry[] = []; + const typing: { start: number; end: number; text: string }[] = []; + const turns: { start: number; end: number }[] = []; + const marks = new Map(); + const clicks = new Map(); + // A hand that types is off the mouse, and the pointer has one place at a time. So typing takes + // the pointer off screen, and a click that follows a click takes the pointer over from it. + let pointerOnScreen = false; + timed.forEach(({ start, beat }, index) => { + if (beat.kind === "type") pointerOnScreen = false; + if (beat.kind !== "click") return; + const next = timed + .slice(index + 1) + .find((later) => later.beat.kind === "type" || later.beat.kind === "click"); + clicks.set( + beat.target, + pointerClick({ + start, + continues: pointerOnScreen, + leaves: next ? next.start : Infinity, + handsOver: next?.beat.kind === "click", + }), + ); + pointerOnScreen = true; + }); + for (const { id, start, end, beat } of timed) { + if (isTranscriptBeat(beat)) entries.push({ id, start, end, beat }); + if (beat.kind === "type") typing.push({ start, end, text: beat.text }); + if (beat.kind === "user") turns.push({ start, end: duration }); + if (beat.kind === "turnEnd") { + const turn = turns.at(-1); + if (turn) turn.end = start; + } + if (beat.kind === "mark") marks.set(beat.name, { start, end }); + } + + function span(mark: Mark) { + const found = marks.get(mark); + if (!found) throw new Error(`The script has no mark named ${mark}`); + return found; + } + + return { + duration, + entries, + draft(ms) { + const beat = typing.find(({ start, end }) => ms >= start && ms < end); + if (!beat) return ""; + const typed = fraction(beat.start, beat.start + typingMs(beat.text), ms); + return beat.text.slice(0, Math.ceil(typed * beat.text.length)); + }, + busy(ms) { + return turns.some(({ start, end }) => ms >= start && ms < end); + }, + entered(ms) { + // The last entry enters at the end of a script that closes on it, so the end counts. + return entries.filter(({ start }) => ms > start || ms >= duration).length; + }, + streamed(entry, ms) { + if (entry.beat.kind !== "agent") return ""; + const { text } = entry.beat; + return text.slice(0, Math.ceil(fraction(entry.start, entry.end, ms) * text.length)); + }, + landed(entry, ms) { + if (entry.beat.kind !== "tools") return 0; + return Math.ceil(fraction(entry.start, entry.end, ms) * entry.beat.calls.length); + }, + reached(mark, ms) { + return ms > span(mark).start || ms >= duration; + }, + progress(mark, ms) { + const { start, end } = span(mark); + return fraction(start, end, ms); + }, + click(target) { + const found = clicks.get(target); + if (!found) throw new Error(`The script has no click on ${target}`); + return found; + }, + }; +} diff --git a/packages/website/src/components/mockup/sidebar.tsx b/packages/website/src/components/mockup/sidebar.tsx index f1e5eeeed4..b536a760bf 100644 --- a/packages/website/src/components/mockup/sidebar.tsx +++ b/packages/website/src/components/mockup/sidebar.tsx @@ -6,7 +6,6 @@ import { CircleHelp, GitPullRequest, History, - House, PanelBottom, PanelLeft, Plus, @@ -18,10 +17,15 @@ import { SquarePlus, } from "lucide-react"; import type * as React from "react"; +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { SIDEBAR_W, TITLEBAR_H } from "./geometry"; +import { HostBadge, type RemoteHostId } from "./hosts"; import { PaseoMark } from "./icons"; import { FADE_IN, FADE_OUT } from "./motion"; +import { DELEGATED_TASKS, tasksDelegated } from "./orchestration"; +import { useSceneClock } from "./player"; +import { pluginInstalled } from "./plugin-build"; import type { MockupStateId } from "./states"; const SIDEBAR_STYLE = { width: SIDEBAR_W }; @@ -41,7 +45,7 @@ interface WorkspaceRow { title: string; avatar: Avatar; time: string; - host?: string; + host?: RemoteHostId; pr?: string; passed?: boolean; running?: boolean; @@ -65,6 +69,7 @@ const WORKING_ROWS: WorkspaceRow[] = [ id: "safe-area", title: "Fix commit safe area in emulators", avatar: PASEO, + host: "mac-mini", time: "4m", running: true, }, @@ -82,6 +87,7 @@ const READY_TO_REVIEW_ROWS: WorkspaceRow[] = [ id: "lineage", title: "Paseo homepage", avatar: PASEO, + host: "devbox", pr: "3981", passed: true, time: "now", @@ -97,6 +103,16 @@ const READY_TO_REVIEW_ROWS: WorkspaceRow[] = [ }, ]; +/** The workspaces the orchestrating agent created, one per delegated task. */ +const DELEGATED_ROWS: WorkspaceRow[] = DELEGATED_TASKS.map((task) => ({ + id: task.id, + title: task.title, + avatar: PASEO, + host: task.host, + time: "now", + running: true, +})); + const DONE_ROWS: WorkspaceRow[] = [ { id: "beta", title: "Release v0.7.0-beta.2", avatar: PASEO, time: "2h" }, { @@ -111,7 +127,7 @@ const DONE_ROWS: WorkspaceRow[] = [ id: "perms", title: "Design semantic permission sy…", avatar: PASEO, - host: "my-server", + host: "devbox", pr: "3981", passed: true, time: "7h", @@ -120,6 +136,7 @@ const DONE_ROWS: WorkspaceRow[] = [ id: "modules", title: "Plan modules and abstractions", avatar: PASEO, + host: "mac-mini", pr: "3884", passed: true, time: "1d", @@ -202,12 +219,7 @@ function RowMeta({ row }: { row: WorkspaceRow }) { if (row.host || row.pr) { return ( - {row.host ? ( - - - {row.host} - - ) : null} + {row.host ? : null} {row.host && row.pr ? · : null} {row.pr ? ( @@ -267,7 +279,18 @@ function GroupHeader({ icon, label }: { icon: React.ReactNode; label: string }) export function Sidebar({ state }: { state: MockupStateId }) { const { t } = useTranslation(); - const extending = state === "extend"; + // The plugin's item joins the nav when the plugin is installed, and each delegated workspace + // joins Working when the orchestrator creates it. + const pluginIsInstalled = useSceneClock("extend", pluginInstalled); + const delegated = useSceneClock("orchestrate", tasksDelegated); + const extending = state === "extend" && pluginIsInstalled; + const workingRows = useMemo( + () => + state === "orchestrate" + ? [...DELEGATED_ROWS.slice(0, delegated), ...WORKING_ROWS] + : WORKING_ROWS, + [state, delegated], + ); return (
@@ -321,7 +344,7 @@ export function Sidebar({ state }: { state: MockupStateId }) { - {WORKING_ROWS.map((row) => ( + {workingRows.map((row) => ( @@ -340,7 +363,7 @@ export function Sidebar({ state }: { state: MockupStateId }) { {t("landing.mockup.app.addProject")} - +
diff --git a/packages/website/src/components/mockup/states.ts b/packages/website/src/components/mockup/states.ts index 392244c267..c78033c8ae 100644 --- a/packages/website/src/components/mockup/states.ts +++ b/packages/website/src/components/mockup/states.ts @@ -1,13 +1,9 @@ -/** - * The states the hero mockup can be in, in pill order. Labels are copy — edit - * them here and nothing else has to change. - */ -/** The scenes the hero mockup can show; each pill's label is `landing.mockup.`. */ -export const MOCKUP_STATES = ["build", "review", "ship", "extend"] as const; +/** The scenes the hero mockup can show, in pill order. Each pill's label is `landing.mockup.`. */ +export const MOCKUP_STATES = ["orchestrate", "remote", "review", "ship", "extend"] as const; export type MockupStateId = (typeof MOCKUP_STATES)[number]; -export const DEFAULT_MOCKUP_STATE: MockupStateId = "build"; +export const DEFAULT_MOCKUP_STATE: MockupStateId = "orchestrate"; /** Which states keep a panel docked to the right of the workspace. */ export function hasRightPanel(_state: MockupStateId): boolean { diff --git a/packages/website/src/components/mockup/titlebar.tsx b/packages/website/src/components/mockup/titlebar.tsx index de99f4db76..849519739a 100644 --- a/packages/website/src/components/mockup/titlebar.tsx +++ b/packages/website/src/components/mockup/titlebar.tsx @@ -106,9 +106,17 @@ const WORKSPACE_TABS: Tab[] = [ const DIFF_TAB: Tab = { id: "diff", label: "Diff", icon: }; +/** The tab a scene has in front. The orchestrating agent is Claude; the remote scene is a terminal. */ +function activeTabId(state: MockupStateId): string { + if (state === "review") return DIFF_TAB.id; + if (state === "orchestrate") return "claude"; + if (state === "remote") return "terminal"; + return "codex"; +} + export function TabStrip({ state }: { state: MockupStateId }) { - const review = state === "review"; - const tabs = review ? [...WORKSPACE_TABS, DIFF_TAB] : WORKSPACE_TABS; + const tabs = state === "review" ? [...WORKSPACE_TABS, DIFF_TAB] : WORKSPACE_TABS; + const activeId = activeTabId(state); return (
{tab.icon} diff --git a/packages/website/src/components/mockup/window.tsx b/packages/website/src/components/mockup/window.tsx index ae95b68867..b2cf07bb3f 100644 --- a/packages/website/src/components/mockup/window.tsx +++ b/packages/website/src/components/mockup/window.tsx @@ -1,57 +1,123 @@ import { AnimatePresence, MotionConfig, motion, useReducedMotion } from "framer-motion"; -import { AgentTranscript, Composer, PluginBuildTranscript } from "./chat"; -import { DESIGN_HEIGHT, DESIGN_WIDTH, RIGHT_PANEL_W } from "./geometry"; +import type * as React from "react"; +import { useMemo } from "react"; +import { + AgentTranscript, + Composer, + ProgressTrack, + ScriptedComposer, + ScriptedTranscript, + SubagentsTrack, +} from "./chat"; +import { DESIGN_HEIGHT, DESIGN_WIDTH } from "./geometry"; +import { HostsModal } from "./hosts"; import { FADE_IN, FADE_OUT, INSTANT_TRANSITION, MOCKUP_TRANSITION } from "./motion"; -import { DiffReviewPane } from "./panes"; -import { RightPanel } from "./right-panel"; +import { ORCHESTRATION } from "./orchestration"; +import { DiffReviewPane, RemoteTerminalPane } from "./panes"; +import { + createScenePlayer, + type ScenePlayer, + ScenePlayerContext, + usePlayerScene, + useSceneClock, +} from "./player"; +import { PLUGIN_BUILD, pluginInstalled } from "./plugin-build"; +import { REVIEW } from "./review"; +import type { ProviderId } from "./providers"; +import { type PanelId, panelWidth, RightPanel } from "./right-panel"; +import type { SceneScript } from "./script"; import { Sidebar } from "./sidebar"; -import { hasRightPanel, type MockupStateId } from "./states"; +import { DEFAULT_MOCKUP_STATE, hasRightPanel, type MockupStateId } from "./states"; import { TabStrip, TitleBar } from "./titlebar"; const WINDOW_STYLE = { width: DESIGN_WIDTH, height: DESIGN_HEIGHT }; -const PANEL_STYLE = { width: RIGHT_PANEL_W }; const PANEL_COLLAPSED = { width: 0, opacity: 0 }; -const PANEL_OPEN = { width: RIGHT_PANEL_W + 1, opacity: 1 }; -/** Which center pane a state shows. States sharing a key keep it mounted. */ -function centerKey(state: MockupStateId): string { - if (state === "review") return "review"; - if (state === "extend") return "extend"; - return "chat"; +/** Which panel is docked on the right. The plugin's panel exists once the plugin is installed. */ +function dockedPanel(state: MockupStateId, pluginIsInstalled: boolean): PanelId { + if (state === "ship") return "ship"; + if (state === "extend" && pluginIsInstalled) return "plugin"; + return "changes"; } -function panelKey(state: MockupStateId): string { - if (state === "ship") return "ship"; - if (state === "extend") return "extend"; - return "changes"; +// Elements passed as props are hoisted so they are not rebuilt on every render. +const PROGRESS_TRACK = ; + +/** The scenes that play a script, with the agent the user talks to and that agent's composer track. */ +const SCRIPTED_SCENES: Partial< + Record +> = { + orchestrate: { script: ORCHESTRATION, agent: "claude", track: }, + extend: { script: PLUGIN_BUILD, agent: "codex" }, +}; + +/** A player for the mockup's scenes. It opens on the default scene. */ +export function createMockupPlayer(): ScenePlayer { + return createScenePlayer(DEFAULT_MOCKUP_STATE, { + orchestrate: ORCHESTRATION.duration, + extend: PLUGIN_BUILD.duration, + review: REVIEW.duration, + }); +} + +export { usePlayerScene as useMockupScene }; + +/** What the agent tab in front says in each scene. */ +function Transcript({ state }: { state: MockupStateId }) { + const scripted = SCRIPTED_SCENES[state]; + if (scripted) return ; + return ; +} + +/** The composer under that transcript: whose agent it is, its track, and whether a turn runs. */ +function ChatComposer({ state }: { state: MockupStateId }) { + const scripted = SCRIPTED_SCENES[state]; + if (scripted) { + return ( + + ); + } + return ; } function CenterPane({ state }: { state: MockupStateId }) { if (state === "review") return ; + if (state === "remote") return ; return (
- {/* Bottom-anchored: the newest turn sits on the composer, older text clips. */} -
- {state === "extend" ? : } + {/* A chat scrolls like this: a short transcript starts at the top, and one taller than the + pane keeps its newest turn on the composer while older text clips. The reversed column + pins the bottom, and the auto margin lifts a short transcript to the top. */} +
+
+ +
- +
); } -/** The docked panel keeps its width while its contents swap. */ -function PanelCrossfade({ state }: { state: MockupStateId }) { +/** The docked panel's contents cross-fade when the panel it shows changes. */ +function PanelCrossfade({ panel }: { panel: PanelId }) { return ( -
+
+ {/* Each panel keeps its own width and the dock clips it, so nothing inside a panel + reflows while the dock resizes. */} - +
@@ -67,7 +133,7 @@ function CenterColumn({ state }: { state: MockupStateId }) {
({ width: panelWidth(panel) + 1, opacity: 1 }), [panel]); return (
- + ); } -export function MockupWindow({ state }: { state: MockupStateId }) { +export function MockupWindow({ player }: { player: ScenePlayer }) { const reduceMotion = useReducedMotion(); + const state = usePlayerScene(player); return ( - -
- {/* Three full-height columns, each owning its own header. The middle + + +
+ {/* Three full-height columns, each owning its own header. The middle header stops at the divider — it never spans over the right panel. */} - -
- - - {hasRightPanel(state) ? : null} - -
- + +
+ + + {hasRightPanel(state) ? : null} + + {/* The remote scene opens the hosts modal over the whole window, as the app dims + everything behind a modal. */} + + {state === "remote" ? ( + + + + ) : null} + +
+ + ); } diff --git a/packages/website/src/downloads.tsx b/packages/website/src/downloads.tsx index a97b18c991..3ca73f6364 100644 --- a/packages/website/src/downloads.tsx +++ b/packages/website/src/downloads.tsx @@ -50,6 +50,7 @@ export function thanksPageHref(fileUrl: string, locale: Locale): string { } export const appStoreUrl = "https://apps.apple.com/app/paseo-pocket-engineer/id6758887924"; +export const testFlightBetaUrl = "https://testflight.apple.com/join/Y5HpSQjJ"; export const playStoreUrl = "https://play.google.com/store/apps/details?id=sh.paseo"; export const webAppUrl = "https://app.paseo.sh"; diff --git a/packages/website/src/i18n/resources/en.json b/packages/website/src/i18n/resources/en.json index b179f26326..9326886f40 100644 --- a/packages/website/src/i18n/resources/en.json +++ b/packages/website/src/i18n/resources/en.json @@ -446,7 +446,8 @@ }, "mockup": { "alt": "Paseo desktop app with coding agents, a conversation, and a code diff open side by side", - "build": "Parallel agents", + "orchestrate": "Orchestration", + "remote": "Remote", "review": "Code review", "ship": "Pull requests", "extend": "Plugins", @@ -459,6 +460,15 @@ "working": "Working", "done": "Done", "addProject": "Add project", + "addHost": "Add host", + "hosts": "Hosts", + "agentCount": "{{count}} agents", + "hostLinks": { + "local": "Local", + "relay": "Relay", + "tailscale": "Tailscale", + "ssh": "SSH" + }, "files": "Files", "changes": "Changes", "uncommitted": "Uncommitted", @@ -473,6 +483,11 @@ "tasksProgress": "{{completed}}/{{total}} tasks", "composerPlaceholder": "Message the agent, tag @files, or use /commands and /skills", "mobileComposerPlaceholder": "Message, @files, /commands", + "reviewCommentPlaceholder": "Leave a comment", + "reviewCancel": "Cancel", + "reviewSave": "Comment", + "sendFeedback": "Send feedback ({{count}})", + "feedbackSent": "Feedback sent to {{recipient}}", "plugin": "plugin", "mergedWeek": "Merged · 7d", "inReview": "In review", @@ -482,7 +497,8 @@ "minutesAgo": "{{count}}m ago", "hoursAgo": "{{count}}h ago", "reviewing": "reviewing", - "subagents": "{{count}} subagents", + "subagents_one": "{{count}} subagent", + "subagents_other": "{{count}} subagents", "checksPassedShort": "passed" } } diff --git a/packages/website/src/i18n/resources/zh-CN.json b/packages/website/src/i18n/resources/zh-CN.json index cc20bdb43e..7c1d8d9617 100644 --- a/packages/website/src/i18n/resources/zh-CN.json +++ b/packages/website/src/i18n/resources/zh-CN.json @@ -446,7 +446,8 @@ }, "mockup": { "alt": "Paseo 桌面应用,并排打开了编程 Agent、一段对话和一份代码 diff", - "build": "并行 Agent", + "orchestrate": "编排", + "remote": "远程", "review": "代码审查", "ship": "Pull Request", "extend": "插件", @@ -459,6 +460,15 @@ "working": "运行中", "done": "已完成", "addProject": "添加 project", + "addHost": "添加主机", + "hosts": "主机", + "agentCount": "{{count}} 个 Agent", + "hostLinks": { + "local": "本地", + "relay": "中继", + "tailscale": "Tailscale", + "ssh": "SSH" + }, "files": "文件", "changes": "变更", "uncommitted": "未 commit", @@ -473,6 +483,11 @@ "tasksProgress": "{{completed}}/{{total}} 项任务", "composerPlaceholder": "给 Agent 发消息,标记 @files,或使用 /commands 和 /skills", "mobileComposerPlaceholder": "发消息,@files,/commands", + "reviewCommentPlaceholder": "留下评论", + "reviewCancel": "取消", + "reviewSave": "评论", + "sendFeedback": "发送反馈 ({{count}})", + "feedbackSent": "已向 {{recipient}} 发送反馈", "plugin": "插件", "mergedWeek": "已合并 · 7 天", "inReview": "审查中", @@ -482,7 +497,8 @@ "minutesAgo": "{{count}} 分钟前", "hoursAgo": "{{count}} 小时前", "reviewing": "审查中", - "subagents": "{{count}} 个 subagent", + "subagents_one": "{{count}} 个 subagent", + "subagents_other": "{{count}} 个 subagent", "checksPassedShort": "通过" } } diff --git a/packages/website/src/routes/{-$locale}/download.tsx b/packages/website/src/routes/{-$locale}/download.tsx index de071302e5..6d4697bd1e 100644 --- a/packages/website/src/routes/{-$locale}/download.tsx +++ b/packages/website/src/routes/{-$locale}/download.tsx @@ -10,6 +10,7 @@ import { downloadUrls, appStoreUrl, playStoreUrl, + testFlightBetaUrl, thanksPageHref, webAppUrl, AppleIcon, @@ -159,13 +160,15 @@ function Download() { - {!onBeta && ( - - + + + {onBeta ? ( + + ) : ( - - - )} + )} + +
diff --git a/packages/website/src/styles.css b/packages/website/src/styles.css index cadcce2b6d..8d007eb5d4 100644 --- a/packages/website/src/styles.css +++ b/packages/website/src/styles.css @@ -770,7 +770,11 @@ --color-mock-tile-violet: #7a6aa8; --color-mock-tile-amber: #8f7838; --color-mock-tile-teal: #368080; + /* Host badge ink — the identity colors as foreground, IDENTITY_FOREGROUND_DARK in the + same file. */ --color-mock-host-teal: #6cacab; + --color-mock-host-violet: #a392d5; + --color-mock-host-orange: #cc8f64; /* Status *dot* band (dark: L=0.72, chroma 90%). Sidebar row state dots only. theme.ts:198-204. */ diff --git a/patches/@gorhom+bottom-sheet+5.2.14.patch b/patches/@gorhom+bottom-sheet+5.2.14.patch index 13d7df0565..7943d4cb19 100644 --- a/patches/@gorhom+bottom-sheet+5.2.14.patch +++ b/patches/@gorhom+bottom-sheet+5.2.14.patch @@ -1,3 +1,37 @@ +diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js +index f3d8f55..72d4322 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js +@@ -55,10 +55,10 @@ const BottomSheetDraggableViewComponent = ({ + const draggableGesture = (0, _react.useMemo)(() => { + let gesture = _reactNativeGestureHandler.Gesture.Pan().enabled(enableContentPanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(contentPanGestureHandler.handleOnStart).onChange(contentPanGestureHandler.handleOnChange).onEnd(contentPanGestureHandler.handleOnEnd).onFinalize(contentPanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); +diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js +index ee9e898..1500886 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js +@@ -59,10 +59,10 @@ function BottomSheetHandleContainerComponent({ + const panGesture = (0, _react.useMemo)(() => { + let gesture = _reactNativeGestureHandler.Gesture.Pan().enabled(enableHandlePanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(handlePanGestureHandler.handleOnStart).onChange(handlePanGestureHandler.handleOnChange).onEnd(handlePanGestureHandler.handleOnEnd).onFinalize(handlePanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetModal/BottomSheetModal.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetModal/BottomSheetModal.js index ee51e76..5fe8f75 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetModal/BottomSheetModal.js @@ -70,6 +104,40 @@ index e44ad86..96555ef 100644 var _useScrollEventsHandlersDefault = require("./hooks/useScrollEventsHandlersDefault"); var _useGestureEventsHandlersDefault = require("./hooks/useGestureEventsHandlersDefault"); var _useBottomSheetGestureHandlers = require("./hooks/useBottomSheetGestureHandlers"); +diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js +index 9efadd2..942b78a 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js +@@ -49,10 +49,10 @@ const BottomSheetDraggableViewComponent = ({ + const draggableGesture = useMemo(() => { + let gesture = Gesture.Pan().enabled(enableContentPanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(contentPanGestureHandler.handleOnStart).onChange(contentPanGestureHandler.handleOnChange).onEnd(contentPanGestureHandler.handleOnEnd).onFinalize(contentPanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); +diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js +index 3d1eafe..bf8e366 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js +@@ -53,10 +53,10 @@ function BottomSheetHandleContainerComponent({ + const panGesture = useMemo(() => { + let gesture = Gesture.Pan().enabled(enableHandlePanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(handlePanGestureHandler.handleOnStart).onChange(handlePanGestureHandler.handleOnChange).onEnd(handlePanGestureHandler.handleOnEnd).onFinalize(handlePanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetModal/BottomSheetModal.js b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetModal/BottomSheetModal.js index 94fabdb..d870aa7 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetModal/BottomSheetModal.js @@ -128,6 +196,19 @@ index 8259637..eb057fe 100644 export { useScrollEventsHandlersDefault } from './hooks/useScrollEventsHandlersDefault'; export { useGestureEventsHandlersDefault } from './hooks/useGestureEventsHandlersDefault'; export { useBottomSheetGestureHandlers } from './hooks/useBottomSheetGestureHandlers'; +diff --git a/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts b/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts +index 6b23056..8d92aae 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts ++++ b/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts +@@ -353,6 +353,6 @@ export type BottomSheetGestureProps = { + + simultaneousHandlers: Parameters< + PanGesture['simultaneousWithExternalGesture'] +- >[0]; +- waitFor: Parameters[0]; ++ >[0] | Parameters; ++ waitFor: Parameters[0] | Parameters; + }; diff --git a/node_modules/@gorhom/bottom-sheet/lib/typescript/index.d.ts b/node_modules/@gorhom/bottom-sheet/lib/typescript/index.d.ts index ffc6caa..550f1b3 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/typescript/index.d.ts @@ -141,6 +222,57 @@ index ffc6caa..550f1b3 100644 export { useScrollEventsHandlersDefault } from './hooks/useScrollEventsHandlersDefault'; export { useGestureEventsHandlersDefault } from './hooks/useGestureEventsHandlersDefault'; export { useBottomSheetGestureHandlers } from './hooks/useBottomSheetGestureHandlers'; +diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts +index 6b23056..8d92aae 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts ++++ b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts +@@ -353,6 +353,6 @@ export type BottomSheetGestureProps = { + + simultaneousHandlers: Parameters< + PanGesture['simultaneousWithExternalGesture'] +- >[0]; +- waitFor: Parameters[0]; ++ >[0] | Parameters; ++ waitFor: Parameters[0] | Parameters; + }; +diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx +index 923e430..eeef8cf 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx ++++ b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx +@@ -65,12 +65,12 @@ const BottomSheetDraggableViewComponent = ({ + .onFinalize(contentPanGestureHandler.handleOnFinalize); + + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + + if (simultaneousHandlers) { + gesture = gesture.simultaneousWithExternalGesture( +- simultaneousHandlers as never ++ ...(simultaneousHandlers as Parameters) + ); + } + +diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx +index 0223843..4ca56e5 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx ++++ b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx +@@ -67,12 +67,12 @@ function BottomSheetHandleContainerComponent({ + .onFinalize(handlePanGestureHandler.handleOnFinalize); + + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + + if (simultaneousHandlers) { + gesture = gesture.simultaneousWithExternalGesture( +- simultaneousHandlers as never ++ ...(simultaneousHandlers as Parameters) + ); + } + diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetModal/BottomSheetModal.tsx b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetModal/BottomSheetModal.tsx index 2954b3f..936300b 100644 --- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetModal/BottomSheetModal.tsx diff --git a/patches/react-native-draggable-flatlist+4.0.3.patch b/patches/react-native-draggable-flatlist+4.0.3.patch index ddbdb92224..9cd964268c 100644 --- a/patches/react-native-draggable-flatlist+4.0.3.patch +++ b/patches/react-native-draggable-flatlist+4.0.3.patch @@ -1,8 +1,8 @@ diff --git a/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts b/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts -index d3a4f1f..083bf19 100644 +index d3a4f1f..66e5124 100644 --- a/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts +++ b/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts -@@ -16,12 +16,14 @@ declare const _default: (props: Omit, "keyExtractor" | "data +@@ -16,12 +16,15 @@ declare const _default: (props: Omit, "keyExtractor" | "data keyExtractor: (item: T, index: number) => string; onDragBegin?: ((index: number) => void) | undefined; onDragEnd?: ((params: import("../types").DragEndParams) => void) | undefined; @@ -14,14 +14,15 @@ index d3a4f1f..083bf19 100644 renderPlaceholder?: import("../types").RenderPlaceholder | undefined; simultaneousHandlers?: React.Ref | React.Ref[] | undefined; + dragGestureHostPresented?: boolean | undefined; ++ dragGestureRef?: React.MutableRefObject | undefined; outerScrollOffset?: Animated.SharedValue | undefined; onAnimValInit?: ((animVals: { activeCellOffset: import("react-native-reanimated").SharedValue; diff --git a/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts b/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts -index d3c6cbb..36e9645 100644 +index d3c6cbb..a586a09 100644 --- a/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts +++ b/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts -@@ -15,12 +15,14 @@ export declare const NestableDraggableFlatList: (props: Omit(props: Omit string; onDragBegin?: ((index: number) => void) | undefined; onDragEnd?: ((params: import("../types").DragEndParams) => void) | undefined; @@ -33,14 +34,15 @@ index d3c6cbb..36e9645 100644 renderPlaceholder?: import("../types").RenderPlaceholder | undefined; simultaneousHandlers?: React.Ref | React.Ref[] | undefined; + dragGestureHostPresented?: boolean | undefined; ++ dragGestureRef?: React.MutableRefObject | undefined; outerScrollOffset?: Animated.SharedValue | undefined; onAnimValInit?: ((animVals: { activeCellOffset: import("react-native-reanimated").SharedValue; diff --git a/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts b/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts -index 2abb4a2..8ca967f 100644 +index 2abb4a2..c60dedf 100644 --- a/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts +++ b/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts -@@ -23,12 +23,16 @@ export declare type DraggableFlatListProps = Modify, { +@@ -23,12 +23,21 @@ export declare type DraggableFlatListProps = Modify, { keyExtractor: (item: T, index: number) => string; onDragBegin?: (index: number) => void; onDragEnd?: (params: DragEndParams) => void; @@ -54,11 +56,132 @@ index 2abb4a2..8ca967f 100644 simultaneousHandlers?: React.Ref | React.Ref[]; + /** @internal Forces handler reattachment when a retained native host is presented. */ + dragGestureHostPresented?: boolean; ++ /** ++ * Ref for the drag pan, so an enclosing gesture can wait for it to fail. The pan then arbitrates ++ * manually, as with `simultaneousHandlers`: it fails on a move unless a row is armed. ++ */ ++ dragGestureRef?: React.MutableRefObject; outerScrollOffset?: Animated.SharedValue; onAnimValInit?: (animVals: ReturnType) => void; itemEnteringAnimation?: AnimateProps["entering"]; +diff --git a/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx b/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx +index e4e861a..f485139 100644 +--- a/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx ++++ b/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx +@@ -8,6 +8,7 @@ import { + } from "react-native"; + import Animated, { + runOnUI, ++ SharedValue, + useAnimatedStyle, + useSharedValue, + } from "react-native-reanimated"; +@@ -40,12 +41,12 @@ function CellRendererComponent(props: Props) { + keyExtractor, + horizontal, + layoutAnimationDisabled, ++ transformHostKeys, + } = useDraggableFlatListContext(); + + const key = keyExtractor(item, index); + const offset = useSharedValue(-1); + const size = useSharedValue(-1); +- const heldTanslate = useSharedValue(0); + + const translate = useCellTranslate({ + cellOffset: offset, +@@ -55,20 +56,6 @@ function CellRendererComponent(props: Props) { + + const isActive = activeKey === key; + +- const animStyle = useAnimatedStyle(() => { +- // When activeKey becomes null at the end of a drag and the list reorders, +- // the animated style may apply before the next paint, causing a flicker. +- // Solution is to hold over the last animated value until the next onLayout. +- // (Not required in web) +- if (translate.value && !isWeb) { +- heldTanslate.value = translate.value; +- } +- const t = activeKey ? translate.value : heldTanslate.value; +- return { +- transform: [horizontalAnim.value ? { translateX: t } : { translateY: t }], +- }; +- }, [translate, activeKey]); +- + const updateCellMeasurements = useStableCallback(() => { + const onSuccess: MeasureLayoutOnSuccessCallback = (x, y, w, h) => { + if (isWeb && horizontal) x += scrollOffset.value; +@@ -99,7 +86,6 @@ function CellRendererComponent(props: Props) { + }); + + const onCellLayout = useStableCallback((e?: LayoutChangeEvent) => { +- heldTanslate.value = 0; + updateCellMeasurements(); + if (onLayout && e) onLayout(e); + }); +@@ -162,14 +148,58 @@ function CellRendererComponent(props: Props) { + ? itemLayoutAnimation + : undefined + } +- style={[props.style, baseStyle, animStyle]} ++ style={[props.style, baseStyle]} + pointerEvents={activeKey ? "none" : "auto"} + > +- {children} ++ ++ {children} ++ + + ); + } + ++// Owns the cell's drag translate. The list remounts it, with the cell's whole subtree, when a ++// drop moves the cell: the reorder commit then paints the new slot with no translate, because a ++// new view has no last animated transform for Reanimated to re-apply. ++function CellTransformHost({ ++ translate, ++ dragging, ++ horizontal, ++ children, ++}: { ++ translate: SharedValue; ++ dragging: boolean; ++ horizontal: boolean; ++ children: React.ReactNode; ++}) { ++ const { horizontalAnim } = useAnimatedValues(); ++ const animStyle = useAnimatedStyle(() => { ++ const t = dragging ? translate.value : 0; ++ return { ++ transform: [horizontalAnim.value ? { translateX: t } : { translateY: t }], ++ }; ++ }, [translate, dragging]); ++ ++ return ( ++ ++ {children} ++ ++ ); ++} ++ ++const styles = { ++ row: { flexDirection: "row" as const }, ++ column: { flexDirection: "column" as const }, ++}; ++ + export default typedMemo(CellRendererComponent); + + declare global { diff --git a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx -index 7c88afc..a74140f 100644 +index 7c88afc..05618ec 100644 --- a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx +++ b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx @@ -16,9 +16,11 @@ import { @@ -88,13 +211,56 @@ index 7c88afc..a74140f 100644 + sessionId: number; + index: number; + } | null>(null); - + const { dragHitSlop = DEFAULT_PROPS.dragHitSlop, -@@ -144,19 +157,88 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -100,6 +113,12 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + } = props; + + let [activeKey, setActiveKey] = useState(null); ++ // Reanimated re-applies a view's last animated transform to every React commit, so a moved ++ // cell would paint once at its new slot plus its old drag translate. The drop gives each ++ // moved cell a new transform host instead: a fresh view has no animated props to re-apply. ++ const [transformHostKeys, setTransformHostKeys] = useState< ++ ReadonlyMap ++ >(() => new Map()); + const [layoutAnimationDisabled, setLayoutAnimationDisabled] = useState( + !propsRef.current.enableLayoutAnimationExperimental + ); +@@ -113,10 +132,26 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + + const dataRef = useRef(props.data); + const dataHasChanged = +- dataRef.current.map(keyExtractor).join("") !== +- props.data.map(keyExtractor).join(""); +- dataRef.current = props.data; ++ dataRef.current.map(keyExtractor).join("") !== props.data.map(keyExtractor).join(""); ++ // Sheet portals can deliver reordered data after the drop callback commits. ++ // Keep the held transforms until that data arrives, then renew moved hosts ++ // in the same render as their new slots. + if (dataHasChanged) { ++ const wasDragging = activeKey !== null; ++ const previousIndices = new Map( ++ dataRef.current.map((item, index) => [keyExtractor(item, index), index]), ++ ); ++ setTransformHostKeys((previous) => { ++ const next = new Map(); ++ props.data.forEach((item, index) => { ++ const key = keyExtractor(item, index); ++ const generation = previous.get(key) ?? 0; ++ next.set(key, generation + (wasDragging && previousIndices.get(key) !== index ? 1 : 0)); ++ }); ++ return next; ++ }); ++ dataRef.current = props.data; ++ setActiveKey(null); + // When data changes make sure `activeKey` is nulled out in the same render pass + activeKey = null; + InteractionManager.runAfterInteractions(() => { +@@ -144,19 +179,88 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { }); }, [props.data, keyExtractor, keyToIndexRef]); - + + const onDragCancel = useStableCallback((sessionId: number, index: number) => { + if (activeDragRef.current?.sessionId !== sessionId) return; + activeDragRef.current = null; @@ -168,7 +334,7 @@ index 7c88afc..a74140f 100644 - activeCellOffset.value = cellData.measurements.offset; - activeCellSize.value = cellData.measurements.size; - } - + const { onDragBegin } = propsRef.current; if (index !== undefined) { - spacerIndexAnim.value = index; @@ -187,10 +353,10 @@ index 7c88afc..a74140f 100644 setActiveKey(activeKey); onDragBegin?.(index); } -@@ -218,8 +300,25 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -218,8 +322,25 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { props.onRelease?.(index); }); - + + const finalizeCancelledDrag = () => { + "worklet"; + const activeIndex = activeIndexAnim.value; @@ -212,12 +378,23 @@ index 7c88afc..a74140f 100644 + if (activeDragRef.current?.sessionId !== sessionId) return; + activeDragRef.current = null; const { onDragEnd, data } = props; - + const newData = [...data]; -@@ -238,26 +337,6 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -230,34 +351,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + + onDragEnd?.({ from, to, data: newData }); + +- setActiveKey(null); +- } ++ // A drop in place doesn't change data, so no data-change reset will clear the armed index. ++ if (from === to) reset(); ++ }, + ); + + const onPlaceholderIndexChange = useStableCallback((index: number) => { props.onPlaceholderIndexChange?.(index); }); - + - // Handle case where user ends drag without moving their finger. - useAnimatedReaction( - () => { @@ -241,15 +418,17 @@ index 7c88afc..a74140f 100644 useAnimatedReaction( () => { return spacerIndexAnim.value; -@@ -271,11 +350,24 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -271,11 +373,26 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { ); - + const gestureDisabled = useSharedValue(false); + const touchStartX = useSharedValue(0); + const touchStartY = useSharedValue(0); + const manualPanActivated = useSharedValue(false); -+ const coordinatesDragWithExternalGesture = Boolean(props.simultaneousHandlers); - ++ const coordinatesDragWithExternalGesture = Boolean( ++ props.simultaneousHandlers || props.dragGestureRef ++ ); + - const panGesture = Gesture.Pan() + let panGesture = Gesture.Pan() .onBegin((evt) => { @@ -267,7 +446,7 @@ index 7c88afc..a74140f 100644 panGestureState.value = evt.state; }) .onUpdate((evt) => { -@@ -286,8 +378,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -286,8 +403,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { : evt.translationY; touchTranslate.value = translation; }) @@ -284,15 +463,15 @@ index 7c88afc..a74140f 100644 // Set touch val to current translate val isTouchActiveNative.value = false; const translation = horizontalAnim.value -@@ -299,6 +398,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { - +@@ -299,6 +423,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + // Only call onDragEnd if actually dragging a cell if (activeIndexAnim.value === -1 || disabled.value) return; + terminalHandled.value = true; disabled.value = true; runOnJS(onRelease)(activeIndexAnim.value); const springTo = placeholderOffset.value - activeCellOffset.value; -@@ -309,22 +409,84 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -309,22 +434,85 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { runOnJS(onDragEnd)({ from: activeIndexAnim.value, to: spacerIndexAnim.value, @@ -371,16 +550,17 @@ index 7c88afc..a74140f 100644 + stateManager.fail(); + } }); - + if (dragHitSlop) panGesture.hitSlop(dragHitSlop); - if (activationDistanceProp) { ++ if (props.dragGestureRef) panGesture.withRef(props.dragGestureRef); + if (coordinatesDragWithExternalGesture) { + panGesture = panGesture.manualActivation(true); + } else if (activationDistanceProp) { const activeOffset = [-activationDistanceProp, activationDistanceProp]; if (props.horizontal) { panGesture.activeOffsetX(activeOffset); -@@ -332,6 +494,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -332,6 +520,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { panGesture.activeOffsetY(activeOffset); } } @@ -399,12 +579,14 @@ index 7c88afc..a74140f 100644 + props.dragGestureHostPresented === false + ? Gesture.Simultaneous(panGesture, Gesture.Manual().enabled(false)) + : panGesture; - + const onScroll = useStableCallback((scrollOffset: number) => { props.onScrollOffsetChange?.(scrollOffset); -@@ -373,8 +550,9 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -372,9 +575,11 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + keyExtractor={keyExtractor} horizontal={!!props.horizontal} layoutAnimationDisabled={layoutAnimationDisabled} ++ transformHostKeys={transformHostKeys} > - + @@ -426,17 +608,17 @@ index 1559352..33eb5de 100644 useSharedValue, @@ -48,7 +48,7 @@ function NestableDraggableFlatListInner( }); - + const onListContainerLayout = useStableCallback(async ({ containerRef }) => { - const nodeHandle = findNodeHandle(scrollableRef.current); + const nodeHandle = scrollableRef.current; - + const onSuccess = (_x: number, y: number) => { listVerticalOffset.value = y; @@ -74,6 +74,10 @@ function NestableDraggableFlatListInner( } ); - + + const onDragTerminate = useStableCallback(() => { + setOuterScrollEnabled(true); + }); @@ -452,11 +634,42 @@ index 1559352..33eb5de 100644 onAnimValInit={onAnimValInit} /> ); +diff --git a/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx b/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx +index 75f7db7..e99faf3 100644 +--- a/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx ++++ b/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx +@@ -5,6 +5,7 @@ type Props = { + keyExtractor: (item: T, index: number) => string; + horizontal: boolean; + layoutAnimationDisabled: boolean; ++ transformHostKeys: ReadonlyMap; + children: React.ReactNode; + }; + +@@ -19,6 +20,7 @@ export default function DraggableFlatListProvider({ + keyExtractor, + horizontal, + layoutAnimationDisabled, ++ transformHostKeys, + children, + }: Props) { + const value = useMemo( +@@ -27,8 +29,9 @@ export default function DraggableFlatListProvider({ + keyExtractor, + horizontal, + layoutAnimationDisabled, ++ transformHostKeys, + }), +- [activeKey, keyExtractor, horizontal, layoutAnimationDisabled] ++ [activeKey, keyExtractor, horizontal, layoutAnimationDisabled, transformHostKeys] + ); + + return ( diff --git a/node_modules/react-native-draggable-flatlist/src/types.ts b/node_modules/react-native-draggable-flatlist/src/types.ts -index d6755c8..1b244a6 100644 +index d6755c8..af70a01 100644 --- a/node_modules/react-native-draggable-flatlist/src/types.ts +++ b/node_modules/react-native-draggable-flatlist/src/types.ts -@@ -36,12 +36,16 @@ export type DraggableFlatListProps = Modify< +@@ -36,12 +36,21 @@ export type DraggableFlatListProps = Modify< keyExtractor: (item: T, index: number) => string; onDragBegin?: (index: number) => void; onDragEnd?: (params: DragEndParams) => void; @@ -470,6 +683,11 @@ index d6755c8..1b244a6 100644 simultaneousHandlers?: React.Ref | React.Ref[]; + /** @internal Forces handler reattachment when a retained native host is presented. */ + dragGestureHostPresented?: boolean; ++ /** ++ * Ref for the drag pan, so an enclosing gesture can wait for it to fail. The pan then arbitrates ++ * manually, as with `simultaneousHandlers`: it fails on a move unless a row is armed. ++ */ ++ dragGestureRef?: React.MutableRefObject; outerScrollOffset?: Animated.SharedValue; onAnimValInit?: (animVals: ReturnType) => void; itemEnteringAnimation?: AnimateProps["entering"]; diff --git a/patches/react-native-gesture-handler+2.32.0.patch b/patches/react-native-gesture-handler+2.32.0.patch index b6e3a810f1..1a8e6ae60f 100644 --- a/patches/react-native-gesture-handler+2.32.0.patch +++ b/patches/react-native-gesture-handler+2.32.0.patch @@ -152,18 +152,92 @@ index 8d78aea..b84d19e 100644 viewGroup: ViewGroup, coords: FloatArray, diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt -index 629c155..dc0790d 100644 +index 629c155..2efd508 100644 --- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt +++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt -@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: +@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: private val jsGestureHandler: GestureHandler? val rootView: ViewGroup private var shouldIntercept = false + private var wasIntercepting = false private var passingTouch = false ++ private var lastTouch: MotionEvent? = null init { -@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + UiThreadUtil.assertOnUiThread() +@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + } + + fun tearDown() { ++ clearLastTouch() + Log.i( + ReactConstants.TAG, + "[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView", +@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + + override fun onCancel() { + shouldIntercept = true +- val time = SystemClock.uptimeMillis() +- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply { +- action = MotionEvent.ACTION_CANCEL +- } + if (rootView is RootView) { +- rootView.onChildStartedNativeGesture(rootView, event) ++ val cancel = createReactCancelEvent() ++ try { ++ rootView.onChildStartedNativeGesture(rootView, cancel) ++ } finally { ++ cancel.recycle() ++ clearLastTouch() ++ } + } +- event.recycle() + } + } + ++ private fun clearLastTouch() { ++ lastTouch?.recycle() ++ lastTouch = null ++ } ++ ++ private fun createReactCancelEvent(): MotionEvent { ++ val now = SystemClock.uptimeMillis() ++ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) ++ // The enclosing React root already dispatched this event before it reached the ++ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS. ++ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1 ++ val count = touch.pointerCount - if (lifted >= 0) 1 else 0 ++ val properties = Array(count) { MotionEvent.PointerProperties() } ++ val coords = Array(count) { MotionEvent.PointerCoords() } ++ var index = 0 ++ for (pointer in 0 until touch.pointerCount) { ++ if (pointer == lifted) continue ++ touch.getPointerProperties(pointer, properties[index]) ++ touch.getPointerCoords(pointer, coords[index]) ++ index++ ++ } ++ return MotionEvent.obtain( ++ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords, ++ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision, ++ touch.deviceId, touch.edgeFlags, touch.source, touch.flags, ++ ) ++ } ++ + fun requestDisallowInterceptTouchEvent() { + // If this method gets called it means that some native view is attempting to grab lock for + // touch event delivery. In that case we cancel all gesture recognizers +@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + // We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell + // if `requestDisallow` has been called as a result of a normal gesture handling process or + // as a result of one of the gesture handlers activating ++ // Keep the stream for recognizers that activate between events (e.g. long press). ++ // Once native handling begins, React no longer receives the remaining touches. ++ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) { ++ clearLastTouch() ++ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) { ++ lastTouch = MotionEvent.obtainNoHistory(event) ++ } ++ } passingTouch = true orchestrator!!.onTouchEvent(event) passingTouch = false diff --git a/plugin-examples/agent-configuration/index.server.ts b/plugin-examples/agent-configuration/index.server.ts index 717f796a81..e8c0141222 100644 --- a/plugin-examples/agent-configuration/index.server.ts +++ b/plugin-examples/agent-configuration/index.server.ts @@ -27,6 +27,10 @@ export default function contribute(server: PluginServerContext) { return { ...request, + appendSystemPrompt: [ + ...(request.appendSystemPrompt ?? []), + "Follow the team engineering guide.", + ], mcpServers: { ...request.mcpServers, company: { diff --git a/plugin-examples/catppuccin/index.client.ts b/plugin-examples/catppuccin/index.client.ts index da65198710..80b2ded1f7 100644 --- a/plugin-examples/catppuccin/index.client.ts +++ b/plugin-examples/catppuccin/index.client.ts @@ -14,6 +14,12 @@ export default function contribute(client: PluginClientContext) { accent: "#cba6f7", mutedForeground: "#a6adc8", ring: "#6c7086", + sidebar: "#181825", + sidebarHover: "#313244", + sidebarSelected: "#45475a", + surface3: "#45475a", + surface4: "#585b70", + foregroundExtraMuted: "#7f849c", }, }); return () => {}; diff --git a/plugin-examples/catppuccin/paseo-plugin.json b/plugin-examples/catppuccin/paseo-plugin.json index 0ebf66ed4e..6b95b42178 100644 --- a/plugin-examples/catppuccin/paseo-plugin.json +++ b/plugin-examples/catppuccin/paseo-plugin.json @@ -1,6 +1,6 @@ { "id": "catppuccin", "requirements": { - "paseo": ">=0.8.0" + "paseo": ">=0.16.0" } } diff --git a/plugin-examples/lifecycle-actions/index.server.ts b/plugin-examples/lifecycle-actions/index.server.ts index 906cd2d565..a89c7aa82f 100644 --- a/plugin-examples/lifecycle-actions/index.server.ts +++ b/plugin-examples/lifecycle-actions/index.server.ts @@ -23,8 +23,9 @@ export default function contribute(server: PluginServerContext) { return; } const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); + const page = await agent.timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries.filter((entry) => entry.turnId === event.turnId); + const text = latestOutputText(turn.map(({ item }) => item)); if (/out of credits/i.test(text)) { console.log("Sending a follow-up after out of credits", event.agent.id); await agent.send("Try again."); diff --git a/plugin-examples/workspace-row-badges/README.md b/plugin-examples/workspace-row-badges/README.md new file mode 100644 index 0000000000..0973457e9f --- /dev/null +++ b/plugin-examples/workspace-row-badges/README.md @@ -0,0 +1,9 @@ +# Workspace row badges + +Install this directory as a plugin. Any workspace that needs input or has failed shows a badge on +the line under its title in the sidebar. Workspaces in any other state show nothing. + +The component reads its own data with `useWorkspace(workspaceId, selector)` and returns `null` when +it has nothing to say. **Show → Workspace attention** in the sidebar's display preferences toggles it. + +See the [reference](../../public-docs/plugins/reference.md#workspace-row-badge-items). diff --git a/plugin-examples/workspace-row-badges/index.client.tsx b/plugin-examples/workspace-row-badges/index.client.tsx new file mode 100644 index 0000000000..9aa371229f --- /dev/null +++ b/plugin-examples/workspace-row-badges/index.client.tsx @@ -0,0 +1,29 @@ +import { useWorkspace } from "@getpaseo/plugin/client"; +import type { + PluginClientContext, + PluginWorkspaceRowBadgeItemProps, +} from "@getpaseo/plugin/client"; +import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; + +function WorkspaceAttention({ workspaceId }: PluginWorkspaceRowBadgeItemProps) { + const status = useWorkspace(workspaceId, (workspace) => workspace.status); + if (status === "needs_input") { + return ; + } + if (status === "failed") { + return ; + } + return null; +} + +export default function contribute(client: PluginClientContext) { + // Apps older than this API do not have the method, and requirements.paseo cannot exclude them. + if (!client.addWorkspaceRowBadgeItem) return () => {}; + client.addWorkspaceRowBadgeItem({ + id: "attention", + title: "Workspace attention", + icon: "CircleAlert", + Component: WorkspaceAttention, + }); + return () => {}; +} diff --git a/plugin-examples/workspace-row-badges/paseo-plugin.json b/plugin-examples/workspace-row-badges/paseo-plugin.json new file mode 100644 index 0000000000..3c824820fb --- /dev/null +++ b/plugin-examples/workspace-row-badges/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "workspace-row-badges", "requirements": { "paseo": ">=0.16.0" } } diff --git a/plugins/codex-usage-source/server/usage.test.ts b/plugins/codex-usage-source/server/usage.test.ts index 4cdefa2bcd..c793d8dd12 100644 --- a/plugins/codex-usage-source/server/usage.test.ts +++ b/plugins/codex-usage-source/server/usage.test.ts @@ -328,9 +328,10 @@ test("reports every named additional limit with its own duration identity", asyn test("a weekly pin means weekly after the provider moves it between slots", async () => { const { resolvePinnedUsage } = await import("../../../packages/app/src/usage/pinned.js"); + const { DEFAULT_USAGE_PREFERENCES } = + await import("../../../packages/app/src/usage/preferences.js"); const preferences = { - displayAs: "used" as const, - serverId: null, + ...DEFAULT_USAGE_PREFERENCES, pins: [{ sourceId: "codex", windowId: "weekly" }], }; for (const primaryWeekly of [false, true]) { diff --git a/plugins/copilot-usage-source/server/usage.test.ts b/plugins/copilot-usage-source/server/usage.test.ts index 8333f28828..def2a2d0c2 100644 --- a/plugins/copilot-usage-source/server/usage.test.ts +++ b/plugins/copilot-usage-source/server/usage.test.ts @@ -171,3 +171,90 @@ it.each([401, 403])("reports an existing login rejected with HTTP %i", async (st else process.env["COPILOT_TOKEN"] = previous; } }); + +it.each([ + { remaining: 1500, percentRemaining: 100, usedPct: 0 }, + { remaining: 1125, percentRemaining: 75, usedPct: 25 }, + { remaining: 0, percentRemaining: 0, usedPct: 100 }, +])( + "reports premium quota with $remaining requests remaining", + async ({ remaining, percentRemaining, usedPct }) => { + const report = await fetchPremiumQuota({ + entitlement: 1500, + remaining, + percent_remaining: percentRemaining, + unlimited: false, + }); + expect(report).toMatchObject({ + status: "available", + planLabel: "individual", + windows: [ + { + id: "premium_interactions", + label: "Premium requests", + usedPct, + remainingPct: percentRemaining, + resetsAt: "2026-12-01T00:00:00.000Z", + }, + ], + details: expect.arrayContaining([ + { + id: "premium_remaining", + label: "Premium requests remaining", + value: `${remaining} / 1500`, + }, + ]), + }); + }, +); + +it.each([ + undefined, + null, + { unlimited: true, percent_remaining: 100, remaining: 1500, entitlement: 1500 }, +])( + "does not invent a finite quota for absent or unlimited premium snapshots (%j)", + async (premium) => { + const report = await fetchPremiumQuota(premium); + expect(report).toMatchObject({ + status: "available", + windows: [], + details: [{ id: "reset", label: "Quota reset", value: "2026-12-01" }], + }); + }, +); + +it("reports a percentage without inventing missing counts and falls back to the legacy reset", async () => { + const report = await fetchPremiumQuota({ percent_remaining: 60, unlimited: false }, null); + expect(report).toMatchObject({ + status: "available", + windows: [{ usedPct: 40, remainingPct: 60, resetsAt: "2026-12-01" }], + details: [{ id: "reset", label: "Quota reset", value: "2026-12-01" }], + }); +}); + +async function fetchPremiumQuota( + premium: unknown, + utcReset: string | null = "2026-12-01T00:00:00.000Z", +) { + const { writeFile } = await import("node:fs/promises"); + const directory = mkdtempSync(join(tmpdir(), "copilot-premium-")); + const locator = join(directory, "hosts.yml"); + try { + await writeFile(locator, "github.com:\n oauth_token: fixture-copilot\n"); + return await fetchUsage({ store: "file", locator }, async () => + jsonResponse({ + copilot_plan: "individual", + quota_reset_date: "2026-12-01", + quota_reset_date_utc: utcReset, + quota_snapshots: { + premium_interactions: premium, + chat: { unlimited: true, percent_remaining: 100 }, + completions: { unlimited: true, percent_remaining: 100 }, + }, + }), + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/plugins/copilot-usage-source/server/usage.ts b/plugins/copilot-usage-source/server/usage.ts index 78ae61bc9f..b7159c6970 100644 --- a/plugins/copilot-usage-source/server/usage.ts +++ b/plugins/copilot-usage-source/server/usage.ts @@ -5,6 +5,8 @@ import { join } from "node:path"; import { z } from "zod"; import { unavailable, + windowFromUsedPct, + type UsageWindow, type UsageAccount, type UsageReport, type UsageDetail, @@ -18,6 +20,19 @@ const ApiOptionalStringSchema = z.preprocess( const CopilotUsageResponseSchema = z.object({ copilot_plan: ApiOptionalStringSchema, quota_reset_date: ApiOptionalStringSchema, + quota_reset_date_utc: ApiOptionalStringSchema, + quota_snapshots: z + .object({ + premium_interactions: z + .object({ + entitlement: z.number().nonnegative().nullish(), + remaining: z.number().nonnegative().nullish(), + percent_remaining: z.number().min(0).max(100).nullish(), + unlimited: z.boolean().optional(), + }) + .nullish(), + }) + .nullish(), }); async function readToken(input: UsageInput): Promise { @@ -72,10 +87,32 @@ export async function fetchUsage( ? [{ id: "reset", label: "Quota reset", value: resp.quota_reset_date }] : []; + const windows: UsageWindow[] = []; + const premium = resp.quota_snapshots?.premium_interactions; + if (premium && !premium.unlimited) { + if (premium.percent_remaining != null) { + windows.push( + windowFromUsedPct({ + id: "premium_interactions", + label: "Premium requests", + utilizationPct: 100 - premium.percent_remaining, + resetsAt: resp.quota_reset_date_utc || resp.quota_reset_date, + }), + ); + } + if (premium.remaining != null && premium.entitlement != null) { + details.push({ + id: "premium_remaining", + label: "Premium requests remaining", + value: `${premium.remaining} / ${premium.entitlement}`, + }); + } + } + return { status: "available", planLabel: resp.copilot_plan || undefined, - windows: [], + windows, balances: [], details, }; diff --git a/plugins/package.json b/plugins/package.json index b160396c83..c0e59d6a6e 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0-beta.1", + "version": "0.16.1", "private": true, "type": "module", "scripts": { diff --git a/plugins/worktree-include/server/copy.test.ts b/plugins/worktree-include/server/copy.test.ts new file mode 100644 index 0000000000..30ada0c06d --- /dev/null +++ b/plugins/worktree-include/server/copy.test.ts @@ -0,0 +1,291 @@ +import { execFileSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { copyWorktreeIncludes } from "./copy.js"; + +let root: string; +let source: string; +let worktree: string; + +async function writeSource(files: Record): Promise { + for (const [file, contents] of Object.entries(files)) { + await mkdir(dirname(join(source, file)), { recursive: true }); + await writeFile(join(source, file), contents); + } +} + +// Total directories Git visits while listing files, read from its trace2 events. +async function directoriesVisited(run: () => Promise): Promise { + const trace = join(root, "trace.json"); + process.env.GIT_TRACE2_EVENT = trace; + try { + await run(); + } finally { + delete process.env.GIT_TRACE2_EVENT; + } + return (await readFile(trace, "utf8")) + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as { event: string; key?: string; value?: string }) + .filter((event) => event.event === "data" && event.key === "directories-visited") + .reduce((total, event) => total + Number(event.value), 0); +} + +async function copied(): Promise { + const result = await copyWorktreeIncludes(worktree, source); + if (result.kind !== "copied") throw new Error(`expected a copy, got ${result.kind}`); + return [...result.copied].sort(); +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "worktree-include-")); + source = join(root, "source"); + worktree = join(root, "worktree"); + await mkdir(source); + await mkdir(worktree); + execFileSync("git", ["init", "-q", source]); +}); + +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +describe("copyWorktreeIncludes", () => { + it("does not search inside an ignored directory that no pattern names", async () => { + await writeSource({ + ".gitignore": "node_modules/\n.env\n", + ".worktreeinclude": ".env\n", + ".env": "SECRET=root", + "apps/web/.env": "SECRET=web", + "node_modules/pkg/.env": "SECRET=package", + }); + + expect(await copied()).toEqual([".env", "apps/web/.env"]); + expect(existsSync(join(worktree, "node_modules"))).toBe(false); + }); + + it("searches inside ignored directories for a pattern that starts with **/", async () => { + await writeSource({ + ".gitignore": "node_modules/\n.env\n", + ".worktreeinclude": "**/.env\n", + ".env": "SECRET=root", + "node_modules/pkg/.env": "SECRET=package", + }); + + expect(await copied()).toEqual([".env", "node_modules/pkg/.env"]); + }); + + it("copies a file in an untracked directory once when a **/ pattern also searches it", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": "**/.env\nnew-package/.env\n", + "new-package/.env": "SECRET=new", + }); + + const result = await copyWorktreeIncludes(worktree, source); + expect(result).toEqual({ + kind: "copied", + copied: ["new-package/.env"], + skipped: [], + }); + }); + + it("copies a path a pattern names inside an ignored directory", async () => { + await writeSource({ + ".gitignore": "node_modules/\n", + ".worktreeinclude": "node_modules/pkg/.env\n", + "node_modules/pkg/.env": "SECRET=package", + "node_modules/other/.env": "SECRET=other", + }); + + expect(await copied()).toEqual(["node_modules/pkg/.env"]); + }); + + it("copies an ignored directory that a pattern names", async () => { + await writeSource({ + ".gitignore": ".secrets/\nbuild/\n", + ".worktreeinclude": ".secrets/\n", + ".secrets/a.key": "a", + ".secrets/nested/b.key": "b", + "build/out.js": "built", + }); + + expect(await copied()).toEqual([".secrets/a.key", ".secrets/nested/b.key"]); + }); + + it("searches inside an ignored directory for a path a pattern names", async () => { + await writeSource({ + ".gitignore": "config/\n", + ".worktreeinclude": "config/*.local.json\n!config/production.local.json\n", + "config/dev.local.json": "dev", + "config/production.local.json": "production", + "config/defaults.json": "defaults", + }); + + expect(await copied()).toEqual(["config/dev.local.json"]); + expect(await readFile(join(worktree, "config/dev.local.json"), "utf8")).toBe("dev"); + }); + + it("copies ignored files inside an untracked directory", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": ".env\n", + "new-package/.env": "SECRET=new", + }); + + expect(await copied()).toEqual(["new-package/.env"]); + }); + + it("copies nothing that is tracked or not ignored", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": ".env\nnotes.txt\n", + "notes.txt": "not ignored", + }); + + expect(await copied()).toEqual([]); + }); + + it("searches only the path a glob-free pattern names directly inside an ignored directory", async () => { + const packages: Record = {}; + for (let i = 0; i < 20; i++) packages[`node_modules/pkg${i}/lib/index.js`] = "code"; + await writeSource({ + ".gitignore": "node_modules/\n", + ".worktreeinclude": "node_modules/.cache\n", + "node_modules/.cache/state.json": "cache", + ...packages, + }); + + let result: Awaited> | undefined; + const visited = await directoriesVisited(async () => { + result = await copyWorktreeIncludes(worktree, source); + }); + + expect(result).toEqual({ + kind: "copied", + copied: ["node_modules/.cache/state.json"], + skipped: [], + }); + expect(visited).toBeLessThan(10); + }); + + it.skipIf(process.platform === "win32")( + "copies includes when an ignored file is named like a Git pathspec", + async () => { + await writeSource({ + ".gitignore": "*.log\n.env\n", + ".worktreeinclude": ".env\n", + ".env": "SECRET=root", + ":(oops.log": "log", + ":!c.log": "log", + }); + + expect(await copied()).toEqual([".env"]); + }, + ); + + it("ignores exclude patterns from the user's git template", async () => { + const template = join(root, "template"); + await mkdir(join(template, "info"), { recursive: true }); + await writeFile(join(template, "info", "exclude"), "*.log\n"); + await writeSource({ + ".gitignore": "*.log\n.env\n", + ".worktreeinclude": ".env\n", + ".env": "SECRET=root", + "debug.log": "log", + }); + + process.env.GIT_TEMPLATE_DIR = template; + try { + expect(await copied()).toEqual([".env"]); + } finally { + delete process.env.GIT_TEMPLATE_DIR; + } + }); + + it("does not search an ignored directory deeper than a pattern without ** can reach", async () => { + const packages: Record = {}; + for (let i = 0; i < 20; i++) packages[`apps/web/node_modules/pkg${i}/lib/index.js`] = "code"; + await writeSource({ + ".gitignore": "node_modules/\n.env\n", + ".worktreeinclude": "apps/*/.env\n", + "apps/web/.env": "SECRET=web", + ...packages, + }); + + let result: Awaited> | undefined; + const visited = await directoriesVisited(async () => { + result = await copyWorktreeIncludes(worktree, source); + }); + + expect(result).toEqual({ kind: "copied", copied: ["apps/web/.env"], skipped: [] }); + expect(visited).toBeLessThan(10); + }); + + it("reads the first pattern after a UTF-8 byte order mark", async () => { + await writeSource({ + ".gitignore": "node_modules/\n", + ".worktreeinclude": "\uFEFFnode_modules/.cache/\n", + "node_modules/.cache/state.json": "cache", + }); + + expect(await copied()).toEqual(["node_modules/.cache/state.json"]); + }); + + it("matches patterns case-insensitively when the source repo ignores case", async () => { + execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]); + await writeSource({ + ".gitignore": ".env\nconfig/\n", + ".worktreeinclude": ".ENV\nCONFIG/a.json\n", + ".env": "SECRET=root", + "config/a.json": "a", + }); + + expect(await copied()).toEqual([".env", "config/a.json"]); + }); + + it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => { + execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]); + await writeSource({ + ".gitignore": "Config/\nÉTÉ/\n", + ".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n", + "Config/a.json": "a", + "ÉTÉ/sub/.env": "SECRET=summer", + }); + + expect(await copied()).toEqual(["Config/a.json", "ÉTÉ/sub/.env"]); + }); + + // Each searched folder is one argument to Git. Windows caps a command line at 32,767 + // characters and Linux at 2 MB, so each platform gets enough folders to exceed its own + // limit, with names short enough for Windows paths. + it("searches more ignored folders than fit on one command line", async () => { + const folders = process.platform === "win32" ? 300 : 15_000; + const name = (i: number) => `${"x".repeat(150)}${i}`; + await writeSource({ + ".gitignore": "x*/\n.env\n", + ".worktreeinclude": "**/.env\n", + [`${name(folders - 1)}/.env`]: "SECRET=last", + }); + for (let i = 0; i < folders - 1; i++) await mkdir(join(source, name(i))); + await Promise.all( + Array.from({ length: folders - 1 }, (_, i) => writeFile(join(source, name(i), "a"), "")), + ); + + expect(await copied()).toEqual([`${name(folders - 1)}/.env`]); + }, 60_000); + + it("copies ignored files inside an untracked directory a pattern names", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": "newdir/\n", + "newdir/.env": "SECRET=new", + "newdir/notes.txt": "untracked", + }); + + expect(await copied()).toEqual(["newdir/.env"]); + }); +}); diff --git a/plugins/worktree-include/server/copy.ts b/plugins/worktree-include/server/copy.ts index 73a3ba63f3..1b8cab3cbd 100644 --- a/plugins/worktree-include/server/copy.ts +++ b/plugins/worktree-include/server/copy.ts @@ -2,7 +2,8 @@ // Copyright (c) 2026 Carlos Precioso. import { execFile } from "node:child_process"; import { constants, existsSync } from "node:fs"; -import { copyFile, mkdir } from "node:fs/promises"; +import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; @@ -22,37 +23,33 @@ async function git(cwd: string, args: string[], input?: string): Promise return stdout; } -async function gitAllowExit1(cwd: string, args: string[], input: string): Promise { +// `git check-ignore --stdin` reads each path as a pathspec, so a name such as `:(x` +// would be parsed as pathspec magic. A `./` prefix keeps every path literal. +async function checkIgnore(cwd: string, args: string[], paths: string[]): Promise { + const input = paths.map((path) => `./${path}\0`).join(""); + let output: string; try { - return await git(cwd, args, input); + output = await git(cwd, [...args, "check-ignore", "--stdin", "-z"], input); } catch (error) { // `git check-ignore` exits 1 when nothing matched. - if ((error as { code?: number }).code === 1) return ""; + if ((error as { code?: number }).code === 1) return []; throw error; } + return splitNul(output).map((path) => path.replace(/^\.\//, "")); } const splitNul = (s: string) => s.split("\0").filter(Boolean); +const isDirectory = (entry: string) => entry.endsWith("/"); // Copy files that match .worktreeinclude (gitignore syntax) // AND are gitignored, so tracked files are never touched. export async function copyWorktreeIncludes(worktree: string, source: string): Promise { if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" }; - const matches = splitNul( - await git(source, [ - "ls-files", - "--others", - "--ignored", - `--exclude-from=${INCLUDE_FILE}`, - "-z", - ]), - ); + const matches = await findIncludedFiles(source); if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] }; - const ignored = splitNul( - await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"), - ); + const ignored = await checkIgnore(source, [], matches); const copied: string[] = []; const skipped: string[] = []; @@ -69,3 +66,152 @@ export async function copyWorktreeIncludes(worktree: string, source: string): Pr } return { kind: "copied", copied, skipped }; } + +// Git lists a directory it ignores as a whole, such as node_modules/, as one entry. +// Only directories that a pattern matches or names a path inside are searched, and +// only as deep as the pattern names, so creating a worktree does not walk every file +// in large ignored trees. +async function findIncludedFiles(source: string): Promise { + const ignored = splitNul( + await git(source, [ + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--directory", + "-z", + ]), + ); + if (ignored.length === 0) return []; + + const ignoreCase = await sourceIgnoresCase(source); + const patterns = parsePatterns(await readFile(join(source, INCLUDE_FILE), "utf8")); + const matched = new Set(await matchIncludePatterns(source, ignored, ignoreCase)); + const files = ignored.filter((entry) => !isDirectory(entry) && matched.has(entry)); + const searched = new Set(); + // Git also lists an untracked folder that holds ignored entries, which are listed on + // their own, so only folders Git ignores as a whole are searched. + const directories = await checkIgnore(source, [], ignored.filter(isDirectory)); + for (const directory of directories) { + if (matched.has(directory)) { + searched.add(directory); + continue; + } + for (const pattern of patterns) { + const inside = searchedPathInside(pattern, directory, ignoreCase); + if (inside !== null) searched.add(inside); + } + } + if (searched.size === 0) return files; + + const pathspecs = [...searched].map( + (path) => `:(${ignoreCase ? "literal,icase" : "literal"})${path}`, + ); + const inside: string[] = []; + for (const batch of commandLineBatches(pathspecs)) { + const listed = await git(source, [ + "ls-files", + "--others", + "--ignored", + `--exclude-from=${INCLUDE_FILE}`, + "-z", + "--", + ...batch, + ]); + inside.push(...splitNul(listed)); + } + return [...new Set([...files, ...inside])]; +} + +// Windows caps a command line at 32,767 characters, so a pattern such as `**/.env` in a +// repo with many ignored folders searches them over several Git calls. +const COMMAND_LINE_BATCH_CHARS = 16_000; + +function commandLineBatches(args: string[]): string[][] { + const batches: string[][] = []; + let batch: string[] = []; + let length = 0; + for (const arg of args) { + if (batch.length > 0 && length + arg.length + 1 > COMMAND_LINE_BATCH_CHARS) { + batches.push(batch); + batch = []; + length = 0; + } + batch.push(arg); + length += arg.length + 1; + } + if (batch.length > 0) batches.push(batch); + return batches; +} + +// Match entries against .worktreeinclude alone, in a scratch repository where no other +// ignore rules apply. Directory entries keep their trailing slash, so directory +// patterns match them without anything on disk. +async function matchIncludePatterns( + source: string, + entries: string[], + ignoreCase: boolean, +): Promise { + const scratch = await mkdtemp(join(tmpdir(), "paseo-worktree-include-")); + try { + // An empty template keeps the user's template `info/exclude` out of the matching. + await git(scratch, ["init", "-q", "--template="]); + return await checkIgnore( + scratch, + [ + "-c", + `core.excludesFile=${join(source, INCLUDE_FILE)}`, + "-c", + `core.ignoreCase=${ignoreCase}`, + ], + entries, + ); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +} + +// The scratch repository would otherwise take core.ignoreCase from the temp folder. +async function sourceIgnoresCase(source: string): Promise { + try { + return (await git(source, ["config", "--type=bool", "core.ignoreCase"])).trim() === "true"; + } catch { + // `git config` exits 1 when the key is unset. + return false; + } +} + +function parsePatterns(contents: string): string[] { + // Git skips a leading UTF-8 byte order mark in exclude files. + return contents + .replace(/^\uFEFF/, "") + .split(/\r?\n/) + .map((line) => line.trimEnd()) + .filter((line) => line !== "" && !line.startsWith("#") && !line.startsWith("!")); +} + +// A pattern with a slash before its end is anchored to the checkout root, so it can +// name a path inside `directory` when its literal start and the directory overlap. +// Without `**`, a pattern matches paths of exactly its own depth, so a directory that +// deep or deeper can hold no match below it. Returns the narrowest path to search: the +// whole path when the pattern has no glob, else the folder before its first glob, or +// `directory` itself when the path ends above it. +function searchedPathInside( + pattern: string, + rawDirectory: string, + ignoreCase: boolean, +): string | null { + // Git folds only ASCII letters when it ignores case. + const fold = (text: string) => + ignoreCase ? text.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()) : text; + const path = fold(pattern.replace(/^\//, "")); + const directory = fold(rawDirectory); + const depth = (text: string) => text.replace(/\/$/, "").split("/").length; + if (depth(path) < 2) return null; + if (!path.includes("**") && depth(directory) >= depth(path)) return null; + const globAt = path.search(/[*?[\\]/); + const literal = globAt === -1 ? path : path.slice(0, globAt); + if (!literal.startsWith(directory) && !directory.startsWith(literal)) return null; + const searched = globAt === -1 ? literal : literal.slice(0, literal.lastIndexOf("/") + 1); + return searched.length > directory.length ? searched : directory; +} diff --git a/public-docs/hub/self-hosting/github-app.md b/public-docs/hub/self-hosting/github-app.md index ad47a03f42..75fc05eca0 100644 --- a/public-docs/hub/self-hosting/github-app.md +++ b/public-docs/hub/self-hosting/github-app.md @@ -35,7 +35,7 @@ Under **Subscribe to events**, select **Issue comment**, **Issues**, **Pull requ ## Connect repositories -After Hub verifies the App, choose **Install on GitHub**. Select the account or organization and repositories the App may access. +After Hub verifies the App, choose **Connect GitHub**. Select the account or organization and repositories the App may access. Start from Hub rather than GitHub's own install button. The round trip binds the installation to the active Hub organization. diff --git a/public-docs/hub/self-hosting/github-app.zh-CN.md b/public-docs/hub/self-hosting/github-app.zh-CN.md index ef892fe815..3c1329b6d1 100644 --- a/public-docs/hub/self-hosting/github-app.zh-CN.md +++ b/public-docs/hub/self-hosting/github-app.zh-CN.md @@ -33,7 +33,7 @@ GitHub 会使用以下 Hub URL: ## 连接仓库 {#connect-repositories} -Hub 验证 App 之后,选择 **Install on GitHub**。选择 App 可以访问的账号或组织以及仓库。 +Hub 验证 App 之后,选择 **Connect GitHub**。选择 App 可以访问的账号或组织以及仓库。 请从 Hub 发起安装,而不是使用 GitHub 自己的安装按钮。这一来一回会把安装绑定到当前的 Hub 组织。 diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index 5e582e2409..fec8f2ff09 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -31,7 +31,7 @@ Names follow `subject.operation.position`: the subject, the operation, then `bef All handlers must be async. Turn completion includes success, failure, and cancellation; inspect `outcome`. Permission completion includes every resolution; inspect `resolution`. -Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. +Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, instructions, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. `worktree.create.after` runs before the workspace is registered. It precedes `workspace.create.after`, and both precede the first agent's `agent.create.before` / `agent.open.before`. @@ -49,22 +49,22 @@ Paseo only sees the returned promise, so detached work gets no error reporting a ## Hooks -| Hook | Waits | Payload | Handler may change | -| ------------------------- | ----- | ----------------------------------------- | ---------------------------------------------- | -| `workspace.create.before` | yes | `{ request }` | Entire create request | -| `workspace.create.after` | no | `{ workspace }` | | -| `workspace.archive.after` | no | `{ workspace }` | | -| `worktree.create.before` | yes | `{ request }` | Creation options and destination | -| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | -| `agent.create.before` | yes | `{ request: { config, env?, metadata } }` | Saved config except `cwd`; `env`; `metadata` | -| `agent.create.after` | no | `{ agent }` | | -| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `tools`, `mcpServers` | -| `agent.close.after` | no | `{ agent }` | | -| `agent.archive.after` | no | `{ agent, archivedAt }` | | -| `agent.turn.before` | no | `{ agent, turnId }` | | -| `agent.turn.after` | no | `{ agent, turnId, outcome, timeline }` | | -| `agent.permission.before` | no | `{ agent, request }` | | -| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | +| Hook | Waits | Payload | Handler may change | +| ------------------------- | ----- | ----------------------------------------- | -------------------------------------------------------------- | +| `workspace.create.before` | yes | `{ request }` | Entire create request | +| `workspace.create.after` | no | `{ workspace }` | | +| `workspace.archive.after` | no | `{ workspace }` | | +| `worktree.create.before` | yes | `{ request }` | Creation options and destination | +| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | +| `agent.create.before` | yes | `{ request: { config, env?, metadata } }` | Saved config except `cwd`; `env`; `metadata` | +| `agent.create.after` | no | `{ agent }` | | +| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `appendSystemPrompt`, `tools`, `mcpServers` | +| `agent.close.after` | no | `{ agent }` | | +| `agent.archive.after` | no | `{ agent, archivedAt }` | | +| `agent.turn.before` | no | `{ agent, turnId }` | | +| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | no | `{ agent, request }` | | +| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | ## Shared payloads @@ -283,7 +283,7 @@ server.addHook("agent.create.after", async ({ agent }) => { ## agent.open.before -Receives `{ request }`; only `env`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. +Receives `{ request }`; only `env`, `appendSystemPrompt`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. Do not await a write to the agent being opened: `setMetadata`, `setLabels`, or an option, model, thinking or mode change. The write waits for the open to finish, the open waits for your hook, so the hook times out and the open fails. Start the write without awaiting it; it runs right after the open: @@ -329,6 +329,19 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { | `purpose` | `interactive`, `history` | | `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | +### Append instructions on every session opening + +```ts +server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Follow the team engineering guide."], +})); +``` + +Instructions follow the saved agent prompt and daemon instructions, in plugin order. They are not saved in the agent configuration and are ignored for history opens. Reload the plugin after changing its data to apply new instructions on the next reopen. Running turns continue; removing an instruction does not remove conversation history. Internal agents also receive these instructions. The ACP adapter does not send system instructions to its providers. Plugin providers receive the composed prompt, but must apply it themselves. + +Codex instruction updates require Codex 0.121.0 or newer with a recognizable version reported by the app server. Source builds reporting `0.0.0` must use a versioned build. Paseo adds a current instruction snapshot to existing threads; earlier snapshots remain in the conversation. A crash during an update or rewinding a thread can repeat a snapshot. + ### Inject environment variables on every session opening ```ts @@ -525,7 +538,7 @@ server.addHook("agent.turn.before", async ({ agent, turnId }) => { ## agent.turn.after -A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome, timeline }`. `outcome.kind` is `completed`, `failed`, or `canceled`. `timeline` is deprecated and always empty; fetch history through the SDK as below. +A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome }`. `outcome.kind` is `completed`, `failed`, or `canceled`. The payload carries no history. Read the turn from the agent's timeline: `refetch({ direction: "tail", limit: 1, wholeTurns: true })` returns the latest turn whole, as below. Keep the entries whose `turnId` equals `event.turnId`, because a turn that starts before your read, such as a follow-up another plugin sent, replaces this one as the latest. The filtered list is empty in that case, and when `event.turnId` is `null`. Plugins built against an older SDK that read `event.timeline` get an empty array. ### Send a follow-up when a turn ends @@ -545,8 +558,9 @@ export default function contribute(server: PluginServerContext) { } const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); + const page = await agent.timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries.filter((entry) => entry.turnId === event.turnId); + const text = latestOutputText(turn.map(({ item }) => item)); if (/out of credits/i.test(text)) { await agent.send("Try again."); } @@ -562,9 +576,6 @@ Turn ends: "out of credits" → a new turn starts ``` -The handler fetches only the last 20 timeline items. Output before that page is not inspected. -Use `cursor` and `direction` to page further when your plugin needs more history. - This sends a new message with the existing SDK. Persistent matches keep sending follow-ups; add limits or delays in your plugin when needed. Attachments and tool effects are not replayed. diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index d78bccd6d2..5bdb94a61b 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -29,7 +29,7 @@ export default function contribute(server: PluginServerContext) { 所有处理函数都必须为异步函数。轮次完成包括成功、失败和取消,请查看 `outcome`。权限完成包括所有处理结果,请查看 `resolution`。 -创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 +创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 `worktree.create.after` 在工作区注册前运行,随后是 `workspace.create.after`,两者都早于第一个 Agent 的 `agent.create.before` / `agent.open.before`。 @@ -47,22 +47,22 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 ## 钩子一览 {#hooks} -| 钩子 | 等待 | 载荷 | 可修改 | -| ------------------------- | ---- | ----------------------------------------- | ------------------------------------------ | -| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | -| `workspace.create.after` | 否 | `{ workspace }` | | -| `workspace.archive.after` | 否 | `{ workspace }` | | -| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | -| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | -| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | -| `agent.create.after` | 否 | `{ agent }` | | -| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`tools`、`mcpServers` | -| `agent.close.after` | 否 | `{ agent }` | | -| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | -| `agent.turn.before` | 否 | `{ agent, turnId }` | | -| `agent.turn.after` | 否 | `{ agent, turnId, outcome, timeline }` | | -| `agent.permission.before` | 否 | `{ agent, request }` | | -| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| 钩子 | 等待 | 载荷 | 可修改 | +| ------------------------- | ---- | ----------------------------------------- | --------------------------------------------------------------- | +| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | +| `workspace.create.after` | 否 | `{ workspace }` | | +| `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | +| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | +| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | +| `agent.create.after` | 否 | `{ agent }` | | +| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers` | +| `agent.close.after` | 否 | `{ agent }` | | +| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | +| `agent.turn.before` | 否 | `{ agent, turnId }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | 否 | `{ agent, request }` | | +| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | ## 共享载荷 {#shared-payloads} @@ -279,7 +279,7 @@ server.addHook("agent.create.after", async ({ agent }) => { ## agent.open.before {#agentopenbefore} -收到 `{ request }`,只能修改 `env`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 +收到 `{ request }`,只能修改 `env`、`appendSystemPrompt`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 不要 await 对正在打开的 Agent 的写入,例如 `setMetadata`。该写入要等打开完成,而打开在等你的钩子,结果钩子超时,打开失败。启动写入但不要 await,它会在打开完成后立即执行: @@ -325,6 +325,19 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { | `purpose` | `interactive`、`history` | | `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | +### 在每次打开会话时追加指令 {#append-instructions-on-every-session-opening} + +```ts +server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Follow the team engineering guide."], +})); +``` + +插件指令按插件顺序追加在已保存的 Agent 提示词和 daemon 指令之后。指令不会保存到 Agent 配置中,读取历史时也会忽略这些指令。插件数据更改后,重新加载插件以在下次重新打开会话时应用新指令。正在运行的轮次会继续。移除指令不会删除对话历史。内部 Agent 也会收到这些指令。ACP 适配器不会向 Provider 发送系统指令。插件 Provider 会收到组合后的提示词,但需要自行应用。 + +更新 Codex 指令需要 Codex 0.121.0 或更新版本,且 app server 报告的版本必须可识别。版本显示为 `0.0.0` 的源码构建需要换用带版本号的构建。Paseo 会向现有会话添加当前指令快照;之前的快照仍保留在对话中。更新期间发生崩溃或回退会话时,快照可能重复。 + ### 在每次打开会话时注入环境变量 {#inject-environment-variables-on-every-session-opening} ```ts @@ -514,7 +527,7 @@ server.addHook("agent.turn.before", async ({ agent, turnId }) => { ## agent.turn.after {#agentturnafter} -实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome, timeline }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。`timeline` 已弃用且始终为空;请按下面的示例通过 SDK 获取历史。 +实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。载荷不含历史。请从 Agent 的时间线读取本轮:`refetch({ direction: "tail", limit: 1, wholeTurns: true })` 会完整返回最近一轮,见下面的示例。只保留 `turnId` 等于 `event.turnId` 的条目:如果在读取前已有新一轮开始(例如另一个插件发送的后续消息),最近一轮就不再是本轮。此时过滤后的列表为空;`event.turnId` 为 `null` 时也为空。基于旧版 SDK 构建、仍读取 `event.timeline` 的插件只会拿到空数组。 ### 在轮次结束时发送后续消息 {#send-a-follow-up-when-a-turn-ends} @@ -531,8 +544,9 @@ export default function contribute(server: PluginServerContext) { } const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); + const page = await agent.timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries.filter((entry) => entry.turnId === event.turnId); + const text = latestOutputText(turn.map(({ item }) => item)); if (/out of credits/i.test(text)) { await agent.send("Try again."); } @@ -548,8 +562,6 @@ Turn ends: "out of credits" → a new turn starts ``` -该处理函数只获取最近 20 条时间线条目,不检查这一页之前的输出。插件需要更多历史时,请用 `cursor` 和 `direction` 继续翻页。 - 这会用现有的 SDK 发送一条新消息。持续匹配会不断发送后续消息;需要时请在插件中添加次数限制或延迟。附件和工具的效果不会被重放。 ## agent.permission.before {#agentpermissionbefore} diff --git a/public-docs/plugins/migration.md b/public-docs/plugins/migration.md index 836a8e57b6..6021e193f5 100644 --- a/public-docs/plugins/migration.md +++ b/public-docs/plugins/migration.md @@ -67,30 +67,31 @@ is a compile error. Use this table as the complete registration checklist. -| Old registration and location | New registration and location | -| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| `plugin.handle(contract, handler)` in the old root entry | `server.handle(contract, handler)` in `index.server.ts` | -| `plugin.addSurface(id, Component)` in the old root entry | `client.addScreen({ id, title, Component })` in `index.client.tsx` | -| `plugin.addSidebarItem({ id, title, icon, surface })` in the old root entry | `client.addSidebarHeaderItem({ id, title, Component })` in `index.client.tsx`; see [sidebar items](reference#sidebar-items) | -| New sidebar footer contribution | `client.addSidebarFooterItem({ id, title, Component })` in `index.client.tsx` | -| New sidebar replacement view | `client.addSidebarView({ id, title, Component })` in `index.client.tsx`; see [sidebar views](sidebar-views) | -| New file panel contribution | `client.addFilePanel(panel)` in `index.client.tsx` | -| `plugin.addWorkspacePanel(panel)` in the old root entry | `client.addWorkspacePanel(panel)` in `index.client.tsx` | -| Agent panel with `context: "agent"` | `client.addAgentPanel(panel)` in `index.client.tsx`; omit `context` | -| `plugin.addCommandCenterItem(item)` in the old root entry | `client.addCommandCenterItem(item)` in `index.client.tsx` | -| `plugin.addClientSlashCommand(command)` in the old root entry | `client.addSlashCommand(command)` in `index.client.tsx` | -| `plugin.addClientSide(fn)` in the old root entry | Delete the wrapper and move the body of `fn` into the default client entry function | -| `client.addComposerPill(pill)` inside the old client callback | `client.addComposerPill(pill)` inside `index.client.tsx` or an imported `client/` function | -| New composer item contribution | `client.addComposerItem(item)` in `index.client.tsx`; see [composer items](reference#composer-items) | -| New New workspace item contribution | `client.addNewWorkspaceItem(item)` in `index.client.tsx`; see [New workspace items](reference#new-workspace-items) | -| New header contribution | `client.addHeaderButton({ id, workspaceId, button })` | -| `plugin.addAttachmentSource(source)` in the old root entry | `client.addAttachmentSource(source)` in `index.client.tsx` | -| New settings screen contribution | `client.addSettingsScreen(screen)` in `index.client.tsx`; see [settings screens](reference#settings-screens) | -| `plugin.addTheme(theme)` in the old root entry | `client.addTheme(theme)` in `index.client.tsx` | -| `plugin.addTimelineTransformer(transformer)` in the old root entry | `client.addTimelineTransformer(transformer)` in `index.client.tsx` | -| `plugin.addTimelineRenderer(renderer)` in the old root entry | `client.addTimelineRenderer(renderer)` in `index.client.tsx` | -| `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` in shared files | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | -| `ZodOutput` handler parameter types | `RpcInput` from `@getpaseo/plugin`; `RpcOutput` for return types | +| Old registration and location | New registration and location | +| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `plugin.handle(contract, handler)` in the old root entry | `server.handle(contract, handler)` in `index.server.ts` | +| `plugin.addSurface(id, Component)` in the old root entry | `client.addScreen({ id, title, Component })` in `index.client.tsx` | +| `plugin.addSidebarItem({ id, title, icon, surface })` in the old root entry | `client.addSidebarHeaderItem({ id, title, Component })` in `index.client.tsx`; see [sidebar items](reference#sidebar-items) | +| New sidebar footer contribution | `client.addSidebarFooterItem({ id, title, Component })` in `index.client.tsx` | +| New sidebar replacement view | `client.addSidebarView({ id, title, Component })` in `index.client.tsx`; see [sidebar views](sidebar-views) | +| New badge on sidebar workspace rows | `client.addWorkspaceRowBadgeItem({ id, title, icon, Component })` in `index.client.tsx`; see [workspace row badge items](reference#workspace-row-badge-items) | +| New file panel contribution | `client.addFilePanel(panel)` in `index.client.tsx` | +| `plugin.addWorkspacePanel(panel)` in the old root entry | `client.addWorkspacePanel(panel)` in `index.client.tsx` | +| Agent panel with `context: "agent"` | `client.addAgentPanel(panel)` in `index.client.tsx`; omit `context` | +| `plugin.addCommandCenterItem(item)` in the old root entry | `client.addCommandCenterItem(item)` in `index.client.tsx` | +| `plugin.addClientSlashCommand(command)` in the old root entry | `client.addSlashCommand(command)` in `index.client.tsx` | +| `plugin.addClientSide(fn)` in the old root entry | Delete the wrapper and move the body of `fn` into the default client entry function | +| `client.addComposerPill(pill)` inside the old client callback | `client.addComposerPill(pill)` inside `index.client.tsx` or an imported `client/` function | +| New composer item contribution | `client.addComposerItem(item)` in `index.client.tsx`; see [composer items](reference#composer-items) | +| New New workspace item contribution | `client.addNewWorkspaceItem(item)` in `index.client.tsx`; see [New workspace items](reference#new-workspace-items) | +| New header contribution | `client.addHeaderButton({ id, workspaceId, button })` | +| `plugin.addAttachmentSource(source)` in the old root entry | `client.addAttachmentSource(source)` in `index.client.tsx` | +| New settings screen contribution | `client.addSettingsScreen(screen)` in `index.client.tsx`; see [settings screens](reference#settings-screens) | +| `plugin.addTheme(theme)` in the old root entry | `client.addTheme(theme)` in `index.client.tsx` | +| `plugin.addTimelineTransformer(transformer)` in the old root entry | `client.addTimelineTransformer(transformer)` in `index.client.tsx` | +| `plugin.addTimelineRenderer(renderer)` in the old root entry | `client.addTimelineRenderer(renderer)` in `index.client.tsx` | +| `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` in shared files | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | +| `ZodOutput` handler parameter types | `RpcInput` from `@getpaseo/plugin`; `RpcOutput` for return types | Register the screen that replaces an `addSidebarItem` under that item's `id` to keep saved links working. A `/plugin//sidebar/` link, and the older `/plugin//`, opens the @@ -207,6 +208,22 @@ setting `id` as an option key and each `value` as that option, and sends changes | `ProviderSetting` type | `ProviderOptionControl` | | `agent.create.before` `config.featureValues` | `config.providerOptions`; a returned `featureValues` edit is still applied | +### Turn history in v0.16 + +`agent.turn.after` has sent an empty `timeline` since v0.13, and the SDK type no longer declares it. +A plugin that reads `event.timeline` now fails typecheck. Read the turn from the agent instead: + +```ts +const turn = await context.paseo.agents + .ref(event.agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); +const items = turn.entries.filter((entry) => entry.turnId === event.turnId).map(({ item }) => item); +``` + +The filter drops entries from a turn that started after this one ended, such as a follow-up another plugin sent. The list is empty when such a turn has already started, or when `event.turnId` is `null`. + +Plugins built against an older SDK keep receiving `timeline: []` until removal after 2027-05-31. + ## 5. Recognize half-migration errors | Compiler or load error | Meaning and fix | diff --git a/public-docs/plugins/migration.zh-CN.md b/public-docs/plugins/migration.zh-CN.md index 216f2437b9..9ca601600c 100644 --- a/public-docs/plugins/migration.zh-CN.md +++ b/public-docs/plugins/migration.zh-CN.md @@ -60,29 +60,30 @@ my-plugin/ 把下表作为完整的注册检查清单。 -| 旧的注册及位置 | 新的注册及位置 | -| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| 旧根入口中的 `plugin.handle(contract, handler)` | `index.server.ts` 中的 `server.handle(contract, handler)` | -| 旧根入口中的 `plugin.addSurface(id, Component)` | `index.client.tsx` 中的 `client.addScreen({ id, title, Component })` | -| 旧根入口中的 `plugin.addSidebarItem({ id, title, icon, surface })` | `index.client.tsx` 中的 `client.addSidebarHeaderItem({ id, title, Component })`;见[侧边栏项](reference#sidebar-items) | -| 新的侧边栏底部贡献 | `index.client.tsx` 中的 `client.addSidebarFooterItem({ id, title, Component })` | -| 新的文件面板贡献 | `index.client.tsx` 中的 `client.addFilePanel(panel)` | -| 旧根入口中的 `plugin.addWorkspacePanel(panel)` | `index.client.tsx` 中的 `client.addWorkspacePanel(panel)` | -| 带有 `context: "agent"` 的 Agent 面板 | `index.client.tsx` 中的 `client.addAgentPanel(panel)`;省略 `context` | -| 旧根入口中的 `plugin.addCommandCenterItem(item)` | `index.client.tsx` 中的 `client.addCommandCenterItem(item)` | -| 旧根入口中的 `plugin.addClientSlashCommand(command)` | `index.client.tsx` 中的 `client.addSlashCommand(command)` | -| 旧根入口中的 `plugin.addClientSide(fn)` | 删除这层包装,把 `fn` 的函数体移入默认的客户端入口函数 | -| 旧客户端回调中的 `client.addComposerPill(pill)` | `index.client.tsx` 或被导入的 `client/` 函数中的 `client.addComposerPill(pill)` | -| 新的编辑器项贡献 | `index.client.tsx` 中的 `client.addComposerItem(item)`;见[编辑器项](reference#composer-items) | -| 新的“新建工作区”项贡献 | `index.client.tsx` 中的 `client.addNewWorkspaceItem(item)`;见[新建工作区项](reference#new-workspace-items) | -| 新的标题栏贡献 | `client.addHeaderButton({ id, workspaceId, button })` | -| 旧根入口中的 `plugin.addAttachmentSource(source)` | `index.client.tsx` 中的 `client.addAttachmentSource(source)` | -| 新的设置界面贡献 | `index.client.tsx` 中的 `client.addSettingsScreen(screen)`;见[设置界面](reference#settings-screens) | -| 旧根入口中的 `plugin.addTheme(theme)` | `index.client.tsx` 中的 `client.addTheme(theme)` | -| 旧根入口中的 `plugin.addTimelineTransformer(transformer)` | `index.client.tsx` 中的 `client.addTimelineTransformer(transformer)` | -| 旧根入口中的 `plugin.addTimelineRenderer(renderer)` | `index.client.tsx` 中的 `client.addTimelineRenderer(renderer)` | -| shared 文件中的 `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | -| 处理函数参数类型 `ZodOutput` | 来自 `@getpaseo/plugin` 的 `RpcInput`;返回类型使用 `RpcOutput` | +| 旧的注册及位置 | 新的注册及位置 | +| --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| 旧根入口中的 `plugin.handle(contract, handler)` | `index.server.ts` 中的 `server.handle(contract, handler)` | +| 旧根入口中的 `plugin.addSurface(id, Component)` | `index.client.tsx` 中的 `client.addScreen({ id, title, Component })` | +| 旧根入口中的 `plugin.addSidebarItem({ id, title, icon, surface })` | `index.client.tsx` 中的 `client.addSidebarHeaderItem({ id, title, Component })`;见[侧边栏项](reference#sidebar-items) | +| 新的侧边栏底部贡献 | `index.client.tsx` 中的 `client.addSidebarFooterItem({ id, title, Component })` | +| 新的工作区行徽章贡献 | `index.client.tsx` 中的 `client.addWorkspaceRowBadgeItem({ id, title, icon, Component })`;见[工作区行徽章项](reference#workspace-row-badge-items) | +| 新的文件面板贡献 | `index.client.tsx` 中的 `client.addFilePanel(panel)` | +| 旧根入口中的 `plugin.addWorkspacePanel(panel)` | `index.client.tsx` 中的 `client.addWorkspacePanel(panel)` | +| 带有 `context: "agent"` 的 Agent 面板 | `index.client.tsx` 中的 `client.addAgentPanel(panel)`;省略 `context` | +| 旧根入口中的 `plugin.addCommandCenterItem(item)` | `index.client.tsx` 中的 `client.addCommandCenterItem(item)` | +| 旧根入口中的 `plugin.addClientSlashCommand(command)` | `index.client.tsx` 中的 `client.addSlashCommand(command)` | +| 旧根入口中的 `plugin.addClientSide(fn)` | 删除这层包装,把 `fn` 的函数体移入默认的客户端入口函数 | +| 旧客户端回调中的 `client.addComposerPill(pill)` | `index.client.tsx` 或被导入的 `client/` 函数中的 `client.addComposerPill(pill)` | +| 新的编辑器项贡献 | `index.client.tsx` 中的 `client.addComposerItem(item)`;见[编辑器项](reference#composer-items) | +| 新的“新建工作区”项贡献 | `index.client.tsx` 中的 `client.addNewWorkspaceItem(item)`;见[新建工作区项](reference#new-workspace-items) | +| 新的标题栏贡献 | `client.addHeaderButton({ id, workspaceId, button })` | +| 旧根入口中的 `plugin.addAttachmentSource(source)` | `index.client.tsx` 中的 `client.addAttachmentSource(source)` | +| 新的设置界面贡献 | `index.client.tsx` 中的 `client.addSettingsScreen(screen)`;见[设置界面](reference#settings-screens) | +| 旧根入口中的 `plugin.addTheme(theme)` | `index.client.tsx` 中的 `client.addTheme(theme)` | +| 旧根入口中的 `plugin.addTimelineTransformer(transformer)` | `index.client.tsx` 中的 `client.addTimelineTransformer(transformer)` | +| 旧根入口中的 `plugin.addTimelineRenderer(renderer)` | `index.client.tsx` 中的 `client.addTimelineRenderer(renderer)` | +| shared 文件中的 `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | +| 处理函数参数类型 `ZodOutput` | 来自 `@getpaseo/plugin` 的 `RpcInput`;返回类型使用 `RpcOutput` | 用原 `addSidebarItem` 项的 `id` 注册替代它的界面,这样已保存的链接仍然有效。`/plugin//sidebar/` 链接以及更早的 `/plugin//` 链接,会打开具有该 `id` 的 `addSidebarItem`,否则打开具有该 `id` 的界面。 @@ -170,6 +171,21 @@ Provider 插件只有一个配置记录 `providerOptions`,并用控件描述 | `ProviderSetting` 类型 | `ProviderOptionControl` | | `agent.create.before` 的 `config.featureValues` | `config.providerOptions`;返回的 `featureValues` 修改仍会被应用 | +### v0.16 中的轮次历史 {#turn-history-in-v016} + +自 v0.13 起,`agent.turn.after` 发送的 `timeline` 始终为空,SDK 类型也不再声明它。读取 `event.timeline` 的插件现在无法通过类型检查。请改为从 Agent 读取本轮: + +```ts +const turn = await context.paseo.agents + .ref(event.agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); +const items = turn.entries.filter((entry) => entry.turnId === event.turnId).map(({ item }) => item); +``` + +过滤会去掉本轮结束后才开始的新一轮的条目,例如另一个插件发送的后续消息。如果这样的新一轮已经开始,或 `event.turnId` 为 `null`,列表为空。 + +基于旧版 SDK 构建的插件在 2027-05-31 之后移除兼容层之前仍会收到 `timeline: []`。 + ## 5. 识别只迁移了一半的错误 {#5-recognize-half-migration-errors} | 编译器或加载错误 | 含义与修复方法 | diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index cdd847ba7f..692313bc5c 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -854,6 +854,60 @@ function hideAlerts() { } ``` +### Workspace row badge items + +`addWorkspaceRowBadgeItem({ id, title, icon, Component })` adds an item to the line under each workspace +title in the sidebar, after the row's own items (host, pull request, checks, services, labels). +`title` and `icon` label the item's toggle in the sidebar's **Show** menu, in a separate plugin group +below a separator. Items start visible. + +`Component` renders once per workspace row on the plugin's host and receives +`PluginWorkspaceRowBadgeItemProps`: `theme`, `host`, `layout`, and `workspaceId`. Render +`WorkspaceRowBadge` from `@getpaseo/plugin/client/ui`, or `null` when there is nothing to say about +the workspace: + +| Prop | Meaning | +| -------------------- | ------------------------------------------------------------------------------ | +| `icon` | Optional. Any [icon](#icons) form, drawn at the line's glyph size. | +| `label` | Optional. A short word. A badge with neither `icon` nor `label` draws nothing. | +| `tone` | `"muted"` (default), `"success"`, `"warning"`, `"danger"`, or `"info"`. | +| `accessibilityLabel` | Defaults to `label`, then the item's `title`. | + +The line adds no separator around your badges, and returning `null` leaves no gap. Render as many +badges as you like. Every row +renders the component, so share one query across rows instead of fetching per workspace: the +plugin's React Query client is shared by all of its components on a host. + +```tsx +import type { PluginWorkspaceRowBadgeItemProps } from "@getpaseo/plugin/client"; +import { useRpc } from "@getpaseo/plugin/client"; +import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; +import { useQuery } from "@tanstack/react-query"; + +function ReviewState({ workspaceId }: PluginWorkspaceRowBadgeItemProps) { + const list = useRpc(reviewStates); + const { data } = useQuery({ + queryKey: ["review-states"], + queryFn: () => list({}), + refetchInterval: 5000, + }); + const state = data?.[workspaceId]; + if (!state) return null; + return ; +} + +client.addWorkspaceRowBadgeItem({ + id: "review", + title: "Review", + icon: "Eye", + Component: ReviewState, +}); +``` + +Apps older than this API have no `addWorkspaceRowBadgeItem`; check for it before calling. + +See the [workspace row badges example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/workspace-row-badges). + ## Host UI Import Paseo-owned UI from `@getpaseo/plugin/client/ui` in client code. This example @@ -1225,9 +1279,12 @@ async function publishReview(agentId: string, { paseo }: PluginHandlerContext) { The daemon stamps `pluginId` from the calling plugin session and rejects this RPC from non-plugin sessions. The row appears live, survives timeline refetches, and keeps only the latest value for the -same plugin and `id`. If its renderer is missing, Paseo shows the existing unavailable row. Daemons -reject `data` over the limit rather than truncating it. Daemons that support this operation -advertise `server_info.features.pluginTimelineItems`. +same plugin and `id`. If its renderer is missing, Paseo shows the existing unavailable row. + +`kind` starts with a lowercase letter and contains lowercase letters, numbers, or hyphens, the same +rule `addTimelineRenderer` applies. Daemons reject any other `kind`. Daemons reject `data` over the +limit rather than truncating it. Daemons that support this operation advertise +`server_info.features.pluginTimelineItems`. ## Theme and layout @@ -1277,6 +1334,12 @@ export default function contribute(client: PluginClientContext) { accent: "#cba6f7", mutedForeground: "#a6adc8", ring: "#6c7086", + sidebar: "#181825", + sidebarHover: "#313244", + sidebarSelected: "#45475a", + surface3: "#45475a", + surface4: "#585b70", + foregroundExtraMuted: "#7f849c", }, }); return () => {}; @@ -1287,16 +1350,29 @@ Every color is a hex string; anything else fails to load. Paseo expands the pale token set the built-in dark themes use, so a contributed theme covers panels, menus, diffs, status colors, and the terminal without listing them. -| Color | Becomes | -| ----------------- | ----------------------------------------------------------------- | -| `background` | App, workspace, and terminal background | -| `foreground` | Primary text, terminal foreground and cursor | -| `raised` | Cards, popovers, and hovered rows | -| `control` | Inputs, secondary fills, and the light-theme sidebar | -| `border` | Borders and the highest raised-surface tint | -| `accent` | Buttons, selection, and focus. Optional; `foreground` if omitted. | -| `mutedForeground` | Secondary text | -| `ring` | Focus rings, scrollbars, and terminal bright black | +| Color | Becomes | +| ---------------------- | ------------------------------------------------------------------------------ | +| `background` | App, workspace, and terminal background | +| `foreground` | Primary text, terminal foreground and cursor | +| `raised` | Cards and popovers | +| `control` | Inputs, secondary fills, and the light-theme sidebar unless `sidebar` is set | +| `border` | Borders | +| `accent` | Buttons, selection, and focus. Optional; `foreground` if omitted. | +| `mutedForeground` | Secondary text | +| `ring` | The keyboard focus outline on web, and terminal bright black | +| `sidebar` | Sidebar background. Optional; `background` in dark themes, `control` in light. | +| `sidebarHover` | Optional hovered sidebar row background. | +| `sidebarSelected` | Optional selected sidebar row background. | +| `surface3` | Optional neutral fill for message bubbles, secondary buttons, and chips. | +| `surface4` | Optional stronger neutral fill for tracks and other states. | +| `foregroundExtraMuted` | Optional tertiary text, including sidebar timestamps. | + +Each optional override is used exactly as given. Omitted state, fill, and tertiary colors are derived +independently from the palette. When you override a color, choose it for readable contrast with the +surfaces or text it accompanies. + +`sidebar` and the five overrides require Paseo 0.16.0 or later. Older apps reject a theme with an unknown color, and the +plugin's other contributions fail to load with it, so raise `requirements.paseo` when you use any of them. `appearance` is `"light"` or `"dark"`. Paseo uses it to select the matching surface, status, diff, syntax, terminal, and shadow derivation. diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 7ab38e8587..724ce623ae 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -705,6 +705,51 @@ function hideAlerts() { } ``` +### 工作区行徽章项 {#workspace-row-badge-items} + +`addWorkspaceRowBadgeItem({ id, title, icon, Component })` 在侧边栏每个工作区标题下方的那一行中添加一项,位于该行自带的各项(主机、拉取请求、检查、服务、标签)之后。`title` 和 `icon` 用于标注该项在侧边栏 **Show** 菜单中的开关,插件开关位于分隔线下方的独立分组中。各项默认可见。 + +`Component` 为插件所在主机上的每个工作区行渲染一次,并接收 `PluginWorkspaceRowBadgeItemProps`:`theme`、`host`、`layout` 和 `workspaceId`。渲染 `@getpaseo/plugin/client/ui` 中的 `WorkspaceRowBadge`;工作区没有需要说明的内容时返回 `null`: + +| 属性 | 含义 | +| -------------------- | --------------------------------------------------------------------- | +| `icon` | 可选。任意[图标](#icons)形式,以该行的图标尺寸绘制。 | +| `label` | 可选。一个简短的词。既没有 `icon` 也没有 `label` 的徽章不绘制。 | +| `tone` | `"muted"`(默认)、`"success"`、`"warning"`、`"danger"` 或 `"info"`。 | +| `accessibilityLabel` | 默认为 `label`,其次是该项的 `title`。 | + +该行不会在你的徽章周围添加分隔符,返回 `null` 不会留下空隙。可以渲染任意数量的徽章。每一行都会渲染该组件,所以请在各行之间共享一次查询,而不是为每个工作区单独获取:插件的 React Query 客户端由它在某台主机上的所有组件共享。 + +```tsx +import type { PluginWorkspaceRowBadgeItemProps } from "@getpaseo/plugin/client"; +import { useRpc } from "@getpaseo/plugin/client"; +import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; +import { useQuery } from "@tanstack/react-query"; + +function ReviewState({ workspaceId }: PluginWorkspaceRowBadgeItemProps) { + const list = useRpc(reviewStates); + const { data } = useQuery({ + queryKey: ["review-states"], + queryFn: () => list({}), + refetchInterval: 5000, + }); + const state = data?.[workspaceId]; + if (!state) return null; + return ; +} + +client.addWorkspaceRowBadgeItem({ + id: "review", + title: "Review", + icon: "Eye", + Component: ReviewState, +}); +``` + +早于此 API 的应用没有 `addWorkspaceRowBadgeItem`;调用前请先检查它是否存在。 + +参见[工作区行徽章示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/workspace-row-badges)。 + ## 宿主 UI {#host-ui} 在客户端代码中从 `@getpaseo/plugin/client/ui` 导入由 Paseo 提供的 UI。下面的示例会打开一个受控的弹窗、渲染一个宿主图标,并用 toast 确认操作: @@ -1015,7 +1060,9 @@ async function publishReview(agentId: string, { paseo }: PluginHandlerContext) { | `version` | 正整数 | 是 | 选择渲染器契约的版本。 | | `data` | 兼容 JSON | 是 | 渲染器负载,JSON 序列化后最多 64 KiB。 | -daemon 会根据发起调用的插件会话写入 `pluginId`,并拒绝来自非插件会话的此 RPC。该行会实时出现,在时间线重新获取后依然保留,并且对于同一插件和 `id` 只保留最新的值。如果它的渲染器缺失,Paseo 会显示现有的“不可用”行。daemon 会拒绝超过限制的 `data`,而不是截断它。支持此操作的 daemon 会声明 `server_info.features.pluginTimelineItems`。 +daemon 会根据发起调用的插件会话写入 `pluginId`,并拒绝来自非插件会话的此 RPC。该行会实时出现,在时间线重新获取后依然保留,并且对于同一插件和 `id` 只保留最新的值。如果它的渲染器缺失,Paseo 会显示现有的“不可用”行。 + +`kind` 以小写字母开头,只包含小写字母、数字或连字符,与 `addTimelineRenderer` 使用的规则相同。daemon 会拒绝其他任何 `kind`。daemon 会拒绝超过限制的 `data`,而不是截断它。支持此操作的 daemon 会声明 `server_info.features.pluginTimelineItems`。 ## 主题与布局 {#theme-and-layout} @@ -1064,6 +1111,12 @@ export default function contribute(client: PluginClientContext) { accent: "#cba6f7", mutedForeground: "#a6adc8", ring: "#6c7086", + sidebar: "#181825", + sidebarHover: "#313244", + sidebarSelected: "#45475a", + surface3: "#45475a", + surface4: "#585b70", + foregroundExtraMuted: "#7f849c", }, }); return () => {}; @@ -1072,16 +1125,26 @@ export default function contribute(client: PluginClientContext) { 每种颜色都是十六进制字符串;其他格式会导致加载失败。Paseo 会把调色板扩展为内置深色主题所使用的完整令牌集合,因此贡献的主题无需逐一列出,就能覆盖面板、菜单、diff、状态颜色和终端。 -| 颜色 | 用作 | -| ----------------- | ------------------------------------------------- | -| `background` | 应用、工作区和终端的背景 | -| `foreground` | 主要文字、终端前景色和光标 | -| `raised` | 卡片、弹出框和悬停的行 | -| `control` | 输入框、次要填充以及浅色主题的侧边栏 | -| `border` | 边框以及最高层凸起表面的色调 | -| `accent` | 按钮、选中和焦点。可选;省略时使用 `foreground`。 | -| `mutedForeground` | 次要文字 | -| `ring` | 焦点环、滚动条以及终端的亮黑色 | +| 颜色 | 用作 | +| ---------------------- | --------------------------------------------------------------- | +| `background` | 应用、工作区和终端的背景 | +| `foreground` | 主要文字、终端前景色和光标 | +| `raised` | 卡片和弹出框 | +| `control` | 输入框、次要填充,以及未设置 `sidebar` 时浅色主题的侧边栏 | +| `border` | 边框 | +| `accent` | 按钮、选中和焦点。可选;省略时使用 `foreground`。 | +| `mutedForeground` | 次要文字 | +| `ring` | Web 上的键盘焦点轮廓,以及终端的亮黑色 | +| `sidebar` | 侧边栏背景。可选;深色主题默认为 `background`,浅色为 `control` | +| `sidebarHover` | 可选的侧边栏行悬停背景 | +| `sidebarSelected` | 可选的侧边栏行选中背景 | +| `surface3` | 可选的消息气泡、次要按钮和芯片中性填充 | +| `surface4` | 可选的轨道和其他状态的较强中性填充 | +| `foregroundExtraMuted` | 可选的三级文字颜色,包括侧边栏时间戳 | + +可选覆盖颜色按原值使用。省略的状态、填充和三级文字颜色分别由调色板推导。覆盖颜色时,请确保它与对应的背景或文字有足够对比度。 + +`sidebar` 和以上五个覆盖颜色需要 Paseo 0.16.0 或更高版本。较旧的应用会拒绝包含未知颜色的主题,该插件的其他贡献也会随之加载失败,因此使用其中任何一个时请提高 `requirements.paseo`。 `appearance` 为 `"light"` 或 `"dark"`。Paseo 用它选择对应的表面、状态、diff、语法高亮、终端和阴影的推导方式。 diff --git a/public-docs/sdk/reference.md b/public-docs/sdk/reference.md index 5a095b2c2a..4db6277f85 100644 --- a/public-docs/sdk/reference.md +++ b/public-docs/sdk/reference.md @@ -118,7 +118,7 @@ workspace the call creates is background too. With a `parent` and no value, the ### Timeline handle -`agent.timeline.refetch(options?)` fetches a page. Options are `direction`, `cursor`, `limit`, `projection`, and `requestId`. +`agent.timeline.refetch(options?)` fetches a page. Options are `direction`, `cursor`, `limit`, `projection`, `wholeTurns`, and `requestId`. `wholeTurns: true` extends a `tail` or `before` page back to the start of the oldest turn it reaches, so `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. It requires `features.wholeTurnTimeline`; older hosts ignore it and return a page of `limit` items. `agent.timeline.subscribe(handler)` establishes network demand for this agent and restores it after reconnect. Its unsubscribe function releases that demand; await `unsubscribe.ready` for initial daemon acknowledgement before starting work. Delivery is live-only. Reconnect emits a local `subscription_restored` event; request missed history explicitly with `refetch()`. A live replacement invalidates the previous epoch. See the callback shapes, paging and failure behavior in [timeline events](./events.md#follow-timeline-events). diff --git a/public-docs/sdk/reference.zh-CN.md b/public-docs/sdk/reference.zh-CN.md index 5879e9cab9..87166ff76f 100644 --- a/public-docs/sdk/reference.zh-CN.md +++ b/public-docs/sdk/reference.zh-CN.md @@ -114,7 +114,7 @@ nav: API 参考 ### 时间线句柄 {#timeline-handle} -`agent.timeline.refetch(options?)` 获取一页时间线。选项有 `direction`、`cursor`、`limit`、`projection` 和 `requestId`。 +`agent.timeline.refetch(options?)` 获取一页时间线。选项有 `direction`、`cursor`、`limit`、`projection`、`wholeTurns` 和 `requestId`。`wholeTurns: true` 会把 `tail` 或 `before` 页向前扩展到它所触及的最早一轮的开头,因此 `{ direction: "tail", limit: 1, wholeTurns: true }` 返回最近一轮。它需要 `features.wholeTurnTimeline`;旧版主机会忽略它,返回 `limit` 条记录。 `agent.timeline.subscribe(handler)` 为该 Agent 建立网络订阅需求,并在重连后恢复它。它返回的取消订阅函数会释放这项需求;开始工作之前,请 await `unsubscribe.ready` 以等待 daemon 的初始确认。投递只包含实时内容。重连时会发出一个本地的 `subscription_restored` 事件;错过的历史请用 `refetch()` 显式请求。实时的替换会使之前的 epoch 失效。回调的形状、分页和失败行为见[时间线事件](./events.md#follow-timeline-events)。 diff --git a/public-docs/updates.md b/public-docs/updates.md index e5a11eee29..84b9d7acae 100644 --- a/public-docs/updates.md +++ b/public-docs/updates.md @@ -52,19 +52,20 @@ Betas are the best way to get fixes and features early. If you hit a bug, report ### How to join the beta channel -In the desktop app: +| Platform | How to get betas | +| -------------- | ------------------------------------------------------------------------------------------------------------- | +| iOS and iPadOS | Join the [Paseo TestFlight beta](https://testflight.apple.com/join/Y5HpSQjJ). | +| Android | Download the APK from a prerelease on the [GitHub releases page](https://github.com/getpaseo/paseo/releases). | +| Desktop | Open **Settings → About** and select **Beta** under **Release channel**. | +| CLI | Run `npm install -g @getpaseo/cli@beta`. Plain `npm install -g @getpaseo/cli` stays on stable. | -1. Open **Settings** -2. Go to **About** -3. Under **Release channel**, select **Beta** - -The app will check for beta updates from then on. +The desktop app checks for beta updates from the moment you select **Beta**. ## App stores Desktop releases and the CLI are usually available first. App Store and Play Store releases can lag behind because they go through review. -There is no beta channel in the app stores right now — only stable builds are submitted. If you want early Android builds, download the APK from the [GitHub releases page](https://github.com/getpaseo/paseo/releases). +The App Store and Play Store listings carry stable builds only. On iOS, the [TestFlight beta](https://testflight.apple.com/join/Y5HpSQjJ) is the beta channel. Every beta is uploaded to it after Apple's beta review, and stable releases are uploaded to it as well, so TestFlight testers stay on the latest build. On Android there is no Play Store beta, so install beta APKs from GitHub. ## What to do if something breaks diff --git a/public-docs/updates.zh-CN.md b/public-docs/updates.zh-CN.md index b83e520db1..90b4526934 100644 --- a/public-docs/updates.zh-CN.md +++ b/public-docs/updates.zh-CN.md @@ -50,19 +50,20 @@ v0.1.92-beta.3 ### 如何加入测试版渠道 {#how-to-join-the-beta-channel} -在桌面应用中: +| 平台 | 获取测试版的方式 | +| ------------- | ------------------------------------------------------------------------------------------------ | +| iOS 和 iPadOS | 加入 [Paseo TestFlight 测试版](https://testflight.apple.com/join/Y5HpSQjJ)。 | +| Android | 从 [GitHub releases 页面](https://github.com/getpaseo/paseo/releases)的预发布版本下载 APK。 | +| 桌面端 | 打开 **设置 → 关于**,在 **发布通道** 下选择 **Beta**。 | +| CLI | 运行 `npm install -g @getpaseo/cli@beta`。直接运行 `npm install -g @getpaseo/cli` 仍使用稳定版。 | -1. 打开 **设置** -2. 进入 **关于** -3. 在 **发布通道** 下选择 **Beta** - -之后应用就会检查测试版更新。 +在桌面应用中选择 **Beta** 后,应用就会检查测试版更新。 ## 应用商店 {#app-stores} 桌面端版本和 CLI 通常最先提供。App Store 和 Play Store 的版本需要经过审核,可能会滞后。 -应用商店目前没有测试版渠道,只提交稳定版构建。如果你想提前使用 Android 构建,请从 [GitHub releases 页面](https://github.com/getpaseo/paseo/releases)下载 APK。 +App Store 和 Play Store 的商店页面只提供稳定版构建。在 iOS 上,[TestFlight 测试版](https://testflight.apple.com/join/Y5HpSQjJ)就是测试版渠道。每个测试版都会在通过 Apple 的测试版审核后上传到 TestFlight,稳定版也会上传到那里,所以 TestFlight 测试者始终使用最新构建。Android 没有 Play Store 测试版,请从 GitHub 安装测试版 APK。 ## 出现问题怎么办 {#what-to-do-if-something-breaks} diff --git a/public-docs/worktrees/index.md b/public-docs/worktrees/index.md index faabb2d81f..55eb4de01b 100644 --- a/public-docs/worktrees/index.md +++ b/public-docs/worktrees/index.md @@ -122,6 +122,19 @@ Both fields accept a multiline shell script or an array of commands; commands ru Commands run with the worktree as `cwd`. Use `$PASEO_SOURCE_CHECKOUT_PATH` to reach files in the original checkout (untracked config, local caches, etc). +Teardown commands share a one minute limit. Set `teardownTimeoutMs` to change it, in milliseconds: + +```json +{ + "worktree": { + "teardown": "docker compose down", + "teardownTimeoutMs": 300000 + } +} +``` + +At the limit, Paseo tries to stop the command and its child processes and stops waiting for output. If teardown fails or reaches the limit, the workspace still archives and the worktree stays on disk. `teardownTimeoutMs` accepts whole numbers from 1 to 2147483647. Other values use the default. + ## Scripts and services `scripts` are named commands you can run inside a worktree on demand. Mark one as a _service_ and Paseo supervises it as a long-running process, assigns it a port, and routes HTTP traffic to it through the daemon's reverse proxy. diff --git a/public-docs/worktrees/index.zh-CN.md b/public-docs/worktrees/index.zh-CN.md index cce65fc090..59f4342627 100644 --- a/public-docs/worktrees/index.zh-CN.md +++ b/public-docs/worktrees/index.zh-CN.md @@ -120,6 +120,19 @@ paseo workspace create \ 命令以 worktree 作为 `cwd` 运行。使用 `$PASEO_SOURCE_CHECKOUT_PATH` 访问原始检出中的文件(未跟踪的配置、本地缓存等)。 +teardown 的所有命令共用一分钟的时限。用 `teardownTimeoutMs` 修改它,单位为毫秒: + +```json +{ + "worktree": { + "teardown": "docker compose down", + "teardownTimeoutMs": 300000 + } +} +``` + +达到时限后,Paseo 会尝试停止命令及其子进程,并停止等待输出。如果 teardown 失败或达到时限,工作区仍会归档,worktree 会保留在磁盘上。`teardownTimeoutMs` 接受 1 到 2147483647 之间的整数。其他值使用默认时限。 + ## 脚本与服务 {#scripts-and-services} `scripts` 是可以在 worktree 中按需运行的具名命令。把其中一个标记为 _service_,Paseo 就会把它作为长时间运行的进程进行监管,为它分配端口,并通过 daemon 的反向代理把 HTTP 流量路由给它。 diff --git a/public-docs/worktrees/worktreeinclude.md b/public-docs/worktrees/worktreeinclude.md index 50c5f0370a..21ba7afc2f 100644 --- a/public-docs/worktrees/worktreeinclude.md +++ b/public-docs/worktrees/worktreeinclude.md @@ -36,6 +36,8 @@ config/*.local.json A pattern only selects files that Git already ignores. Adding a path here does not ignore it, so also configure `.gitignore` when needed. Tracked files and untracked files that Git does not ignore are excluded. +Paseo does not search inside a directory that Git ignores as a whole, such as `node_modules/`, unless a pattern names that directory or a path inside it. A bare name like `.env` matches `.env` and `apps/web/.env`, but not `node_modules/pkg/.env`. To copy from inside an ignored directory, name it in the pattern, as in `node_modules/pkg/.env` or `.secrets/`. A pattern with a glob in its first directory name, such as `**/.env` or `*/.env`, searches every ignored directory, including `node_modules/`, so name the directory instead when it is large. + ## When files are copied The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run. diff --git a/public-docs/worktrees/worktreeinclude.zh-CN.md b/public-docs/worktrees/worktreeinclude.zh-CN.md index e80e386a01..f391865999 100644 --- a/public-docs/worktrees/worktreeinclude.zh-CN.md +++ b/public-docs/worktrees/worktreeinclude.zh-CN.md @@ -36,6 +36,8 @@ config/*.local.json 模式只会选择 Git 已忽略的文件。在此添加路径不会使 Git 忽略该文件,需要时还应配置 `.gitignore`。已跟踪的文件和未被 Git 忽略的未跟踪文件都不会被复制。 +对于被 Git 整体忽略的目录(例如 `node_modules/`),除非某个模式指明了该目录或其中的路径,否则 Paseo 不会在其中查找。像 `.env` 这样的纯文件名会匹配 `.env` 和 `apps/web/.env`,但不会匹配 `node_modules/pkg/.env`。要从被忽略的目录中复制文件,请在模式中写出该目录,例如 `node_modules/pkg/.env` 或 `.secrets/`。第一级目录名中带有通配符的模式(例如 `**/.env` 或 `*/.env`)会在所有被忽略的目录中查找,包括 `node_modules/`,因此目录较大时请直接写出目录。 + ## 文件复制时机 {#when-files-are-copied} 内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。 diff --git a/scripts/dev-home.sh b/scripts/dev-home.sh index a7cea3e051..89322ccc9d 100755 --- a/scripts/dev-home.sh +++ b/scripts/dev-home.sh @@ -4,62 +4,10 @@ default_dev_paseo_root() { git rev-parse --show-toplevel 2>/dev/null || pwd } -copy_json_tree() { - local source_dir="$1" - local target_dir="$2" - - if [ ! -d "$source_dir" ]; then - return - fi - - mkdir -p "$target_dir" - if command -v rsync >/dev/null 2>&1; then - rsync -a --include='*/' --include='*.json' --exclude='*' "$source_dir/" "$target_dir/" - return - fi - - while IFS= read -r -d '' source_file; do - local relative_path="${source_file#"$source_dir"/}" - local target_file="$target_dir/$relative_path" - mkdir -p "$(dirname "$target_file")" - cp "$source_file" "$target_file" - done < <(find "$source_dir" -type f -name '*.json' -print0) -} - -has_files() { - [ -d "$1" ] && [ -n "$(find "$1" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ] -} - seed_worktree_paseo_home() { - local source_home="${PASEO_DEV_SEED_HOME:-$HOME/.paseo}" - local target_home="$1" - - if [ ! -d "$source_home" ]; then - echo " Seed: skipped (${source_home} missing)" - return - fi - - if [ "$source_home" = "$target_home" ]; then - echo " Seed: skipped (source is target)" - return - fi - - if [ "${PASEO_DEV_RESET_HOME:-0}" = "1" ]; then - rm -rf "$target_home" - elif has_files "$target_home"; then - echo " Seed: skipped (${target_home} already has data)" - return - fi - - mkdir -p "$target_home" - echo " Seed: copying metadata from ${source_home}" - copy_json_tree "$source_home/agents" "$target_home/agents" - copy_json_tree "$source_home/projects" "$target_home/projects" - if [ -f "$source_home/config.json" ]; then - cp "$source_home/config.json" "$target_home/config.json" - fi - - echo " Seed: copied metadata from ${source_home}" + local script_dir + script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + node "$script_dir/seed-dev-home.mjs" "${PASEO_DEV_SEED_HOME:-$HOME/.paseo}" "$1" } configure_dev_daemon_config() { diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index b67cd113aa..b8321013ff 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -48,6 +48,10 @@ const patchedPackages = [ nodeModulesPath: "node_modules/@legendapp/list", patchPrefix: "@legendapp+list+", }, + // Native sidebar lists. Besides gesture sessions and panel-gesture arbitration, the drop gives + // each moved cell a fresh transform host. Reanimated re-applies a view's last animated + // transform to every React commit, so a reused host painted one frame of new order plus old + // drag translate (upstream computerjazz/react-native-draggable-flatlist#621, open). { nodeModulesPath: "node_modules/react-native-draggable-flatlist", patchPrefix: "react-native-draggable-flatlist+", diff --git a/scripts/seed-dev-home.mjs b/scripts/seed-dev-home.mjs new file mode 100644 index 0000000000..c82d878821 --- /dev/null +++ b/scripts/seed-dev-home.mjs @@ -0,0 +1,84 @@ +import { + cpSync, + realpathSync, + existsSync, + mkdirSync, + readdirSync, + rmSync, + statSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +export function seedPaseoHome(source, target) { + if (!existsSync(source)) { + console.log(` Seed: skipped (${source} missing)`); + return; + } + + if (source === target) { + console.log(" Seed: skipped (source is target)"); + return; + } + + if (process.env.PASEO_DEV_RESET_HOME !== "1" && hasEntries(target)) { + console.log(` Seed: skipped (${target} already has data)`); + return; + } + + const configPath = join(source, "config.json"); + const config = existsSync(configPath) + ? JSON.parse(readFileSync(configPath, "utf8").replace(/^\uFEFF/, "")) + : { version: 1 }; + + if (process.env.PASEO_DEV_RESET_HOME === "1") { + rmSync(target, { recursive: true, force: true }); + } + + mkdirSync(target, { recursive: true }); + console.log(` Seed: copying metadata from ${source}`); + copyJsonTree(join(source, "agents"), join(target, "agents")); + copyJsonTree(join(source, "projects"), join(target, "projects")); + + // A snapshot does not own the source daemon's pending work. Recovery normalizes + // copied running records on startup without sending a prompt when disabled. + config.agents = { ...config.agents, resumeOnStartup: false }; + writeFileSync(join(target, "config.json"), JSON.stringify(config, null, 2)); + + console.log(` Seed: copied metadata from ${source}`); +} + +// Durable JSON metadata only. Runtime files (pid files, sockets, logs) must not be copied. +function copyJsonTree(source, target) { + if (!existsSync(source)) { + return; + } + + cpSync(source, target, { + recursive: true, + dereference: true, + filter: (path) => isDirectory(path) || path.endsWith(".json"), + }); +} + +function hasEntries(path) { + try { + return readdirSync(path).length > 0; + } catch { + return false; + } +} + +function isDirectory(path) { + try { + return statSync(path).isDirectory(); + } catch { + return false; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) { + seedPaseoHome(process.argv[2], process.argv[3]); +} diff --git a/scripts/seed-worktree-dev-state.mjs b/scripts/seed-worktree-dev-state.mjs index d645789596..87ebd28e2a 100644 --- a/scripts/seed-worktree-dev-state.mjs +++ b/scripts/seed-worktree-dev-state.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs"; +import { cpSync, existsSync, mkdirSync } from "node:fs"; import { dirname, join } from "node:path"; // Worktree setup runs through a stable script shell: bash on macOS/Linux, but PowerShell @@ -7,6 +7,8 @@ import { dirname, join } from "node:path"; // `./scripts/*.sh`) cannot express this step portably, so the seeding lives in Node — the // one interpreter every Paseo checkout already depends on. +import { seedPaseoHome } from "./seed-dev-home.mjs"; + const sourceRoot = process.env.PASEO_SOURCE_CHECKOUT_PATH; const targetRoot = process.env.PASEO_WORKTREE_PATH || process.cwd(); @@ -14,55 +16,12 @@ if (!sourceRoot || sourceRoot === targetRoot) { process.exit(0); } -seedPaseoHome(); +seedPaseoHome( + process.env.PASEO_DEV_SEED_HOME || join(sourceRoot, ".dev/paseo-home"), + join(targetRoot, ".dev/paseo-home"), +); copyServerEnv(); -function seedPaseoHome() { - const source = process.env.PASEO_DEV_SEED_HOME || join(sourceRoot, ".dev/paseo-home"); - const target = join(targetRoot, ".dev/paseo-home"); - - if (!existsSync(source)) { - console.log(` Seed: skipped (${source} missing)`); - return; - } - - if (source === target) { - console.log(" Seed: skipped (source is target)"); - return; - } - - if (process.env.PASEO_DEV_RESET_HOME === "1") { - rmSync(target, { recursive: true, force: true }); - } else if (hasEntries(target)) { - console.log(` Seed: skipped (${target} already has data)`); - return; - } - - mkdirSync(target, { recursive: true }); - console.log(` Seed: copying metadata from ${source}`); - copyJsonTree(join(source, "agents"), join(target, "agents")); - copyJsonTree(join(source, "projects"), join(target, "projects")); - - const config = join(source, "config.json"); - if (existsSync(config)) { - cpSync(config, join(target, "config.json")); - } - - console.log(` Seed: copied metadata from ${source}`); -} - -// Durable JSON metadata only. Runtime files (pid files, sockets, logs) must not be copied. -function copyJsonTree(source, target) { - if (!existsSync(source)) { - return; - } - - cpSync(source, target, { - recursive: true, - filter: (path) => isDirectory(path) || path.endsWith(".json"), - }); -} - function copyServerEnv() { const source = join(sourceRoot, "packages/server/.env"); const target = join(targetRoot, "packages/server/.env"); @@ -77,19 +36,3 @@ function copyServerEnv() { cpSync(source, target); console.log(` Env: copied ${source}`); } - -function hasEntries(path) { - try { - return readdirSync(path).length > 0; - } catch { - return false; - } -} - -function isDirectory(path) { - try { - return statSync(path).isDirectory(); - } catch { - return false; - } -} diff --git a/skills/paseo-plugin/SKILL.md b/skills/paseo-plugin/SKILL.md index 53a301eeb6..85030768d9 100644 --- a/skills/paseo-plugin/SKILL.md +++ b/skills/paseo-plugin/SKILL.md @@ -52,6 +52,36 @@ Pick the contribution that matches the request. Each row names the registration, | Inject launch-only MCP servers and save Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | | Attach a tool to selected agents | [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | +## Develop plugins in a local folder + +Develop a plugin in a local folder that you own, the same way you develop an npm package. Install +that folder by path. Paseo runs the plugin from that folder, `paseo plugin reload ` loads your +edits, and `paseo plugin update` does not change it. + +Do not edit, build, or commit inside the installation of a Git or npm plugin. That folder is +Paseo's managed storage in the `plugins/` directory of the daemon home. `paseo plugin update` +replaces it, and `paseo plugin remove` deletes it. Both commands discard every edit and commit in +that folder. + +Before you edit an installed plugin, run `paseo plugin ls ` and read the SOURCE column. A +`git:` source, an `npm:` source, or a registry source such as `/owner/slug` is a +managed installation. Its DIRECTORY column shows the managed folder. + +To develop a plugin that is installed from Git or npm: + +1. Clone the source repository of the plugin into a folder outside the daemon home. For an npm + plugin, find the repository in its `package.json`. +2. If SOURCE ends with `:`, use that subfolder of the clone as the plugin folder. +3. If the managed folder holds edits or commits, move them into the plugin folder. +4. In the plugin folder, install the dependencies and run the `build` commands from + `paseo-plugin.json`. Paseo runs `build` only for managed installations. +5. Ask the user before you remove the managed installation. `paseo plugin remove ` also + deletes the saved settings of the plugin. +6. Run `paseo plugin remove `. +7. Run `paseo plugin install /absolute/path/to/plugin-folder --id ` to keep the runtime ID. +8. Edit the plugin folder, and run `paseo plugin reload ` after each change. If a change needs + a `build` command, run that command before `reload`. + ## Create the project Use an absolute path on the daemon machine. `init` writes files but does not install packages. diff --git a/skills/paseo/SKILL.md b/skills/paseo/SKILL.md index cb08f49aa4..f3dce11ef7 100644 --- a/skills/paseo/SKILL.md +++ b/skills/paseo/SKILL.md @@ -84,7 +84,7 @@ Detach is an explicit user action in the subagents track, not an agent tool. A c Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false` when you want explicit reporting or no completion callback. -**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. Set `activeTurnBehavior` to `steer` or `interrupt` to override the default. Steering falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver after two quiet seconds. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback. +**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. For agent-scoped calls, `steer` waits until the recipient's current turn ends, and only `interrupt` stops a running turn. For top-level calls, `steer` joins the running turn and falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver together after two quiet seconds, or after the recipient's turn ends if it is running. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback. **`update_agent`** — `{ agentId, name?, labels?, settings? }`. Use `settings` for runtime changes on an existing agent: `modeId`, `model`, `thinkingOptionId`, and provider-specific `features`. For Codex fast mode, pass `settings: { features: { "fast_mode": true } }`.