From 8f205d5095a2ae7b3b9073074b8e9467e868ed67 Mon Sep 17 00:00:00 2001 From: Steve Castaneda Date: Sat, 7 Nov 2026 13:27:58 +0000 Subject: [PATCH 1/5] chore: add oxfmt and format every file Pins oxfmt 0.77.0 in a private root package.json that only holds repo tooling, with printWidth 160. Every other change is the formatter's own output. --- .oxfmtrc.json | 5 + CONTRIBUTING.md | 16 +- README.md | 18 +- history/client/dialog.test.ts | 92 +- history/client/directory.ts | 4 +- history/client/hover-button.tsx | 15 +- history/client/lifecycle.test.ts | 13 +- history/client/load-history.test.ts | 49 +- history/client/messages.test.ts | 28 +- history/client/pills.tsx | 86 +- history/client/task-notification.test.ts | 31 +- history/client/task-notification.tsx | 96 +- history/client/turn-jump.test.ts | 60 +- history/client/viewer.tsx | 493 +++++--- history/client/web.ts | 16 +- history/package.json | 22 +- history/paseo-plugin.json | 6 +- history/server/files.test.ts | 44 +- history/server/files.ts | 34 +- history/server/history.test.ts | 45 +- history/server/history.ts | 17 +- history/server/opencode.test.ts | 9 +- history/server/opencode.ts | 32 +- history/shared/citations.test.ts | 3 +- history/shared/citations.ts | 2 +- history/shared/entries.test.ts | 198 +++- history/shared/entries.ts | 238 ++-- history/shared/task-notification.test.ts | 21 +- history/shared/task-notification.ts | 13 +- history/tsconfig.json | 14 +- package-lock.json | 402 +++++++ package.json | 12 + playwright-pulse/client/lifecycle.test.ts | 6 +- playwright-pulse/client/motion.tsx | 52 +- playwright-pulse/client/panel.tsx | 187 ++- playwright-pulse/client/reporter-banner.tsx | 59 +- playwright-pulse/client/row.tsx | 17 +- playwright-pulse/client/screenshot.tsx | 91 +- playwright-pulse/client/section-title.tsx | 13 +- playwright-pulse/client/spinner.tsx | 18 +- playwright-pulse/client/stop-button.tsx | 31 +- playwright-pulse/client/tabs.tsx | 82 +- playwright-pulse/client/tests.tsx | 449 +++++-- playwright-pulse/package.json | 26 +- playwright-pulse/paseo-plugin.json | 6 +- playwright-pulse/server/attachments.ts | 7 +- playwright-pulse/server/programs.ts | 14 +- .../server/pulse-reporter.test.ts | 22 +- playwright-pulse/server/pulse.ts | 23 +- playwright-pulse/server/reporter-install.ts | 4 +- .../server/reporter-lifecycle.test.ts | 5 +- playwright-pulse/server/server.test.ts | 152 ++- playwright-pulse/server/stop.ts | 6 +- playwright-pulse/shared/view.test.ts | 207 +++- playwright-pulse/shared/view.ts | 45 +- playwright-pulse/tsconfig.json | 13 +- progress/README.md | 26 +- progress/client/attachments.tsx | 62 +- progress/client/blocks.tsx | 41 +- progress/client/chat-row-view.tsx | 25 +- progress/client/chat-row.test.ts | 54 +- progress/client/chat-row.ts | 6 +- progress/client/dashboard-query.ts | 13 +- progress/client/deliverables.test.ts | 9 +- progress/client/deliverables.tsx | 76 +- progress/client/dialog-stack.test.ts | 32 +- progress/client/dialog-stack.tsx | 140 ++- progress/client/directory.ts | 4 +- progress/client/errors.ts | 7 +- progress/client/history.tsx | 307 +++-- progress/client/i18n.test.ts | 109 +- progress/client/i18n.ts | 15 +- progress/client/launcher.tsx | 72 +- progress/client/lifecycle.test.ts | 44 +- progress/client/locales/en.ts | 49 +- progress/client/locales/zh-CN.ts | 32 +- progress/client/motion.tsx | 52 +- progress/client/page-screen.tsx | 31 +- progress/client/panel-opened.ts | 4 +- progress/client/panel.tsx | 602 +++++++--- progress/client/pdf.test.ts | 12 +- progress/client/pdf.tsx | 22 +- progress/client/pieces.ts | 7 +- progress/client/pill-popover.test.ts | 95 +- progress/client/pill-popover.tsx | 126 +- progress/client/pills.tsx | 43 +- progress/client/preview.test.ts | 120 +- progress/client/preview.tsx | 335 ++++-- progress/client/questions.test.ts | 36 +- progress/client/questions.tsx | 216 +++- progress/client/row.tsx | 17 +- progress/client/section-title.tsx | 13 +- progress/client/settings.tsx | 100 +- progress/client/show-more.tsx | 29 +- progress/client/spinner.tsx | 18 +- progress/client/status-badge.tsx | 16 +- progress/client/tabs.test.ts | 54 +- progress/client/tabs.tsx | 118 +- progress/client/ticket-dialog.tsx | 307 +++-- progress/client/time-bar.tsx | 7 +- progress/client/video.tsx | 4 +- progress/client/whats-new.tsx | 130 ++- progress/client/when.tsx | 3 +- progress/client/write-up.tsx | 78 +- progress/index.client.tsx | 38 +- progress/index.server.ts | 20 +- progress/package.json | 24 +- progress/scripts/windows-check.mjs | 40 +- progress/server/cli.ts | 93 +- progress/server/dashboard.ts | 22 +- progress/server/launcher.ts | 24 +- progress/server/lock.ts | 5 +- progress/server/open.ts | 34 +- progress/server/progress.test.ts | 1037 ++++++++++++----- progress/server/question-mode.ts | 5 +- progress/server/skill.ts | 22 +- progress/server/store.ts | 17 +- progress/server/tool.test.ts | 132 ++- progress/server/tool.ts | 118 +- progress/server/whats-new.test.ts | 34 +- progress/server/whats-new.ts | 23 +- progress/shared/attachments.ts | 26 +- progress/shared/blocks.ts | 15 +- progress/shared/dashboard.ts | 60 +- progress/shared/events.ts | 22 +- progress/shared/markdown.test.ts | 70 +- progress/shared/markdown.ts | 24 +- progress/shared/question-modes.ts | 13 +- progress/shared/rpc.ts | 9 +- progress/shared/show.ts | 28 +- progress/shared/ticket-story.ts | 4 +- progress/tsconfig.json | 13 +- scripts/check-install.mjs | 5 +- scripts/dev.mjs | 9 +- scripts/security-review.mjs | 17 +- setup-monitor/client/buttons.tsx | 30 +- setup-monitor/client/directory.ts | 4 +- setup-monitor/client/lifecycle.test.ts | 73 +- setup-monitor/client/popover.test.ts | 41 +- setup-monitor/client/popover.tsx | 57 +- setup-monitor/package.json | 22 +- setup-monitor/paseo-plugin.json | 6 +- setup-monitor/server/daemon.test.ts | 24 +- setup-monitor/server/daemon.ts | 10 +- setup-monitor/server/snapshot.test.ts | 17 +- setup-monitor/shared/snapshot.ts | 4 +- setup-monitor/tsconfig.json | 15 +- shell-yeah/README.md | 2 +- shell-yeah/client/directory.ts | 4 +- shell-yeah/client/live.test.ts | 47 +- shell-yeah/client/live.ts | 60 +- shell-yeah/client/output.tsx | 141 ++- shell-yeah/client/palette.test.ts | 67 +- shell-yeah/client/palette.ts | 24 +- shell-yeah/client/paste.tsx | 46 +- shell-yeah/client/run-row.tsx | 384 ++++-- shell-yeah/client/run-window.tsx | 169 ++- shell-yeah/client/ui.tsx | 140 ++- shell-yeah/index.client.test.ts | 27 +- shell-yeah/index.client.tsx | 5 +- shell-yeah/index.server.ts | 13 +- shell-yeah/package.json | 24 +- shell-yeah/server/claude.test.ts | 346 +++++- shell-yeah/server/claude.ts | 68 +- shell-yeah/server/logs.ts | 16 +- shell-yeah/server/runs.test.ts | 179 ++- shell-yeah/server/runs.ts | 72 +- shell-yeah/server/screen.test.ts | 40 +- shell-yeah/server/screen.ts | 45 +- shell-yeah/server/shells.ts | 21 +- shell-yeah/shared/row.ts | 5 +- shell-yeah/shared/rpc.ts | 20 +- shell-yeah/shared/text.test.ts | 5 +- shell-yeah/shared/text.ts | 15 +- shell-yeah/shared/view.test.ts | 120 +- shell-yeah/shared/view.ts | 108 +- shell-yeah/tsconfig.json | 13 +- test-support/client-harness.d.mts | 5 +- test-support/client-harness.mjs | 240 +++- time-since/client/directory.ts | 4 +- time-since/client/lifecycle.test.ts | 129 +- time-since/client/settings-panel.test.ts | 59 +- time-since/client/settings-panel.tsx | 55 +- time-since/client/settings.ts | 8 +- time-since/client/ticker.tsx | 54 +- time-since/package.json | 22 +- time-since/paseo-plugin.json | 6 +- time-since/server/elapsed.test.ts | 8 +- time-since/server/last-reply.test.ts | 5 +- time-since/server/last-reply.ts | 10 +- time-since/server/settings.ts | 10 +- time-since/shared/elapsed.ts | 15 +- time-since/tsconfig.json | 15 +- workspace-links/client/directory.ts | 4 +- workspace-links/client/lifecycle.test.ts | 91 +- workspace-links/client/panel.tsx | 319 +++-- workspace-links/client/phone-layout.test.ts | 23 +- workspace-links/client/pills.tsx | 37 +- workspace-links/client/popover.tsx | 25 +- workspace-links/package.json | 22 +- workspace-links/paseo-plugin.json | 5 +- workspace-links/server/links.test.ts | 5 +- workspace-links/server/links.ts | 5 +- .../server/shortcut.storage.test.ts | 5 +- workspace-links/server/shortcut.ts | 10 +- workspace-links/server/status.test.ts | 23 +- workspace-links/shared/links.ts | 12 +- workspace-links/shared/menu.ts | 10 +- workspace-links/tsconfig.json | 13 +- 209 files changed, 9766 insertions(+), 3407 deletions(-) create mode 100644 .oxfmtrc.json create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 00000000..92be4aed --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,5 @@ +{ + "$schema": "./node_modules/oxfmt/configuration_schema.json", + "printWidth": 160, + "ignorePatterns": ["**/package-lock.json"] +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 86f21a86..9683b20e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,10 +28,10 @@ npm run dev To see which copy Paseo is using, run `paseo plugin ls`. If `paseo` isn't on your `PATH`, use `/Applications/Paseo.app/Contents/Resources/bin/paseo`. `npm run dev` finds it either way. -| Problem | Fix | -| --- | --- | +| Problem | Fix | +| ---------------------------------------------------- | ------------------------------------------------------------------------------ | | `npm run typecheck failed` in a copy you didn't edit | Its dependencies are out of date. Run `npm install`, then `npm run dev` again. | -| Checks pass but the plugin isn't `running` | Run `paseo plugin logs ` to see why it didn't start. | +| Checks pass but the plugin isn't `running` | Run `paseo plugin logs ` to see why it didn't start. | Switching copies keeps what a plugin saved in `~/.paseo/plugin-data/`. @@ -41,11 +41,11 @@ Each plugin versions itself in that directory's `package.json`. npm and the Pase Versions follow [semver](https://semver.org). Each plugin moves from 0.x to `1.0.0` at its next release. From then on: -| The change | Bump | Example | -| --- | --- | --- | -| Breaks something for people already using the plugin: removes a feature or setting, moves saved data | First number | `1.4.2` to `2.0.0` | -| Adds a feature, or raises the minimum Paseo version | Middle number | `1.4.2` to `1.5.0` | -| Fixes a bug, or changes only the README or store page | Last number | `1.4.2` to `1.4.3` | +| The change | Bump | Example | +| ---------------------------------------------------------------------------------------------------- | ------------- | ------------------ | +| Breaks something for people already using the plugin: removes a feature or setting, moves saved data | First number | `1.4.2` to `2.0.0` | +| Adds a feature, or raises the minimum Paseo version | Middle number | `1.4.2` to `1.5.0` | +| Fixes a bug, or changes only the README or store page | Last number | `1.4.2` to `1.4.3` | A raised minimum Paseo version breaks nothing for current users. A Paseo older than the new `requirements.paseo` refuses the update and keeps the installed version running. diff --git a/README.md b/README.md index e062ffa9..1ef80ee4 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,15 @@ Plugins for [Paseo](https://paseo.sh). Each plugin lives in its own directory and can be installed independently. -| Plugin | What it adds | -| --- | --- | -| [time-since](time-since/README.md) | Elapsed time since the last chat message, shown above the composer. | -| [setup-monitor](setup-monitor/README.md) | Live worktree setup progress and logs from a top-bar button. | -| [workspace-links](workspace-links/README.md) | Quick access to workspace URLs from a JSON file. | -| [history](history/README.md) | Inspect chat messages, tools, and raw session records from a composer pill. | -| [progress](progress/README.md) | A live progress dashboard per worktree, drawn from a file agents write with the Progress tools on Paseo 0.14 and later, or the `paseo-progress` command. | -| [playwright-pulse](playwright-pulse/README.md) | A live dashboard for a worktree's Playwright test run, with each failure's screenshot, video and trace. | -| [shell-yeah](shell-yeah/README.md) | `/sh` runs a command as you, with live output in the chat that the agent sees only if you send it. Commands the agent hands you get a Run button. | +| Plugin | What it adds | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [time-since](time-since/README.md) | Elapsed time since the last chat message, shown above the composer. | +| [setup-monitor](setup-monitor/README.md) | Live worktree setup progress and logs from a top-bar button. | +| [workspace-links](workspace-links/README.md) | Quick access to workspace URLs from a JSON file. | +| [history](history/README.md) | Inspect chat messages, tools, and raw session records from a composer pill. | +| [progress](progress/README.md) | A live progress dashboard per worktree, drawn from a file agents write with the Progress tools on Paseo 0.14 and later, or the `paseo-progress` command. | +| [playwright-pulse](playwright-pulse/README.md) | A live dashboard for a worktree's Playwright test run, with each failure's screenshot, video and trace. | +| [shell-yeah](shell-yeah/README.md) | `/sh` runs a command as you, with live output in the chat that the agent sees only if you send it. Commands the agent hands you get a Run button. | ## Install diff --git a/history/client/dialog.test.ts b/history/client/dialog.test.ts index 8b814697..40e2dc1e 100644 --- a/history/client/dialog.test.ts +++ b/history/client/dialog.test.ts @@ -13,45 +13,78 @@ test("clicks inside the portaled dialog do not rerun the composer action or relo let pillPresses = 0; const native = Object.fromEntries(["View", "Text", "Pressable", "ActivityIndicator"].map((name) => [name, name])); const Modal = Object.assign(({ open, children }) => React.createElement(Open.Provider, { value: open }, children), { - Content: ({ children }) => useContext(Open) ? React.createElement("dialog", null, children) : null, + Content: ({ children }) => (useContext(Open) ? React.createElement("dialog", null, children) : null), }); const rpc = async () => { reads++; const text = JSON.stringify({ type: "user", message: { role: "user", content: "Visible message" } }) + "\n"; - return { path: "/tmp/log.jsonl", source: "one", provider: "claude", text, offset: 0, - nextOffset: text.length, totalBytes: text.length, modifiedAt: "2026-09-13" }; + return { + path: "/tmp/log.jsonl", + source: "one", + provider: "claude", + text, + offset: 0, + nextOffset: text.length, + totalBytes: text.length, + modifiedAt: "2026-09-13", + }; }; const h = clientHarness(fileURLToPath(new URL("..", import.meta.url)), { "react-native": { ...native, Platform: { OS: "web" } }, "@getpaseo/plugin/client": { useRpc: () => rpc }, "@getpaseo/plugin/client/ui": { - Modal, ScrollView: "ScrollView", Icon: "Icon", Markdown: "Markdown", copyText: async () => {}, - FlatList: ({ data, renderItem }) => React.createElement("list", null, data.map((item, index) => - React.createElement(React.Fragment, { key: index }, renderItem({ item, index })))), + Modal, + ScrollView: "ScrollView", + Icon: "Icon", + Markdown: "Markdown", + copyText: async () => {}, + FlatList: ({ data, renderItem }) => + React.createElement( + "list", + null, + data.map((item, index) => React.createElement(React.Fragment, { key: index }, renderItem({ item, index }))), + ), }, }); const stop = h.load("index.client.tsx").default(h.client); - h.agents.bootstrap([{ agent: { id: "a", workspaceId: "w" } }]); await h.flush(); + h.agents.bootstrap([{ agent: { id: "a", workspaceId: "w" } }]); + await h.flush(); const button = h.registrations[0].button; let pendingAction: Promise | undefined; function Host() { const [pending, setPending] = useState(false); - return React.createElement("pill", { - onClick: () => { - // Paseo's PluginButtonStore.run always marks actions pending, and - // ButtonView replaces the custom-icon subtree with a spinner. - pillPresses++; setPending(true); - pendingAction = Promise.resolve(button.behavior.onPress()).finally(() => setPending(false)); + return React.createElement( + "pill", + { + onClick: () => { + // Paseo's PluginButtonStore.run always marks actions pending, and + // ButtonView replaces the custom-icon subtree with a spinner. + pillPresses++; + setPending(true); + pendingAction = Promise.resolve(button.behavior.onPress()).finally(() => setPending(false)); + }, }, - }, pending ? React.createElement("spinner") : React.createElement(button.icon, { - context: "agent", agentId: "a", workspaceId: "w", size: 14, color: "gray", - host: { id: "host", label: "Host" }, layout: { platform: "web", compact: false }, - theme: { colors: {} }, - })); + pending + ? React.createElement("spinner") + : React.createElement(button.icon, { + context: "agent", + agentId: "a", + workspaceId: "w", + size: 14, + color: "gray", + host: { id: "host", label: "Host" }, + layout: { platform: "web", compact: false }, + theme: { colors: {} }, + }), + ); } let renderer; - await act(async () => { renderer = create(React.createElement(Host)); }); - await act(async () => { button.behavior.onPress(); }); + await act(async () => { + renderer = create(React.createElement(Host)); + }); + await act(async () => { + button.behavior.onPress(); + }); assert.equal(reads, 1); // React portals retain the logical React ancestry. Bubble a click from the @@ -59,13 +92,19 @@ test("clicks inside the portaled dialog do not rerun the composer action or relo const message = renderer.root.findAllByType("Markdown").find((item) => item.props.children === "Visible message"); assert.ok(message); let stopped = false; - const event = { stopPropagation: () => { stopped = true; } }; + const event = { + stopPropagation: () => { + stopped = true; + }, + }; act(() => { for (let node = message; node && !stopped; node = node.parent) { if (typeof node.type === "string") node.props.onClick?.(event); } }); - await act(async () => { await pendingAction; }); + await act(async () => { + await pendingAction; + }); assert.deepEqual({ pillPresses, reads }, { pillPresses: 0, reads: 1 }); const sourceButton = renderer.root.findAllByType("Pressable").find((item) => item.props.accessibilityLabel === "Raw source"); @@ -77,9 +116,14 @@ test("clicks inside the portaled dialog do not rerun the composer action or relo if (typeof node.type === "string") node.props.onClick?.(event); } }); - await act(async () => { await pendingAction; }); + await act(async () => { + await pendingAction; + }); assert.ok(renderer.root.findAllByType("Text").some((item) => item.props.children === "/tmp/log.jsonl")); const results = { pillPresses, reads }; - await act(async () => { renderer.unmount(); stop(); }); + await act(async () => { + renderer.unmount(); + stop(); + }); assert.deepEqual(results, { pillPresses: 0, reads: 1 }); }); diff --git a/history/client/directory.ts b/history/client/directory.ts index 1e59d614..9b267b07 100644 --- a/history/client/directory.ts +++ b/history/client/directory.ts @@ -7,9 +7,7 @@ type PaseoApi = ReturnType; type Handler = Subscribe extends (handler: infer H) => unknown ? H : never; export type PaseoAgentUpdate = Parameters>[0]; export type PaseoWorkspaceUpdate = Parameters>[0]; -type Message = Parameters< - Parameters>["subscription"]>["subscribe"]>[0]["update"] ->[0]; +type Message = Parameters>["subscription"]>["subscribe"]>[0]["update"]>[0]; type OwnedSubscription = { subscribe(observer: { snapshot(snapshot: T): void; update(message: Message): void; error?(error: unknown): void }): () => void; release(): Promise; diff --git a/history/client/hover-button.tsx b/history/client/hover-button.tsx index e25978f3..fba35b1d 100644 --- a/history/client/hover-button.tsx +++ b/history/client/hover-button.tsx @@ -2,13 +2,20 @@ import React, { useState, type ReactNode } from "react"; import { Pressable, type PressableProps } from "react-native"; import type { PluginButtonIconProps } from "@getpaseo/plugin/client"; -export function HoverButton({ colors, children, active = false, ...props }: Omit & { +export function HoverButton({ + colors, + children, + active = false, + ...props +}: Omit & { colors: PluginButtonIconProps["theme"]["colors"]; active?: boolean; children(color: string): ReactNode; }) { const [hovered, setHovered] = useState(false); - return setHovered(true)} onHoverOut={() => setHovered(false)}> - {children(active || (hovered && !props.disabled) ? colors.foreground : colors.foregroundMuted)} - ; + return ( + setHovered(true)} onHoverOut={() => setHovered(false)}> + {children(active || (hovered && !props.disabled) ? colors.foreground : colors.foregroundMuted)} + + ); } diff --git a/history/client/lifecycle.test.ts b/history/client/lifecycle.test.ts index 34497669..15b462a9 100644 --- a/history/client/lifecycle.test.ts +++ b/history/client/lifecycle.test.ts @@ -6,7 +6,8 @@ import { clientHarness } from "../../test-support/client-harness.mjs"; test("registers once per agent, follows workspace moves, and cleans up", async () => { const h = clientHarness(fileURLToPath(new URL("..", import.meta.url))); const stop = h.load("index.client.tsx").default(h.client); - h.agents.bootstrap([{ agent: { id: "a", workspaceId: "w" } }]); await h.flush(); + h.agents.bootstrap([{ agent: { id: "a", workspaceId: "w" } }]); + await h.flush(); assert.equal(h.registrations.length, 1); assert.equal(h.registrations[0].button.label, "History"); assert.equal(h.registrations[0].button.behavior.kind, "action"); @@ -18,12 +19,16 @@ test("registers once per agent, follows workspace moves, and cleans up", async ( assert.equal(h.registrations[1].workspaceId, "w2"); h.agents.update({ kind: "remove", agentId: "a" }); assert.equal(h.registrations[1].removed, true); - stop(); assert.equal(h.agents.listenerCount, 0); assert.equal(h.timers.size, 0); + stop(); + assert.equal(h.agents.listenerCount, 0); + assert.equal(h.timers.size, 0); }); test("does not register pills after stopping during the initial fetch", async () => { const h = clientHarness(fileURLToPath(new URL("..", import.meta.url))); - const stop = h.load("index.client.tsx").default(h.client); stop(); - h.agents.bootstrap([{ agent: { id: "a", workspaceId: "w" } }]); await h.flush(); + const stop = h.load("index.client.tsx").default(h.client); + stop(); + h.agents.bootstrap([{ agent: { id: "a", workspaceId: "w" } }]); + await h.flush(); assert.equal(h.registrations.length, 0); }); diff --git a/history/client/load-history.test.ts b/history/client/load-history.test.ts index 3ec7bf5f..a4eae653 100644 --- a/history/client/load-history.test.ts +++ b/history/client/load-history.test.ts @@ -10,12 +10,24 @@ test("automatically reads past context-only pages to visible conversation messag ]; let calls = 0; const totalBytes = texts.reduce((total, text) => total + Buffer.byteLength(text), 0); - const result = await loadConversationBatch(async (input) => { - const text = texts[calls++]!; - const offset = input.offset ?? 0; - return { path: "/tmp/test.jsonl", provider: "codex", source: "one", text, offset, - nextOffset: offset + Buffer.byteLength(text), totalBytes, modifiedAt: "2026-09-13T00:00:00Z" }; - }, { agentId: "a" }, () => false); + const result = await loadConversationBatch( + async (input) => { + const text = texts[calls++]!; + const offset = input.offset ?? 0; + return { + path: "/tmp/test.jsonl", + provider: "codex", + source: "one", + text, + offset, + nextOffset: offset + Buffer.byteLength(text), + totalBytes, + modifiedAt: "2026-09-13T00:00:00Z", + }; + }, + { agentId: "a" }, + () => false, + ); assert.equal(calls, 3); assert.match(result!.text, /My actual message/); assert.equal(result!.page.nextOffset, totalBytes); @@ -23,10 +35,23 @@ test("automatically reads past context-only pages to visible conversation messag test("stops fetching immediately when the dialog closes", async () => { let calls = 0; - const result = await loadConversationBatch(async () => { - calls++; - return { path: "/tmp/test.jsonl", provider: "codex", source: "one", text: "{}\n", offset: 0, - nextOffset: 3, totalBytes: 100, modifiedAt: "2026-09-13T00:00:00Z" }; - }, { agentId: "a" }, () => true); - assert.equal(calls, 1); assert.equal(result, null); + const result = await loadConversationBatch( + async () => { + calls++; + return { + path: "/tmp/test.jsonl", + provider: "codex", + source: "one", + text: "{}\n", + offset: 0, + nextOffset: 3, + totalBytes: 100, + modifiedAt: "2026-09-13T00:00:00Z", + }; + }, + { agentId: "a" }, + () => true, + ); + assert.equal(calls, 1); + assert.equal(result, null); }); diff --git a/history/client/messages.test.ts b/history/client/messages.test.ts index 89bdc529..3afd0bf9 100644 --- a/history/client/messages.test.ts +++ b/history/client/messages.test.ts @@ -9,13 +9,18 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true; function renderViewer() { const reply = "**Found it.**\n\nMEMORY.md: PRIVATE_METADATA"; - const text = [{ type: "user", message: { role: "user", content: "Why is the total off?" } }, - { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: reply }] } }] - .map((record) => JSON.stringify(record)).join("\n") + "\n"; + const text = + [ + { type: "user", message: { role: "user", content: "Why is the total off?" } }, + { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: reply }] } }, + ] + .map((record) => JSON.stringify(record)) + .join("\n") + "\n"; const h = clientHarness(fileURLToPath(new URL("..", import.meta.url)), { "react-native": { View: "View", Text: "Text", Pressable: "Pressable", ActivityIndicator: "ActivityIndicator", Platform: { OS: "web" } }, - "@getpaseo/plugin/client": { useRpc: () => async () => - ({ path: "/tmp/log", source: "one", provider: "claude", text, offset: 0, nextOffset: text.length, totalBytes: text.length }) }, + "@getpaseo/plugin/client": { + useRpc: () => async () => ({ path: "/tmp/log", source: "one", provider: "claude", text, offset: 0, nextOffset: text.length, totalBytes: text.length }), + }, "@getpaseo/plugin/client/ui": { Icon: "Icon", Markdown: "Markdown", copyText: async () => {}, FlatList: "list", ScrollView: "scroll" }, }); return create(React.createElement(h.load("client/viewer.tsx").HistoryViewer, { agentId: "a", theme: { colors: {} } })); @@ -23,15 +28,22 @@ function renderViewer() { test("draws messages with Paseo's Markdown and hides memory citations", async () => { let renderer; - await act(async () => { renderer = renderViewer(); }); - assert.deepEqual(renderer.root.findAllByType("Markdown").map((node) => node.props.children), ["Why is the total off?", "**Found it.**"]); + await act(async () => { + renderer = renderViewer(); + }); + assert.deepEqual( + renderer.root.findAllByType("Markdown").map((node) => node.props.children), + ["Why is the total off?", "**Found it.**"], + ); assert.ok(!JSON.stringify(renderer.toJSON()).includes("PRIVATE_METADATA")); await act(async () => renderer.unmount()); }); test("tells screen readers on the web which toggles are on and whether a record is expanded", async () => { let renderer; - await act(async () => { renderer = renderViewer(); }); + await act(async () => { + renderer = renderViewer(); + }); const raw = () => renderer.root.findAllByType("Pressable").find((node) => node.props.accessibilityLabel === "Raw turn entries"); assert.equal(raw().props["aria-selected"], false); assert.equal(raw().props["aria-pressed"], false); diff --git a/history/client/pills.tsx b/history/client/pills.tsx index 7b42ff9b..5cf7df79 100644 --- a/history/client/pills.tsx +++ b/history/client/pills.tsx @@ -9,8 +9,16 @@ import { modalEventBoundary } from "./web"; export function contributePills(client: PluginClientContext) { let selected: string | null = null; const listeners = new Set<() => void>(); - const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; }; - const select = (id: string | null) => { selected = id; for (const listener of listeners) listener(); }; + const subscribe = (listener: () => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }; + const select = (id: string | null) => { + selected = id; + for (const listener of listeners) listener(); + }; const pills = new Map(); // The action toggles a controlled host modal mounted beside the custom icon. @@ -18,37 +26,67 @@ export function contributePills(client: PluginClientContext) { // reactivate the host pill, whose pending state unmounts its icon subtree. function HistoryIcon(props: PluginButtonIconProps) { const agentId = props.context === "agent" ? props.agentId : ""; - const open = useSyncExternalStore(subscribe, () => selected === agentId, () => false); - return <> - - - { if (!next) select(null); }}> - - {open ? : null} - - - - ; + const open = useSyncExternalStore( + subscribe, + () => selected === agentId, + () => false, + ); + return ( + <> + + + { + if (!next) select(null); + }} + > + + {open ? : null} + + + + + ); } const remove = (id: string) => { if (selected === id) select(null); - pills.get(id)?.pill.remove(); pills.delete(id); + pills.get(id)?.pill.remove(); + pills.delete(id); }; const register = (agent: { id: string; workspaceId?: string | null; archivedAt?: string | null }) => { - if (!agent.workspaceId || agent.archivedAt) { remove(agent.id); return; } + if (!agent.workspaceId || agent.archivedAt) { + remove(agent.id); + return; + } const existing = pills.get(agent.id); if (existing?.workspaceId === agent.workspaceId) return; if (existing) remove(agent.id); - pills.set(agent.id, { workspaceId: agent.workspaceId, pill: client.addComposerPill({ - id: "history", workspaceId: agent.workspaceId, agentId: agent.id, - button: { title: "History", label: "History", icon: HistoryIcon, - behavior: { kind: "action", onPress: () => { select(agent.id); } } }, - }) }); + pills.set(agent.id, { + workspaceId: agent.workspaceId, + pill: client.addComposerPill({ + id: "history", + workspaceId: agent.workspaceId, + agentId: agent.id, + button: { + title: "History", + label: "History", + icon: HistoryIcon, + behavior: { + kind: "action", + onPress: () => { + select(agent.id); + }, + }, + }, + }), + }); }; const stop = observeDirectory({ list: (options) => client.paseo.agents.list({ ...options, filter: { includeArchived: false } }), - select: (message) => message.type === "agent_update" ? message.payload : undefined, + select: (message) => (message.type === "agent_update" ? message.payload : undefined), snapshot: (entries) => { const ids = new Set(entries.map(({ agent }) => agent.id)); for (const id of pills.keys()) if (!ids.has(id)) remove(id); @@ -60,8 +98,10 @@ export function contributePills(client: PluginClientContext) { }, }); return () => { - stop(); select(null); + stop(); + select(null); for (const { pill } of pills.values()) pill.remove(); - pills.clear(); listeners.clear(); + pills.clear(); + listeners.clear(); }; } diff --git a/history/client/task-notification.test.ts b/history/client/task-notification.test.ts index 71f374c4..0d424952 100644 --- a/history/client/task-notification.test.ts +++ b/history/client/task-notification.test.ts @@ -16,10 +16,24 @@ test("shows result Markdown immediately, expands details, and copies the result" const Body = h.load("client/task-notification.tsx").TaskNotificationBody; const result = "## Findings\n\n**Everything passed.**\n\nMEMORY.md:3"; let renderer; - await act(async () => { renderer = create(React.createElement(Body, { - notification: { taskId: "private-task-id", outputFile: "/tmp/private.output", note: "Can resume", status: "completed", summary: 'Agent "Check chart" finished', result, toolUses: 53 }, - colors: {}, copy: (text) => copied.push(text), onError: assert.fail, - })); }); + await act(async () => { + renderer = create( + React.createElement(Body, { + notification: { + taskId: "private-task-id", + outputFile: "/tmp/private.output", + note: "Can resume", + status: "completed", + summary: 'Agent "Check chart" finished', + result, + toolUses: 53, + }, + colors: {}, + copy: (text) => copied.push(text), + onError: assert.fail, + }), + ); + }); const initial = JSON.stringify(renderer.toJSON()); assert.ok(initial.includes("Check chart")); assert.equal(renderer.root.findByType("Markdown").props.children, "## Findings\n\n**Everything passed.**"); @@ -29,12 +43,17 @@ test("shows result Markdown immediately, expands details, and copies the result" assert.ok(!initial.includes("/tmp/private.output")); await act(async () => { details().props.onPress(); - renderer.root.findAllByType("Pressable").find((node) => node.props.accessibilityLabel === "Copy task result").props.onPress(); + renderer.root + .findAllByType("Pressable") + .find((node) => node.props.accessibilityLabel === "Copy task result") + .props.onPress(); }); assert.equal(details().props["aria-expanded"], true); const expanded = JSON.stringify(renderer.toJSON()); assert.ok(expanded.includes("private-task-id")); assert.ok(expanded.includes("/tmp/private.output")); assert.deepEqual(copied, [result]); - await act(async () => { renderer.unmount(); }); + await act(async () => { + renderer.unmount(); + }); }); diff --git a/history/client/task-notification.tsx b/history/client/task-notification.tsx index d179c1db..5eb8e3c0 100644 --- a/history/client/task-notification.tsx +++ b/history/client/task-notification.tsx @@ -6,7 +6,11 @@ import type { PluginButtonIconProps } from "@getpaseo/plugin/client"; import { notificationUsage, type TaskNotification } from "../shared/task-notification"; import { hideCitations } from "../shared/citations"; -export function TaskNotificationBody({ notification, colors, copy }: { +export function TaskNotificationBody({ + notification, + colors, + copy, +}: { notification: TaskNotification; colors: PluginButtonIconProps["theme"]["colors"]; copy(text: string): void; @@ -14,33 +18,67 @@ export function TaskNotificationBody({ notification, colors, copy }: { const [details, setDetails] = useState(false); const usage = notificationUsage(notification); const summary = notification.summary.replace(/^Agent "(.+)" finished$/, "$1"); - return - {summary} - {notification.result ? {hideCitations(notification.result)} : null} - - {usage ? {usage} : null} - {notification.result ? copy(notification.result!)} style={({ pressed }) => ({ minHeight: 32, minWidth: 32, justifyContent: "center", alignItems: "center", opacity: pressed ? 0.6 : 1 })}> - {color => <> - - } - : null} - setDetails(!details)} style={({ pressed }) => ({ flexDirection: "row", gap: 5, alignItems: "center", minHeight: 32, paddingHorizontal: 6, opacity: pressed ? 0.6 : 1 })}> - {color => <> - - Details - } - + return ( + + + {summary} + + {notification.result ? {hideCitations(notification.result)} : null} + + {usage ? {usage} : null} + {notification.result ? ( + copy(notification.result!)} + style={({ pressed }) => ({ minHeight: 32, minWidth: 32, justifyContent: "center", alignItems: "center", opacity: pressed ? 0.6 : 1 })} + > + {(color) => ( + <> + + + )} + + ) : null} + setDetails(!details)} + style={({ pressed }) => ({ flexDirection: "row", gap: 5, alignItems: "center", minHeight: 32, paddingHorizontal: 6, opacity: pressed ? 0.6 : 1 })} + > + {(color) => ( + <> + + Details + + )} + + + {details ? ( + + {( + [ + ["Task ID", notification.taskId], + ["Tool use ID", notification.toolUseId], + ["Output file", notification.outputFile], + ["Status", notification.status], + ["Note", notification.note], + ] as const + ) + .filter(([, value]) => value) + .map(([label, value]) => ( + + {label} + + {value} + + + ))} + + ) : null} - {details ? - {([ - ["Task ID", notification.taskId], ["Tool use ID", notification.toolUseId], - ["Output file", notification.outputFile], ["Status", notification.status], ["Note", notification.note], - ] as const).filter(([, value]) => value).map(([label, value]) => - {label} - {value} - )} - : null} - ; + ); } diff --git a/history/client/turn-jump.test.ts b/history/client/turn-jump.test.ts index 24fa503e..b3a0fd12 100644 --- a/history/client/turn-jump.test.ts +++ b/history/client/turn-jump.test.ts @@ -10,30 +10,39 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true; async function mount(roles) { const jumps = []; const stats = { reads: 0 }; - const text = roles.map((role, index) => JSON.stringify({ type: role, - message: { role, content: `Message ${index}` } })).join("\n") + "\n"; + const text = roles.map((role, index) => JSON.stringify({ type: role, message: { role, content: `Message ${index}` } })).join("\n") + "\n"; const h = clientHarness(fileURLToPath(new URL("..", import.meta.url)), { "react-native": { View: "View", Text: "Text", Pressable: "Pressable", ActivityIndicator: "ActivityIndicator", Platform: { OS: "web" } }, - "@getpaseo/plugin/client": { useRpc: () => async () => { - stats.reads++; - return { path: "/tmp/log", source: "one", provider: "claude", text, offset: 0, nextOffset: text.length, totalBytes: text.length }; - } }, + "@getpaseo/plugin/client": { + useRpc: () => async () => { + stats.reads++; + return { path: "/tmp/log", source: "one", provider: "claude", text, offset: 0, nextOffset: text.length, totalBytes: text.length }; + }, + }, "@getpaseo/plugin/client/ui": { - Icon: "Icon", Markdown: "Markdown", copyText: async () => {}, FlatList: "list", + Icon: "Icon", + Markdown: "Markdown", + copyText: async () => {}, + FlatList: "list", ScrollView: ({ ref, ...props }) => { - useImperativeHandle(ref, () => ({ scrollTo: args => jumps.push(args) })); + useImperativeHandle(ref, () => ({ scrollTo: (args) => jumps.push(args) })); return React.createElement("scroll", props, props.children); }, }, }); let renderer; - await act(async () => { renderer = create(React.createElement(h.load("client/viewer.tsx").HistoryViewer, { agentId: "a", theme: { colors: {} } })); }); - const button = label => renderer.root.findAllByType("Pressable").find(node => node.props.accessibilityLabel === label); + await act(async () => { + renderer = create(React.createElement(h.load("client/viewer.tsx").HistoryViewer, { agentId: "a", theme: { colors: {} } })); + }); + const button = (label) => renderer.root.findAllByType("Pressable").find((node) => node.props.accessibilityLabel === label); const scroller = () => renderer.root.findByType("scroll"); return { - renderer, jumps, stats, button, + renderer, + jumps, + stats, + button, layoutTurns(offsets) { - const nodes = renderer.root.findAllByType("View").filter(node => node.props.onLayout); + const nodes = renderer.root.findAllByType("View").filter((node) => node.props.onLayout); act(() => nodes.forEach((node, index) => node.props.onLayout({ nativeEvent: { layout: { y: offsets[index] } } }))); }, size(viewport, content) { @@ -42,11 +51,20 @@ async function mount(roles) { scroller().props.onContentSizeChange(400, content); }); }, - scroll(y) { act(() => scroller().props.onScroll({ nativeEvent: { contentOffset: { y } } })); }, - press(label) { act(() => button(label).props.onPress()); }, + scroll(y) { + act(() => scroller().props.onScroll({ nativeEvent: { contentOffset: { y } } })); + }, + press(label) { + act(() => button(label).props.onPress()); + }, // No scroll events for as long as the viewer waits: whatever was scrolling has stopped. quiet() { - act(() => [...h.timers].forEach(([id, timer]) => { h.timers.delete(id); timer.callback(); })); + act(() => + [...h.timers].forEach(([id, timer]) => { + h.timers.delete(id); + timer.callback(); + }), + ); }, arrows: () => ({ previous: !button("Previous turn").props.disabled, next: !button("Next turn").props.disabled }), unmount: () => act(async () => renderer.unmount()), @@ -68,7 +86,7 @@ test("footer arrows navigate turns without replacing the conversation", async () v.press("Previous turn"); assert.equal(v.jumps[1].y, 0); assert.equal(v.stats.reads, 1); - assert.equal(v.renderer.root.findAllByType("Markdown").filter(node => /^Message \d$/.test(node.props.children)).length, 3); + assert.equal(v.renderer.root.findAllByType("Markdown").filter((node) => /^Message \d$/.test(node.props.children)).length, 3); v.press("Raw source"); assert.equal(v.button("Next turn"), undefined); v.press("Conversation"); @@ -127,7 +145,10 @@ test("a double press moves two turns while the first jump is still scrolling", a v.press("Next turn"); v.scroll(400); v.press("Next turn"); - assert.deepEqual(v.jumps.map(jump => jump.y), [1000, 1400]); + assert.deepEqual( + v.jumps.map((jump) => jump.y), + [1000, 1400], + ); assert.deepEqual(v.arrows(), { previous: true, next: false }, "Next is off as soon as the end is the destination"); v.scroll(900); v.scroll(1400); @@ -206,6 +227,9 @@ test("reversing during a jump keeps counting from the new destination", async () // One more event from the first jump, still heading down. v.scroll(1120); v.press("Previous turn"); - assert.deepEqual(v.jumps.map(jump => jump.y), [1400, 1000, 0]); + assert.deepEqual( + v.jumps.map((jump) => jump.y), + [1400, 1000, 0], + ); await v.unmount(); }); diff --git a/history/client/viewer.tsx b/history/client/viewer.tsx index afdbf8b8..f6b9663d 100644 --- a/history/client/viewer.tsx +++ b/history/client/viewer.tsx @@ -11,68 +11,143 @@ import { HoverButton } from "./hover-button"; import { TaskNotificationBody } from "./task-notification"; type Colors = PluginButtonIconProps["theme"]["colors"]; -const mono = () => Platform.OS === "ios" ? "Menlo" : "monospace"; +const mono = () => (Platform.OS === "ios" ? "Menlo" : "monospace"); -function Action({ label, icon, text, disabled = false, active, onPress, colors }: { - label: string; icon: string; text?: string; disabled?: boolean; active?: boolean; onPress(): void; colors: Colors; +function Action({ + label, + icon, + text, + disabled = false, + active, + onPress, + colors, +}: { + label: string; + icon: string; + text?: string; + disabled?: boolean; + active?: boolean; + onPress(): void; + colors: Colors; }) { - return ({ paddingHorizontal: text ? 10 : 7, minHeight: 32, minWidth: 32, - flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 6, borderRadius: 6, - backgroundColor: pressed || active ? colors.surface2 : "transparent", opacity: disabled ? 0.4 : 1 })}> - {color => <> - - {text ? {text} : null} - } - ; + return ( + ({ + paddingHorizontal: text ? 10 : 7, + minHeight: 32, + minWidth: 32, + flexDirection: "row", + alignItems: "center", + justifyContent: "center", + gap: 6, + borderRadius: 6, + backgroundColor: pressed || active ? colors.surface2 : "transparent", + opacity: disabled ? 0.4 : 1, + })} + > + {(color) => ( + <> + + {text ? ( + + {text} + + ) : null} + + )} + + ); } function RawEntry({ entry, colors, copy }: { entry: HistoryEntry; colors: Colors; copy(text: string): void }) { const [expanded, setExpanded] = useState(false); - return - - setExpanded(!expanded)} - style={({ pressed }) => ({ flex: 1, flexDirection: "row", gap: 8, alignItems: "center", minHeight: 36, - paddingHorizontal: 6, borderRadius: 4, backgroundColor: pressed ? colors.surface2 : "transparent" })}> - {color => <> - - - {entry.title} - {!expanded ? {entry.preview.slice(0, 240)} : null} - - } - - copy(entry.raw)} /> + return ( + + + setExpanded(!expanded)} + style={({ pressed }) => ({ + flex: 1, + flexDirection: "row", + gap: 8, + alignItems: "center", + minHeight: 36, + paddingHorizontal: 6, + borderRadius: 4, + backgroundColor: pressed ? colors.surface2 : "transparent", + })} + > + {(color) => ( + <> + + + + {entry.title} + + {!expanded ? ( + + {entry.preview.slice(0, 240)} + + ) : null} + + + )} + + copy(entry.raw)} /> + + {expanded ? ( + + + {entry.valid ? JSON.stringify(JSON.parse(entry.raw), null, 2) : entry.raw} + + + ) : null} - {expanded ? - - {entry.valid ? JSON.stringify(JSON.parse(entry.raw), null, 2) : entry.raw} - - : null} - ; + ); } function Message({ entry, colors, copy }: { entry: HistoryEntry; colors: Colors; copy(text: string): void }) { const [raw, setRaw] = useState(false); const notification = entry.notification; const subject = notification?.summary.startsWith("Agent ") ? "Agent" : "Task"; - const label = notification ? `${subject} ${notification.status === "completed" ? "finished" : notification.status}` - : entry.role === "user" ? "You" : "Assistant"; - const icon = notification ? notification.status === "completed" ? "Check" : notification.status === "failed" ? "CircleAlert" : "Activity" - : entry.role === "user" ? "User" : "Sparkles"; - return - - - {label} - copy(entry.preview)} /> - setRaw(!raw)} /> + const label = notification + ? `${subject} ${notification.status === "completed" ? "finished" : notification.status}` + : entry.role === "user" + ? "You" + : "Assistant"; + const icon = notification + ? notification.status === "completed" + ? "Check" + : notification.status === "failed" + ? "CircleAlert" + : "Activity" + : entry.role === "user" + ? "User" + : "Sparkles"; + return ( + + + + {label} + copy(entry.preview)} /> + setRaw(!raw)} /> + + {notification ? : {hideCitations(entry.preview)}} + {raw ? : null} - {notification ? - : {hideCitations(entry.preview)}} - {raw ? : null} - ; + ); } function Turn({ turn, colors, copy, onLayout }: { turn: HistoryTurn; colors: Colors; copy(text: string): void; onLayout(event: LayoutChangeEvent): void }) { @@ -80,31 +155,70 @@ function Turn({ turn, colors, copy, onLayout }: { turn: HistoryTurn; colors: Col const messages = turn.entries.filter((entry) => entry.category === "message"); const timestamp = turn.entries.find((entry) => entry.timestamp)?.timestamp; const date = timestamp ? new Date(timestamp) : null; - const tags = ([['tools', 'Tools', 'Terminal'], ['reasoning', 'Reasoning', 'Brain'], ['context', 'Context', 'Files'], ['events', 'Events', 'Activity']] as const) - .map(([category, label, icon]) => ({ category, label, icon, entries: turn.entries.filter((entry) => entry.category === category - || (category === "tools" && entry.hasTools) || (category === "reasoning" && entry.hasReasoning)) })) + const tags = ( + [ + ["tools", "Tools", "Terminal"], + ["reasoning", "Reasoning", "Brain"], + ["context", "Context", "Files"], + ["events", "Events", "Activity"], + ] as const + ) + .map(([category, label, icon]) => ({ + category, + label, + icon, + entries: turn.entries.filter( + (entry) => entry.category === category || (category === "tools" && entry.hasTools) || (category === "reasoning" && entry.hasReasoning), + ), + })) .filter((tag) => tag.entries.length); - const shown = detail === "raw" ? turn.entries : tags.find((tag) => tag.category === detail)?.entries ?? []; - return - - - - {turn.title} + const shown = detail === "raw" ? turn.entries : (tags.find((tag) => tag.category === detail)?.entries ?? []); + return ( + + + + + + {turn.title} + + + + {date && !Number.isNaN(date.getTime()) ? date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : ""} + - {date && !Number.isNaN(date.getTime()) ? date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : ""} - - {messages.map((entry, index) => )} - - {tags.map((tag) => setDetail(detail === tag.category ? null : tag.category)} />)} - setDetail(detail === "raw" ? null : "raw")} /> + {messages.map((entry, index) => ( + + ))} + + {tags.map((tag) => ( + setDetail(detail === tag.category ? null : tag.category)} + /> + ))} + setDetail(detail === "raw" ? null : "raw")} + /> + + {detail ? ( + + {shown.map((entry, index) => ( + + ))} + + ) : null} - {detail ? - {shown.map((entry, index) => )} - : null} - ; + ); } export function HistoryViewer({ agentId, theme }: PluginButtonIconProps & { agentId: string }) { @@ -123,36 +237,60 @@ export function HistoryViewer({ agentId, theme }: PluginButtonIconProps & { agen // Where an arrow's animated scroll is heading. The arrows count from there until the view arrives or scrolling goes quiet. const [jump, setJump] = useState(null); const jumpTimer = useRef>(undefined); - const endJump = () => { clearTimeout(jumpTimer.current); setJump(null); }; + const endJump = () => { + clearTimeout(jumpTimer.current); + setJump(null); + }; // Scroll events fire every frame while anything scrolls, so a gap means the jump finished, stopped short or never moved. - const holdJump = () => { clearTimeout(jumpTimer.current); jumpTimer.current = setTimeout(endJump, 250); }; + const holdJump = () => { + clearTimeout(jumpTimer.current); + jumpTimer.current = setTimeout(endJump, 250); + }; useEffect(() => () => clearTimeout(jumpTimer.current), []); const [positions, setPositions] = useState>({}); - const measure = (key: string, y: number) => setPositions(previous => previous[key] === y ? previous : { ...previous, [key]: y }); + const measure = (key: string, y: number) => setPositions((previous) => (previous[key] === y ? previous : { ...previous, [key]: y })); const colors = theme.colors; const entries = useMemo(() => parseEntries(text), [text]); - const turns = useMemo(() => groupTurns(entries).filter((turn) => turn.title !== "Session details" - || turn.entries.some((entry) => entry.category === "message")), [entries]); + const turns = useMemo( + () => groupTurns(entries).filter((turn) => turn.title !== "Session details" || turn.entries.some((entry) => entry.category === "message")), + [entries], + ); async function load(append = false) { const id = ++request.current; - setBusy(true); setError(null); setNotice(""); + setBusy(true); + setError(null); + setNotice(""); try { - const result = await loadConversationBatch(rpc, { agentId, offset: append && page ? page.nextOffset : 0, - ...(append && page ? { source: page.source } : {}) }, () => request.current !== id); + const result = await loadConversationBatch( + rpc, + { agentId, offset: append && page ? page.nextOffset : 0, ...(append && page ? { source: page.source } : {}) }, + () => request.current !== id, + ); if (!result || request.current !== id) return; - if (!append) { setScrollY(0); endJump(); if (page) conversationScroll.current?.scrollTo({ y: 0, animated: false }); } - setPage(result.page); setText((current) => append ? current + result.text : result.text); + if (!append) { + setScrollY(0); + endJump(); + if (page) conversationScroll.current?.scrollTo({ y: 0, animated: false }); + } + setPage(result.page); + setText((current) => (append ? current + result.text : result.text)); } catch (reason) { if (request.current === id) setError(reason instanceof Error ? reason.message : "Could not read the log. Try again."); - } finally { if (request.current === id) setBusy(false); } + } finally { + if (request.current === id) setBusy(false); + } } useEffect(() => { void load(); - return () => { request.current++; }; + return () => { + request.current++; + }; }, [agentId]); const copy = (value: string) => { - void copyText(value).then(() => setNotice("Copied")).catch(() => setError("Could not copy. You can select the text instead.")); + void copyText(value) + .then(() => setNotice("Copied")) + .catch(() => setError("Could not copy. You can select the text instead.")); }; // Before the scroll area has its size nothing can scroll, so every stop is at the top. const maxScrollY = viewportHeight > 0 ? Math.max(0, contentHeight - viewportHeight) : 0; @@ -162,8 +300,8 @@ export function HistoryViewer({ agentId, theme }: PluginButtonIconProps & { agen return y === undefined ? [] : [Math.min(y, maxScrollY)]; }); const from = jump === null ? scrollY : Math.min(jump, maxScrollY); - const previousStop = stops.findLast(y => y < from - 2); - const nextStop = stops.find(y => y > from + 2); + const previousStop = stops.findLast((y) => y < from - 2); + const nextStop = stops.find((y) => y > from + 2); const jumpTo = (y: number | undefined) => { if (y === undefined) return; setJump(y); @@ -173,55 +311,146 @@ export function HistoryViewer({ agentId, theme }: PluginButtonIconProps & { agen const onScroll = (y: number) => { setScrollY(y); if (jump === null) return; - if (Math.abs(y - from) <= 2) endJump(); else holdJump(); + if (Math.abs(y - from) <= 2) endJump(); + else holdJump(); }; const hasMore = page && page.nextOffset < page.totalBytes; - return - - { if (source) setScrollY(0); setSource(false); }} /> - { endJump(); setSource(true); }} /> - - {busy ? - : void load()} />} - - {source && page ? - - {page.path} - copy(page.path)} /> - : null} - {error ? - - {error} - : null} - {source ? String(index)} style={{ flex: 1, minHeight: 0 }} - contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 16 }} renderItem={({ item }) => } /> - : setViewportHeight(event.nativeEvent.layout.height)} onContentSizeChange={(_, height) => setContentHeight(height)} - onScroll={event => onScroll(event.nativeEvent.contentOffset.y)} contentContainerStyle={{ paddingHorizontal: 20, paddingBottom: 16 }}> - {turns.map((turn, index) => measure(`turn-${index}`, event.nativeEvent.layout.y)} />)} - {turns.length === 0 ? {busy ? "Reading history…" : "No messages saved yet"} : null} - } - - {!source ? - jumpTo(previousStop)} /> - jumpTo(nextStop)} /> - : null} - - - - {notice || (page ? `${entries.length} entries` : 'Saved on this host')} - - {hasMore ? <> - · - void load(true)} - style={({ pressed }) => ({ minHeight: 32, paddingHorizontal: 4, justifyContent: "center", borderRadius: 4, - opacity: busy ? 0.4 : 1, backgroundColor: pressed ? colors.surface2 : "transparent" })}> - {color => More} - - : null} + return ( + + + { + if (source) setScrollY(0); + setSource(false); + }} + /> + { + endJump(); + setSource(true); + }} + /> + + {busy ? ( + + ) : ( + void load()} /> + )} + + {source && page ? ( + + + + {page.path} + + copy(page.path)} /> + + ) : null} + {error ? ( + + + + {error} + + + ) : null} + {source ? ( + String(index)} + style={{ flex: 1, minHeight: 0 }} + contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 16 }} + renderItem={({ item }) => } + /> + ) : ( + setViewportHeight(event.nativeEvent.layout.height)} + onContentSizeChange={(_, height) => setContentHeight(height)} + onScroll={(event) => onScroll(event.nativeEvent.contentOffset.y)} + contentContainerStyle={{ paddingHorizontal: 20, paddingBottom: 16 }} + > + {turns.map((turn, index) => ( + measure(`turn-${index}`, event.nativeEvent.layout.y)} /> + ))} + {turns.length === 0 ? ( + {busy ? "Reading history…" : "No messages saved yet"} + ) : null} + + )} + + {!source ? ( + + jumpTo(previousStop)} /> + jumpTo(nextStop)} /> + + ) : null} + + + + {notice || (page ? `${entries.length} entries` : "Saved on this host")} + + {hasMore ? ( + <> + · + void load(true)} + style={({ pressed }) => ({ + minHeight: 32, + paddingHorizontal: 4, + justifyContent: "center", + borderRadius: 4, + opacity: busy ? 0.4 : 1, + backgroundColor: pressed ? colors.surface2 : "transparent", + })} + > + {(color) => ( + + More + + )} + + + ) : null} + - ; + ); } diff --git a/history/client/web.ts b/history/client/web.ts index 3d7cc27b..cbfffaf4 100644 --- a/history/client/web.ts +++ b/history/client/web.ts @@ -3,7 +3,9 @@ import { Platform } from "react-native"; type BubblingEvent = { stopPropagation(): void }; type KeyEvent = BubblingEvent & { key: string }; -function stop(event: BubblingEvent) { event.stopPropagation(); } +function stop(event: BubblingEvent) { + event.stopPropagation(); +} function stopActivationKey(event: KeyEvent) { if (event.key === "Enter" || event.key === " ") event.stopPropagation(); } @@ -11,9 +13,11 @@ function stopActivationKey(event: KeyEvent) { // A web modal is a React portal: events still bubble to the composer Pressable // in its React ancestry. Isolate its actions without blocking Escape dismissal. export function modalEventBoundary() { - return Platform.OS === "web" ? { - onClick: stop, - onKeyDown: stopActivationKey, - onKeyUp: stopActivationKey, - } : {}; + return Platform.OS === "web" + ? { + onClick: stop, + onKeyDown: stopActivationKey, + onKeyUp: stopActivationKey, + } + : {}; } diff --git a/history/package.json b/history/package.json index 7b554231..bddc411d 100644 --- a/history/package.json +++ b/history/package.json @@ -2,6 +2,13 @@ "name": "@stevecastaneda/paseo-history", "version": "1.2.1", "description": "Inspect chat messages, tools, and raw session records from a composer pill in Paseo.", + "keywords": [ + "history", + "paseo", + "paseo-plugin", + "transcript" + ], + "homepage": "https://github.com/stevecastaneda/paseo-plugins/tree/main/history#readme", "license": "MIT", "author": "Steve Castaneda", "repository": { @@ -9,17 +16,6 @@ "url": "git+https://github.com/stevecastaneda/paseo-plugins.git", "directory": "history" }, - "homepage": "https://github.com/stevecastaneda/paseo-plugins/tree/main/history#readme", - "keywords": [ - "paseo", - "paseo-plugin", - "history", - "transcript" - ], - "type": "module", - "engines": { - "node": "^22.18.0 || >=23.6.0" - }, "files": [ "paseo-plugin.json", "OVERVIEW.md", @@ -33,6 +29,7 @@ "tsconfig.json", "!**/*.test.ts" ], + "type": "module", "publishConfig": { "access": "public" }, @@ -53,5 +50,8 @@ "react-test-renderer": "19.1.0", "typescript": "^5.9.3", "zod": "^4.4.3" + }, + "engines": { + "node": "^22.18.0 || >=23.6.0" } } diff --git a/history/paseo-plugin.json b/history/paseo-plugin.json index 07164165..ebee855c 100644 --- a/history/paseo-plugin.json +++ b/history/paseo-plugin.json @@ -1,11 +1,7 @@ { "id": "history", "icon": "icon.png", - "media": [ - "images/1-conversation.png", - "images/2-tags.png", - "images/3-source.png" - ], + "media": ["images/1-conversation.png", "images/2-tags.png", "images/3-source.png"], "requirements": { "paseo": ">=0.13.0" } diff --git a/history/server/files.test.ts b/history/server/files.test.ts index 7837126b..22ea2d65 100644 --- a/history/server/files.test.ts +++ b/history/server/files.test.ts @@ -13,7 +13,8 @@ async function fixture(t: { after(fn: () => Promise): void }) { test("finds the exact Codex session including archived logs, ignoring newer unrelated files", async (t) => { const dir = await fixture(t); - const archive = join(dir, "archived_sessions"); await mkdir(archive); + const archive = join(dir, "archived_sessions"); + await mkdir(archive); const path = join(archive, "rollout-2026-09-13-session-123.jsonl"); await writeFile(path, "correct"); await writeFile(join(archive, "rollout-2026-09-14-other-session.jsonl"), "wrong"); @@ -23,37 +24,45 @@ test("finds the exact Codex session including archived logs, ignoring newer unre test("finds Claude log in encoded project directories and rejects ambiguity", async (t) => { const dir = await fixture(t); - await mkdir(join(dir, "project-one")); await mkdir(join(dir, "project-two")); - const path = join(dir, "project-one", "session-123.jsonl"); await writeFile(path, "{}"); + await mkdir(join(dir, "project-one")); + await mkdir(join(dir, "project-two")); + const path = join(dir, "project-one", "session-123.jsonl"); + await writeFile(path, "{}"); assert.equal(await findLog([dir], "session-123", "claude"), path); await writeFile(join(dir, "project-two", "session-123.jsonl"), "{}"); await assert.rejects(findLog([dir], "session-123", "claude"), /Multiple logs/); }); test("does not follow symlinks or substitute a different session", async (t) => { - const dir = await fixture(t); const other = await fixture(t); + const dir = await fixture(t); + const other = await fixture(t); await writeFile(join(other, "session-123.jsonl"), "private"); await symlink(other, join(dir, "project")); await assert.rejects(findLog([dir], "session-123", "claude"), /No raw log/); }); test("reconstructs exact UTF-8 content without splitting JSONL records", async (t) => { - const dir = await fixture(t); const path = join(dir, "log.jsonl"); - const original = JSON.stringify({ message: "x".repeat(PAGE_BYTES - 1) + "🐟" }) + "\r\n" - + JSON.stringify({ message: "é中".repeat(PAGE_BYTES) }) + "\n"; + const dir = await fixture(t); + const path = join(dir, "log.jsonl"); + const original = JSON.stringify({ message: "x".repeat(PAGE_BYTES - 1) + "🐟" }) + "\r\n" + JSON.stringify({ message: "é中".repeat(PAGE_BYTES) }) + "\n"; await writeFile(path, original); - let offset = 0; let restored = ""; let source: string | undefined; + let offset = 0; + let restored = ""; + let source: string | undefined; do { const page = await readPage(path, offset, source); for (const line of page.text.trim().split("\n")) assert.doesNotThrow(() => JSON.parse(line)); assert.ok(page.nextOffset > offset); - restored += page.text; offset = page.nextOffset; source = page.source; + restored += page.text; + offset = page.nextOffset; + source = page.source; } while (offset < Buffer.byteLength(original)); assert.equal(restored, original); }); test("limits oversized records and preserves incomplete final lines", async (t) => { - const dir = await fixture(t); const path = join(dir, "log.jsonl"); + const dir = await fixture(t); + const path = join(dir, "log.jsonl"); await writeFile(path, '{"partial":'); assert.equal((await readPage(path, 0)).text, '{"partial":'); await writeFile(path, "x".repeat(4 * 1024 * 1024)); @@ -61,15 +70,20 @@ test("limits oversized records and preserves incomplete final lines", async (t) }); test("supports append and empty logs; detects shortening and source replacement", async (t) => { - const dir = await fixture(t); const path = join(dir, "log.jsonl"); - await writeFile(path, ""); const empty = await readPage(path, 0); - assert.equal(empty.text, ""); assert.equal(empty.nextOffset, 0); + const dir = await fixture(t); + const path = join(dir, "log.jsonl"); + await writeFile(path, ""); + const empty = await readPage(path, 0); + assert.equal(empty.text, ""); + assert.equal(empty.nextOffset, 0); await appendFile(path, "hello\n"); - const page = await readPage(path, 0, empty.source); assert.equal(page.text, "hello\n"); + const page = await readPage(path, 0, empty.source); + assert.equal(page.text, "hello\n"); await appendFile(path, "world\n"); assert.equal((await readPage(path, page.nextOffset, page.source)).text, "world\n"); await writeFile(path, ""); await assert.rejects(readPage(path, page.nextOffset, page.source), /shortened/); - await rename(path, join(dir, "old")); await writeFile(path, "new"); + await rename(path, join(dir, "old")); + await writeFile(path, "new"); await assert.rejects(readPage(path, 0, page.source), /source changed/); }); diff --git a/history/server/files.ts b/history/server/files.ts index 3c1625e3..ae55c707 100644 --- a/history/server/files.ts +++ b/history/server/files.ts @@ -14,8 +14,9 @@ export async function findLog(roots: string[], sessionId: string, provider: stri async function walk(directory: string, depth: number): Promise { if (depth > 8) return; let entries; - try { entries = await readdir(directory, { withFileTypes: true }); } - catch (error) { + try { + entries = await readdir(directory, { withFileTypes: true }); + } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; } @@ -23,9 +24,10 @@ export async function findLog(roots: string[], sessionId: string, provider: stri if (++visited > 100_000) throw new Error("The session directory is too large to search."); const path = join(directory, entry.name); if (entry.isDirectory()) await walk(path, depth + 1); - else if (entry.isFile() && (provider === "claude" - ? entry.name === `${sessionId}.jsonl` - : entry.name.startsWith("rollout-") && entry.name.endsWith(`-${sessionId}.jsonl`))) { + else if ( + entry.isFile() && + (provider === "claude" ? entry.name === `${sessionId}.jsonl` : entry.name.startsWith("rollout-") && entry.name.endsWith(`-${sessionId}.jsonl`)) + ) { matches.push(path); } } @@ -53,16 +55,24 @@ export async function readPage(path: string, offset: number, expectedSource?: st const { bytesRead } = await file.read(chunk, 0, chunk.length, offset + buffer.length); if (!bytesRead) break; buffer = Buffer.concat([buffer, chunk.subarray(0, bytesRead)]); - const newline = buffer.length <= PAGE_BYTES - ? buffer.lastIndexOf(10) - : buffer.indexOf(10); - if (newline >= 0) { end = newline + 1; break; } + const newline = buffer.length <= PAGE_BYTES ? buffer.lastIndexOf(10) : buffer.indexOf(10); + if (newline >= 0) { + end = newline + 1; + break; + } if (buffer.length >= MAX_ENTRY_BYTES) throw new Error("This entry exceeds 4 MiB. Open the source file in an editor to inspect it."); } if (!end) end = buffer.length; return { - path, source, text: buffer.subarray(0, end).toString("utf8"), offset, - nextOffset: offset + end, totalBytes: stat.size, modifiedAt: stat.mtime.toISOString(), + path, + source, + text: buffer.subarray(0, end).toString("utf8"), + offset, + nextOffset: offset + end, + totalBytes: stat.size, + modifiedAt: stat.mtime.toISOString(), }; - } finally { await file.close(); } + } finally { + await file.close(); + } } diff --git a/history/server/history.test.ts b/history/server/history.test.ts index 59f9ee32..dc6d0d77 100644 --- a/history/server/history.test.ts +++ b/history/server/history.test.ts @@ -40,9 +40,12 @@ test("reads a derived Claude provider's log from the config dir in its env", asy await mkdir(join(dir, "projects", "project"), { recursive: true }); const path = join(dir, "projects", "project", "session-123.jsonl"); await writeFile(path, "{}\n"); - const result = await handleReadHistory({ agentId: "agent", offset: 0 }, context("claude-my", { - "claude-my": { extends: "claude", label: "Claude My", env: { CLAUDE_CONFIG_DIR: dir } }, - })); + const result = await handleReadHistory( + { agentId: "agent", offset: 0 }, + context("claude-my", { + "claude-my": { extends: "claude", label: "Claude My", env: { CLAUDE_CONFIG_DIR: dir } }, + }), + ); assert.equal(result.path, path); assert.equal(result.provider, "claude"); }); @@ -53,9 +56,12 @@ test("reads a derived Codex provider's log from the CODEX_HOME in its env", asyn await mkdir(join(dir, "sessions", "2026"), { recursive: true }); const path = join(dir, "sessions", "2026", "rollout-2026-10-11-session-123.jsonl"); await writeFile(path, "{}\n"); - const result = await handleReadHistory({ agentId: "agent", offset: 0 }, context("codex-full-access", { - "codex-full-access": { extends: "codex", label: "Codex Full Access", env: { CODEX_HOME: dir } }, - })); + const result = await handleReadHistory( + { agentId: "agent", offset: 0 }, + context("codex-full-access", { + "codex-full-access": { extends: "codex", label: "Codex Full Access", env: { CODEX_HOME: dir } }, + }), + ); assert.equal(result.path, path); assert.equal(result.provider, "codex"); }); @@ -65,9 +71,12 @@ test("a derived provider without its own config dir falls back to the daemon env await mkdir(join(dir, "projects", "project"), { recursive: true }); const path = join(dir, "projects", "project", "session-123.jsonl"); await writeFile(path, "{}\n"); - const result = await handleReadHistory({ agentId: "agent", offset: 0 }, context("claude-work", { - "claude-work": { extends: "claude", label: "Claude Work" }, - })); + const result = await handleReadHistory( + { agentId: "agent", offset: 0 }, + context("claude-work", { + "claude-work": { extends: "claude", label: "Claude Work" }, + }), + ); assert.equal(result.path, path); }); @@ -77,17 +86,23 @@ test("the built-in Claude provider honours a config dir set on its own entry", a await mkdir(join(dir, "projects", "project"), { recursive: true }); const path = join(dir, "projects", "project", "session-123.jsonl"); await writeFile(path, "{}\n"); - const result = await handleReadHistory({ agentId: "agent", offset: 0 }, context("claude", { - claude: { env: { CLAUDE_CONFIG_DIR: dir } }, - })); + const result = await handleReadHistory( + { agentId: "agent", offset: 0 }, + context("claude", { + claude: { env: { CLAUDE_CONFIG_DIR: dir } }, + }), + ); assert.equal(result.path, path); }); test("still rejects providers that extend an unsupported harness", async () => { await assert.rejects( - handleReadHistory({ agentId: "agent", offset: 0 }, context("my-copilot", { - "my-copilot": { extends: "copilot", label: "My Copilot" }, - })), + handleReadHistory( + { agentId: "agent", offset: 0 }, + context("my-copilot", { + "my-copilot": { extends: "copilot", label: "My Copilot" }, + }), + ), /Raw history is not supported for my-copilot yet/, ); }); diff --git a/history/server/history.ts b/history/server/history.ts index 3fe98daa..5aa615c8 100644 --- a/history/server/history.ts +++ b/history/server/history.ts @@ -6,10 +6,7 @@ import { readOpenCodeHistory } from "./opencode.ts"; type ProviderEntry = { extends?: string; env?: Record }; -export async function handleReadHistory( - input: { agentId: string; offset: number; source?: string }, - { paseo }: PluginHandlerContext, -) { +export async function handleReadHistory(input: { agentId: string; offset: number; source?: string }, { paseo }: PluginHandlerContext) { const handle = paseo.agents.ref(input.agentId); await handle.refresh(); const agent = handle.current(); @@ -26,13 +23,9 @@ export async function handleReadHistory( const env = { ...process.env, ...entry?.env }; const sessionId = agent.persistence?.nativeHandle ?? agent.persistence?.sessionId ?? agent.runtimeInfo?.sessionId; if (!sessionId) throw new Error("This chat has no saved session yet. Send a message, then refresh."); - if (provider === "opencode") return { ...await readOpenCodeHistory(sessionId, input.offset, input.source, env), provider }; - const root = provider === "codex" - ? env.CODEX_HOME ?? join(homedir(), ".codex") - : env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"); - const roots = provider === "codex" - ? [join(root, "sessions"), join(root, "archived_sessions")] - : [join(root, "projects")]; + if (provider === "opencode") return { ...(await readOpenCodeHistory(sessionId, input.offset, input.source, env)), provider }; + const root = provider === "codex" ? (env.CODEX_HOME ?? join(homedir(), ".codex")) : (env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude")); + const roots = provider === "codex" ? [join(root, "sessions"), join(root, "archived_sessions")] : [join(root, "projects")]; const path = await findLog(roots, sessionId, provider); - return { ...await readPage(path, input.offset, input.source), provider }; + return { ...(await readPage(path, input.offset, input.source)), provider }; } diff --git a/history/server/opencode.test.ts b/history/server/opencode.test.ts index 4365ba8b..91612866 100644 --- a/history/server/opencode.test.ts +++ b/history/server/opencode.test.ts @@ -16,7 +16,14 @@ test("paginates exports on whole records with byte-correct Unicode offsets", () assert.ok(first.nextOffset < first.totalBytes); const second = pageOpenCodeExport(json, sessionId, first.nextOffset, first.source); assert.equal(second.nextOffset, second.totalBytes); - assert.deepEqual((first.text + second.text).trim().split("\n").map(JSON.parse as (text: string) => unknown).slice(1), messages); + assert.deepEqual( + (first.text + second.text) + .trim() + .split("\n") + .map(JSON.parse as (text: string) => unknown) + .slice(1), + messages, + ); assert.equal(first.modifiedAt, new Date(1).toISOString()); assert.equal(pageOpenCodeExport(json, sessionId, second.nextOffset, second.source).text, ""); }); diff --git a/history/server/opencode.ts b/history/server/opencode.ts index afb1f37c..1d3df0fe 100644 --- a/history/server/opencode.ts +++ b/history/server/opencode.ts @@ -13,23 +13,31 @@ export async function readOpenCodeHistory(sessionId: string, offset: number, sou let stdout: string; try { ({ stdout } = await exec("opencode", ["export", sessionId, "--pure"], { - encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024, env, cwd: homedir(), + encoding: "utf8", + timeout: 30_000, + maxBuffer: 64 * 1024 * 1024, + env, + cwd: homedir(), })); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") { throw new Error("OpenCode is not available on the Paseo daemon PATH. Install OpenCode to read this history."); } - throw new Error("Could not export this OpenCode session. Check that it is saved and that the daemon's OpenCode supports export --pure. Exports are limited to 64 MiB and 30 seconds."); + throw new Error( + "Could not export this OpenCode session. Check that it is saved and that the daemon's OpenCode supports export --pure. Exports are limited to 64 MiB and 30 seconds.", + ); } return pageOpenCodeExport(stdout, sessionId, offset, source); } export function pageOpenCodeExport(json: string, sessionId: string, offset: number, expectedSource?: string) { let data; - try { data = JSON.parse(json); } - catch { throw new Error("OpenCode returned an invalid session export. Check that the session is saved and try Refresh."); } - if (data?.info?.id !== sessionId || !Array.isArray(data.messages) - || data.messages.some((message: any) => !message?.info || !Array.isArray(message.parts))) { + try { + data = JSON.parse(json); + } catch { + throw new Error("OpenCode returned an invalid session export. Check that the session is saved and try Refresh."); + } + if (data?.info?.id !== sessionId || !Array.isArray(data.messages) || data.messages.some((message: any) => !message?.info || !Array.isArray(message.parts))) { throw new Error("OpenCode returned an invalid session export."); } // Keep each exported message intact, including unknown parts and metadata. @@ -42,8 +50,8 @@ export function pageOpenCodeExport(json: string, sessionId: string, offset: numb // OpenCode updates messages in place. Byte offsets are valid only for the same // export; reject changes rather than skipping or duplicating message content. if (expectedSource && source !== expectedSource) throw new Error("The OpenCode history changed. Refresh to start again."); - if (!Number.isSafeInteger(offset) || offset < 0 || offset > buffer.length - || (offset > 0 && buffer[offset - 1] !== 10)) throw new Error("Invalid OpenCode history offset. Refresh to start again."); + if (!Number.isSafeInteger(offset) || offset < 0 || offset > buffer.length || (offset > 0 && buffer[offset - 1] !== 10)) + throw new Error("Invalid OpenCode history offset. Refresh to start again."); let end = offset; while (end < buffer.length) { end = buffer.indexOf(10, end) + 1; @@ -51,8 +59,12 @@ export function pageOpenCodeExport(json: string, sessionId: string, offset: numb } const updated = data.info.time?.updated; return { - path: `opencode export ${sessionId}`, source, text: buffer.subarray(offset, end).toString("utf8"), - offset, nextOffset: end, totalBytes: buffer.length, + path: `opencode export ${sessionId}`, + source, + text: buffer.subarray(offset, end).toString("utf8"), + offset, + nextOffset: end, + totalBytes: buffer.length, modifiedAt: typeof updated === "number" && Number.isFinite(new Date(updated).getTime()) ? new Date(updated).toISOString() : "", }; } diff --git a/history/shared/citations.test.ts b/history/shared/citations.test.ts index acd36e1b..ceaf6e0c 100644 --- a/history/shared/citations.test.ts +++ b/history/shared/citations.test.ts @@ -3,7 +3,8 @@ import assert from "node:assert/strict"; import { hideCitations } from "./citations.ts"; test("drops memory citations and keeps the message around them", () => { - const source = "**Found it.**\n\n\n\nMEMORY.md:23-27\n\n\n\nHere is the fix: MEMORY.md:4done."; + const source = + "**Found it.**\n\n\n\nMEMORY.md:23-27\n\n\n\nHere is the fix: MEMORY.md:4done."; assert.equal(hideCitations(source), "**Found it.**\n\nHere is the fix: done."); }); diff --git a/history/shared/citations.ts b/history/shared/citations.ts index e96432ae..8474ed64 100644 --- a/history/shared/citations.ts +++ b/history/shared/citations.ts @@ -25,5 +25,5 @@ export function hideCitations(source: string): string { } function strip(prose: string): string { - return prose.replace(INLINE, (match, ticks) => ticks ? match : "").replace(/(\r?\n){3,}/g, "$1$1"); + return prose.replace(INLINE, (match, ticks) => (ticks ? match : "")).replace(/(\r?\n){3,}/g, "$1$1"); } diff --git a/history/shared/entries.test.ts b/history/shared/entries.test.ts index 34e778c8..d453aade 100644 --- a/history/shared/entries.test.ts +++ b/history/shared/entries.test.ts @@ -6,23 +6,38 @@ const lines = (...entries: unknown[]) => entries.map((entry) => JSON.stringify(e test("OpenCode exports preserve raw records and group messages, tools, and reasoning", () => { const entry = (role: string, parts: unknown[]) => ({ info: { id: "msg_one", role, time: { created: 1 } }, parts }); - const user = entry("user", [{ type: "text", text: "Hello" }, { type: "file", filename: "photo.png" }]); - const entries = parseEntries(lines( - { info: { id: "ses_test", title: "Example" } }, user, - entry("assistant", [{ type: "reasoning", text: "Thinking" }]), - entry("assistant", [{ type: "tool", tool: "bash", state: { input: { command: "pwd" }, output: "/tmp" } }]), - entry("assistant", [{ type: "text", text: "**Done**" }, { type: "reasoning", text: "Internal" }]), - entry("assistant", [{ type: "step-finish", cost: 0 }]), - entry("user", [{ type: "text", text: "Next" }]), - )); - assert.deepEqual(entries.map((entry) => entry.category), ["context", "message", "reasoning", "tools", "message", "events", "message"]); + const user = entry("user", [ + { type: "text", text: "Hello" }, + { type: "file", filename: "photo.png" }, + ]); + const entries = parseEntries( + lines( + { info: { id: "ses_test", title: "Example" } }, + user, + entry("assistant", [{ type: "reasoning", text: "Thinking" }]), + entry("assistant", [{ type: "tool", tool: "bash", state: { input: { command: "pwd" }, output: "/tmp" } }]), + entry("assistant", [ + { type: "text", text: "**Done**" }, + { type: "reasoning", text: "Internal" }, + ]), + entry("assistant", [{ type: "step-finish", cost: 0 }]), + entry("user", [{ type: "text", text: "Next" }]), + ), + ); + assert.deepEqual( + entries.map((entry) => entry.category), + ["context", "message", "reasoning", "tools", "message", "events", "message"], + ); assert.equal(entries[1]!.raw, JSON.stringify(user)); assert.equal(entries[1]!.preview, "Hello\n\n[File: photo.png]"); assert.equal(entries[1]!.timestamp, new Date(1).toISOString()); assert.match(entries[3]!.preview, /bash[\s\S]*command[\s\S]*\/tmp/); assert.equal(entries[4]!.preview, "**Done**"); assert.equal(entries[4]!.hasReasoning, true); - assert.deepEqual(groupTurns(entries).map((turn) => turn.title), ["Session details", "Turn 1", "Turn 2"]); + assert.deepEqual( + groupTurns(entries).map((turn) => turn.title), + ["Session details", "Turn 1", "Turn 2"], + ); }); test("groups Codex turns, keeping mirrored events out of readable messages", () => { @@ -36,27 +51,44 @@ test("groups Codex turns, keeping mirrored events out of readable messages", () { type: "event_msg", payload: { type: "task_started", turn_id: "two" } }, ); const turns = groupTurns(parseEntries(text)); - assert.deepEqual(turns.map((turn) => turn.title), ["Session details", "Turn 1", "Turn 2"]); - assert.deepEqual(turns[1]!.entries.filter((entry) => entry.category === "message").map((entry) => entry.preview), ["Hello", "Hi"]); + assert.deepEqual( + turns.map((turn) => turn.title), + ["Session details", "Turn 1", "Turn 2"], + ); + assert.deepEqual( + turns[1]!.entries.filter((entry) => entry.category === "message").map((entry) => entry.preview), + ["Hello", "Hi"], + ); assert.equal(turns[1]!.entries.filter((entry) => entry.category === "tools").length, 1); assert.equal(turns[1]!.entries[1]!.raw, text.split("\n")[2]); }); test("Claude tool results do not start a new turn or render as user messages", () => { - const turns = groupTurns(parseEntries(lines( - { type: "user", message: { role: "user", content: "Hello" } }, - { type: "assistant", message: { role: "assistant", content: [{ type: "tool_use", name: "Read", input: {} }] } }, - { type: "user", message: { role: "user", content: [{ type: "tool_result", content: "result" }] } }, - { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: "Done" }] } }, - { type: "user", message: { role: "user", content: "Next" } }, - ))); + const turns = groupTurns( + parseEntries( + lines( + { type: "user", message: { role: "user", content: "Hello" } }, + { type: "assistant", message: { role: "assistant", content: [{ type: "tool_use", name: "Read", input: {} }] } }, + { type: "user", message: { role: "user", content: [{ type: "tool_result", content: "result" }] } }, + { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: "Done" }] } }, + { type: "user", message: { role: "user", content: "Next" } }, + ), + ), + ); assert.equal(turns.length, 2); - assert.deepEqual(turns[0]!.entries.filter((entry) => entry.category === "message").map((entry) => entry.preview), ["Hello", "Done"]); + assert.deepEqual( + turns[0]!.entries.filter((entry) => entry.category === "message").map((entry) => entry.preview), + ["Hello", "Done"], + ); }); test("Claude Code request records stay out of the conversation", () => { const blob = (role: string, content: unknown[], extra = {}) => ({ - type: "api-request-blob", sessionId: "11111111-2222-3333-4444-555555555555", hash: "a".repeat(64), message: { role, content }, ...extra, + type: "api-request-blob", + sessionId: "11111111-2222-3333-4444-555555555555", + hash: "a".repeat(64), + message: { role, content }, + ...extra, }); const blobs = [ blob("user", [ @@ -65,7 +97,13 @@ test("Claude Code request records stay out of the conversation", () => { ]), blob("system", [ { type: "text", text: "You are Claude Code." }, - { type: "tool_addition", tool: { type: "tool_definition", definition: { name: "Read", description: "Read a file.", input_schema: { type: "object", properties: { file_path: { type: "string" } } } } } }, + { + type: "tool_addition", + tool: { + type: "tool_definition", + definition: { name: "Read", description: "Read a file.", input_schema: { type: "object", properties: { file_path: { type: "string" } } } }, + }, + }, ]), blob("assistant", [ { type: "thinking", thinking: "I should list them.", signature: "sig" }, @@ -76,18 +114,26 @@ test("Claude Code request records stay out of the conversation", () => { ]; const text = lines( { type: "user", message: { role: "user", content: "List the files" } }, - blobs[0], blobs[1], + blobs[0], + blobs[1], { type: "assistant", message: { role: "assistant", content: [{ type: "tool_use", id: "toolu_01abc", name: "Bash", input: { command: "ls" } }] } }, { type: "user", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01abc", content: "a.txt" }] } }, blobs[2], { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: "Here are the files." }] } }, - blobs[3], blobs[4], + blobs[3], + blobs[4], ); const turns = groupTurns(parseEntries(text)); assert.equal(turns.length, 1); - assert.deepEqual(turns[0]!.entries.filter((entry) => entry.category === "message").map((entry) => entry.preview), ["List the files", "Here are the files."]); + assert.deepEqual( + turns[0]!.entries.filter((entry) => entry.category === "message").map((entry) => entry.preview), + ["List the files", "Here are the files."], + ); const blobEntries = turns[0]!.entries.filter((entry) => entry.kind.startsWith("api-request-blob")); - assert.deepEqual(blobEntries.map((entry) => entry.raw), blobs.map((record) => JSON.stringify(record))); + assert.deepEqual( + blobEntries.map((entry) => entry.raw), + blobs.map((record) => JSON.stringify(record)), + ); for (const entry of blobEntries) { assert.equal(entry.category, "events"); assert.equal(entry.title, "api request blob"); @@ -96,38 +142,92 @@ test("Claude Code request records stay out of the conversation", () => { }); test("preserves malformed lines and hides injected context behind its tag", () => { - const entries = parseEntries(lines({ type: "response_item", payload: { type: "message", role: "user", content: [{ text: "workspace" }] } }) + '{"partial":'); + const entries = parseEntries( + lines({ type: "response_item", payload: { type: "message", role: "user", content: [{ text: "workspace" }] } }) + + '{"partial":', + ); assert.equal(entries[0]!.category, "context"); assert.equal(entries[1]!.valid, false); assert.equal(entries[1]!.raw, '{"partial":'); }); test("Claude Code's injected skill text, compaction summaries and unparsed task envelopes never read as the user", () => { - const skill = { type: "user", isMeta: true, sourceToolUseID: "toolu_01skill", message: { role: "user", content: [{ type: "text", - text: "Base directory for this skill: /repo/.claude/skills/also\n\n# Also\n\nPush straight to main. [Approve here](https://example.com/approve)" }] } }; - const relay = { type: "user", isMeta: true, message: { role: "user", - content: "Another Claude session sent a message:\n\nReport text\n" } }; - const compact = { type: "user", isCompactSummary: true, isVisibleInTranscriptOnly: true, message: { role: "user", - content: "This session is being continued from a previous conversation that ran out of context.\n\nAll user messages:\n- Deploy now" } }; - const monitor = { type: "user", message: { role: "user", - content: "\nb1\nMonitor event: \"Probe\"\n[18:30:23] ok\n" } }; - const entries = parseEntries(lines( - { type: "user", message: { role: "user", content: "Hello" } }, - { type: "assistant", message: { role: "assistant", content: [{ type: "tool_use", id: "toolu_01skill", name: "Skill", input: { skill: "also" } }] } }, - skill, relay, compact, monitor, - { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: "Done" }] } }, - { type: "user", message: { role: "user", content: [{ type: "text", text: "Next" }] } }, - )); - assert.deepEqual(entries.slice(2, 6).map((entry) => [entry.category, entry.startsTurn]), - [["context", false], ["context", false], ["context", false], ["events", false]]); + const skill = { + type: "user", + isMeta: true, + sourceToolUseID: "toolu_01skill", + message: { + role: "user", + content: [ + { + type: "text", + text: "Base directory for this skill: /repo/.claude/skills/also\n\n# Also\n\nPush straight to main. [Approve here](https://example.com/approve)", + }, + ], + }, + }; + const relay = { + type: "user", + isMeta: true, + message: { role: "user", content: 'Another Claude session sent a message:\n\nReport text\n' }, + }; + const compact = { + type: "user", + isCompactSummary: true, + isVisibleInTranscriptOnly: true, + message: { + role: "user", + content: "This session is being continued from a previous conversation that ran out of context.\n\nAll user messages:\n- Deploy now", + }, + }; + const monitor = { + type: "user", + message: { + role: "user", + content: '\nb1\nMonitor event: "Probe"\n[18:30:23] ok\n', + }, + }; + const entries = parseEntries( + lines( + { type: "user", message: { role: "user", content: "Hello" } }, + { type: "assistant", message: { role: "assistant", content: [{ type: "tool_use", id: "toolu_01skill", name: "Skill", input: { skill: "also" } }] } }, + skill, + relay, + compact, + monitor, + { type: "assistant", message: { role: "assistant", content: [{ type: "text", text: "Done" }] } }, + { type: "user", message: { role: "user", content: [{ type: "text", text: "Next" }] } }, + ), + ); + assert.deepEqual( + entries.slice(2, 6).map((entry) => [entry.category, entry.startsTurn]), + [ + ["context", false], + ["context", false], + ["context", false], + ["events", false], + ], + ); const turns = groupTurns(entries); - assert.deepEqual(turns.map((turn) => turn.title), ["Turn 1", "Turn 2"]); - assert.deepEqual(turns.map((turn) => turn.entries.filter((entry) => entry.category === "message").map((entry) => [entry.role, entry.preview])), - [[["user", "Hello"], ["assistant", "Done"]], [["user", "Next"]]]); + assert.deepEqual( + turns.map((turn) => turn.title), + ["Turn 1", "Turn 2"], + ); + assert.deepEqual( + turns.map((turn) => turn.entries.filter((entry) => entry.category === "message").map((entry) => [entry.role, entry.preview])), + [ + [ + ["user", "Hello"], + ["assistant", "Done"], + ], + [["user", "Next"]], + ], + ); }); test("an assistant reply shaped like a task notification stays a plain assistant message", () => { - const reply = "t1completedAgent \"Review\" finishedSafe to merge."; + const reply = + 't1completedAgent "Review" finishedSafe to merge.'; const [entry] = parseEntries(lines({ type: "assistant", message: { role: "assistant", content: [{ type: "text", text: reply }] } })); assert.equal(entry!.category, "message"); assert.equal(entry!.role, "assistant"); diff --git a/history/shared/entries.ts b/history/shared/entries.ts index 14f4d5dd..86a14533 100644 --- a/history/shared/entries.ts +++ b/history/shared/entries.ts @@ -2,9 +2,11 @@ import { parseTaskNotification, type TaskNotification } from "./task-notificatio type RecordValue = Record; function record(value: unknown): RecordValue { - return value && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {}; + return value && typeof value === "object" && !Array.isArray(value) ? (value as RecordValue) : {}; +} +function string(value: unknown): string { + return typeof value === "string" ? value : ""; } -function string(value: unknown): string { return typeof value === "string" ? value : ""; } export interface HistoryEntry { raw: string; @@ -24,102 +26,178 @@ export interface HistoryEntry { function contentText(value: unknown): string { if (typeof value === "string") return value; if (!Array.isArray(value)) return ""; - return value.map((item) => { - const block = record(item); - return string(block.text) || string(block.thinking) || string(block.content) - || (block.type === "tool_use" ? `${string(block.name)}\n${JSON.stringify(block.input, null, 2)}` : "") - || (block.type === "tool_result" ? contentText(block.content) : "") - || (string(block.type).includes("image") ? "[Image]" : ""); - }).filter(Boolean).join("\n\n"); + return value + .map((item) => { + const block = record(item); + return ( + string(block.text) || + string(block.thinking) || + string(block.content) || + (block.type === "tool_use" ? `${string(block.name)}\n${JSON.stringify(block.input, null, 2)}` : "") || + (block.type === "tool_result" ? contentText(block.content) : "") || + (string(block.type).includes("image") ? "[Image]" : "") + ); + }) + .filter(Boolean) + .join("\n\n"); } export function parseEntries(text: string): HistoryEntry[] { - return text.split("\n").filter((line) => line.trim()).map((raw) => { - try { - const parsed: unknown = JSON.parse(raw); - const data = record(parsed); - if (string(record(data.info).id).startsWith("ses_") || (data.info && Array.isArray(data.parts))) { - return parseOpenCodeEntry(data, raw); + return text + .split("\n") + .filter((line) => line.trim()) + .map((raw) => { + try { + const parsed: unknown = JSON.parse(raw); + const data = record(parsed); + if (string(record(data.info).id).startsWith("ses_") || (data.info && Array.isArray(data.parts))) { + return parseOpenCodeEntry(data, raw); + } + const payload = record(data.payload); + const kind = string(data.type) || "object"; + const chat = kind === "user" || kind === "assistant"; + const message = chat ? record(data.message) : {}; + const body = Object.keys(payload).length ? payload : Object.keys(message).length ? message : data; + const subtype = string(body.type); + const role = string(body.role) || (chat ? kind : ""); + const title = role ? `${role[0]!.toUpperCase()}${role.slice(1)}` : (subtype || kind).replace(/[_-]/g, " "); + const preview = + contentText(body.content) || + string(body.message) || + string(body.text) || + string(body.output) || + string(body.arguments) || + string(body.summary) || + string(body.cwd) || + string(data.summary) || + JSON.stringify(parsed); + const blocks = Array.isArray(body.content) ? body.content.map(record) : []; + const tool = /(?:function|custom_tool)_call/.test(subtype) || blocks.some((block) => block.type === "tool_use" || block.type === "tool_result"); + const reasoning = subtype === "reasoning" || blocks.some((block) => block.type === "thinking"); + const messageText = + typeof body.content === "string" + ? body.content + : blocks + .filter((block) => ["text", "input_text", "output_text"].includes(string(block.type))) + .map((block) => string(block.text)) + .join("\n\n"); + const conversation = role === "user" || role === "assistant"; + // Claude Code delivers harness task envelopes as user entries, never as assistant text. + const envelope = role === "user" && /^\s*/.test(messageText); + const parsedNotification = envelope ? (parseTaskNotification(messageText) ?? undefined) : undefined; + // First matching rule wins. Claude Code marks text it injects (skill bodies, + // command expansions, compaction summaries) with isMeta or isCompactSummary. + const category = + ( + [ + ["context", role === "developer" || role === "system" || kind === "session_meta" || kind === "turn_context" || kind === "world_state"], + ["context", data.isMeta === true || data.isCompactSummary === true], + ["context", role === "user" && /^(?:# AGENTS\.md||)/.test(preview.trim())], + ["events", envelope && !parsedNotification], + ["message", conversation && Boolean(messageText)], + ["tools", tool], + ["reasoning", reasoning], + ["message", conversation], + ] as const + ).find(([, matches]) => matches)?.[0] ?? "events"; + const displayText = category === "message" ? messageText || preview : preview; + const notification = category === "message" ? parsedNotification : undefined; + // Codex event_msg item_completed/message mirrors are kept as events; only + // canonical response_item messages enter the readable conversation. + return { + raw, + title, + kind: subtype && subtype !== kind ? `${kind} · ${subtype}` : kind, + timestamp: string(data.timestamp) || string(body.timestamp), + preview: displayText, + valid: true, + category, + role, + startsTurn: subtype === "task_started" || (kind === "user" && category === "message" && !tool && !notification), + hasTools: tool, + hasReasoning: reasoning, + notification, + }; + } catch { + return { + raw, + title: "Unparsed entry", + kind: "raw text", + timestamp: "", + preview: "This line is incomplete or is not valid JSON. Its original text is preserved below.", + valid: false, + category: "events", + role: "", + startsTurn: false, + hasTools: false, + hasReasoning: false, + }; } - const payload = record(data.payload); - const kind = string(data.type) || "object"; - const chat = kind === "user" || kind === "assistant"; - const message = chat ? record(data.message) : {}; - const body = Object.keys(payload).length ? payload : Object.keys(message).length ? message : data; - const subtype = string(body.type); - const role = string(body.role) || (chat ? kind : ""); - const title = role ? `${role[0]!.toUpperCase()}${role.slice(1)}` - : (subtype || kind).replace(/[_-]/g, " "); - const preview = contentText(body.content) || string(body.message) || string(body.text) - || string(body.output) || string(body.arguments) || string(body.summary) - || string(body.cwd) || string(data.summary) || JSON.stringify(parsed); - const blocks = Array.isArray(body.content) ? body.content.map(record) : []; - const tool = /(?:function|custom_tool)_call/.test(subtype) || blocks.some((block) => block.type === "tool_use" || block.type === "tool_result"); - const reasoning = subtype === "reasoning" || blocks.some((block) => block.type === "thinking"); - const messageText = typeof body.content === "string" ? body.content : blocks - .filter((block) => ["text", "input_text", "output_text"].includes(string(block.type))) - .map((block) => string(block.text)).join("\n\n"); - const conversation = role === "user" || role === "assistant"; - // Claude Code delivers harness task envelopes as user entries, never as assistant text. - const envelope = role === "user" && /^\s*/.test(messageText); - const parsedNotification = envelope ? parseTaskNotification(messageText) ?? undefined : undefined; - // First matching rule wins. Claude Code marks text it injects (skill bodies, - // command expansions, compaction summaries) with isMeta or isCompactSummary. - const category = ([ - ["context", role === "developer" || role === "system" || kind === "session_meta" || kind === "turn_context" || kind === "world_state"], - ["context", data.isMeta === true || data.isCompactSummary === true], - ["context", role === "user" && /^(?:# AGENTS\.md||)/.test(preview.trim())], - ["events", envelope && !parsedNotification], - ["message", conversation && Boolean(messageText)], - ["tools", tool], - ["reasoning", reasoning], - ["message", conversation], - ] as const).find(([, matches]) => matches)?.[0] ?? "events"; - const displayText = category === "message" ? messageText || preview : preview; - const notification = category === "message" ? parsedNotification : undefined; - // Codex event_msg item_completed/message mirrors are kept as events; only - // canonical response_item messages enter the readable conversation. - return { raw, title, kind: subtype && subtype !== kind ? `${kind} · ${subtype}` : kind, - timestamp: string(data.timestamp) || string(body.timestamp), preview: displayText, valid: true, - category, role, startsTurn: subtype === "task_started" || (kind === "user" && category === "message" && !tool && !notification), - hasTools: tool, hasReasoning: reasoning, notification }; - } catch { - return { raw, title: "Unparsed entry", kind: "raw text", timestamp: "", - preview: "This line is incomplete or is not valid JSON. Its original text is preserved below.", valid: false, - category: "events", role: "", startsTurn: false, hasTools: false, hasReasoning: false }; - } - }); + }); } function parseOpenCodeEntry(data: RecordValue, raw: string): HistoryEntry { const info = record(data.info); const role = string(info.role); const parts = Array.isArray(data.parts) ? data.parts.map(record) : []; - const text = parts.filter((part) => part.type === "text").map((part) => string(part.text)).filter(Boolean).join("\n\n"); + const text = parts + .filter((part) => part.type === "text") + .map((part) => string(part.text)) + .filter(Boolean) + .join("\n\n"); const hasTools = parts.some((part) => part.type === "tool"); const hasReasoning = parts.some((part) => part.type === "reasoning"); - const attachments = parts.filter((part) => part.type === "file").map((part) => `[File: ${string(part.filename) || string(part.mime) || "attachment"}]`).join("\n"); - const category = !role || role === "system" || role === "developer" ? "context" - : text || attachments ? "message" : hasTools ? "tools" : hasReasoning ? "reasoning" : "events"; - const preview = [text, attachments].filter(Boolean).join("\n\n") || parts.map((part) => { - if (part.type === "reasoning") return string(part.text); - if (part.type === "tool") { - const state = record(part.state); - return [string(part.tool), JSON.stringify(state.input, null, 2), string(state.output) || string(state.error)].filter(Boolean).join("\n"); - } - return JSON.stringify(part); - }).join("\n\n") || string(info.title) || JSON.stringify(info); + const attachments = parts + .filter((part) => part.type === "file") + .map((part) => `[File: ${string(part.filename) || string(part.mime) || "attachment"}]`) + .join("\n"); + const category = + !role || role === "system" || role === "developer" + ? "context" + : text || attachments + ? "message" + : hasTools + ? "tools" + : hasReasoning + ? "reasoning" + : "events"; + const preview = + [text, attachments].filter(Boolean).join("\n\n") || + parts + .map((part) => { + if (part.type === "reasoning") return string(part.text); + if (part.type === "tool") { + const state = record(part.state); + return [string(part.tool), JSON.stringify(state.input, null, 2), string(state.output) || string(state.error)].filter(Boolean).join("\n"); + } + return JSON.stringify(part); + }) + .join("\n\n") || + string(info.title) || + JSON.stringify(info); const created = record(info.time).created; const timestamp = typeof created === "number" && Number.isFinite(new Date(created).getTime()) ? new Date(created).toISOString() : ""; - const notification = category === "message" && role === "user" ? parseTaskNotification(preview) ?? undefined : undefined; + const notification = category === "message" && role === "user" ? (parseTaskNotification(preview) ?? undefined) : undefined; return { - raw, title: role ? `${role[0]!.toUpperCase()}${role.slice(1)}` : "Session details", - kind: `opencode · ${role || "session"}`, timestamp, preview, valid: true, - category, role, startsTurn: role === "user" && !notification, hasTools, hasReasoning, notification, + raw, + title: role ? `${role[0]!.toUpperCase()}${role.slice(1)}` : "Session details", + kind: `opencode · ${role || "session"}`, + timestamp, + preview, + valid: true, + category, + role, + startsTurn: role === "user" && !notification, + hasTools, + hasReasoning, + notification, }; } -export interface HistoryTurn { entries: HistoryEntry[]; title: string; } +export interface HistoryTurn { + entries: HistoryEntry[]; + title: string; +} export function groupTurns(entries: HistoryEntry[]): HistoryTurn[] { const turns: HistoryTurn[] = []; diff --git a/history/shared/task-notification.test.ts b/history/shared/task-notification.test.ts index 741609f5..13a07640 100644 --- a/history/shared/task-notification.test.ts +++ b/history/shared/task-notification.test.ts @@ -3,13 +3,14 @@ import assert from "node:assert/strict"; import { parseTaskNotification, notificationUsage } from "./task-notification.ts"; import { parseEntries, groupTurns } from "./entries.ts"; -const envelope = '\nsame-tasktool-1/tmp/task.outputcompletedAgent "Check chart" finishedCan resume.## Results\n\n- **Passed**\n\n```html\n
Example
\n```
8365153391880\n
'; +const envelope = + '\nsame-tasktool-1/tmp/task.outputcompletedAgent "Check chart" finishedCan resume.## Results\n\n- **Passed**\n\n```html\n
Example
\n```
8365153391880\n
'; test("extracts known notification fields while preserving Markdown, HTML examples, and original source", () => { const notification = parseTaskNotification(envelope)!; assert.equal(notification.taskId, "same-task"); assert.equal(notification.outputFile, "/tmp/task.output"); - assert.equal(notification.result, '## Results\n\n- **Passed**\n\n```html\n
Example
\n```'); + assert.equal(notification.result, "## Results\n\n- **Passed**\n\n```html\n
Example
\n```"); assert.equal(notificationUsage(notification), "83,651 tokens · 53 tool uses · 6m 32s"); const raw = JSON.stringify({ type: "user", message: { role: "user", content: envelope } }); const entry = parseEntries(raw)[0]!; @@ -27,16 +28,18 @@ test("notifications stay in the current turn and repeated task IDs are retained" test("quoted examples, incomplete envelopes, duplicate and unknown fields fall back unchanged", () => { for (const text of [ - '```xml\n' + envelope + '\n```', 'An example:\n' + envelope, - envelope.replace('
', ''), - envelope.replace('', 'extra'), - envelope.replace('', 'duplicate'), - '
ordinary HTML
', - ]) assert.equal(parseTaskNotification(text), null); + "```xml\n" + envelope + "\n```", + "An example:\n" + envelope, + envelope.replace("
", ""), + envelope.replace("", "extra"), + envelope.replace("", "duplicate"), + "
ordinary HTML
", + ]) + assert.equal(parseTaskNotification(text), null); }); test("accepts a failure without a result and keeps missing usage distinct from zero", () => { - const minimal = 'xfailedTask stopped'; + const minimal = "xfailedTask stopped"; assert.equal(parseTaskNotification(minimal)!.status, "failed"); assert.equal(notificationUsage(parseTaskNotification(minimal)!), ""); assert.equal(notificationUsage({ ...parseTaskNotification(minimal)!, tokens: 0, durationMs: 0 }), "0 tokens · 0s"); diff --git a/history/shared/task-notification.ts b/history/shared/task-notification.ts index 66cc9374..f834fe8e 100644 --- a/history/shared/task-notification.ts +++ b/history/shared/task-notification.ts @@ -39,9 +39,16 @@ export function parseTaskNotification(source: string): TaskNotification | null { const usage = value.usage === undefined ? {} : fields(value.usage, new Set(["subagent_tokens", "tool_uses", "duration_ms"])); if (!usage) return null; return { - taskId: value["task-id"].trim(), toolUseId: value["tool-use-id"]?.trim(), outputFile: value["output-file"]?.trim(), - status: value.status.trim(), summary: value.summary.trim(), note: value.note?.trim(), result: value.result, - tokens: number(usage.subagent_tokens), toolUses: number(usage.tool_uses), durationMs: number(usage.duration_ms), + taskId: value["task-id"].trim(), + toolUseId: value["tool-use-id"]?.trim(), + outputFile: value["output-file"]?.trim(), + status: value.status.trim(), + summary: value.summary.trim(), + note: value.note?.trim(), + result: value.result, + tokens: number(usage.subagent_tokens), + toolUses: number(usage.tool_uses), + durationMs: number(usage.duration_ms), }; } diff --git a/history/tsconfig.json b/history/tsconfig.json index 06994f75..318fe0ce 100644 --- a/history/tsconfig.json +++ b/history/tsconfig.json @@ -3,9 +3,7 @@ "target": "ES2020", "module": "ESNext", "moduleResolution": "Bundler", - "lib": [ - "ES2023" - ], + "lib": ["ES2023"], "jsx": "react-jsx", "strict": true, "skipLibCheck": true, @@ -14,12 +12,6 @@ "esModuleInterop": true, "allowSyntheticDefaultImports": true }, - "include": [ - "**/*.ts", - "**/*.tsx" - ], - "exclude": [ - "**/*.test.ts", - "node_modules" - ] + "include": ["**/*.ts", "**/*.tsx"], + "exclude": ["**/*.test.ts", "node_modules"] } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..cc84dc74 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,402 @@ +{ + "name": "paseo-plugins-tooling", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "paseo-plugins-tooling", + "devDependencies": { + "oxfmt": "0.77.0" + } + }, + "node_modules/@oxfmt/binding-android-arm-eabi": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.77.0.tgz", + "integrity": "sha512-zmPiuOvkuu0csMx4U3gdMunIFWNcWulzikFMdAPBzLazVAA3LhdHzv9yzgUgAckv/zje5vz4XJcseNQKdSsWMw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-android-arm64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.77.0.tgz", + "integrity": "sha512-shXOIK9sj3bvt4H6K47qFWNKaYBwEhzj97iUwoLGyyRDrXt1OdAAuCiupCinG1i7ETL81knjEKeB+JmhOOfPew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-arm64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.77.0.tgz", + "integrity": "sha512-lrTX0I54buv9CW2leEWchWLdfcrblZ5Rj8uAilKzBEyWif8CTN6zBHdFc12K1b6U2cnlvOFBd1LxdLdqLKX2EA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-x64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.77.0.tgz", + "integrity": "sha512-SD44K3x/Im8EsOtdHxjVmTBi0cafAaunRpCeq+w91tkD2keqYagR8oAvxkJHUK+KPg5NQk7JZqQnzGHnVEBrDw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-freebsd-x64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.77.0.tgz", + "integrity": "sha512-N+gUflsCx3FAVkxi5sxGlL5LwO+7pv5NexHJufBqPyl3BcPv1rXpfwqhL/Vj+XfshfoxMFTBbzrbJgGVaPVkAw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.77.0.tgz", + "integrity": "sha512-DXGwP8818IUZ4cxcfugg9PXqnI6fVCWIqgCgBoUKdl/QhJF4Po+lucJBrnrX/b5BNKwVMc3xSrvbI9rl8+RrBA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-musleabihf": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.77.0.tgz", + "integrity": "sha512-HUiJTgdV10PkCW41nHqVYYlW8Uc+39YBOoluZLfJE2MBPKVTNElhL+vpdSEuVaCGhGkzOGR6XyxM37gu31L1Qw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.77.0.tgz", + "integrity": "sha512-+w3V07y6yy8FdACnGtzgDsG/CHgA0Y/W2/bzZuPYgvBAa23Lap/nmvyNQmCiGKkSaChTPlY7QpIShGGAC7IGEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-musl": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.77.0.tgz", + "integrity": "sha512-FASxWQAuLW4WXFViDa77ybd3Y1lbkBx5DTtL4OGl+pL64/ymtydTFvJM0xz/0vnCirNzPUDAI6TiTBDGsFbEVg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-ppc64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.77.0.tgz", + "integrity": "sha512-WRdlgZahG35zCieq7Po7QU8mBgkFAIdEpgS5p3vVZrHt0FXTbFgzqC7xeBCceh9gpFGgr4VWblULNnU8gdw0DA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.77.0.tgz", + "integrity": "sha512-CVzNO94x/UzQe/INVUu9qt5X1MjLEooqwc/5VcQ88eyLXiEIIsjubpPQgwEMKwfWtAA5hnpFL2GF74zSdCg07Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-musl": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.77.0.tgz", + "integrity": "sha512-NrCcVheqL0kRUi9gptqjkQhxSFayotM+zycC3lSOSrsf5SroZq49u66ShyuZkHCCzKPHB0AT0pL/s+ET9R3qQQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-s390x-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.77.0.tgz", + "integrity": "sha512-LWDQ9T/Bo/kt/q223j9fYLiNTkUYyuMkk7ZrIsIAV7l19MmuKxgd/1tZ8xhoUuVIdsyET7sJrQ6X/vRG6V+bZQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.77.0.tgz", + "integrity": "sha512-5JbOT3ucC/2kROUjyyOW06FjXO8trPjYb+kE7E7cLxmpGAnw0jjeU4Tjg4C8H9JR1MZ2oH4fXE1NqLNZ89ISnw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-musl": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.77.0.tgz", + "integrity": "sha512-/q9p495bmmKtxqWlIrNiJ15hoddgk/jPvJwMW6Nh796UgVRMTCKD7yI+AAL7/7xWlC3+2ls5l1RPywuV4lOdlw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-openharmony-arm64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.77.0.tgz", + "integrity": "sha512-tmN3OEI38xXr48UeAkQMAX1jMHszVHv4I9lzh44DKrMlIFxEU0aBYl3Zs7PzRBuJOLR7h77m6bUlCh0E06MVXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-arm64-msvc": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.77.0.tgz", + "integrity": "sha512-v//nJMk72xRT+/9QB9mJWEPV3/5XncMvxtYQAYbAsv5VcxLlRcbj2n2srQSERglVcTft4jI3MK30ceCoRcDTJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-ia32-msvc": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.77.0.tgz", + "integrity": "sha512-D3SMXWBkVogzAlzd3RfMaFuHOTdPpRDFT+jVbtXszWwck9PCK4hYoRoncjuAjWZuWzRFND3/Mk91qFvJyoJbLA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-x64-msvc": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.77.0.tgz", + "integrity": "sha512-2vyyODjP1Sb830rTVgfFqZoIUYF8uYdGx9S/Usih+Av6gQ9QyxXzwEGXS7poxfsxxQftZW1IbcFlhvQkeDRekQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/oxfmt": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.77.0.tgz", + "integrity": "sha512-3bPDJwLZf4i6dOaQS+6GOI/YUFTHNif7qw4nknbZyzdB0uws57tD8jA/GLGC9J7kjyf6d/eVWm73b43VeMUqGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinypool": "2.2.0" + }, + "bin": { + "oxfmt": "bin/oxfmt" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxfmt/binding-android-arm-eabi": "0.77.0", + "@oxfmt/binding-android-arm64": "0.77.0", + "@oxfmt/binding-darwin-arm64": "0.77.0", + "@oxfmt/binding-darwin-x64": "0.77.0", + "@oxfmt/binding-freebsd-x64": "0.77.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.77.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.77.0", + "@oxfmt/binding-linux-arm64-gnu": "0.77.0", + "@oxfmt/binding-linux-arm64-musl": "0.77.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.77.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.77.0", + "@oxfmt/binding-linux-riscv64-musl": "0.77.0", + "@oxfmt/binding-linux-s390x-gnu": "0.77.0", + "@oxfmt/binding-linux-x64-gnu": "0.77.0", + "@oxfmt/binding-linux-x64-musl": "0.77.0", + "@oxfmt/binding-openharmony-arm64": "0.77.0", + "@oxfmt/binding-win32-arm64-msvc": "0.77.0", + "@oxfmt/binding-win32-ia32-msvc": "0.77.0", + "@oxfmt/binding-win32-x64-msvc": "0.77.0" + }, + "peerDependencies": { + "@astrojs/compiler-rs": "^0.5.0", + "svelte": "^5.0.0", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "@astrojs/compiler-rs": { + "optional": true + }, + "svelte": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, + "node_modules/tinypool": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.0.0 || >=22.0.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..de41288c --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "paseo-plugins-tooling", + "private": true, + "description": "Formatting and lint checks for the whole repo. Each plugin installs and ships on its own.", + "scripts": { + "format": "oxfmt", + "format:check": "oxfmt --check" + }, + "devDependencies": { + "oxfmt": "0.77.0" + } +} diff --git a/playwright-pulse/client/lifecycle.test.ts b/playwright-pulse/client/lifecycle.test.ts index 8af9355a..02cdfa2a 100644 --- a/playwright-pulse/client/lifecycle.test.ts +++ b/playwright-pulse/client/lifecycle.test.ts @@ -11,7 +11,11 @@ const plain = (value: unknown) => JSON.parse(JSON.stringify(value)); test("the pill's title carries the run status, so the phone menu row shows it", async () => { const h = clientHarness(directory); let brief: object = { runId: "r", status: "running", done: 25, total: 47, failed: 0 }; - h.responses["pulse.briefs"] = { get briefs() { return { "/w": brief }; } }; + h.responses["pulse.briefs"] = { + get briefs() { + return { "/w": brief }; + }, + }; const stop = h.load("index.client.tsx").default(h.client); h.workspaces.bootstrap([{ id: "w", workspaceDirectory: "/w", projectRootPath: "/w" }]); await h.flush(); diff --git a/playwright-pulse/client/motion.tsx b/playwright-pulse/client/motion.tsx index cb88891b..282ef260 100644 --- a/playwright-pulse/client/motion.tsx +++ b/playwright-pulse/client/motion.tsx @@ -33,7 +33,13 @@ export function useLastPresent(value: T | null): T | null { } // A button that scales to 0.96 while pressed. `static` turns the scale off. -export function PressScale({ static: isStatic, style, outerStyle, children, ...props }: Omit & { +export function PressScale({ + static: isStatic, + style, + outerStyle, + children, + ...props +}: Omit & { static?: boolean; // Layout for the pressable itself, e.g. alignSelf; `style` is what scales. outerStyle?: StyleProp; @@ -46,14 +52,29 @@ export function PressScale({ static: isStatic, style, outerStyle, children, ...p const [pressed, setPressed] = useState(false); const [hovered, setHovered] = useState(false); return ( - { setHovered(true); props.onHoverIn?.(event); }} - onHoverOut={(event) => { setHovered(false); props.onHoverOut?.(event); }} - onPressIn={(event) => { setPressed(true); if (!isStatic) to(0.96); props.onPressIn?.(event); }} - onPressOut={(event) => { setPressed(false); if (!isStatic) to(1); props.onPressOut?.(event); }}> - - {children} - + { + setHovered(true); + props.onHoverIn?.(event); + }} + onHoverOut={(event) => { + setHovered(false); + props.onHoverOut?.(event); + }} + onPressIn={(event) => { + setPressed(true); + if (!isStatic) to(0.96); + props.onPressIn?.(event); + }} + onPressOut={(event) => { + setPressed(false); + if (!isStatic) to(1); + props.onPressOut?.(event); + }} + > + {children} ); } @@ -129,7 +150,13 @@ export function Presence({ show, order = 0, children }: { show: boolean; order?: return; } const firstLoad = start !== null && Date.now() - start < FIRST_LOAD_MS; - const animation = Animated.timing(enter, { toValue: 1, duration: ENTER_MS, delay: firstLoad ? order * STAGGER_MS : 0, easing: easeOut(), useNativeDriver: nativeDriver() }); + const animation = Animated.timing(enter, { + toValue: 1, + duration: ENTER_MS, + delay: firstLoad ? order * STAGGER_MS : 0, + easing: easeOut(), + useNativeDriver: nativeDriver(), + }); setMoving(true); animation.start(({ finished }) => finished && setMoving(false)); return () => animation.stop(); @@ -165,9 +192,6 @@ export function Presence({ show, order = 0, children }: { show: boolean; order?: function blurStyle(enter: Animated.Value, exit: Animated.Value) { // Blur is 4px at either end of the motion and 0 at rest. - const amount = Animated.add( - enter.interpolate({ inputRange: [0, 1], outputRange: [4, 0] }), - exit.interpolate({ inputRange: [0, 1], outputRange: [0, 4] }), - ); + const amount = Animated.add(enter.interpolate({ inputRange: [0, 1], outputRange: [4, 0] }), exit.interpolate({ inputRange: [0, 1], outputRange: [0, 4] })); return { filter: amount.interpolate({ inputRange: [0, 4], outputRange: ["blur(0px)", "blur(4px)"] }) }; } diff --git a/playwright-pulse/client/panel.tsx b/playwright-pulse/client/panel.tsx index 7b178605..ceb20017 100644 --- a/playwright-pulse/client/panel.tsx +++ b/playwright-pulse/client/panel.tsx @@ -4,7 +4,22 @@ import React, { useEffect, useRef, useState } from "react"; import { ActivityIndicator, Animated, ScrollView, Text, View } from "react-native"; import { openAttachment } from "../shared/rpc"; import type { RunSnapshot } from "../shared/run"; -import { STATUS_TITLE, commandLine, counts, formatAgo, formatClock, formatDuration, formatTimeLeft, isLive, runElapsed, slowest, timeLeft, folderLabel, folders, type Counts } from "../shared/view"; +import { + STATUS_TITLE, + commandLine, + counts, + formatAgo, + formatClock, + formatDuration, + formatTimeLeft, + isLive, + runElapsed, + slowest, + timeLeft, + folderLabel, + folders, + type Counts, +} from "../shared/view"; import { mono } from "./mono"; import { IconSwap, Presence, StaggerRoot, nativeDriver } from "./motion"; import { NARROW_MAX, NarrowProvider } from "./narrow"; @@ -30,18 +45,27 @@ function WorkspacePulse({ theme, workspaceId, host, tab }: PluginWorkspacePanelP const [narrow, setNarrow] = useState(false); return ( - setNarrow(event.nativeEvent.layout.width <= NARROW_MAX)} - style={{ flex: 1, backgroundColor: colors.surface0 }} contentContainerStyle={{ paddingBottom: 16 }}> - {query.isPending && directory ? : null} + setNarrow(event.nativeEvent.layout.width <= NARROW_MAX)} + style={{ flex: 1, backgroundColor: colors.surface0 }} + contentContainerStyle={{ paddingBottom: 16 }} + > + {query.isPending && directory ? ( + + ) : null} {query.error ? ( Could not read the test run: {query.error.message} ) : null} - {result && !result.run ? : null} + + {result && !result.run ? : null} + {/* Keyed by run: a new run starts with fresh folds and dialogs. */} - {result?.run ? : null} + {result?.run ? ( + + ) : null} ); @@ -59,7 +83,8 @@ function EmptyState({ colors, file, reporterPath }: { colors: Colors; file: stri
- The next Playwright run in this worktree shows up here live: each test as it runs, its current step, and any failure with its screenshot and trace. Add the Pulse reporter to playwright.config.ts: + The next Playwright run in this worktree shows up here live: each test as it runs, its current step, and any failure with its screenshot and trace. Add + the Pulse reporter to playwright.config.ts: @@ -67,7 +92,12 @@ function EmptyState({ colors, file, reporterPath }: { colors: Colors; file: stri - A --reporter flag replaces the config's reporters, so leave it off. The README has the full snippet. Runs are kept outside the repo, in {file}. + A --reporter flag replaces the config's reporters, so leave it off. + The README has the full snippet. Runs are kept outside the repo, in{" "} + + {file} + + .
); @@ -85,7 +115,19 @@ function useNow(intervalMs: number | null): number { return now; } -function RunView({ colors, tab, run, workspaceId, workspaceDirectory }: { colors: Colors; tab: PluginTab; run: RunSnapshot; workspaceId: string; workspaceDirectory: string }) { +function RunView({ + colors, + tab, + run, + workspaceId, + workspaceDirectory, +}: { + colors: Colors; + tab: PluginTab; + run: RunSnapshot; + workspaceId: string; + workspaceDirectory: string; +}) { const live = isLive(run); const now = useNow(live ? 1000 : 30_000); const tally = counts(run); @@ -120,14 +162,39 @@ function RunView({ colors, tab, run, workspaceId, workspaceDirectory }: { colors {/* Folders and the slowest tests share one card: they're rarely wanted at once. */} 0} order={4}> {run.status !== "starting" && tally.total > 0 ? ( - }, - { id: "slowest", label: "Slowest", icon: "Hourglass", count: slowestCount, empty: "No finished tests yet.", content: }, - ]} /> + , + }, + { + id: "slowest", + label: "Slowest", + icon: "Hourglass", + count: slowestCount, + empty: "No finished tests yet.", + content: , + }, + ]} + /> ) : null} - setShot(null)} onOpenOnHost={(target) => actions.open(target, "screenshot")} /> + setShot(null)} + onOpenOnHost={(target) => actions.open(target, "screenshot")} + /> ); } @@ -147,7 +214,8 @@ function useAttachmentActions(run: RunSnapshot, workspaceId: string, workspaceDi if (!traceCommand) return toast.show("Showed the trace in its folder", { durationMs: 2500 }); return copyText(traceCommand).then( () => toast.show("Showed the trace in its folder and copied the command that views it", { variant: "success", durationMs: 4000 }), - () => toast.show(`Showed the trace in its folder. To view it, run: ${traceCommand}`, { durationMs: 8000 })); + () => toast.show(`Showed the trace in its folder. To view it, run: ${traceCommand}`, { durationMs: 8000 }), + ); }) .catch((error: unknown) => toast.error(error instanceof Error ? error.message : "Could not open it.")); }, @@ -164,7 +232,21 @@ function statusColor(colors: Colors, run: RunSnapshot, tally: Counts): string { } // The run at a glance: its state and clock, the command, and the bar. -function Header({ colors, run, tally, now, workspaceId, workspaceDirectory }: { colors: Colors; run: RunSnapshot; tally: Counts; now: number; workspaceId: string; workspaceDirectory: string }) { +function Header({ + colors, + run, + tally, + now, + workspaceId, + workspaceDirectory, +}: { + colors: Colors; + run: RunSnapshot; + tally: Counts; + now: number; + workspaceId: string; + workspaceDirectory: string; +}) { const live = isLive(run); const color = statusColor(colors, run, tally); // A live run that already has a failure says so in its title, in red. @@ -174,13 +256,25 @@ function Header({ colors, run, tally, now, workspaceId, workspaceDirectory }: { - {live ? - : } + {live ? ( + + ) : ( + + )} {title} - + {live ? formatClock(runElapsed(run, now)) : formatDuration(runElapsed(run, now))} {live ? : null} @@ -193,7 +287,9 @@ function Header({ colors, run, tally, now, workspaceId, workspaceDirectory }: { {run.projects.map((project) => ( - {project} + + {project} + ))} @@ -223,8 +319,18 @@ function ProgressBar({ colors, tally, live, left }: { colors: Colors; tally: Cou // The bar and its counts read as one group: 6 within, 12 to the text above. return ( - + {segments.map((segment) => ( {segment.shimmer ? : null} @@ -266,10 +372,12 @@ function Tally({ colors, color, count, label }: { colors: Colors; color: string; function Shimmer() { const value = useRef(new Animated.Value(0)).current; useEffect(() => { - const loop = Animated.loop(Animated.sequence([ - Animated.timing(value, { toValue: 1, duration: 900, useNativeDriver: nativeDriver() }), - Animated.timing(value, { toValue: 0, duration: 900, useNativeDriver: nativeDriver() }), - ])); + const loop = Animated.loop( + Animated.sequence([ + Animated.timing(value, { toValue: 1, duration: 900, useNativeDriver: nativeDriver() }), + Animated.timing(value, { toValue: 0, duration: 900, useNativeDriver: nativeDriver() }), + ]), + ); loop.start(); return () => loop.stop(); }, [value]); @@ -282,7 +390,9 @@ function StartingUp({ colors, run, now }: { colors: Colors; run: RunSnapshot; no const waited = now - Date.parse(run.startedAt); return ( - + + + Getting ready @@ -296,7 +406,10 @@ function StartingUp({ colors, run, now }: { colors: Colors; run: RunSnapshot; no // Errors outside any test, like a web server that never came up. function RunErrors({ colors, errors }: { colors: Colors; errors: string[] }) { return ( - + @@ -304,7 +417,21 @@ function RunErrors({ colors, errors }: { colors: Colors; errors: string[] }) { {errors.map((error, index) => ( - + {error} ))} diff --git a/playwright-pulse/client/reporter-banner.tsx b/playwright-pulse/client/reporter-banner.tsx index 154f5dad..d0ccc051 100644 --- a/playwright-pulse/client/reporter-banner.tsx +++ b/playwright-pulse/client/reporter-banner.tsx @@ -40,20 +40,49 @@ export function ReporterBanner({ colors, status }: { colors: Colors; status: Rep // Until the next poll catches up with a successful retry. const notice = status && !(mutation.isSuccess && (status.state === "missing" || status.state === "unknown")) ? reporterNotice(status) : null; return ( - {notice ? ( - - {/* Held on the first line: the text wraps to several lines in the Explorer pane. */} - - {notice.text} - {notice.action ? ( - mutation.mutate()} - style={({ pressed, hovered }) => ({ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 4, backgroundColor: colors.accent, opacity: pressed || mutation.isPending ? 0.7 : hovered ? 0.85 : 1 })}> - - {mutation.isPending ? "Writing…" : notice.action} - - - ) : null} - - ) : null} + + {notice ? ( + + {/* Held on the first line: the text wraps to several lines in the Explorer pane. */} + + + + + {notice.text} + + {notice.action ? ( + mutation.mutate()} + style={({ pressed, hovered }) => ({ + paddingHorizontal: 10, + paddingVertical: 5, + borderRadius: 4, + backgroundColor: colors.accent, + opacity: pressed || mutation.isPending ? 0.7 : hovered ? 0.85 : 1, + })} + > + + {mutation.isPending ? "Writing…" : notice.action} + + + ) : null} + + ) : null} + ); } diff --git a/playwright-pulse/client/row.tsx b/playwright-pulse/client/row.tsx index 6f669bca..aa5adaa7 100644 --- a/playwright-pulse/client/row.tsx +++ b/playwright-pulse/client/row.tsx @@ -13,7 +13,14 @@ export function rowTint(colors: Colors, state: { hovered: boolean; pressed: bool } // A full-width row that opens something. `resting` is its background at rest. -export function PressableRow({ colors, onSurface1 = false, transparentAtRest = true, style, children, ...props }: Omit & { +export function PressableRow({ + colors, + onSurface1 = false, + transparentAtRest = true, + style, + children, + ...props +}: Omit & { colors: Colors; onSurface1?: boolean; // Rows on a surface1 background rest transparent; the working ticket rests on surface1. @@ -23,11 +30,15 @@ export function PressableRow({ colors, onSurface1 = false, transparentAtRest = t }) { const [hovered, setHovered] = useState(false); return ( - setHovered(true)} onHoverOut={() => setHovered(false)} + setHovered(true)} + onHoverOut={() => setHovered(false)} style={({ pressed }) => { const tint = rowTint(colors, { hovered, pressed }, onSurface1); return [style, { backgroundColor: !hovered && !pressed && transparentAtRest ? "transparent" : tint }]; - }}> + }} + > {children} ); diff --git a/playwright-pulse/client/screenshot.tsx b/playwright-pulse/client/screenshot.tsx index 91fb5617..2cd4a4fa 100644 --- a/playwright-pulse/client/screenshot.tsx +++ b/playwright-pulse/client/screenshot.tsx @@ -12,7 +12,14 @@ type Colors = PluginWorkspacePanelProps["theme"]["colors"]; export type ScreenshotRef = { runId: string; testId: string; index: number; title: string; path: string }; // A failure screenshot in a dialog, with a way out to the host's own app. -export function ScreenshotDialog({ colors, shot, workspaceId, workspaceDirectory, onClose, onOpenOnHost }: { +export function ScreenshotDialog({ + colors, + shot, + workspaceId, + workspaceDirectory, + onClose, + onOpenOnHost, +}: { colors: Colors; shot: ScreenshotRef | null; workspaceId: string; @@ -24,17 +31,39 @@ export function ScreenshotDialog({ colors, shot, workspaceId, workspaceDirectory // Keeps the image while the dialog animates closed. const shown = useLastPresent(shot); return ( - } - open={open} onOpenChange={(next) => { if (!next) onClose(); }}> + } + open={open} + onOpenChange={(next) => { + if (!next) onClose(); + }} + > - {shown ? { onClose(); onOpenOnHost(shown); }} /> : null} + {shown ? ( + { + onClose(); + onOpenOnHost(shown); + }} + /> + ) : null} ); } -function ScreenshotBody({ colors, shot, workspaceId, workspaceDirectory, onOpenOnHost }: { +function ScreenshotBody({ + colors, + shot, + workspaceId, + workspaceDirectory, + onOpenOnHost, +}: { colors: Colors; shot: ScreenshotRef; workspaceId: string; @@ -56,8 +85,16 @@ function ScreenshotBody({ colors, shot, workspaceId, workspaceDirectory, onOpenO useEffect(() => { if (!uri) return; let current = true; - Image.getSize(uri, (width, height) => { if (current && width && height) setRatio(width / height); }, () => {}); - return () => { current = false; }; + Image.getSize( + uri, + (width, height) => { + if (current && width && height) setRatio(width / height); + }, + () => {}, + ); + return () => { + current = false; + }; }, [uri]); return ( @@ -69,8 +106,12 @@ function ScreenshotBody({ colors, shot, workspaceId, workspaceDirectory, onOpenO ) : null} {uri ? ( - + ) : null} {preview.data && !uri ? ( Too large to show here. Open it in its default app. @@ -80,13 +121,29 @@ function ScreenshotBody({ colors, shot, workspaceId, workspaceDirectory, onOpenO {/* The server opens a screenshot only if it passes the preview's checks. */} - {preview.data ? - ({ flexDirection: "row", alignItems: "center", gap: 6, paddingVertical: 6, paddingStart: 8, paddingEnd: 10, borderRadius: 6, ...raised(colors), backgroundColor: pressed ? colors.surface1 : colors.surface2 })}> - - Open - - : null} + {preview.data ? ( + + ({ + flexDirection: "row", + alignItems: "center", + gap: 6, + paddingVertical: 6, + paddingStart: 8, + paddingEnd: 10, + borderRadius: 6, + ...raised(colors), + backgroundColor: pressed ? colors.surface1 : colors.surface2, + })} + > + + Open + + + ) : null} ); } diff --git a/playwright-pulse/client/section-title.tsx b/playwright-pulse/client/section-title.tsx index 7ef3b25e..bca7f8f0 100644 --- a/playwright-pulse/client/section-title.tsx +++ b/playwright-pulse/client/section-title.tsx @@ -6,7 +6,14 @@ import { Text, View, type ViewStyle } from "react-native"; type Colors = PluginWorkspacePanelProps["theme"]["colors"]; // A card's heading: a 14px Lucide icon beside the 13px semibold title. -export function SectionTitle({ colors, icon, title, color, style, children }: { +export function SectionTitle({ + colors, + icon, + title, + color, + style, + children, +}: { colors: Colors; icon: string; title: string; @@ -17,7 +24,9 @@ export function SectionTitle({ colors, icon, title, color, style, children }: { return ( - {title} + + {title} + {children} ); diff --git a/playwright-pulse/client/spinner.tsx b/playwright-pulse/client/spinner.tsx index 3a80e1b1..55463648 100644 --- a/playwright-pulse/client/spinner.tsx +++ b/playwright-pulse/client/spinner.tsx @@ -8,9 +8,11 @@ import { nativeDriver } from "./motion"; export function Spinner({ color, size = 12 }: { color: string; size?: number }) { return ( - {Platform.OS === "ios" - ? - : } + {Platform.OS === "ios" ? ( + + ) : ( + + )} ); } @@ -20,10 +22,12 @@ export function Spinner({ color, size = 12 }: { color: string; size?: number }) export function StalledPulse({ color, size = 12 }: { color: string; size?: number }) { const opacity = useRef(new Animated.Value(1)).current; useEffect(() => { - const loop = Animated.loop(Animated.sequence([ - Animated.timing(opacity, { toValue: 0.35, duration: 700, easing: Easing.inOut(Easing.ease), useNativeDriver: nativeDriver() }), - Animated.timing(opacity, { toValue: 1, duration: 700, easing: Easing.inOut(Easing.ease), useNativeDriver: nativeDriver() }), - ])); + const loop = Animated.loop( + Animated.sequence([ + Animated.timing(opacity, { toValue: 0.35, duration: 700, easing: Easing.inOut(Easing.ease), useNativeDriver: nativeDriver() }), + Animated.timing(opacity, { toValue: 1, duration: 700, easing: Easing.inOut(Easing.ease), useNativeDriver: nativeDriver() }), + ]), + ); loop.start(); return () => loop.stop(); }, [opacity]); diff --git a/playwright-pulse/client/stop-button.tsx b/playwright-pulse/client/stop-button.tsx index 463421ce..bc7bb6fc 100644 --- a/playwright-pulse/client/stop-button.tsx +++ b/playwright-pulse/client/stop-button.tsx @@ -18,7 +18,17 @@ type Phase = "idle" | "confirm" | "stopping" | "force"; // Stops the run as Ctrl+C would. The first press asks, so a stray click // can't end a long suite; if the run hasn't ended a while after stopping, the // button offers to force it, as a second Ctrl+C does. -export function StopButton({ colors, runId, workspaceId, workspaceDirectory }: { colors: Colors; runId: string; workspaceId: string; workspaceDirectory: string }) { +export function StopButton({ + colors, + runId, + workspaceId, + workspaceDirectory, +}: { + colors: Colors; + runId: string; + workspaceId: string; + workspaceDirectory: string; +}) { const stop = useRpc(stopRun); const toast = useToast(); const [phase, setPhase] = useState("idle"); @@ -45,14 +55,25 @@ export function StopButton({ colors, runId, workspaceId, workspaceDirectory }: { const asking = phase === "confirm" || phase === "force"; const label = phase === "confirm" ? "Stop run?" : phase === "stopping" ? "Stopping…" : phase === "force" ? "Force stop" : "Stop"; return ( - ({ - flexDirection: "row", alignItems: "center", gap: 5, paddingVertical: 4, paddingStart: 7, paddingEnd: 9, borderRadius: 4, + flexDirection: "row", + alignItems: "center", + gap: 5, + paddingVertical: 4, + paddingStart: 7, + paddingEnd: 9, + borderRadius: 4, ...(asking ? {} : raised(colors)), backgroundColor: asking ? colors.statusDanger : pressed ? colors.surface2 : hovered ? colors.surface2 : colors.surface1, opacity: phase === "stopping" ? 0.6 : asking && (pressed || hovered) ? 0.88 : 1, - })}> + })} + > diff --git a/playwright-pulse/client/tabs.tsx b/playwright-pulse/client/tabs.tsx index a43d5245..4f313cd6 100644 --- a/playwright-pulse/client/tabs.tsx +++ b/playwright-pulse/client/tabs.tsx @@ -33,39 +33,97 @@ export function TabbedCard({ colors, workspaceId, paseoTab, tabs }: { colors: Co }, [workspaceId, chosen, saved, save]); const current = tabs.find((entry) => entry.id === chosen) ?? tabs[0]; return ( - setShowIcons(event.nativeEvent.layout.width >= TAB_ICONS_MIN)} - style={{ margin: 12, marginBottom: 0, ...raised(colors), borderRadius: 6, overflow: "hidden" }}> - + setShowIcons(event.nativeEvent.layout.width >= TAB_ICONS_MIN)} + style={{ margin: 12, marginBottom: 0, ...raised(colors), borderRadius: 6, overflow: "hidden" }} + > + {tabs.map((entry) => ( - save({ tab: entry.id })} /> + save({ tab: entry.id })} + /> ))} {current.count === 0 ? ( {current.empty} - ) : current.content} + ) : ( + current.content + )} ); } // Instant feedback: tabs switch often, so hover and press change color only. // Narrow tightens the spacing so every tab stays on one line at the sidebar's 320px. -function Tab({ colors, narrow, label, icon, count, selected, onPress }: { colors: Colors; narrow: boolean; label: string; icon: string | null; count: number; selected: boolean; onPress(): void }) { +function Tab({ + colors, + narrow, + label, + icon, + count, + selected, + onPress, +}: { + colors: Colors; + narrow: boolean; + label: string; + icon: string | null; + count: number; + selected: boolean; + onPress(): void; +}) { const [hovered, setHovered] = useState(false); return ( - setHovered(true)} onHoverOut={() => setHovered(false)} + setHovered(true)} + onHoverOut={() => setHovered(false)} style={({ pressed }) => ({ - flexDirection: "row", alignItems: "center", gap: narrow ? 4 : 5, paddingTop: 8, paddingBottom: 6, marginBottom: -1, + flexDirection: "row", + alignItems: "center", + gap: narrow ? 4 : 5, + paddingTop: 8, + paddingBottom: 6, + marginBottom: -1, borderBottomWidth: 2, borderBottomColor: selected ? colors.accent : pressed || hovered ? colors.border : "transparent", - })}> + })} + > {/* 12px: a Lucide glyph fills its box, so this matches the label's capitals; 14px towers over them. */} {icon ? : null} {label} {/* Count badge: muted on every tab; the chosen tab's number reads darker. */} - {count} + + {count} + ); diff --git a/playwright-pulse/client/tests.tsx b/playwright-pulse/client/tests.tsx index ecaa59aa..62278d7c 100644 --- a/playwright-pulse/client/tests.tsx +++ b/playwright-pulse/client/tests.tsx @@ -3,7 +3,32 @@ import { Icon, copyText, useToast } from "@getpaseo/plugin/client/ui"; import React, { useRef, useState } from "react"; import { Text, View } from "react-native"; import type { PulseTest, RunSnapshot } from "../shared/run"; -import { folders, assignSlots, attachmentKind, isLive, slowest, slowestPrompt, type Folder, errorPreview, failureMessage, formatClock, formatDuration, isFailure, testWhere, timeoutShare, runningSlotCount, workerCount, MAX_WORKER_DOTS, MAX_WORKER_DOTS_NARROW, shownFailure, stepFailure, verdict, verdictNote, type AttachmentKind, type Counts } from "../shared/view"; +import { + folders, + assignSlots, + attachmentKind, + isLive, + slowest, + slowestPrompt, + type Folder, + errorPreview, + failureMessage, + formatClock, + formatDuration, + isFailure, + testWhere, + timeoutShare, + runningSlotCount, + workerCount, + MAX_WORKER_DOTS, + MAX_WORKER_DOTS_NARROW, + shownFailure, + stepFailure, + verdict, + verdictNote, + type AttachmentKind, + type Counts, +} from "../shared/view"; import { IconSwap, PressScale } from "./motion"; import { mono } from "./mono"; import { useNarrow } from "./narrow"; @@ -21,8 +46,15 @@ export interface AttachmentActions { function Card({ colors, children, tone }: { colors: Colors; children: React.ReactNode; tone?: "danger" }) { return ( - + {children} ); @@ -37,7 +69,11 @@ const SLOW_STEP_MS = 2_000; export function RunningSection({ colors, run, now }: { colors: Colors; run: RunSnapshot; now: number }) { const running = run.tests.filter((test) => test.status === "running"); const slots = useRef<(string | null)[]>([]); - slots.current = assignSlots(slots.current, running.map((test) => test.id), runningSlotCount(run, running.length)); + slots.current = assignSlots( + slots.current, + running.map((test) => test.id), + runningSlotCount(run, running.length), + ); const narrow = useNarrow(); return ( @@ -61,12 +97,24 @@ function WorkerCount({ colors, count }: { colors: Colors; count: ReturnType {count.dots.map((busy, index) => ( - + ))} ) : null} - {count.label} + + {count.label} + ); @@ -81,10 +129,30 @@ function RunningTest({ colors, test, now }: { colors: Colors; test: PulseTest | const stepElapsed = test?.step ? now - Date.parse(test.step.startedAt) : 0; const trail = [...(test?.recentSteps ?? [])].reverse().slice(0, TRAIL_ROWS); return ( - + - + {test ? test.title : "Waiting for the next test"} {test?.retry ? : null} @@ -94,23 +162,41 @@ function RunningTest({ colors, test, now }: { colors: Colors; test: PulseTest | The space after the last "›" can't break, or the screen drops it. */} {test?.titlePath.length ? ( - {test.titlePath.join(" › ")}{" ›\u00a0"} + + {test.titlePath.join(" › ")} + {" ›\u00a0"} + ) : null} - {test ? `${test.file}:${test.line}` : " "} + + {test ? `${test.file}:${test.line}` : " "} + - : } - title={test ? (test.step?.title ?? "Setting up") : ""} subtitle={test?.step?.subtitle} - context={test?.step?.context} time={stepElapsed >= SLOW_STEP_MS ? formatClock(stepElapsed) : undefined} /> + title={test ? (test.step?.title ?? "Setting up") : ""} + subtitle={test?.step?.subtitle} + context={test?.step?.context} + time={stepElapsed >= SLOW_STEP_MS ? formatClock(stepElapsed) : undefined} + /> {Array.from({ length: TRAIL_ROWS }, (_, index) => { const step = trail[index]; return step ? ( - } - title={step.title} subtitle={step.subtitle} time={formatDuration(step.duration)} /> - ) : {open ? ( - + {/* Scrolling past the end stays in the output instead of moving the chat. */} - - {more} + + + {more} + ) : null} diff --git a/progress/client/chat-row.test.ts b/progress/client/chat-row.test.ts index ddbba74f..5fe155dd 100644 --- a/progress/client/chat-row.test.ts +++ b/progress/client/chat-row.test.ts @@ -39,12 +39,22 @@ test("a Progress call from Claude Code draws the first line of what the tool ret const { transformer, transform, drawn } = contributed(); assert.deepEqual(plain(transformer.query), { itemType: "tool_call" }); const added = transform(claudeDone("mcp__paseo__progress_ticket_add", { output: "Added T01: Write the spec for the full tool set (30m)" })); - assert.deepEqual(drawn(added), { line: "Added T01: Write the spec for the full tool set (30m)", more: "Added T01: Write the spec for the full tool set (30m)" }, "a line that truncates on a phone still opens to its full text"); - const started = transform(claudeDone("mcp__paseo__progress_start", { output: "Started run: Progress agent tools\nQuestion mode: Stop, set by the user in Paseo's Settings." })); - assert.deepEqual(drawn(started), { - line: "Started run: Progress agent tools", - more: "Started run: Progress agent tools\nQuestion mode: Stop, set by the user in Paseo's Settings.", - }, "the row opens to the full output"); + assert.deepEqual( + drawn(added), + { line: "Added T01: Write the spec for the full tool set (30m)", more: "Added T01: Write the spec for the full tool set (30m)" }, + "a line that truncates on a phone still opens to its full text", + ); + const started = transform( + claudeDone("mcp__paseo__progress_start", { output: "Started run: Progress agent tools\nQuestion mode: Stop, set by the user in Paseo's Settings." }), + ); + assert.deepEqual( + drawn(started), + { + line: "Started run: Progress agent tools", + more: "Started run: Progress agent tools\nQuestion mode: Stop, set by the user in Paseo's Settings.", + }, + "the row opens to the full output", + ); assert.equal(drawn(transform(claudeDone("progress_finish", { output: "Finished run: Export" }))).line, "Finished run: Export", "an unprefixed name"); }); @@ -61,27 +71,43 @@ test("a Progress call from Codex, named server.tool with the MCP result, draws t const refused = { content: [{ type: "text", text: "No ticket T09.\nUsage: paseo-progress ticket update " }], isError: true }; const failure = transform(claudeDone("paseo.progress_ticket_update", refused)); assert.equal(failure.items[0].data.state, "failed", "drawn in the error color"); - assert.deepEqual(drawn(failure), { - line: "No ticket T09.", - more: "No ticket T09.\nUsage: paseo-progress ticket update ", - }, "a result Codex marks as an error draws as a failure"); + assert.deepEqual( + drawn(failure), + { + line: "No ticket T09.", + more: "No ticket T09.\nUsage: paseo-progress ticket update ", + }, + "a result Codex marks as an error draws as a failure", + ); }); test("a failed call carries the command's error, whichever way Claude Code stored it", () => { const { transform, drawn } = contributed(); const error = 'Unknown status "in_progress". Statuses: not_started, working, blocked, done, skipped.\nUsage: paseo-progress ticket update '; - const failed = (stored: unknown) => transform({ name: "mcp__paseo__progress_ticket_update", status: "failed", detail: { type: "unknown", input: {}, output: null }, error: stored }); + const failed = (stored: unknown) => + transform({ name: "mcp__paseo__progress_ticket_update", status: "failed", detail: { type: "unknown", input: {}, output: null }, error: stored }); const expected = { line: 'Unknown status "in_progress". Statuses: not_started, working, blocked, done, skipped.', more: error }; - assert.deepEqual(plain(failed({ type: "tool_result", tool_use_id: "c1", content: error, is_error: true }).items[0].data), { tool: "progress_ticket_update", state: "failed", error }); + assert.deepEqual(plain(failed({ type: "tool_result", tool_use_id: "c1", content: error, is_error: true }).items[0].data), { + tool: "progress_ticket_update", + state: "failed", + error, + }); assert.deepEqual(drawn(failed({ type: "tool_result", content: error, is_error: true })), expected); assert.deepEqual(drawn(failed({ type: "tool_result", content: [{ type: "text", text: error }], is_error: true })), expected, "as text blocks"); assert.deepEqual(drawn(failed({ message: "Tool call failed" })), { line: "Tool call failed", more: "Tool call failed" }, "Paseo's own failure message"); - assert.deepEqual(drawn(failed({ type: "tool_result", content: "", is_error: true })), { line: "Update ticket: failed", more: null }, "an empty error still says it failed"); + assert.deepEqual( + drawn(failed({ type: "tool_result", content: "", is_error: true })), + { line: "Update ticket: failed", more: null }, + "an empty error still says it failed", + ); }); test("a running call shows what the tool is doing; a canceled one says so", () => { const { transform, drawn } = contributed(); - const running = transform({ name: "mcp__paseo__progress_ticket_add", status: "running", detail: { type: "unknown", input: { title: "x" }, output: null } }, "streaming"); + const running = transform( + { name: "mcp__paseo__progress_ticket_add", status: "running", detail: { type: "unknown", input: { title: "x" }, output: null } }, + "streaming", + ); assert.deepEqual(drawn(running), { line: "Adding ticket…", more: null }); const canceled = transform({ name: "mcp__paseo__progress_question_ask", status: "canceled", detail: { type: "unknown", input: {}, output: null } }); assert.deepEqual(drawn(canceled), { line: "Ask question: canceled", more: null }); diff --git a/progress/client/chat-row.ts b/progress/client/chat-row.ts index 79c497c9..bd56b24c 100644 --- a/progress/client/chat-row.ts +++ b/progress/client/chat-row.ts @@ -67,7 +67,11 @@ export function transformChatRow({ item }: { item: ToolCall }) { // truncates on a narrow chat, so any text at all can be opened. export function chatRowText(row: ChatRow, m: ProgressMessages): { line: string; more: string | null } { const labels = m.toolRow[row.tool]; - const firstLine = (text: string) => text.split("\n").map((line) => line.trim()).find(Boolean) ?? ""; + const firstLine = (text: string) => + text + .split("\n") + .map((line) => line.trim()) + .find(Boolean) ?? ""; const withMore = (line: string, text: string) => ({ line, more: text.trim() || null }); switch (row.state) { case "running": diff --git a/progress/client/dashboard-query.ts b/progress/client/dashboard-query.ts index 9dcc0f1e..2592ac17 100644 --- a/progress/client/dashboard-query.ts +++ b/progress/client/dashboard-query.ts @@ -9,13 +9,19 @@ export const POLL_MS = 3_000; // `previous` is what the cache already holds. Polls send its version, and an // "unchanged" reply keeps that same object, so nothing re-renders. -export function dashboardQueryOptions(fetchDashboard: FetchDashboard, hostId: string, workspaceId: string, directory: string | null, previous?: () => DashboardResult | undefined) { +export function dashboardQueryOptions( + fetchDashboard: FetchDashboard, + hostId: string, + workspaceId: string, + directory: string | null, + previous?: () => DashboardResult | undefined, +) { return { queryKey: ["progress", "dashboard", hostId, workspaceId, directory], queryFn: async (): Promise => { const last = previous?.(); const result = await fetchDashboard({ workspaceId, workspaceDirectory: directory!, ...(last ? { since: last.version } : {}) }); - return "unchanged" in result && last ? last : result as DashboardResult; + return "unchanged" in result && last ? last : (result as DashboardResult); }, enabled: Boolean(directory), staleTime: POLL_MS, @@ -26,7 +32,6 @@ export function dashboardQueryOptions(fetchDashboard: FetchDashboard, hostId: st export function useDashboard(hostId: string, workspaceId: string, directory: string | null) { const fetchDashboard = useRpc(getDashboard); const queryClient = useQueryClient(); - const options = dashboardQueryOptions(fetchDashboard, hostId, workspaceId, directory, - () => queryClient.getQueryData(options.queryKey)); + const options = dashboardQueryOptions(fetchDashboard, hostId, workspaceId, directory, () => queryClient.getQueryData(options.queryKey)); return useQuery(options); } diff --git a/progress/client/deliverables.test.ts b/progress/client/deliverables.test.ts index dfd58b33..bddb3ddb 100644 --- a/progress/client/deliverables.test.ts +++ b/progress/client/deliverables.test.ts @@ -20,8 +20,13 @@ function tabTargets(platform: string): string[] { messages = h.load("client/i18n.ts").messagesFor("en"); const { DeliverablesList } = h.load("client/deliverables.tsx"); const deliverable = (id: string, path: string) => ({ id, title: id, path, kind: "file", addedAt: "2026-10-30T00:00:00Z" }); - const drawn = DeliverablesList({ colors: {}, now: Date.parse("2026-10-30T01:00:00Z"), workspaceId: "w", workspaceDirectory: "/repo", - deliverables: [deliverable("D1", "docs/My spec (v2).pdf"), deliverable("D2", "docs/notes.md")] }); + const drawn = DeliverablesList({ + colors: {}, + now: Date.parse("2026-10-30T01:00:00Z"), + workspaceId: "w", + workspaceDirectory: "/repo", + deliverables: [deliverable("D1", "docs/My spec (v2).pdf"), deliverable("D2", "docs/notes.md")], + }); const links: string[] = []; const walk = (node: unknown) => { if (Array.isArray(node)) return node.forEach(walk); diff --git a/progress/client/deliverables.tsx b/progress/client/deliverables.tsx index 101fda1e..05857c4e 100644 --- a/progress/client/deliverables.tsx +++ b/progress/client/deliverables.tsx @@ -24,7 +24,14 @@ const BUTTON_PAIR_GAP = 4; const TAP_AREA_FILL = Array(8).fill("████").join(" "); // The Deliverables tab: newest first, 10 at a time (see usePaged). -export function DeliverablesList({ colors, deliverables, now, workspaceId, workspaceDirectory, navigation }: { +export function DeliverablesList({ + colors, + deliverables, + now, + workspaceId, + workspaceDirectory, + navigation, +}: { colors: Colors; now: number; deliverables: Deliverable[]; @@ -42,18 +49,35 @@ export function DeliverablesList({ colors, deliverables, now, workspaceId, works const attachment = deliverableAttachment(deliverable); const tab = opensInTab(attachment, { platform: Platform.OS }); return ( - void open(attachment)} - style={{ flexDirection: "row", gap: ROW_GAP, paddingHorizontal: 10, paddingVertical: 8, borderTopWidth: index ? 1 : 0, borderTopColor: colors.border }}> + style={{ + flexDirection: "row", + gap: ROW_GAP, + paddingHorizontal: 10, + paddingVertical: 8, + borderTopWidth: index ? 1 : 0, + borderTopColor: colors.border, + }} + > {/* Optical: centers the 14px icon on the 18px title line. */} - + + + {/* What the agent found is the headline; the row itself is what opens. */} - {deliverable.title} + + {deliverable.title} + {/* Just the name, ticket and age. The full path is one press of Copy away. */} - {[shortName(attachment), deliverable.ticketLabel ?? deliverable.ticketId, formatClientAgo(locale, deliverable.addedAt, now)].filter(Boolean).join(" · ")} + {[shortName(attachment), deliverable.ticketLabel ?? deliverable.ticketId, formatClientAgo(locale, deliverable.addedAt, now)] + .filter(Boolean) + .join(" · ")} {tab ? ( @@ -61,22 +85,37 @@ export function DeliverablesList({ colors, deliverables, now, workspaceId, works ) : null} {deliverable.path ? ( // Optical: the 22px button centers on the 18px title line. - void copyPath(attachment)} // A step above the row's own hover tint (surface1), so it reads as its own target. - style={({ pressed, hovered }) => ({ padding: 4, borderRadius: 4, backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent" })}> + style={({ pressed, hovered }) => ({ + padding: 4, + borderRadius: 4, + backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent", + })} + > ) : ( - + + + )} ); })} - setPreviewing(null)} context={{ workspaceId, workspaceDirectory, navigation }} - root={previewing ? { kind: "preview", attachment: previewing, group: galleryFiles(deliverables.map(deliverableAttachment)), fullScreen: false } : null} /> + setPreviewing(null)} + context={{ workspaceId, workspaceDirectory, navigation }} + root={previewing ? { kind: "preview", attachment: previewing, group: galleryFiles(deliverables.map(deliverableAttachment)), fullScreen: false } : null} + /> ); } @@ -87,10 +126,19 @@ function TabButton({ colors, label, target }: { colors: Colors; label: string; t const linkTakesFocus = Platform.OS === "web"; const keepPressFromRow = () => {}; return ( - ({ padding: 4, borderRadius: 4, overflow: "hidden", backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent" })}> + style={({ pressed, hovered }) => ({ + padding: 4, + borderRadius: 4, + overflow: "hidden", + backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent", + })} + > {`[${TAP_AREA_FILL}](${target})`} diff --git a/progress/client/dialog-stack.test.ts b/progress/client/dialog-stack.test.ts index e13b6fa4..880a5a2d 100644 --- a/progress/client/dialog-stack.test.ts +++ b/progress/client/dialog-stack.test.ts @@ -19,7 +19,12 @@ function dialogHarness() { useState(initial: unknown) { const index = slot++; if (!(index in slots)) slots[index] = initial; - return [slots[index], (next: unknown) => { slots[index] = typeof next === "function" ? next(slots[index]) : next; }]; + return [ + slots[index], + (next: unknown) => { + slots[index] = typeof next === "function" ? next(slots[index]) : next; + }, + ]; }, useRef(initial: unknown) { const index = slot++; @@ -30,7 +35,12 @@ function dialogHarness() { useContext: () => ({ locale: "en", messages }), }, "@getpaseo/plugin/client": { useRpc: () => async () => ({}) }, - "@getpaseo/plugin/client/ui": { Modal: Object.assign(() => null, { Content: () => null }), Icon: () => null, useToast: () => ({}), copyText: async () => {} }, + "@getpaseo/plugin/client/ui": { + Modal: Object.assign(() => null, { Content: () => null }), + Icon: () => null, + useToast: () => ({}), + copyText: async () => {}, + }, }); messages = h.load("client/i18n.ts").messagesFor("en"); const { StackedDialog } = h.load("client/dialog-stack.tsx"); @@ -52,8 +62,13 @@ test("Esc leaves a full-screen image for the preview dialog, and a second Esc cl const render = dialogHarness(); let closed = 0; const shot = { ref: "d1", title: "Home screen", path: "shots/home.png" }; - const props = { colors: {}, now: 0, onClose: () => closed++, context: { workspaceId: "w", workspaceDirectory: "/w" }, - root: { kind: "preview", attachment: shot, group: [shot], fullScreen: false } }; + const props = { + colors: {}, + now: 0, + onClose: () => closed++, + context: { workspaceId: "w", workspaceDirectory: "/w" }, + root: { kind: "preview", attachment: shot, group: [shot], fullScreen: false }, + }; render(props).preview!.props.onFullScreen(true); let { modal, preview } = render(props); @@ -76,8 +91,13 @@ test("stepping through the gallery keeps full screen for images and drops to the const home = { ref: "d1", title: "Home screen", path: "shots/home.png" }; const settings = { ref: "d2", title: "Settings", path: "shots/settings.png" }; const notes = { ref: "d3", title: "Notes", path: "notes.md" }; - const props = { colors: {}, now: 0, onClose() {}, context: { workspaceId: "w", workspaceDirectory: "/w" }, - root: { kind: "preview", attachment: home, group: [home, settings, notes], fullScreen: false } }; + const props = { + colors: {}, + now: 0, + onClose() {}, + context: { workspaceId: "w", workspaceDirectory: "/w" }, + root: { kind: "preview", attachment: home, group: [home, settings, notes], fullScreen: false }, + }; render(props).preview!.props.onFullScreen(true); render(props).preview!.props.gallery.onSelect(settings); diff --git a/progress/client/dialog-stack.tsx b/progress/client/dialog-stack.tsx index a3d949e2..eb039525 100644 --- a/progress/client/dialog-stack.tsx +++ b/progress/client/dialog-stack.tsx @@ -25,7 +25,17 @@ export type Step = // Paseo gives each dialog its own backdrop, so opening a second one darkens // the screen while the first fades out; steps swap content inside this one instead. -export function StackedDialog({ colors, root, onClose, questions = [], dashboard, now, live = true, compact = false, context }: { +export function StackedDialog({ + colors, + root, + onClose, + questions = [], + dashboard, + now, + live = true, + compact = false, + context, +}: { colors: Colors; root: Step | null; onClose(): void; @@ -50,7 +60,10 @@ export function StackedDialog({ colors, root, onClose, questions = [], dashboard const group = useRef([]); const push = (step: Step) => setSteps((current) => [...current, step]); const replaceTop = (step: Step) => setSteps((current) => [...current.slice(0, -1), step]); - const opener = useAttachmentOpener({ ...context, onPreview: (attachment) => push({ kind: "preview", attachment, group: galleryFiles(group.current), fullScreen: false }) }); + const opener = useAttachmentOpener({ + ...context, + onPreview: (attachment) => push({ kind: "preview", attachment, group: galleryFiles(group.current), fullScreen: false }), + }); const openAttachment = (attachment: Attachment, from: Attachment[]) => { group.current = from; // A link or a page opens outside the dialog; close first so it isn't left behind it. @@ -58,10 +71,12 @@ export function StackedDialog({ colors, root, onClose, questions = [], dashboard void opener.open(attachment); }; // Opens the agent's chat in its workspace, with the dialog out of the way. - const openAgent = context.navigation ? (agentId: string) => { - onClose(); - context.navigation!.openAgent({ agentId }); - } : undefined; + const openAgent = context.navigation + ? (agentId: string) => { + onClose(); + context.navigation!.openAgent({ agentId }); + } + : undefined; const copy = useCopy(); const top = steps.at(-1); const back = steps.length > 1 ? () => setSteps((current) => current.slice(0, -1)) : undefined; @@ -71,8 +86,13 @@ export function StackedDialog({ colors, root, onClose, questions = [], dashboard const preview = top?.kind === "preview" ? top : undefined; const setFullScreen = (on: boolean) => preview && replaceTop({ ...preview, fullScreen: on, leftFullScreen: !on }); // The ticket or question it opened on went away (answered elsewhere, or a new run): close rather than show a blank dialog. - const rootMissing = root !== null && (root.kind === "ticket" ? !dashboard?.tickets.some((candidate) => candidate.id === root.id) - : root.kind === "question" ? !questions.some((candidate) => candidate.id === root.id) : false); + const rootMissing = + root !== null && + (root.kind === "ticket" + ? !dashboard?.tickets.some((candidate) => candidate.id === root.id) + : root.kind === "question" + ? !questions.some((candidate) => candidate.id === root.id) + : false); useEffect(() => { if (rootMissing) onClose(); }, [rootMissing]); @@ -81,44 +101,87 @@ export function StackedDialog({ colors, root, onClose, questions = [], dashboard const icon = ticket ? "ListChecks" : question ? "MessageCircleQuestion" : preview ? attachmentIcon(preview.attachment) : "ListChecks"; return ( - } - open={Boolean(root)} onOpenChange={(next) => { + } + open={Boolean(root)} + onOpenChange={(next) => { if (next) return; // Esc leaves full screen first; the dialog stays open under it. if (preview?.fullScreen) setFullScreen(false); else onClose(); - }}> + }} + > {/* One Modal.Content for every step: replacing it would re-present the sheet on phones. Full screen turns its scrolling off. The image's fixed position reaches the window only when no ancestor has a transform, and a scroll view has one. */} - - {/* A dialog has room for clock times, however narrow the panel that opened it. */} - - {preview ? ( - { onClose(); void opener.openOnHost(preview.attachment); }} - onCopyPath={() => void opener.copyPath(preview.attachment)} onBack={back} - gallery={{ items: preview.group, onSelect: (attachment) => replaceTop({ ...preview, attachment, fullScreen: preview.fullScreen && previewKind(attachment.path ?? "") === "image", leftFullScreen: false }) }} - onLong={setPreviewLong} ownScroll={previewLong || preview.fullScreen} fullScreen={preview.fullScreen} leftFullScreen={preview.leftFullScreen === true} onFullScreen={setFullScreen} - onOpenEntry={openAttachment} /> - ) : ( - <> - {ticket && dashboard ? ( - push({ kind: "question", id })} /> - ) : null} - {question ? ( - { void copy(question, letter); onClose(); }} - onOpenAttachment={openAttachment}> - {back ? : null} - - ) : null} - - )} - - + + {/* A dialog has room for clock times, however narrow the panel that opened it. */} + + {preview ? ( + { + onClose(); + void opener.openOnHost(preview.attachment); + }} + onCopyPath={() => void opener.copyPath(preview.attachment)} + onBack={back} + gallery={{ + items: preview.group, + onSelect: (attachment) => + replaceTop({ + ...preview, + attachment, + fullScreen: preview.fullScreen && previewKind(attachment.path ?? "") === "image", + leftFullScreen: false, + }), + }} + onLong={setPreviewLong} + ownScroll={previewLong || preview.fullScreen} + fullScreen={preview.fullScreen} + leftFullScreen={preview.leftFullScreen === true} + onFullScreen={setFullScreen} + onOpenEntry={openAttachment} + /> + ) : ( + <> + {ticket && dashboard ? ( + push({ kind: "question", id })} + /> + ) : null} + {question ? ( + { + void copy(question, letter); + onClose(); + }} + onOpenAttachment={openAttachment} + > + {back ? : null} + + ) : null} + + )} + + ); @@ -127,4 +190,3 @@ export function StackedDialog({ colors, root, onClose, questions = [], dashboard function stepKey(step: Step): string { return step.kind === "preview" ? `preview:${step.attachment.ref}` : `${step.kind}:${step.id}`; } - diff --git a/progress/client/directory.ts b/progress/client/directory.ts index 1e59d614..9b267b07 100644 --- a/progress/client/directory.ts +++ b/progress/client/directory.ts @@ -7,9 +7,7 @@ type PaseoApi = ReturnType; type Handler = Subscribe extends (handler: infer H) => unknown ? H : never; export type PaseoAgentUpdate = Parameters>[0]; export type PaseoWorkspaceUpdate = Parameters>[0]; -type Message = Parameters< - Parameters>["subscription"]>["subscribe"]>[0]["update"] ->[0]; +type Message = Parameters>["subscription"]>["subscribe"]>[0]["update"]>[0]; type OwnedSubscription = { subscribe(observer: { snapshot(snapshot: T): void; update(message: Message): void; error?(error: unknown): void }): () => void; release(): Promise; diff --git a/progress/client/errors.ts b/progress/client/errors.ts index 8d03723c..57f29213 100644 --- a/progress/client/errors.ts +++ b/progress/client/errors.ts @@ -2,5 +2,10 @@ export function errorText(error: unknown, fallback: string): string { const message = (error as { message?: unknown } | null)?.message; if (typeof message !== "string") return fallback; - return message.replace(/^Request failed: /, "").replace(/ requestType=\S+(?: code=\S+)?$/, "").trim() || fallback; + return ( + message + .replace(/^Request failed: /, "") + .replace(/ requestType=\S+(?: code=\S+)?$/, "") + .trim() || fallback + ); } diff --git a/progress/client/history.tsx b/progress/client/history.tsx index 9624fc1e..ba75578d 100644 --- a/progress/client/history.tsx +++ b/progress/client/history.tsx @@ -13,12 +13,7 @@ type Colors = PluginWorkspacePanelProps["theme"]["colors"]; // Run history stays on this computer unless the repo opts in. This quiet row // is the only place that changes it; nothing in the repo changes until then. -export function HistoryRow({ colors, workspaceId, directory, savedTo }: { - colors: Colors; - workspaceId: string; - directory: string; - savedTo: string | null; -}) { +export function HistoryRow({ colors, workspaceId, directory, savedTo }: { colors: Colors; workspaceId: string; directory: string; savedTo: string | null }) { const { messages: m } = useProgressLanguage(); const [picking, setPicking] = useState(false); const set = useRpc(setHistoryFolder); @@ -35,35 +30,79 @@ export function HistoryRow({ colors, workspaceId, directory, savedTo }: { // While saving, the button that started it says so. const busy = mutation.isPending ? (mutation.variables === null ? "stop" : "pick") : null; const actions: { label: string; busyLabel: string; kind: "pick" | "stop"; onPress(): void }[] = savedTo - ? [{ label: m.changeFolder, busyLabel: m.saving, kind: "pick", onPress: () => setPicking(true) }, { label: m.stopSaving, busyLabel: m.stopping, kind: "stop", onPress: () => mutation.mutate(null) }] + ? [ + { label: m.changeFolder, busyLabel: m.saving, kind: "pick", onPress: () => setPicking(true) }, + { label: m.stopSaving, busyLabel: m.stopping, kind: "stop", onPress: () => mutation.mutate(null) }, + ] : [{ label: m.saveToRepo, busyLabel: m.saving, kind: "pick", onPress: () => setPicking(true) }]; return ( - + + + - {savedTo ? <>{m.historyInRepo[0]}{savedTo}{m.historyInRepo[1]} : m.localHistory} + {savedTo ? ( + <> + {m.historyInRepo[0]} + {savedTo} + {m.historyInRepo[1]} + + ) : ( + m.localHistory + )} {actions.map((action) => ( - ({ paddingHorizontal: 8, paddingVertical: 4, borderRadius: 4, opacity: mutation.isPending ? 0.7 : 1, - backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent" })}> - {busy === action.kind ? action.busyLabel : action.label} + ({ + paddingHorizontal: 8, + paddingVertical: 4, + borderRadius: 4, + opacity: mutation.isPending ? 0.7 : 1, + backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent", + })} + > + + {busy === action.kind ? action.busyLabel : action.label} + ))} - setPicking(false)} onPick={(folder) => { setPicking(false); mutation.mutate(folder); }} /> + setPicking(false)} + onPick={(folder) => { + setPicking(false); + mutation.mutate(folder); + }} + /> ); } // Browses the repo's folders on the daemon host. A new folder only needs a // name: it's made the first time a run is saved there. -function FolderPicker({ colors, workspaceId, directory, open, start, onClose, onPick }: { +function FolderPicker({ + colors, + workspaceId, + directory, + open, + start, + onClose, + onPick, +}: { colors: Colors; workspaceId: string; directory: string; @@ -85,78 +124,190 @@ function FolderPicker({ colors, workspaceId, directory, open, start, onClose, on }); const join = (name: string) => (at ? `${at}/${name}` : name); const crumbs = at ? at.split("/") : []; - const close = () => { setNaming(null); setAt(parentOf(start)); onClose(); }; + const close = () => { + setNaming(null); + setAt(parentOf(start)); + onClose(); + }; const newName = naming?.trim().replace(/\/+$/, "") ?? ""; return ( - } open={open} onOpenChange={(next) => { if (!next) close(); }}> + } + open={open} + onOpenChange={(next) => { + if (!next) close(); + }} + > {/* Paseo sizes a non-scrolling dialog to 85% of the window, so let it size to its content; the list's own height cap keeps the buttons in view. */} - - - {m.historyFolderHint} - - - {[m.repoTop, ...crumbs].map((crumb, index) => ( - - {index ? : null} - { setNaming(null); setAt(crumbs.slice(0, index).join("/")); }} - style={({ pressed, hovered }) => ({ paddingHorizontal: 4, paddingVertical: 2, borderRadius: 4, - backgroundColor: index === crumbs.length ? "transparent" : pressed ? colors.border : hovered ? colors.surface2 : "transparent" })}> - {crumb} - - - ))} - + + {m.historyFolderHint} + + {[m.repoTop, ...crumbs].map((crumb, index) => ( + + {index ? : null} + { + setNaming(null); + setAt(crumbs.slice(0, index).join("/")); + }} + style={({ pressed, hovered }) => ({ + paddingHorizontal: 4, + paddingVertical: 2, + borderRadius: 4, + backgroundColor: index === crumbs.length ? "transparent" : pressed ? colors.border : hovered ? colors.surface2 : "transparent", + })} + > + + {crumb} + + + + ))} + - {/* Only the list scrolls, so Use and Cancel stay in view in a big repo. */} - - {listed.isPending ? : null} - {listed.data?.folders.map((name) => ( - { setNaming(null); setAt(join(name)); }} - style={{ flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 8, paddingVertical: 6, borderRadius: 6 }}> - - {name} - - - ))} - {listed.data && !listed.data.folders.length ? ( - {m.noFolders} - ) : null} - {listed.error ? {errorText(listed.error, m.listFoldersFailure)} : null} - + {/* Only the list scrolls, so Use and Cancel stay in view in a big repo. */} + + {listed.isPending ? ( + + ) : null} + {listed.data?.folders.map((name) => ( + { + setNaming(null); + setAt(join(name)); + }} + style={{ flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 8, paddingVertical: 6, borderRadius: 6 }} + > + + + {name} + + + + ))} + {listed.data && !listed.data.folders.length ? ( + {m.noFolders} + ) : null} + {listed.error ? ( + + {errorText(listed.error, m.listFoldersFailure)} + + ) : null} + - {naming === null ? ( - setNaming("")} - style={({ pressed, hovered }) => ({ alignSelf: "flex-start", flexDirection: "row", alignItems: "center", gap: 6, paddingHorizontal: 8, paddingVertical: 5, borderRadius: 6, backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent" })}> - - {m.newFolder} - - ) : ( - - { if (newName) onPick(join(newName)); }} - autoCapitalize="none" autoCorrect={false} spellCheck={false} accessibilityLabel={m.newFolderName} placeholder="progress-history" placeholderTextColor={colors.foregroundMuted} - style={{ flex: 1, color: colors.foreground, fontSize: 12, lineHeight: 16, paddingHorizontal: 8, paddingVertical: 6, borderRadius: 6, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.surface1 }} /> - onPick(join(newName))} - style={({ pressed, hovered }) => ({ paddingHorizontal: 10, paddingVertical: 6, borderRadius: 6, backgroundColor: colors.accent, opacity: !newName ? 0.5 : pressed ? 0.7 : hovered ? 0.85 : 1 })}> - {m.useNewFolder} + {naming === null ? ( + setNaming("")} + style={({ pressed, hovered }) => ({ + alignSelf: "flex-start", + flexDirection: "row", + alignItems: "center", + gap: 6, + paddingHorizontal: 8, + paddingVertical: 5, + borderRadius: 6, + backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent", + })} + > + + {m.newFolder} - - )} + ) : ( + + { + if (newName) onPick(join(newName)); + }} + autoCapitalize="none" + autoCorrect={false} + spellCheck={false} + accessibilityLabel={m.newFolderName} + placeholder="progress-history" + placeholderTextColor={colors.foregroundMuted} + style={{ + flex: 1, + color: colors.foreground, + fontSize: 12, + lineHeight: 16, + paddingHorizontal: 8, + paddingVertical: 6, + borderRadius: 6, + borderWidth: 1, + borderColor: colors.border, + backgroundColor: colors.surface1, + }} + /> + onPick(join(newName))} + style={({ pressed, hovered }) => ({ + paddingHorizontal: 10, + paddingVertical: 6, + borderRadius: 6, + backgroundColor: colors.accent, + opacity: !newName ? 0.5 : pressed ? 0.7 : hovered ? 0.85 : 1, + })} + > + {m.useNewFolder} + + + )} - - {at ? null : {m.pickFolderHint}} - ({ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 6, backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent" })}> - {m.cancel} - - onPick(at)} outerStyle={{ flexShrink: 1 }} - style={({ pressed, hovered }) => ({ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 6, backgroundColor: colors.accent, opacity: !at ? 0.5 : pressed ? 0.7 : hovered ? 0.85 : 1 })}> - {at ? m.useNamedFolder(crumbs[crumbs.length - 1]) : m.useFolder} - - - + + {at ? null : {m.pickFolderHint}} + ({ + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: 6, + backgroundColor: pressed ? colors.border : hovered ? colors.surface2 : "transparent", + })} + > + {m.cancel} + + onPick(at)} + outerStyle={{ flexShrink: 1 }} + style={({ pressed, hovered }) => ({ + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: 6, + backgroundColor: colors.accent, + opacity: !at ? 0.5 : pressed ? 0.7 : hovered ? 0.85 : 1, + })} + > + + {at ? m.useNamedFolder(crumbs[crumbs.length - 1]) : m.useFolder} + + + + ); diff --git a/progress/client/i18n.test.ts b/progress/client/i18n.test.ts index 894f7090..0c1f5089 100644 --- a/progress/client/i18n.test.ts +++ b/progress/client/i18n.test.ts @@ -12,8 +12,10 @@ const plain = (value: unknown) => JSON.parse(JSON.stringify(value)); test("explicit preferences override system locale without selecting Simplified for Traditional Chinese", () => { const { resolveLocale } = clientHarness(directory).load("client/i18n.ts"); - for (const system of ["zh", "zh-CN", "zh_SG", "zh-Hans", "zh-Hans-CN", "ZH-hans-sg", "zh-Hans-HK", "zh-Hans-TW", "zh-u-nu-hanidec", "zh-CN-u-ca-chinese"]) assert.equal(resolveLocale("system", system), "zh-CN", system); - for (const system of ["", "en-US", "fr-FR", "zh-TW", "zh-HK", "zh-MO", "zh-Hant", "zh-Hant-CN", "zh-Hant-TW-u-nu-hanidec", "zh-US"]) assert.equal(resolveLocale("system", system), "en", system); + for (const system of ["zh", "zh-CN", "zh_SG", "zh-Hans", "zh-Hans-CN", "ZH-hans-sg", "zh-Hans-HK", "zh-Hans-TW", "zh-u-nu-hanidec", "zh-CN-u-ca-chinese"]) + assert.equal(resolveLocale("system", system), "zh-CN", system); + for (const system of ["", "en-US", "fr-FR", "zh-TW", "zh-HK", "zh-MO", "zh-Hant", "zh-Hant-CN", "zh-Hant-TW-u-nu-hanidec", "zh-US"]) + assert.equal(resolveLocale("system", system), "en", system); assert.equal(resolveLocale("en", "zh-CN"), "en"); assert.equal(resolveLocale("zh-CN", "en-US"), "zh-CN"); }); @@ -54,7 +56,16 @@ test("client duration boundaries localize while shared CLI formatters remain Eng const h = clientHarness(directory); const { formatClientMinutes, formatClientWorkDone, formatClientAgo } = h.load("client/i18n.ts"); const { formatMinutes, formatWorkDone } = h.load("shared/format.ts"); - const cases: Array<[number, string, string]> = [[-1, "<1m", "<1 分钟"], [0, "<1m", "<1 分钟"], [0.99, "<1m", "<1 分钟"], [1, "1m", "1 分钟"], [59.9, "59m", "59 分钟"], [60, "1h", "1 小时"], [61, "1h 1m", "1 小时 1 分钟"], [120, "2h", "2 小时"]]; + const cases: Array<[number, string, string]> = [ + [-1, "<1m", "<1 分钟"], + [0, "<1m", "<1 分钟"], + [0.99, "<1m", "<1 分钟"], + [1, "1m", "1 分钟"], + [59.9, "59m", "59 分钟"], + [60, "1h", "1 小时"], + [61, "1h 1m", "1 小时 1 分钟"], + [120, "2h", "2 小时"], + ]; for (const [minutes, en, zh] of cases) { assert.equal(formatClientMinutes("en", minutes), en); assert.equal(formatClientMinutes("zh-CN", minutes), zh); @@ -86,13 +97,35 @@ test("headlines derive from structured counts while preserving server copy and c const h = clientHarness(directory); const { clientHeadline } = h.load("client/i18n.ts"); const { EMPTY_DASHBOARD } = h.load("shared/dashboard.ts"); - const ticket = (status: Ticket["status"]): Ticket => ({ id: "T01", title: "Authored title", estimateMin: 10, status, statusSince: "2026-10-21T00:00:00Z", history: [] }); - const dashboard: Dashboard = { ...EMPTY_DASHBOARD, run: { title: "Authored run", startedAt: "2026-10-21T00:00:00Z", itemLabel: "API Task" }, - tickets: [ticket("done"), ticket("working"), ticket("skipped")], headline: [{ text: "Server copy", tone: "normal" }], - questions: { open: [{ id: "Q1", title: "Choice", question: "Question?", options: [], recommended: "A", state: "waiting", files: [], askedAt: "2026-10-21T00:00:00Z" }], answered: [] }, - stuck: [{ kind: "manual", key: "manual:S1", id: "S1", title: "Authored blocker", reason: "Authored reason", since: "2026-10-21T00:00:00Z" }] }; - assert.deepEqual(plain(clientHeadline("en", dashboard)), [{ text: "1 of 2 api tasks done", tone: "normal" }, { text: "1 question waiting for you", tone: "normal" }, { text: "1 stuck", tone: "danger" }]); - assert.deepEqual(plain(clientHeadline("zh-CN", dashboard)), [{ text: "API Task 已完成 1/2", tone: "normal" }, { text: "1 个问题等待你的回答", tone: "normal" }, { text: "1 项卡住", tone: "danger" }]); + const ticket = (status: Ticket["status"]): Ticket => ({ + id: "T01", + title: "Authored title", + estimateMin: 10, + status, + statusSince: "2026-10-21T00:00:00Z", + history: [], + }); + const dashboard: Dashboard = { + ...EMPTY_DASHBOARD, + run: { title: "Authored run", startedAt: "2026-10-21T00:00:00Z", itemLabel: "API Task" }, + tickets: [ticket("done"), ticket("working"), ticket("skipped")], + headline: [{ text: "Server copy", tone: "normal" }], + questions: { + open: [{ id: "Q1", title: "Choice", question: "Question?", options: [], recommended: "A", state: "waiting", files: [], askedAt: "2026-10-21T00:00:00Z" }], + answered: [], + }, + stuck: [{ kind: "manual", key: "manual:S1", id: "S1", title: "Authored blocker", reason: "Authored reason", since: "2026-10-21T00:00:00Z" }], + }; + assert.deepEqual(plain(clientHeadline("en", dashboard)), [ + { text: "1 of 2 api tasks done", tone: "normal" }, + { text: "1 question waiting for you", tone: "normal" }, + { text: "1 stuck", tone: "danger" }, + ]); + assert.deepEqual(plain(clientHeadline("zh-CN", dashboard)), [ + { text: "API Task 已完成 1/2", tone: "normal" }, + { text: "1 个问题等待你的回答", tone: "normal" }, + { text: "1 项卡住", tone: "danger" }, + ]); assert.equal(dashboard.headline[0].text, "Server copy"); }); @@ -100,12 +133,17 @@ test("timeline descriptors preserve English labels and distinguish Added from la const h = clientHarness(directory); const { ticketTimeline } = h.load("shared/ticket-story.ts"); const { timelineLabel, messagesFor } = h.load("client/i18n.ts"); - const steps: TimelineStep[] = ticketTimeline({ history: [ - { at: "2026-10-21T00:00:00Z", status: "not_started" }, - { at: "2026-10-21T00:01:00Z", status: "working", stage: "Authored stage" }, - { at: "2026-10-21T00:02:00Z", status: "not_started" }, - { at: "2026-10-21T00:03:00Z", status: "done" }, - ] }, Date.parse("2026-10-21T00:04:00Z")); + const steps: TimelineStep[] = ticketTimeline( + { + history: [ + { at: "2026-10-21T00:00:00Z", status: "not_started" }, + { at: "2026-10-21T00:01:00Z", status: "working", stage: "Authored stage" }, + { at: "2026-10-21T00:02:00Z", status: "not_started" }, + { at: "2026-10-21T00:03:00Z", status: "done" }, + ], + }, + Date.parse("2026-10-21T00:04:00Z"), + ); assert.deepEqual(plain(steps.map((step) => timelineLabel(messagesFor("en"), step.label))), ["Added", "Authored stage stage", "Back to not started", "Done"]); assert.deepEqual(plain(steps.map((step) => timelineLabel(messagesFor("zh-CN"), step.label))), ["已添加", "Authored stage 阶段", "恢复为未开始", "已完成"]); }); @@ -118,21 +156,42 @@ function languageHarness() { const cleanups: Array<() => void> = []; const definitions: string[] = []; const h = clientHarness(directory, { - react: { ...React, useContext: () => current, useEffect: (effect: () => void) => effects.push(effect), - useSyncExternalStore: (subscribe: (listener: () => void) => () => void, snapshot: () => unknown) => { cleanups.push(subscribe(() => {})); return snapshot(); } }, - "@getpaseo/plugin/client": { useSettings: (definition: { id: string }) => { - definitions.push(definition.id); - return status === "ready" ? { status, values: { language: preference }, revision: "r1" } : { status, error: "Raw host error" }; - } }, + react: { + ...React, + useContext: () => current, + useEffect: (effect: () => void) => effects.push(effect), + useSyncExternalStore: (subscribe: (listener: () => void) => () => void, snapshot: () => unknown) => { + cleanups.push(subscribe(() => {})); + return snapshot(); + }, + }, + "@getpaseo/plugin/client": { + useSettings: (definition: { id: string }) => { + definitions.push(definition.id); + return status === "ready" ? { status, values: { language: preference }, revision: "r1" } : { status, error: "Raw host error" }; + }, + }, }); function renderProvider() { const rendered = h.load("client/language.tsx").ProgressLanguageProvider({ children: null }); current = rendered.props.value; return rendered.props.value; } - return { h, effects, cleanups, definitions, renderProvider, - setLanguage(value: ProgressLocale) { preference = value; renderProvider(); }, - setStatus(value: string) { status = value; return renderProvider(); } }; + return { + h, + effects, + cleanups, + definitions, + renderProvider, + setLanguage(value: ProgressLocale) { + preference = value; + renderProvider(); + }, + setStatus(value: string) { + status = value; + return renderProvider(); + }, + }; } test("pending and failed settings reads leave content usable, and a saved override updates the provider", () => { diff --git a/progress/client/i18n.ts b/progress/client/i18n.ts index d9e9ea6b..49e0b0f9 100644 --- a/progress/client/i18n.ts +++ b/progress/client/i18n.ts @@ -77,10 +77,15 @@ export function clientHeadline(locale: ProgressLocale, dashboard: Dashboard): He export function timelineLabel(m: ProgressMessages, label: TimelineLabel): string { switch (label.kind) { - case "added": return m.added; - case "reset": return m.resetStatus; - case "stage": return m.stageLabel(label.stage); - case "status": return m.status[label.status]; - case "waiting": return m.waitingForTicket(label.id); + case "added": + return m.added; + case "reset": + return m.resetStatus; + case "stage": + return m.stageLabel(label.stage); + case "status": + return m.status[label.status]; + case "waiting": + return m.waitingForTicket(label.id); } } diff --git a/progress/client/launcher.tsx b/progress/client/launcher.tsx index 1c683a32..4a351fa8 100644 --- a/progress/client/launcher.tsx +++ b/progress/client/launcher.tsx @@ -5,7 +5,16 @@ import React from "react"; import { Text, View } from "react-native"; import { PressScale, Presence } from "./motion"; import { raised } from "./surfaces"; -import { getLauncherStatus, getSkillStatus, getToolsStatus, installLauncher, installSkill, type LauncherStatus, type SkillStatus, type ToolsState } from "../shared/rpc"; +import { + getLauncherStatus, + getSkillStatus, + getToolsStatus, + installLauncher, + installSkill, + type LauncherStatus, + type SkillStatus, + type ToolsState, +} from "../shared/rpc"; import { messagesFor, type ProgressMessages } from "./i18n"; import { errorText } from "./errors"; import { useProgressLanguage } from "./language"; @@ -111,7 +120,13 @@ export function SkillBanner({ colors, host }: { colors: Colors; host: PluginWork return ; } -function SetupBanner({ colors, icon, notice, pending, onPress }: { +function SetupBanner({ + colors, + icon, + notice, + pending, + onPress, +}: { colors: Colors; icon: string; notice: { text: string; action?: string } | null; @@ -120,20 +135,47 @@ function SetupBanner({ colors, icon, notice, pending, onPress }: { }) { const { messages: m } = useProgressLanguage(); return ( - {notice ? ( - - {/* Held on the first line: the text wraps to several lines in the Explorer pane. */} - - {notice.text} - {notice.action ? ( - ({ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 4, backgroundColor: colors.accent, opacity: pressed || pending ? 0.7 : hovered ? 0.85 : 1 })}> - - {pending ? m.installing : notice.action} + + {notice ? ( + + {/* Held on the first line: the text wraps to several lines in the Explorer pane. */} + + + + + {notice.text} - + {notice.action ? ( + ({ + paddingHorizontal: 10, + paddingVertical: 5, + borderRadius: 4, + backgroundColor: colors.accent, + opacity: pressed || pending ? 0.7 : hovered ? 0.85 : 1, + })} + > + {pending ? m.installing : notice.action} + + ) : null} + ) : null} - - ) : null} + ); } diff --git a/progress/client/lifecycle.test.ts b/progress/client/lifecycle.test.ts index 4f2d4180..b024789e 100644 --- a/progress/client/lifecycle.test.ts +++ b/progress/client/lifecycle.test.ts @@ -19,15 +19,28 @@ test("registers the Progress panel and a Command Center item that opens it as a assert.equal(item.title, "Open Progress"); item.onSelect({ openPanel: (id: string, options?: object) => h.client.openPanel(id, { workspaceId: "w", ...options }) }); assert.deepEqual(plain(h.openedPanels), [{ id: "progress", workspaceId: "w", location: "explorer" }], "Command Center opens the panel in Explorer"); - assert.deepEqual(plain(h.settingsScreens.map(({ id, title }) => ({ id, title }))), [{ id: "settings", title: "Settings" }], "the plugin has a Settings page in Paseo's Settings"); + assert.deepEqual( + plain(h.settingsScreens.map(({ id, title }) => ({ id, title }))), + [{ id: "settings", title: "Settings" }], + "the plugin has a Settings page in Paseo's Settings", + ); const [page] = h.screens; assert.equal(page.id, "page", "an HTML deliverable has a screen of its own"); assert.equal(page.title({ title: "How Mortly runs" }), "How Mortly runs", "the screen is titled after the deliverable"); - assert.deepEqual(plain(h.filePanels.map(({ id, files }) => ({ id, files }))), [{ id: "pdf", files: { extensions: ["pdf"] } }], "Progress shows PDFs opened in a tab"); + assert.deepEqual( + plain(h.filePanels.map(({ id, files }) => ({ id, files }))), + [{ id: "pdf", files: { extensions: ["pdf"] } }], + "Progress shows PDFs opened in a tab", + ); assert.equal(h.requests.length, 0, "nothing is read until a panel is shown"); stop(); - assert.ok(h.panels.every((panel) => panel.removed) && h.commandItems.every((entry) => entry.removed) && h.settingsScreens.every((entry) => entry.removed) && h.screens.every((entry) => entry.removed) - && h.filePanels.every((entry) => entry.removed)); + assert.ok( + h.panels.every((panel) => panel.removed) && + h.commandItems.every((entry) => entry.removed) && + h.settingsScreens.every((entry) => entry.removed) && + h.screens.every((entry) => entry.removed) && + h.filePanels.every((entry) => entry.removed), + ); }); test("on Android, PDFs opened in a tab keep Paseo's own panel", () => { @@ -224,7 +237,11 @@ test("a run shows a Progress pill until the panel is opened, then never again", const active = () => h.registrations.filter((entry) => !entry.removed) as unknown as Array<{ button: any }>; assert.equal(active()[0]?.button.label, "Progress"); active()[0].button.behavior.onPress(); - assert.deepEqual(JSON.parse(JSON.stringify(h.openedPanels)), [{ id: "progress", workspaceId: "w", location: "explorer" }], "pressing it opens the panel in Explorer"); + assert.deepEqual( + JSON.parse(JSON.stringify(h.openedPanels)), + [{ id: "progress", workspaceId: "w", location: "explorer" }], + "pressing it opens the panel in Explorer", + ); h.responses["progress.attention"] = run(false, 2); await h.tick(PILL_POLL_MS); @@ -269,7 +286,10 @@ test("local deliverable paths resolve against the workspace directory", () => { test("a failed request shows the handler's own words, without Paseo's log wrapper", () => { const { errorText } = clientHarness(directory).load("client/errors.ts"); - assert.equal(errorText(new Error("Request failed: Can't open files on steve-dev requestType=plugin.rpc.invoke.request code=handler_error"), "Could not open it"), "Can't open files on steve-dev"); + assert.equal( + errorText(new Error("Request failed: Can't open files on steve-dev requestType=plugin.rpc.invoke.request code=handler_error"), "Could not open it"), + "Can't open files on steve-dev", + ); assert.equal(errorText(new Error("shots/a.png no longer exists."), "Could not open it"), "shots/a.png no longer exists."); assert.equal(errorText("not an error", "Could not open it"), "Could not open it"); }); @@ -279,7 +299,10 @@ test("the install banner shows until the command is installed and reachable", () const { launcherNotice } = h.load("client/launcher.tsx"); const path = "/Users/s/.local/bin/paseo-progress"; assert.equal(launcherNotice({ path, state: "missing", onPath: true }).action, "Install command"); - assert.match(launcherNotice({ path, state: "missing", onPath: true }).text, /isn't installed yet\. Installing adds it at \/Users\/s\/\.local\/bin\/paseo-progress/); + assert.match( + launcherNotice({ path, state: "missing", onPath: true }).text, + /isn't installed yet\. Installing adds it at \/Users\/s\/\.local\/bin\/paseo-progress/, + ); assert.equal(launcherNotice({ path, state: "outdated", onPath: true }).action, "Update command"); assert.equal(launcherNotice({ path, state: "foreign", onPath: true }).action, undefined, "never offers to replace another file"); assert.equal(launcherNotice({ path, state: "current", onPath: true }), null); @@ -304,8 +327,11 @@ test("with Paseo tools on, the command banner only offers an optional install; o }); test("app-side code imports no Node modules, which Paseo refuses to bundle into the app", () => { - const files = ["client", "shared"].flatMap((folder) => readdirSync(join(directory, folder)) - .filter((name) => /\.tsx?$/.test(name) && !name.endsWith(".test.ts")).map((name) => join(folder, name))); + const files = ["client", "shared"].flatMap((folder) => + readdirSync(join(directory, folder)) + .filter((name) => /\.tsx?$/.test(name) && !name.endsWith(".test.ts")) + .map((name) => join(folder, name)), + ); const offenders = files.filter((file) => /from\s+["']node:|require\(["']node:/.test(readFileSync(join(directory, file), "utf8"))); assert.deepEqual(offenders, []); }); diff --git a/progress/client/locales/en.ts b/progress/client/locales/en.ts index 08fa8c3e..b8c7b582 100644 --- a/progress/client/locales/en.ts +++ b/progress/client/locales/en.ts @@ -2,30 +2,30 @@ import type { ProgressMessages } from "../messages"; export const messages: ProgressMessages = { status: { - "not_started": "Not started", - "working": "Working", - "blocked": "Blocked", - "done": "Done", - "skipped": "Skipped" + not_started: "Not started", + working: "Working", + blocked: "Blocked", + done: "Done", + skipped: "Skipped", }, questionModes: { - "stop": { - "label": "Stop", - "hint": "Agents stop all work when they ask, until you answer." + stop: { + label: "Stop", + hint: "Agents stop all work when they ask, until you answer.", }, "work-around": { - "label": "Work around", - "hint": "Agents hold what your answer affects and keep working on the rest." + label: "Work around", + hint: "Agents hold what your answer affects and keep working on the rest.", }, "keep-building": { - "label": "Keep building", - "hint": "Agents build their recommended option while you decide, and change course if you pick another. Big questions still wait." - } + label: "Keep building", + hint: "Agents build their recommended option while you decide, and change course if you pick another. Big questions still wait.", + }, }, noteKinds: { - "new": "New", - "improved": "Improved", - "fixed": "Fixed" + new: "New", + improved: "Improved", + fixed: "Fixed", }, loading: "Loading…", loadingProgress: "Loading progress", @@ -33,7 +33,8 @@ export const messages: ProgressMessages = { openSettings: "Open Progress settings", noProgress: "No progress recorded yet", emptyIntro: ["An agent working in this worktree records progress with the ", " command. It shows up here as soon as the first run starts."], - emptyIntroTools: "An agent working in this worktree records progress with the Progress tools Paseo gives it. It shows up here as soon as the first run starts.", + emptyIntroTools: + "An agent working in this worktree records progress with the Progress tools Paseo gives it. It shows up here as soon as the first run starts.", toolsOn: "Agents record progress with Paseo tools. The paseo-progress command is a fallback for agents without them.", toolsNote: [ "Let agents record progress without the command.", @@ -175,7 +176,8 @@ export const messages: ProgressMessages = { systemLanguage: "System", readProgressError: (error: string) => `Could not read progress: ${error}`, savedOutside: ["Progress is saved outside the repo, in ", ", so git never sees it."], - staleWarning: (duration: string) => `Possibly stale. No update for ${duration}. The work may have stopped, so working items show a warning until the next update.`, + staleWarning: (duration: string) => + `Possibly stale. No update for ${duration}. The work may have stopped, so working items show a warning until the next update.`, itemHeading: (label: string) => `${label}s`, noItems: (label: string) => `No ${label.toLowerCase()}s yet.`, skippedLines: (count: number, file: string) => `Skipped ${count} ${count === 1 ? "line" : "lines"} in ${file}: `, @@ -189,7 +191,7 @@ export const messages: ProgressMessages = { details: (id: string) => `${id} details`, stageStarted: (stage: string) => `${stage} stage started `, waitsFor: (title: string) => `Waits for ${title}`, - hasDeliverables: (count: number) => count === 1 ? "Has a deliverable" : `Has ${count} deliverables`, + hasDeliverables: (count: number) => (count === 1 ? "Has a deliverable" : `Has ${count} deliverables`), questionCount: (count: number) => `${count} ${count === 1 ? "question" : "questions"}`, shortQuestions: (count: number) => `${count}Q`, stuckCount: (count: number) => `${count} stuck`, @@ -208,7 +210,8 @@ export const messages: ProgressMessages = { waitingForTicket: (id: string) => `Waiting for ${id}`, openItem: (title: string) => `Open ${title}`, workedEstimate: (worked: string, estimate: string) => `Worked ${worked} of a ${estimate} estimate`, - byTimeHint: (id: string, label: string) => `Items marked “by time” weren't tagged to ${id}; they happened while it was the ${label.toLowerCase()} being worked on.`, + byTimeHint: (id: string, label: string) => + `Items marked “by time” weren't tagged to ${id}; they happened while it was the ${label.toLowerCase()} being worked on.`, openAgentChat: (title: string) => `Open the chat with ${title}`, stageLabel: (stage: string) => `${stage} stage`, soFar: (duration: string) => `${duration} so far`, @@ -230,11 +233,13 @@ export const messages: ProgressMessages = { useNamedFolder: (name: string) => `Use ${name}`, launcherMissing: (path: string) => `Agents record progress with the paseo-progress command, which isn't installed yet. Installing adds it at ${path}`, launcherOutdated: (path: string) => `An older paseo-progress command is installed at ${path}.`, - launcherForeign: (path: string) => `Something else already exists at ${path}, so the plugin won't install there. The README shows how to install it elsewhere.`, + launcherForeign: (path: string) => + `Something else already exists at ${path}, so the plugin won't install there. The README shows how to install it elsewhere.`, launcherOffPath: (path: string) => `paseo-progress is installed, but its folder isn't on the PATH Paseo uses, so agents need the full path: ${path}`, launcherInstalled: (path: string) => `Installed paseo-progress at ${path}`, skillSkipped: (paths: string) => ` Something else is already at ${paths}, so the plugin leaves it alone.`, - skillMissing: (paths: string, skipped: string) => `Agents learn when to record progress from the paseo-progress skill, which isn't installed yet. Installing adds a link in ${paths}.${skipped}`, + skillMissing: (paths: string, skipped: string) => + `Agents learn when to record progress from the paseo-progress skill, which isn't installed yet. Installing adds a link in ${paths}.${skipped}`, skillOutdated: (paths: string, skipped: string) => `The paseo-progress skill in ${paths} points to a copy of the plugin Paseo no longer runs.${skipped}`, resetTo: (label: string) => `Go back to ${label}`, ago: (duration: string) => `${duration} ago`, diff --git a/progress/client/locales/zh-CN.ts b/progress/client/locales/zh-CN.ts index 7d151c76..3a1845a7 100644 --- a/progress/client/locales/zh-CN.ts +++ b/progress/client/locales/zh-CN.ts @@ -2,30 +2,30 @@ import type { ProgressMessages } from "../messages"; export const messages: ProgressMessages = { status: { - "not_started": "未开始", - "working": "进行中", - "blocked": "受阻", - "done": "已完成", - "skipped": "已跳过" + not_started: "未开始", + working: "进行中", + blocked: "受阻", + done: "已完成", + skipped: "已跳过", }, questionModes: { - "stop": { - "label": "停止", - "hint": "智能体提问后会停止所有工作,直到你回答。" + stop: { + label: "停止", + hint: "智能体提问后会停止所有工作,直到你回答。", }, "work-around": { - "label": "继续其他工作", - "hint": "智能体暂停受回答影响的工作,继续处理其余事项。" + label: "继续其他工作", + hint: "智能体暂停受回答影响的工作,继续处理其余事项。", }, "keep-building": { - "label": "继续构建", - "hint": "你做决定期间,智能体会先按推荐方案构建;若你选择其他方案,则调整方向。重大问题仍会等待回答。" - } + label: "继续构建", + hint: "你做决定期间,智能体会先按推荐方案构建;若你选择其他方案,则调整方向。重大问题仍会等待回答。", + }, }, noteKinds: { - "new": "新增", - "improved": "改进", - "fixed": "修复" + new: "新增", + improved: "改进", + fixed: "修复", }, loading: "加载中…", loadingProgress: "正在加载进度", diff --git a/progress/client/motion.tsx b/progress/client/motion.tsx index ec3fb13e..528d651f 100644 --- a/progress/client/motion.tsx +++ b/progress/client/motion.tsx @@ -25,7 +25,13 @@ export function useReducedMotion(): boolean { } // A button that scales to 0.96 while pressed. `static` turns the scale off. -export function PressScale({ static: isStatic, style, outerStyle, children, ...props }: Omit & { +export function PressScale({ + static: isStatic, + style, + outerStyle, + children, + ...props +}: Omit & { static?: boolean; // Reaches the pressable itself, e.g. to focus it. ref?: React.Ref; @@ -40,14 +46,29 @@ export function PressScale({ static: isStatic, style, outerStyle, children, ...p const [pressed, setPressed] = useState(false); const [hovered, setHovered] = useState(false); return ( - { setHovered(true); props.onHoverIn?.(event); }} - onHoverOut={(event) => { setHovered(false); props.onHoverOut?.(event); }} - onPressIn={(event) => { setPressed(true); if (!isStatic) to(0.96); props.onPressIn?.(event); }} - onPressOut={(event) => { setPressed(false); if (!isStatic) to(1); props.onPressOut?.(event); }}> - - {children} - + { + setHovered(true); + props.onHoverIn?.(event); + }} + onHoverOut={(event) => { + setHovered(false); + props.onHoverOut?.(event); + }} + onPressIn={(event) => { + setPressed(true); + if (!isStatic) to(0.96); + props.onPressIn?.(event); + }} + onPressOut={(event) => { + setPressed(false); + if (!isStatic) to(1); + props.onPressOut?.(event); + }} + > + {children} ); } @@ -123,7 +144,13 @@ export function Presence({ show, order = 0, children }: { show: boolean; order?: return; } const firstLoad = start !== null && Date.now() - start < FIRST_LOAD_MS; - const animation = Animated.timing(enter, { toValue: 1, duration: ENTER_MS, delay: firstLoad ? order * STAGGER_MS : 0, easing: easeOut(), useNativeDriver: nativeDriver() }); + const animation = Animated.timing(enter, { + toValue: 1, + duration: ENTER_MS, + delay: firstLoad ? order * STAGGER_MS : 0, + easing: easeOut(), + useNativeDriver: nativeDriver(), + }); setMoving(true); animation.start(({ finished }) => finished && setMoving(false)); return () => animation.stop(); @@ -159,9 +186,6 @@ export function Presence({ show, order = 0, children }: { show: boolean; order?: function blurStyle(enter: Animated.Value, exit: Animated.Value) { // Blur is 4px at either end of the motion and 0 at rest. - const amount = Animated.add( - enter.interpolate({ inputRange: [0, 1], outputRange: [4, 0] }), - exit.interpolate({ inputRange: [0, 1], outputRange: [0, 4] }), - ); + const amount = Animated.add(enter.interpolate({ inputRange: [0, 1], outputRange: [4, 0] }), exit.interpolate({ inputRange: [0, 1], outputRange: [0, 4] })); return { filter: amount.interpolate({ inputRange: [0, 4], outputRange: ["blur(0px)", "blur(4px)"] }) }; } diff --git a/progress/client/page-screen.tsx b/progress/client/page-screen.tsx index 1652fb2d..d09bf935 100644 --- a/progress/client/page-screen.tsx +++ b/progress/client/page-screen.tsx @@ -14,7 +14,11 @@ export function addPageScreen(client: PluginClientContext) { const stop = client.addScreen({ id: PAGE_SCREEN_ID, title: (params) => params.title ?? "", - Component: (props) => , + Component: (props) => ( + + + + ), }); return () => { setPageOpener(null); @@ -79,9 +83,24 @@ function PageScreen({ params, theme: { colors }, navigation }: PluginScreenProps {/* `allow-scripts` alone, as in Paseo's own HTML preview: the page runs its scripts (and loads them from the web, so no CSP) in an opaque origin that can't reach Paseo's DOM or storage, navigate the app, open windows or submit forms. */} -