diff --git a/bun.lock b/bun.lock index 9734104eefd6..16ac0b6bfa01 100644 --- a/bun.lock +++ b/bun.lock @@ -1065,6 +1065,7 @@ "@tanstack/virtual-core@3.17.8": "patches/@tanstack%2Fvirtual-core@3.17.8.patch", "@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch", "electron-updater@6.8.9": "patches/electron-updater@6.8.9.patch", + "@kobalte/core@0.13.13": "patches/@kobalte%2Fcore@0.13.13.patch", "pacote@21.5.1": "patches/pacote@21.5.1.patch", "@opentunnel/protocol@0.6.1": "patches/@opentunnel%2Fprotocol@0.6.1.patch", "@npmcli/agent@4.0.2": "patches/@npmcli%2Fagent@4.0.2.patch", @@ -1098,7 +1099,7 @@ "@effect/platform-node-shared": "4.1.0", "@effect/sql-sqlite-bun": "4.1.0", "@effect/sql-sqlite-node": "4.1.0", - "@hona/strobe": "0.34.0", + "@hona/strobe": "0.39.0", "@kobalte/core": "0.13.13", "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", @@ -1641,19 +1642,19 @@ "@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="], - "@hona/strobe": ["@hona/strobe@0.34.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.34.0", "@hona/strobe-darwin-x64": "0.34.0", "@hona/strobe-linux-arm64": "0.34.0", "@hona/strobe-linux-x64": "0.34.0", "@hona/strobe-win32-arm64": "0.34.0", "@hona/strobe-win32-x64": "0.34.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-3zh8ptLWFd1NP/uMRwLx7WexuoYmlLkQBdkkfMQe7Ntgh+jT2MhwQOiJ5DARL0x9ehEefYlex3VggQv5oV+mUw=="], + "@hona/strobe": ["@hona/strobe@0.39.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.39.0", "@hona/strobe-darwin-x64": "0.39.0", "@hona/strobe-linux-arm64": "0.39.0", "@hona/strobe-linux-x64": "0.39.0", "@hona/strobe-win32-arm64": "0.39.0", "@hona/strobe-win32-x64": "0.39.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-s2mHqIkmPJlXQMzG3WIy67rjiXR8vQ0IEvGdC5hq6MvXSkuhpnBcTS/OmcwMB7mcKiK/pXF1o1v3Hh2RjVpEmQ=="], - "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.34.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-uk67cN/3OfXsXWsADG8vTZluuxyqTS+/A9o3K72F90nJVR4zKE31rGDfjSjvzItNpITe5wkQPOkXWXwh4bC5sg=="], + "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.39.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+7ZxFUoaBGGlLmEYfU0cGwCxX9ipHB9Zg5NfaV8ZWPbUnqB5BdhgeAVpFbWI/2kJWvqx/HAv/uvCm3jhGfw0VA=="], - "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.34.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-n0aSQ1/I9RmC5K3n4LxG7AvFa3Jieib6KQApP1Y0s/hj+x13ad4taf3gNf8F2YN7VVW050ASVf2cl8T3YZbYcA=="], + "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.39.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-zAiKXHeF8jPI67o+tEcHYaPdX/myroa0OhUrnMlLiR90dwLTqcNz1BooPhFz9w4e5/gxMLmcGdsJRooAVgymTg=="], - "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.34.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-WtqYcbgZyiP1Uk16dPW7lSRaHC87sn+9lgC9wV5ZHKPjQA3o+EZKik+yKNSJF9dRWzMm+brySf78XpMWxGv0jA=="], + "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.39.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-jtibTr5ExvxMK38A5kKflBI4zbm4yAxUK8oy1Bk5Esr+a1myZMzM5uRIyS/InGR50c8ZCJg6NzFIXsRJIKJEQw=="], - "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.34.0", "", { "os": "linux", "cpu": "x64" }, "sha512-mHBSonDppJzJ/n80gkyqg4fcNqokQgvH26p3CqLk38r8DFtunzYf0FqwcpXbTmxs1z3JD7ToffNtJPky3jb7xg=="], + "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.39.0", "", { "os": "linux", "cpu": "x64" }, "sha512-t0plZMADXWOrWmvbBtiinExpm1fcqTdyto9zphkjE1j0U1Yg+jd7rXtrlTbO53KY+PTBBtuasr5/unWTpFocmg=="], - "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.34.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-XwYdRJFDuj90jDcv2XmBQ8HAyRCoK6ms2RfztT5kuPgGeQdbH2Wi/yNz/e0akHvlg8RigziJ9QYeHdjfzzTgOQ=="], + "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.39.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-z9HZAOgl7Gkq/bFlPDKrIQ6LdT4jIpdvR53gid4CeTsOZkc3AwGvSzvnnVwk4KBjS1JFZe0rtB8lvSjj2gfxsw=="], - "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.34.0", "", { "os": "win32", "cpu": "x64" }, "sha512-moHbYiWex//RLEEhHUaHb4ec9bpmxy4A/YeIfgGccFjgf9VmPmvxNhuccM6gO72KNTcKJsCITqQO9Adr58bCbw=="], + "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.39.0", "", { "os": "win32", "cpu": "x64" }, "sha512-eii01I8fg0G+5G5cSfSMqmdX/PzrB09FfPOpj1zuPTSMZcch+UptK3Sr8v99Kczl7jVGx5TdGKkCMWUoOwiEWA=="], "@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="], diff --git a/docs/sync-2026-11-13-dev.md b/docs/sync-2026-11-13-dev.md new file mode 100644 index 000000000000..89c1a1db41e6 --- /dev/null +++ b/docs/sync-2026-11-13-dev.md @@ -0,0 +1,272 @@ +# Upstream dev sync — 2026-11-13 PST + +## Summary and ancestry + +- Fork base: `b8986cff5753cf8051f04c47fd90a422a4bdabbc` (`origin/integration-v2`), including #490's sync/release PR gate, #491's stopped-command test fix and PowerShell stall diagnostics, and #492's `GH_TOKEN` build fix. +- Previous upstream pin: `73abe63ac23224d88e739e7028882e547ef65a79` (parent of the v2.3.0 release commit #489 merged). +- Upstream target: `cbe71595e1f370ff91b3081872b96bbe56519c41` (`upstream/dev` HEAD, branch symref verified as `dev`); **40 commits** past `73abe63ac2`. The task brief reported 38; the fetched drift is 40. +- Normal two-parent merge `6782796613` on `upstream-sync`, targeting `shuv1337/shuvcode:integration-v2`, following #484, #487 and #489. No rebase or force push. Focused tests and independently reviewed repairs follow the merge commit; the audit is maintained alongside them. +- Fetched `upstream/dev` and `--prune`d origin first. Origin HEAD is `integration-v2`; upstream HEAD is `dev`. +- The prescribed local-base check found local `integration-v2` stale at `72423e0520`, as in #487 and #489. That other worktree was left untouched; the topic starts at refreshed `origin/integration-v2` and the inventory used the same base. +- No default-branch push, merge, tag, release, publish, deployment or live-service change. This PR is sync-only: no version bump, and it does not publish. + +### No new upstream version in this range + +Upstream's root manifest stays `2.3.0`; this window is post-release development. Dev's release commit `a554d70499` is the dev-line twin of the tag commit `a6b15d33da` already in the fork: the `## v2.3.0` CHANGELOG section is byte-identical in both, so the merge keeps one section and the fork's `2.3.0-shuv.1` notes. The CLI manifest and lockfile stay at **2.3.0-shuv.1**; nothing bare-upstream is published. + +### Release recommendation + +Do not release from this PR. It carries real user-facing fixes (shell timeout→background by default, read-tool limits, six-byte GIF detection, connect-dialog polish, submenu/tooltip behaviour), so if the hosts should get them, a separate release-prep PR should bump to **`2.3.0-shuv.2`** on channel **`latest`**: the suffix sorts above `2.3.0-shuv.1` and below the next upstream base, and the base is still `2.3.0`. Keeping release prep out of this PR leaves the 343-file code merge as the only review surface and lets the lead time QA and host upgrades (npm platform tarballs 404 for a few minutes after publish). + +## Conflict resolutions + +Seven paths conflicted: + +| Path | Resolution | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `CHANGELOG.md` | Keep the fork's `2.3.0-shuv.1` note and all earlier fork notes; keep one upstream `## v2.3.0` section (verified byte-identical to the copy already in the fork). No duplicate section, no new fork entry for a sync that does not release. | +| `bun.lock` | Keep the `shuvcode` workspace name and `2.3.0-shuv.1`; take upstream's `@hona/strobe` 0.39.0 hashes and the new `@kobalte/core` patch entry. `bun install --frozen-lockfile` validates the result. | +| `packages/cli/package.json` | Keep fork `name` `shuvcode`, sole `shuvcode` bin and `2.3.0-shuv.1`; adopt upstream's remaining manifest content. | +| `packages/app/src/runtime/i18n/en.ts` | Keep the fork's removal of the `provider.connect.claudeAgent.*` strings (hidden provider); adopt upstream's ellipsis-free `provider.connect.command.waiting`; the unused fork-only `provider.connect.title.anthropicProMax` key goes with upstream's removal (no locale or caller referenced it). | +| `packages/app/src/providers/connect/dialog.tsx` | Adopt upstream's hoisted `STEP_CLASS`, `methodLabel` and `METHOD_ICON` (used by the surviving steps); keep the fork's deletion of the Claude Agent setup UI (`ClaudeAgentSetup`, `CLAUDE_CODE_SETUP_URL`, and its `narrow("claude")` match), because that provider is hidden. | +| `packages/app/e2e/regression/settings.spec.ts` | Keep the fork's deletion of the Claude Agent provider e2e case. Upstream rewrote the same case (Check again / navigate back), but it still drives a provider the fork hides, so it cannot pass here. | +| `packages/tui/test/app-lifecycle.test.tsx` | Keep both fork update/quit "Run shuvcode to use …" tests; adopt upstream's `ttft` removal in the assistant-footer assertions above them. | + +Every other both-sides-changed file auto-merged. For the semantic ones the fork's delta is preserved unchanged: `@opencode/util/hidden-provider` filters in the TUI session route and the provider-connect controller, the fork `ToolFailure` re-export in `@opencode/ai`, the tab-popover e2e assertion, and the Go-upsell art width. The #491 delta in `packages/core/test/tool-shell.test.ts` (147 changed lines: stopped-command race fix plus stalled-PowerShell reporting) is byte-for-byte identical after the merge. + +## Fork preservation and managed policy + +Unchanged: Shuvcode package/bin/XDG roots/ports (`Global.app = "shuvcode"`, `0x1337`/`0x1338`, server listen fallback `0x1337`), client `Service.fallback()` and default spawn `["shuvcode", "serve", "--service"]`, npm-only updates and the `shuv1337/shuvcode` publish guard, bundled Claude/Antigravity/Quota/UI integrations, tool-activity leases, rich failures, inactivity interruption, headless TUI schema split and configuration diagnostics. + +All three Claude Agent SDK hiding layers hold: `ProviderPlugins` still drops `opencode.provider.claude-agent`, the config provider plugin still filters both hidden ids through `isHiddenProvider`, and every client/provider/model list keeps calling that predicate. Upstream Claude Agent code stays on disk, unregistered. + +Server policy is unchanged from the fork base: `model.list`, `model.default`, `provider.list`, `generate.*`, `voice.*` and `websearch.query` wait at most five seconds for plugin activation, then fail 503 if incomplete; other catalog reads remain non-waiting. No activation wait was added. + +Upstream graduated and deleted the `shell_timeout_background` flag (#63699/#63703): timed-out foreground shell commands now move to the background by default. The fork adopts that upstream default; there is no fork flag for it, and the historical CHANGELOG/docs references to the old flag are left as release history. + +## Validation + +Bun 1.4.4. Package suites ran from their package directories with an isolated environment (`env -i` with a private `HOME`, `TMPDIR` and no inherited `OPENCODE_*`), because this worktree's parent shell carries the live `OPENCODE_CONFIG_DIR`/`OPENCODE_*` values and the SDK suite reads them. No privileged/systemd container, no host `/dev`, `/sys`, `/run/udev` or `/run/dbus` mount. + +| Gate | Result | +| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Root `bun run check` (lint + 40-package typecheck) | Pass, 40/40 tasks, lint exit 0 (one advisory ast-grep "unused suppression" help in the unchanged `packages/util/src/cross-spawn-spawner.ts`; not an error) | +| `bun run generate` from `packages/client` | Pass, no generated drift | +| `bun install --frozen-lockfile` | Pass, 1597 packages, no lockfile change | +| Whitespace (`git diff --check`) | Pass | +| Effect simplification lint (`lint:effect-simplifications`) | Pass | +| Full forced Turbo unit gate, concurrency 3 | 31 of the 32 suites that reported were green; SDK failed only under the inherited `OPENCODE_*` environment. Turbo then hit the known failure-path SIGSEGV `pc_4bef4e2422a7` before core, TUI and CLI finished, so those three ran individually. | +| Core (`packages/core`) | 7,633 pass / 16 skip / 11 fail across 333 files — all 11 are the environmental GitLab OAuth port conflict below | +| CLI (`packages/cli`) | 477 pass / 7 skip / 0 fail across 69 files, 283s | +| TUI (`packages/tui`) | 1,753 pass / 2 skip / 0 fail across 211 files, 173s | +| Server | 139 pass / 1 skip / 0 fail | +| SDK | 40 pass / 0 fail with an isolated environment (the inherited `OPENCODE_*` shell variables cause a pre-existing `workerd-seeded model never loaded` failure; reproduced on unmodified `origin/integration-v2` too) | +| App unit + browser | 2,718 pass / 0 fail and 360 pass / 0 fail | +| Other suites | ai 2,241; codemode 1,641; gui-plugins 1,130; ui 626; session-ui 602; merman 508; client 274; site 242; util 146; latex 123; plugin 37; plugin-browser 113; protocol 14; schema 92; the four `@shuvcode/*` plugins 205 combined — all 0 fail | + +### Core failures + +Eleven core tests failed, all `GitLabPlugin OAuth` cases that need the fixed local callback port: `Integration.Authorization: GitLab login needs local port 8080, but it is already in use`. Something already listens on `127.0.0.1:8080` on this host, so the suite can never bind it. The same file fails identically (8 pass / 11 fail) on unmodified `origin/integration-v2`, so this is the dev host, not the merge; a GitHub runner has the port free. No test, timeout or skip was changed. The SDK `workerd-seeded` case has the same shape: the inherited `OPENCODE_*` shell environment makes it fail on both trees, and it passes in an isolated environment. + +## Independent review repairs + +Astra's review of `c9f400054a` found two regressions in the upstream delta; neither is waived for the sync: + +- Preview find used lowercased-string offsets on original DOM text, so Unicode case expansion (`İx`) highlighted the wrong character or threw. Both document and sandboxed HTML preview search now use escaped, case-insensitive Unicode regular expressions over the original text. +- The new timeline dropped nonzero-exit, timeout and stopped outcomes from direct user shell messages. Its shell card again renders the existing localized outcome badge, including commands with no output. + +Focused component regressions failed before the production repairs (two preview cases, three shell outcomes). After repairs, preview tests passed 20/20 attempts; the entire shell component spec passed 120/120 attempts, both at two workers with no retries. The preview run started with a cleared story optimizer cache; neither green run logged dependency-optimizer reloads. Root `bun run check` passed 40/40 and `git diff --check` passed. Linux Chromium only; no Windows/macOS execution claimed. Full browser suites and replacement-head CI remain merge gates; focused runs are not a full-suite claim. + +A pre-edit strobe comparison against the actual fork default `origin/integration-v2` was started (`exp_e1b549`) but bounded out during dependency setup; no performance verdict is claimed. The mechanical UI detector reported no findings. These fixes preserve the existing UI and introduce no feature flag. Independent re-review of the replacement head is required. + +### New timeline boundary repair + +The first replacement-head unit run (workflow run `43565490213`, unit job `132358367582`) failed exactly one test: `@opencode/session-ui`'s `src/timeline-next/boundary.test.ts:34` reported `session-ui/src/timeline/terminal-work.stories.tsx` as an unauthorized importer of the New timeline (601 passed, 1 failed). Turbo then hit the known failure-path SIGSEGV with exit 139, which does not remove the preceding assertion failure. The boundary rule is upstream's own and is kept unchanged: `upstream/dev`'s `boundary.test.ts` is byte-identical to this branch, and its only outside-folder importers are the two timeline switches. `timeline-next/index.ts` exports no shell message, and any `@opencode/session-ui/timeline-next` import from a story matches the rule, so there is no allowed public surface for the old timeline to reach the experiment. + +The repair moves fixture ownership instead of touching the rule, its allowlist or its regex: + +- `timeline/terminal-work.stories.tsx` is restored to its pre-repair route: `SessionShellMessage` only, no `next` argument and no New timeline import. +- `timeline-next/stories/user-command.stories.tsx` is the New timeline's own story. It renders the production `ShellMessage` and completes a running user command into nonzero-exit, timeout or killed metadata with no output. +- The three outcome component tests in `session-ui/component-tests/session-shell.spec.ts` mount that New-timeline-owned story. The old story's tests, including the three direct-shell failure cases, the live-output cases and the copy cases, are unchanged. + +The localized outcome badge in `timeline-next/tools/shell.tsx` is untouched. With that badge removed, the three cases failed on the new route (3 failed); with it restored they pass, so the story exercises the production fix rather than passing vacuously. + +Validation (Bun 1.4.4, Linux Chromium only; no Windows or macOS execution claimed): + +| Gate | Result | +| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `packages/session-ui` `bun test src --only-failures` (package script) | 602 pass, 0 fail across 57 files, 3.25s | +| `src/timeline-next/boundary.test.ts` alone | 3 pass, 0 fail | +| Full `packages/session-ui` component suite, cold story optimizer cache | 218 passed, 4.3m, zero `new dependencies optimized` / `optimized dependencies changed` lines | +| `session-shell.spec.ts` at 2 workers, `--repeat-each=10 --retries=0` | 120 passed, no retries, no optimizer reloads | +| Root `bun run check` | 40/40 tasks, typecheck and lint exit 0 | +| Whitespace (`git diff --check`) | Pass | + +Fork CI runs `unit` and `e2e` (including the session-ui and app component legs) only on `ubuntu-latest`; there are no Windows or macOS legs to cover in this repository. The changed files contain story ids, relative imports and localized badge text, with no platform-specific path or geometry assertions. The full Linux `unit` and `e2e` jobs of the new head remain the merge gate; the focused and full-package runs above are local Linux evidence, and CI result is not claimed here. + +## Branch inventory + +Inspected all **160** pre-existing unmerged local/origin refs (the topic branch excluded) against refreshed `origin/integration-v2` with tips, first-parent unique commit counts, tip subjects and refreshed fork PR status. Every ref/tip and PR state matches #489's audited inventory; the only additions are the two `pwsh-ci-diag` refs created for #493's stall diagnostics. Nothing is landed or deleted. Evidence is retained locally in `$HOME/.cache/agent-ws/sync-231/inventory-evidence.json` and `fork-prs.tsv`. + +| Ref | Tip | Latest fork PR | Disposition | +| ------------------------------------------------- | ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pwsh-ci-diag` | `fb789a630a` | No fork PR | Intentionally parked diagnostic ref for #493 (`do not merge`): only `.github/workflows/test.yml` pwsh latency tracing; preserved for the next pwsh stall report, not merged in this sync. | +| `integration-v230` | `5d2a74a382` | No fork PR | Already landed as #450 / 3e02afbd9f; rebased predecessor. | +| `primary-backup-20260916` | `b226dca264` | No fork PR | Intentionally parked and preserved as work ref `primary-backup-20260916`; no landing/discard decision in this sync. | +| `integration-backup-20260915` | `c9813e253b` | No fork PR | Intentionally parked and preserved under work ref `integration-backup-20260915`; historical changes, no landing/discard decision in this sync. | +| `fix-channel-resolution` | `6d2354465f` | No fork PR | Intentionally parked and preserved as work ref `fix-channel-resolution`; no landing/discard decision in this sync. | +| `nightly-backup` | `4b47862c91` | No fork PR | Intentionally parked and preserved as work ref `nightly-backup`; no landing/discard decision in this sync. | +| `upstream-rebase` | `8adb6e0c57` | No fork PR | Intentionally parked and preserved as work ref `upstream-rebase`; no landing/discard decision in this sync. | +| `pre-sync-backup` | `31e460ecde` | No fork PR | Intentionally parked and preserved as work ref `pre-sync-backup`; no landing/discard decision in this sync. | +| `sync-latest-v2` | `81d57449ba` | No fork PR | Intentionally parked and preserved as work ref `sync-latest-v2`; no landing/discard decision in this sync. | +| `sync-upstream-tabs` | `9cfa3fc4f9` | No fork PR | Intentionally parked and preserved as work ref `sync-upstream-tabs`; no landing/discard decision in this sync. | +| `shuvcode-dev` | `a5d3b86a4f` | #329 MERGED | Previously landed via #329; historical/rebased ref preserved. No old tree re-import. | +| `default-commands-missing` | `041bd7d557` | #318 CLOSED | Intentionally parked and preserved as work ref `default-commands-missing`; no landing/discard decision in this sync. | +| `sidebar-indicator-fixup` | `2c8cb0c196` | #317 CLOSED | Intentionally parked and preserved as work ref `sidebar-indicator-fixup`; no landing/discard decision in this sync. | +| `shuvcode-dev-old` | `8d21fbfb9d` | No fork PR | Intentionally parked and preserved as work ref `shuvcode-dev-old`; no landing/discard decision in this sync. | +| `pr-9124` | `cb93d509bb` | No fork PR | Intentionally parked and preserved as work ref `pr-9124`; no landing/discard decision in this sync. | +| `feat/usage-tracking` | `b7df5d3ad9` | No fork PR | Intentionally parked and preserved as work ref `feat/usage-tracking`; no landing/discard decision in this sync. | +| `feat/skills-registry` | `fbd90d65ac` | No fork PR | Intentionally parked and preserved under work ref `feat/skills-registry`; historical changes, no landing/discard decision in this sync. | +| `feat/codex-multi-account` | `467fad9930` | No fork PR | Intentionally parked and preserved under work ref `feat/codex-multi-account`; historical changes, no landing/discard decision in this sync. | +| `backup/shuvcode-dev-20260114-235741` | `58176ee0f8` | No fork PR | Intentionally parked and preserved as work ref `backup/shuvcode-dev-20260114-235741`; no landing/discard decision in this sync. | +| `pr-300` | `bdba5f1183` | No fork PR | Intentionally parked and preserved as work ref `pr-300`; no landing/discard decision in this sync. | +| `pr-298` | `df300ff3a1` | No fork PR | Intentionally parked and preserved as work ref `pr-298`; no landing/discard decision in this sync. | +| `feat/tui-variant-cycle-tooltip` | `ea74b8e3e6` | #291 CLOSED | Intentionally parked and preserved as work ref `feat/tui-variant-cycle-tooltip`; no landing/discard decision in this sync. | +| `tui-variant-cycle-tooltip` | `d84a2f9b49` | #290 CLOSED | Intentionally parked and preserved as work ref `tui-variant-cycle-tooltip`; no landing/discard decision in this sync. | +| `merge/v1.1.1-integration` | `d6f823eaca` | No fork PR | Intentionally parked and preserved as work ref `merge/v1.1.1-integration`; no landing/discard decision in this sync. | +| `shuvcode-dev-backup-v1.0.223` | `3460aafc07` | No fork PR | Intentionally parked and preserved under work ref `shuvcode-dev-backup-v1.0.223`; historical changes, no landing/discard decision in this sync. | +| `fix/directory-handling-combined` | `53e2855bb6` | #256 CLOSED | Intentionally parked and preserved under work ref `fix/directory-handling-combined`; historical changes, no landing/discard decision in this sync. | +| `fix/root-file-view` | `11acee97ea` | #233 CLOSED | Intentionally parked and preserved as work ref `fix/root-file-view`; no landing/discard decision in this sync. | +| `feat/image-preview-tabs` | `a47063c2f8` | #218 CLOSED | Intentionally parked and preserved as work ref `feat/image-preview-tabs`; no landing/discard decision in this sync. | +| `fix/file-viewer-project-root` | `35681dc118` | No fork PR | Intentionally parked and preserved as work ref `fix/file-viewer-project-root`; no landing/discard decision in this sync. | +| `fix/file-viewer-blank-content` | `14cf82c0e8` | No fork PR | Intentionally parked and preserved under work ref `fix/file-viewer-blank-content`; historical changes, no landing/discard decision in this sync. | +| `pr-6372-image-preview` | `ce4570ed1b` | No fork PR | Intentionally parked and preserved as work ref `pr-6372-image-preview`; no landing/discard decision in this sync. | +| `plugin-slash-commands` | `49d1595fad` | No fork PR | Intentionally parked and preserved as work ref `plugin-slash-commands`; no landing/discard decision in this sync. | +| `upstream-pr-5917` | `8dbd3ac4b8` | No fork PR | Intentionally parked and preserved as work ref `upstream-pr-5917`; no landing/discard decision in this sync. | +| `pr-183-temp` | `471c33b1b0` | No fork PR | Intentionally parked and preserved as work ref `pr-183-temp`; no landing/discard decision in this sync. | +| `fix/dockerfile-add-git` | `3997e0d88a` | #182 CLOSED | Intentionally parked and preserved as work ref `fix/dockerfile-add-git`; no landing/discard decision in this sync. | +| `feat/save-favorite-models-desktop` | `4c7cd33f4d` | No fork PR | Intentionally parked and preserved as work ref `feat/save-favorite-models-desktop`; no landing/discard decision in this sync. | +| `fix/mobile-timeline-rail` | `2330c8bccd` | No fork PR | Intentionally parked and preserved as work ref `fix/mobile-timeline-rail`; no landing/discard decision in this sync. | +| `revert-pr-4773-subagent-restrictions` | `e568ad2cc1` | #105 MERGED | Historical landing: #105 / 4690583e26. Remaining historical work intentionally parked under `revert-pr-4773-subagent-restrictions`; preserved, not re-imported. | +| `pre-integration` | `7d42627e65` | No fork PR | Intentionally parked and preserved as work ref `pre-integration`; no landing/discard decision in this sync. | +| `sidebar-fix` | `c76c32c11d` | #97 MERGED | Historical landing: #97 / 9233e33358. Remaining historical work intentionally parked under `sidebar-fix`; preserved, not re-imported. | +| `origin/191-merge` | `54580871d1` | #198 MERGED | Previously landed via #198; historical/rebased ref preserved. No old tree re-import. | +| `origin/197-consolidate-ask-tool-implementations` | `5392b8c8dc` | #201 MERGED | Previously landed via #201; historical/rebased ref preserved. No old tree re-import. | +| `origin/73-fix-branding-update-message` | `8a1b2b5c24` | #75 MERGED | Previously landed via #75; historical/rebased ref preserved. No old tree re-import. | +| `origin/73-fix-branding-upgrade` | `26c72de8be` | #76 MERGED | Previously landed via #76; historical/rebased ref preserved. No old tree re-import. | +| `origin/add-model-favorites` | `ce61e9ec78` | #35 MERGED | Previously landed via #35; historical/rebased ref preserved. No old tree re-import. | +| `origin/add-pr-4515` | `d86d620113` | #93 MERGED | Previously landed via #93; historical/rebased ref preserved. No old tree re-import. | +| `origin/config-hot-reload` | `6a4cca152a` | #29 CLOSED | Previously landed via #20; historical/rebased ref preserved. No old tree re-import. | +| `origin/copilot/install-bun-version-1-3-3` | `2ab19f8fb2` | #95 MERGED | Previously landed via #95; historical/rebased ref preserved. No old tree re-import. | +| `origin/copilot/resolve-upstream-sync-conflict` | `7ce35ef6c4` | #38 CLOSED | Intentionally parked and preserved as work ref `copilot/resolve-upstream-sync-conflict`; no landing/discard decision in this sync. | +| `origin/copilot/sub-pr-105` | `0388a7633c` | #106 MERGED | Previously landed via #106; historical/rebased ref preserved. No old tree re-import. | +| `origin/copilot/sub-pr-27` | `96ef37296d` | #28 CLOSED | Intentionally parked and preserved as work ref `copilot/sub-pr-27`; no landing/discard decision in this sync. | +| `origin/copilot/sub-pr-325` | `13501a24d2` | #326 MERGED | Previously landed via #326; historical/rebased ref preserved. No old tree re-import. | +| `origin/copilot/sub-pr-97` | `b005b693b1` | #98 MERGED | Previously landed via #98; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/ab-check-git-ad5d` | `fbd03ae4b6` | #388 MERGED | Previously landed via #388; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/antigravity-quota-errors-c5e1` | `3ee7aff758` | #427 MERGED | Previously landed via #427; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/ci-integration-v2-61f7` | `c80279ae2d` | #415 CLOSED | Intentionally parked and preserved as work ref `cursor/ci-integration-v2-61f7`; no landing/discard decision in this sync. | +| `origin/cursor/cli-test-env-a867` | `336effb840` | #396 MERGED | Previously landed via #396; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/client-test-contract-de6d` | `18823adc3d` | #421 MERGED | Previously landed via #421; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/core-test-node-a8d0` | `2769dcf17b` | #426 MERGED | Previously landed via #426; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/dependency-inspection-a7f4` | `2b5a49aaed` | #395 MERGED | Previously landed via #395; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/host-deploy-channel-5f72` | `c7b49996ea` | #414 MERGED | Previously landed via #414; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/jj-pr-review-149d` | `dd326d57f1` | #423 MERGED | Previously landed via #423; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/large-pr-diff-87a3` | `d45563597c` | #394 MERGED | Previously landed via #394; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/legacy-health-probe-5e6a` | `7f39e0127a` | #424 MERGED | Previously landed via #424; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/live-service-binary-8c38` | `78ea063e6e` | #390 MERGED | Previously landed via #390; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/persist-session-log-5c6b` | `b66e278dc6` | #422 MERGED | Previously landed via #422; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/pre-sync-checklist-b97e` | `8468a92d0b` | #389 MERGED | Previously landed via #389; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/remote-port-probes-4afe` | `2756f48b00` | #392 MERGED | Previously landed via #392; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/standalone-global-flag-1969` | `a5f15a7ab5` | #428 MERGED | Previously landed via #428; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/stdin-epipe-listener-968d` | `aedf6dd481` | #425 CLOSED | Intentionally parked and preserved as work ref `cursor/stdin-epipe-listener-968d`; no landing/discard decision in this sync. | +| `origin/cursor/tui-probe-404-7466` | `4c7e7aa894` | #418 MERGED | Previously landed via #418; historical/rebased ref preserved. No old tree re-import. | +| `origin/cursor/whitespace-check-docs-bdca` | `8147925044` | #387 MERGED | Previously landed via #387; historical/rebased ref preserved. No old tree re-import. | +| `origin/dev-pr` | `b1372b14cb` | #208 MERGED | Previously landed via #208; historical/rebased ref preserved. No old tree re-import. | +| `origin/docs/plan-ios-rebrand` | `6eddaeffe3` | #472 CLOSED | Intentionally parked, preserved; #472 closed; iOS source hunt is not part of this sync. | +| `origin/feat-v186` | `fbd343d502` | #196 MERGED | Previously landed via #196; historical/rebased ref preserved. No old tree re-import. | +| `origin/feat/codex-multi-account` | `5577b5b64b` | No fork PR | Intentionally parked and preserved as work ref `feat/codex-multi-account`; no landing/discard decision in this sync. | +| `origin/feat/image-preview-tabs` | `a47063c2f8` | #218 CLOSED | Intentionally parked and preserved as work ref `feat/image-preview-tabs`; no landing/discard decision in this sync. | +| `origin/feat/reconnect` | `7639636cbf` | #262 MERGED | Previously landed via #262; historical/rebased ref preserved. No old tree re-import. | +| `origin/feat/save-favorite-models-desktop` | `4c7cd33f4d` | No fork PR | Intentionally parked and preserved as work ref `feat/save-favorite-models-desktop`; no landing/discard decision in this sync. | +| `origin/feat/skills-registry` | `eb1ecf16ca` | No fork PR | Intentionally parked and preserved as work ref `feat/skills-registry`; no landing/discard decision in this sync. | +| `origin/feat/tui-variant-cycle-tooltip` | `ea74b8e3e6` | #291 CLOSED | Intentionally parked and preserved as work ref `feat/tui-variant-cycle-tooltip`; no landing/discard decision in this sync. | +| `origin/fix-prefill` | `25e4042eaa` | #356 MERGED | Previously landed via #356; historical/rebased ref preserved. No old tree re-import. | +| `origin/fix-tui-img-attachments` | `534bb79d1f` | #26 CLOSED | Intentionally parked and preserved as work ref `fix-tui-img-attachments`; no landing/discard decision in this sync. | +| `origin/fix/directory-handling-combined` | `ab9f5a31e4` | #256 CLOSED | Intentionally parked and preserved as work ref `fix/directory-handling-combined`; no landing/discard decision in this sync. | +| `origin/fix/file-viewer-add-img-support` | `7434e1f95a` | No fork PR | Intentionally parked and preserved as work ref `fix/file-viewer-add-img-support`; no landing/discard decision in this sync. | +| `origin/fix/file-viewer-blank-content` | `df040037b2` | No fork PR | Intentionally parked and preserved as work ref `fix/file-viewer-blank-content`; no landing/discard decision in this sync. | +| `origin/fix/mobile-timeline-rail` | `2330c8bccd` | No fork PR | Intentionally parked and preserved as work ref `fix/mobile-timeline-rail`; no landing/discard decision in this sync. | +| `origin/fix/root-file-view` | `11acee97ea` | #233 CLOSED | Intentionally parked and preserved as work ref `fix/root-file-view`; no landing/discard decision in this sync. | +| `origin/fleet-hygiene` | `4450a8092f` | #451 MERGED | Previously landed via #451; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-361-jj-channel` | `29efc2fd65` | #377 MERGED | Previously landed via #377; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-362-agent-model` | `c16b50387d` | #378 MERGED | Previously landed via #378; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-363-prompt-keys` | `f9cb57de18` | #393 MERGED | Previously landed via #393; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-373-jev` | `8803f6d56c` | #397 MERGED | Previously landed via #397; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-ci-reenable` | `a9c5efc1ab` | #420 MERGED | Previously landed via #420; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-cursor-378` | `41c749ffb1` | #431 MERGED | Previously landed via #431; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-e2e-timeline` | `06511bea6b` | #432 MERGED | Previously landed via #432; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-folderswitch-quarantine` | `b0527abf89` | #439 MERGED | Previously landed via #439; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-i407-toolcall-recovery` | `39aefb825f` | #437 MERGED | Previously landed via #437; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-i411-watcher-flake` | `cbc2a85896` | #433 MERGED | Previously landed via #433; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-i412-run-admission` | `6248a7c425` | #434 MERGED | Previously landed via #434; historical/rebased ref preserved. No old tree re-import. | +| `origin/fm/sc-i438-tab-popover` | `098a70eba6` | #442 MERGED | Previously landed via #442; historical/rebased ref preserved. No old tree re-import. | +| `origin/integration` | `a5d3b86a4f` | #183 CLOSED | Previously landed via #32; historical/rebased ref preserved. No old tree re-import. | +| `origin/integration-backup-20260915` | `fe267dfaa9` | No fork PR | Intentionally parked and preserved as work ref `integration-backup-20260915`; no landing/discard decision in this sync. | +| `origin/intergation-streamline` | `91a6ff8fa3` | No fork PR | Intentionally parked and preserved as work ref `intergation-streamline`; no landing/discard decision in this sync. | +| `origin/merge-PRs` | `1d16bf70d6` | #65 MERGED | Previously landed via #65; historical/rebased ref preserved. No old tree re-import. | +| `origin/merge-v1.0.153` | `3518a2ada9` | No fork PR | Intentionally parked and preserved as work ref `merge-v1.0.153`; no landing/discard decision in this sync. | +| `origin/merge-v1.1.39` | `46db693ee6` | #325 MERGED | Previously landed via #325; historical/rebased ref preserved. No old tree re-import. | +| `origin/merge/upstream-v2.1.4` | `a56efe2d54` | #456 CLOSED | Obsolete sync proposal #456, superseded by #457 / 6bab70f39a; ref preserved. | +| `origin/mobile-pairing` | `6a9f0f188f` | #336 MERGED | Previously landed via #336; historical/rebased ref preserved. No old tree re-import. | +| `origin/model-diag-cleanup` | `1f91715278` | #40 CLOSED | Intentionally parked and preserved as work ref `model-diag-cleanup`; no landing/discard decision in this sync. | +| `origin/native-supervisor` | `1a8a997cd6` | #440 CLOSED | Intentionally parked, preserved; #440 closed, native supervisor is not part of this sync. | +| `origin/opencode/happy-mountain` | `f806194393` | #324 MERGED | Previously landed via #324; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue102-20251210030021` | `3439392061` | #104 CLOSED | Previously landed via #103; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue113-20251211062235` | `9118d30d5b` | #115 CLOSED | Intentionally parked and preserved as work ref `opencode/issue113-20251211062235`; no landing/discard decision in this sync. | +| `origin/opencode/issue114-20251211062613` | `5b68d29028` | #116 CLOSED | Intentionally parked and preserved as work ref `opencode/issue114-20251211062613`; no landing/discard decision in this sync. | +| `origin/opencode/issue117-20251211083034` | `17977ebb47` | #119 MERGED | Previously landed via #119; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue120-20251211165001` | `f0f45933db` | #122 CLOSED | Previously landed via #121; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue126-20251211201237` | `b460393a40` | #128 CLOSED | Previously landed via #127; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue144-20251219021522` | `5083acfe76` | #145 MERGED | Previously landed via #145; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue146-20251219134518` | `d1dd3ce149` | #147 MERGED | Previously landed via #147; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue151-20251220031612` | `16171d726c` | #153 MERGED | Previously landed via #153; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue152-20251220033120` | `46e79d193a` | #154 CLOSED | Intentionally parked and preserved as work ref `opencode/issue152-20251220033120`; no landing/discard decision in this sync. | +| `origin/opencode/issue155-20251220035024` | `10a6e5975d` | #156 CLOSED | Intentionally parked and preserved as work ref `opencode/issue155-20251220035024`; no landing/discard decision in this sync. | +| `origin/opencode/issue157-20251220040932` | `ff528b5884` | #158 MERGED | Previously landed via #158; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue159-20251220111304` | `fca266b6a5` | #160 CLOSED | Intentionally parked and preserved as work ref `opencode/issue159-20251220111304`; no landing/discard decision in this sync. | +| `origin/opencode/issue161-20251220123030` | `5327451fc0` | #162 CLOSED | Intentionally parked and preserved as work ref `opencode/issue161-20251220123030`; no landing/discard decision in this sync. | +| `origin/opencode/issue167-20251220154038` | `7665eeafa3` | #168 CLOSED | Intentionally parked and preserved as work ref `opencode/issue167-20251220154038`; no landing/discard decision in this sync. | +| `origin/opencode/issue169-20251220160245` | `449c158bae` | #170 MERGED | Previously landed via #170; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue176-20251221020906` | `99cc7523c7` | #177 CLOSED | Intentionally parked and preserved as work ref `opencode/issue176-20251221020906`; no landing/discard decision in this sync. | +| `origin/opencode/issue178-20251221030922` | `afe1e792e7` | #179 MERGED | Previously landed via #179; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue67-20251201020527` | `9bae941529` | No fork PR | Intentionally parked and preserved as work ref `opencode/issue67-20251201020527`; no landing/discard decision in this sync. | +| `origin/opencode/issue68-20251201093246` | `85199590d5` | No fork PR | Intentionally parked and preserved as work ref `opencode/issue68-20251201093246`; no landing/discard decision in this sync. | +| `origin/opencode/issue70-20251201190836` | `40c4eeda7f` | No fork PR | Intentionally parked and preserved as work ref `opencode/issue70-20251201190836`; no landing/discard decision in this sync. | +| `origin/opencode/issue74-20251202181455` | `069b244200` | No fork PR | Intentionally parked and preserved as work ref `opencode/issue74-20251202181455`; no landing/discard decision in this sync. | +| `origin/opencode/issue77-20251202201913` | `52a5e7032d` | No fork PR | Intentionally parked and preserved as work ref `opencode/issue77-20251202201913`; no landing/discard decision in this sync. | +| `origin/opencode/issue78-20251203114126` | `ac256ed024` | #79 MERGED | Previously landed via #79; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue80-20251204034025` | `df4c1f7510` | #82 CLOSED | Previously landed via #81; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue83-20251204041504` | `9174faa11a` | #84 MERGED | Previously landed via #84; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue86-20251204220607` | `ed75889426` | #88 CLOSED | Previously landed via #87; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue89-20251205204907` | `5821af50ab` | #91 CLOSED | Previously landed via #90; historical/rebased ref preserved. No old tree re-import. | +| `origin/opencode/issue99-20251209180809` | `b02de610af` | #101 CLOSED | Previously landed via #100; historical/rebased ref preserved. No old tree re-import. | +| `origin/plugin-slash-commands` | `49d1595fad` | No fork PR | Intentionally parked and preserved as work ref `plugin-slash-commands`; no landing/discard decision in this sync. | +| `origin/prompt-shuvcode` | `7ba4a9c567` | #300 CLOSED | Intentionally parked and preserved as work ref `prompt-shuvcode`; no landing/discard decision in this sync. | +| `origin/pwsh-ci-diag` | `fb789a630a` | No fork PR | Intentionally parked diagnostic ref for #493 (`do not merge`): only `.github/workflows/test.yml` pwsh latency tracing; preserved for the next pwsh stall report, not merged in this sync. | +| `origin/reply-routing-recovery` | `61953c8ebb` | #364 MERGED | Previously landed via #364; historical/rebased ref preserved. No old tree re-import. | +| `origin/revert-pr-4773-subagent-restrictions` | `f500359cec` | #105 MERGED | Previously landed via #105; historical/rebased ref preserved. No old tree re-import. | +| `origin/sc-cursor-377` | `033bbe0580` | #430 MERGED | Previously landed via #430; historical/rebased ref preserved. No old tree re-import. | +| `origin/sc-permission-fixes` | `35b78d5586` | #429 MERGED | Previously landed via #429; historical/rebased ref preserved. No old tree re-import. | +| `origin/sewer56-subagent-restrict` | `a6ee592131` | #57 MERGED | Previously landed via #57; historical/rebased ref preserved. No old tree re-import. | +| `origin/shuvbotta/anthropic-claude-code` | `ed1f8bd2ce` | #349 MERGED | Previously landed via #349; historical/rebased ref preserved. No old tree re-import. | +| `origin/shuvbotta/codemode-fixes` | `935dc2dcd2` | #348 MERGED | Previously landed via #348; historical/rebased ref preserved. No old tree re-import. | +| `origin/shuvcode-dev` | `a5d3b86a4f` | #329 MERGED | Previously landed via #329; historical/rebased ref preserved. No old tree re-import. | +| `origin/shuvcode-dev-backup-v1.0.223` | `edb9f9ffaa` | No fork PR | Intentionally parked and preserved as work ref `shuvcode-dev-backup-v1.0.223`; no landing/discard decision in this sync. | +| `origin/sidebar-fix` | `90d3e7e8f9` | #97 MERGED | Previously landed via #97; historical/rebased ref preserved. No old tree re-import. | +| `origin/sync-latest-v2` | `81d57449ba` | No fork PR | Intentionally parked and preserved as work ref `sync-latest-v2`; no landing/discard decision in this sync. | +| `origin/sync-v2-aug13` | `0edf34c9fb` | No fork PR | Intentionally parked and preserved as work ref `sync-v2-aug13`; no landing/discard decision in this sync. | +| `origin/sync-v2-sep` | `5151e9faf7` | No fork PR | Intentionally parked and preserved as work ref `sync-v2-sep`; no landing/discard decision in this sync. | +| `origin/sync/upstream-v1.1.20` | `4feb204219` | #301 MERGED | Previously landed via #301; historical/rebased ref preserved. No old tree re-import. | +| `origin/tui-variant-cycle-tooltip` | `d84a2f9b49` | #290 CLOSED | Intentionally parked and preserved as work ref `tui-variant-cycle-tooltip`; no landing/discard decision in this sync. | +| `origin/v1.1.1.1-integration-test` | `d16007bfb8` | #263 MERGED | Previously landed via #263; historical/rebased ref preserved. No old tree re-import. | diff --git a/package.json b/package.json index f2203e3a88b3..f5c0ff4836f2 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "@effect/sql-sqlite-node": "4.1.0", "@npmcli/arborist": "9.4.0", "@types/bun": "1.4.3", - "@hona/strobe": "0.34.0", + "@hona/strobe": "0.39.0", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@opentui/core": "0.8.4", @@ -177,6 +177,7 @@ "@opentunnel/client@0.6.1": "patches/@opentunnel%2Fclient@0.6.1.patch", "@opentunnel/protocol@0.6.1": "patches/@opentunnel%2Fprotocol@0.6.1.patch", "@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch", - "@modelcontextprotocol/client@2.4.0": "patches/@modelcontextprotocol%2Fclient@2.4.0.patch" + "@modelcontextprotocol/client@2.4.0": "patches/@modelcontextprotocol%2Fclient@2.4.0.patch", + "@kobalte/core@0.13.13": "patches/@kobalte%2Fcore@0.13.13.patch" } } diff --git a/packages/ai/README.md b/packages/ai/README.md index 8292ccd22592..a8c2157a36f1 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1031,12 +1031,29 @@ const program = Effect.gen(function* () { The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes. +### Image jobs + +`ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same +calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and +read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read; +`result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an +`UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on +every image model today all four fail with an `UnsupportedOperation` reason before sending anything. + +```ts +const program = Effect.gen(function* () { + const job = yield* ai.image.start({ model, prompt: "A lighthouse" }) + const status = yield* ai.image.status(model, job.id) // { status, progress? } + if (status.status === "completed") return yield* ai.image.result(model, job.id) +}) +``` + ## Video generation Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`, fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's -`token`, plain JSON you can store and read back from another process, so recovering after a restart is the same call -as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`, +`id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart +is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`, `BytePlus`, `MiniMax` and `Google` facades. ```ts @@ -1057,22 +1074,28 @@ const program = Effect.gen(function* () { resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value sound: false, }) - job.token // `{ requestID }` for xAI: store it with the provider and model ID + job.id // the provider's job ID: store it with the provider and model ID - const status = yield* ai.video.status(model, job.token) + const status = yield* ai.video.status(model, job.id) status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired" status.progress // 0..1, only when the provider reports it - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk }) ``` The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`; everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only -fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider +fails before sending when its protocol has no way to express it, such as a reference video on xAI. `sound` is the +exception: on models whose sound can't be switched (MiniMax H3 and Gemini Omni always have it, Hailuo never does) it +isn't sent, and the model's own behavior applies. Values the provider may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed. +`start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with +`Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references +whose type isn't stated are sent and checked by the provider. `references` take any kind. + `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads @@ -1110,11 +1133,11 @@ Provider notes: `/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` / `reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes `ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a - `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound, - so `sound: false` fails before sending. On Hailuo, `start` and `end` map to `first_frame_image` and + `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound + and has no field for it, so `sound` isn't sent. On Hailuo, `start` and `end` map to `first_frame_image` and `last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which - expires after one hour. Hailuo is silent and has no aspect field, so `sound: true`, an explicit `aspect`, and video - or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields + expires after one hour. Hailuo is always silent, so `sound` isn't sent; it has no aspect field, so an explicit + `aspect` and video or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`. - **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video @@ -1122,7 +1145,7 @@ Provider notes: `reference_to_video` for references only; with both, the prompt decides. `duration` becomes `response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the - first frame) and `sound: false` (Omni always generates audio). Videos come back as inline bytes. `cancel` posts to + first frame). Omni always generates audio and has no field for it, so `sound` isn't sent. Videos come back as inline bytes. `cancel` posts to `/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id` to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`. @@ -1132,8 +1155,8 @@ The promise client has the same calls, each accepting `{ signal }`: import { ai } from "@opencode/ai" const job = await ai.video.start({ model, prompt }) -const status = await ai.video.status(model, job.token) -if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4") +const status = await ai.video.status(model, job.id) +if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).video, "./kite.mp4") ``` ## Public API @@ -1147,9 +1170,9 @@ Everything below is exported from `@opencode/ai/effect` unless noted. - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model. - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model. - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams. -- **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. +- **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs). - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`. -- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by a stored token; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer. +- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer. - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests. - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes. - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer. diff --git a/packages/ai/package.json b/packages/ai/package.json index fcc44b3779de..776cc31ec4b8 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -136,6 +136,7 @@ "./providers/vercel-ai-gateway/responses": "./src/providers/vercel-ai-gateway/responses.ts", "./providers/xai": "./src/providers/xai.ts", "./providers/xai/images": "./src/providers/xai/images.ts", + "./providers/xai/videos": "./src/providers/xai/videos.ts", "./providers/zai": "./src/providers/zai.ts", "./providers/zai-coding-plan": "./src/providers/zai-coding-plan.ts", "./providers/zai-coding-plan/chat": "./src/providers/zai-coding-plan/chat.ts", diff --git a/packages/ai/src/image-client.ts b/packages/ai/src/image-client.ts index 44e819e389fc..63bddd00841b 100644 --- a/packages/ai/src/image-client.ts +++ b/packages/ai/src/image-client.ts @@ -1,20 +1,89 @@ -import { Context } from "effect" +import { Context, Effect, Layer, Schema, Stream } from "effect" +import type { AwaitOptions } from "./generation.js" import { MediaClient } from "./media-client.js" -import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js" +import { RequestExecutor } from "./route/executor.js" +import { AIError, UnsupportedOperationError } from "./schema/index.js" +import type { ImageEvent, ImageJob, ImageModel, ImageRequest, ImageResponse, ImageStatus } from "./image.js" -export type Interface = MediaClient.Interface +/** `start`, `status`, `result` and `cancel` fail with `UnsupportedOperation` on inline and stream routes. */ +export interface Interface + extends Pick, "generate" | "stream"> { + readonly start: (request: ImageRequest) => Effect.Effect + readonly status: (model: ImageModel, id: string) => Effect.Effect + readonly result: (model: ImageModel, id: string) => Effect.Effect + readonly cancel: (model: ImageModel, id: string) => Effect.Effect +} export class ImageClientService extends Context.Service()("@opencode/ImageClient") {} export const Service = ImageClientService export type Service = ImageClientService -export const ImageClient = { +const responseEvents = (response: ImageResponse) => [ + ...response.images.map((image, index) => ({ type: "image" as const, index, image })), + { type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata }, +] + +// A queued image route whose token isn't a string is a programmer defect, not a provider error. +const decodeID = (token: unknown) => Schema.decodeUnknownEffect(Schema.String)(token).pipe(Effect.orDie) + +export const layer = Layer.effect( Service, - ...MediaClient.make(Service, { - modality: "image", - responseEvents: (response: ImageResponse) => [ - ...response.images.map((image, index) => ({ type: "image" as const, index, image })), - { type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata }, - ], + Effect.gen(function* () { + const executor = yield* RequestExecutor.Service + const media = MediaClient.operations(executor.execute, { + modality: "image", + responseEvents, + }) + const attach = (model: ImageModel, id: string, operation: string) => { + if (model.route.kind !== "queued") return Effect.fail(MediaClient.notQueued("image", model.route, operation)) + return model.route.attach(model, id, executor.execute) + } + return Service.of({ + generate: media.generate, + stream: media.stream, + start: (request) => + media.start(request).pipe( + // The token, not the snapshot id, is what `status` and `result` decode; `ImageModel.fromRoute` makes it a string. + Effect.flatMap((generation) => decodeID(generation.token)), + Effect.map((id) => ({ id })), + ), + status: (model, id) => + attach(model, id, "status").pipe( + Effect.flatMap((route) => route.status), + Effect.map((snapshot) => ({ status: snapshot.status, progress: snapshot.progress })), + ), + result: (model, id) => attach(model, id, "result").pipe(Effect.flatMap((route) => route.result)), + cancel: (model, id) => + attach(model, id, "cancel").pipe( + Effect.flatMap( + (route) => + route.cancel ?? + Effect.fail( + new AIError({ + reason: new UnsupportedOperationError({ + operation: "image.cancel", + provider: model.provider, + route: model.route.id, + message: `${model.provider}/${model.route.id} has no way to cancel an image generation`, + }), + }), + ), + ), + ), + }) }), +) + +export const ImageClient = { + Service, + layer, + responseEvents, + generate: (request: ImageRequest, options?: AwaitOptions) => + Service.use((client) => client.generate(request, options)), + stream: (request: ImageRequest, options?: AwaitOptions) => + Stream.unwrap(Service.useSync((client) => client.stream(request, options))), + start: (request: ImageRequest) => Service.use((client) => client.start(request)), + status: (model: ImageModel, id: string) => Service.use((client) => client.status(model, id)), + result: (model: ImageModel, id: string) => Service.use((client) => client.result(model, id)), + cancel: (model: ImageModel, id: string) => Service.use((client) => client.cancel(model, id)), } as const diff --git a/packages/ai/src/image.ts b/packages/ai/src/image.ts index fb242669ddae..dd1799d920e6 100644 --- a/packages/ai/src/image.ts +++ b/packages/ai/src/image.ts @@ -1,5 +1,5 @@ import { Effect, Schema, Stream } from "effect" -import { Generation, ProgressEvent, QueuedEvent, type AwaitOptions } from "./generation.js" +import { ProgressEvent, QueuedEvent, type AwaitOptions, type Status } from "./generation.js" import { Media } from "./media.js" import { MediaModel, composeRoute, tryRequest } from "./media-model.js" import { MediaRoute } from "./route/media.js" @@ -24,7 +24,10 @@ export type ImageRoute = MediaRoute.AnyRoute extends MediaModel { declare protected readonly _ImageModel: void - /** The number of type arguments selects the kind: ``, ``, or ``. */ + /** + * The number of type arguments selects the kind: `` for inline or queued, `` for + * stream. A queued route's token is the provider's job ID, so `ImageJob.id` is exactly what `status` and `result` take. + */ static fromRoute( route: MediaModel.InlineRouteInput>, ImageResponse>, input: MediaRoute.ModelInput, @@ -33,12 +36,12 @@ export class ImageModel extends Med route: MediaModel.StreamRouteInput>, ImageEvent, Frame, State>, input: MediaRoute.ModelInput, ): ImageModel - static fromRoute( - route: MediaModel.QueuedRouteInput>, ImageResponse, Token>, + static fromRoute( + route: MediaModel.QueuedRouteInput>, ImageResponse, string>, input: MediaRoute.ModelInput, ): ImageModel - static fromRoute( - route: MediaModel.AnyRouteInput>, ImageEvent, ImageResponse, Frame, State, Token>, + static fromRoute( + route: MediaModel.AnyRouteInput>, ImageEvent, ImageResponse, Frame, State, string>, input: MediaRoute.ModelInput, ) { return new ImageModel({ @@ -99,9 +102,21 @@ export type ImageRequestInput = Omit< } // --------------------------------------------------------------------------- -// Response and events +// Job, status, response and events // --------------------------------------------------------------------------- +/** A submitted generation on a queued route. Store `id` with the model to read the job later, from any process. */ +export interface ImageJob { + /** The provider's job ID. */ + readonly id: string +} + +export interface ImageStatus { + readonly status: Status + /** 0..1, only when the provider reports progress. */ + readonly progress?: number +} + export class ImageResponse extends Schema.Class("Image.Response")({ images: Schema.Array(Media.AssetSchema), usage: Schema.optional(MediaUsage), @@ -193,21 +208,32 @@ export function stream(input: ImageRequestInput, options?: AwaitOptions) { return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => ImageClient.stream(request, options)))) } -/** Inline and streaming routes fail with `UnsupportedOperation`. */ +/** Submit a generation and return at once; nothing polls. Inline and stream routes fail with `UnsupportedOperation`. */ export function start( input: ImageRequestInput, -): Effect.Effect, AIError, Service> +): Effect.Effect export function start(input: ImageRequestInput) { return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.start(request))) } -export const resume = (model: ImageModel, token: unknown): Effect.Effect, AIError, Service> => - ImageClient.resume(model, token) +/** One status read for a job ID. */ +export const status = (model: ImageModel, id: string): Effect.Effect => + ImageClient.status(model, id) + +/** The finished images; fails while the job is still running, or with the provider's reason when it failed. */ +export const result = (model: ImageModel, id: string): Effect.Effect => + ImageClient.result(model, id) + +/** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */ +export const cancel = (model: ImageModel, id: string): Effect.Effect => + ImageClient.cancel(model, id) export const Image = { request, generate, stream, start, - resume, + status, + result, + cancel, } as const diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index a985831ca484..8495891924da 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -241,10 +241,14 @@ export const make = (options: Options = {}) => { input: ImageRequestInput | ImageRequest, options?: AwaitOptions & RunOptions, ) => iterate(Image.stream(input, options), options), + /** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */ start: (input: ImageRequestInput | ImageRequest, options?: RunOptions) => - run(Image.start(input), options).then(handle), - resume: (model: ImageModel, token: unknown, options?: RunOptions) => - run(Image.resume(model, token), options).then(handle), + run(Image.start(input), options), + /** One status read for a job ID. */ + status: (model: ImageModel, id: string, options?: RunOptions) => run(Image.status(model, id), options), + /** The finished images; fails while the job is still running. */ + result: (model: ImageModel, id: string, options?: RunOptions) => run(Image.result(model, id), options), + cancel: (model: ImageModel, id: string, options?: RunOptions) => run(Image.cancel(model, id), options), }, decision: { request: Decision.request, @@ -260,14 +264,14 @@ export const make = (options: Options = {}) => { }, video: { request: Video.request, - /** Submit a generation and return its `{ id, token }` at once; nothing polls. */ + /** Submit a generation and return its `{ id }` at once; nothing polls. */ start: (input: VideoRequestInput | VideoRequest, options?: RunOptions) => run(Video.start(input), options), - /** One status read for a stored token. */ - status: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.status(model, token), options), + /** One status read for a job ID. */ + status: (model: VideoModel, id: string, options?: RunOptions) => run(Video.status(model, id), options), /** The finished videos; fails while the job is still running. */ - result: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.result(model, token), options), - cancel: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.cancel(model, token), options), + result: (model: VideoModel, id: string, options?: RunOptions) => run(Video.result(model, id), options), + cancel: (model: VideoModel, id: string, options?: RunOptions) => run(Video.cancel(model, id), options), }, /** Experimental: may change without compatibility guarantees. */ experimental: { diff --git a/packages/ai/src/media-client.ts b/packages/ai/src/media-client.ts index 622bfa7fdbad..5de4cbe584e9 100644 --- a/packages/ai/src/media-client.ts +++ b/packages/ai/src/media-client.ts @@ -2,7 +2,7 @@ import { type Context, Effect, Layer, Stream } from "effect" import { resultEvents, type AwaitOptions, type Generation, type Observation } from "./generation.js" import { RequestExecutor } from "./route/executor.js" import type { MediaRoute } from "./route/media.js" -import { AIError, UnsupportedOperationError } from "./schema/index.js" +import { AIError, UnsupportedOperationError, type ProviderID } from "./schema/index.js" /** A media request whose model carries the route that executes it. */ export interface RoutedRequest extends MediaRoute.MediaRequest { @@ -17,55 +17,71 @@ export interface Interface, Even readonly resume: (model: Req["model"], token: unknown) => Effect.Effect, AIError> } -/** One modality's layer and service accessors, dispatching each request on its route's `kind`. */ +export interface Input { + readonly modality: string + /** A completed response expanded into the streaming event shape. */ + readonly responseEvents: (response: Response) => ReadonlyArray +} + +/** `${modality}.${operation}` on a route that is not queued. */ +export const notQueued = ( + modality: string, + route: { readonly provider: ProviderID; readonly id: string }, + operation: string, +) => + new AIError({ + reason: new UnsupportedOperationError({ + operation: `${modality}.${operation}`, + provider: route.provider, + route: route.id, + message: `${route.provider}/${route.id} is not a queued route; use generate or stream`, + }), + }) + +/** One modality's operations over an executor, dispatching each request on its route's `kind`. */ +export const operations = , Event, Response>( + execute: MediaRoute.Execute, + input: Input, +): Interface => { + const start = (request: Req) => { + const route = request.model.route + if (route.kind !== "queued") return Effect.fail(notQueued(input.modality, route, "start")) + return route.start(request, execute) + } + return { + start, + resume: (model, token) => { + if (model.route.kind !== "queued") return Effect.fail(notQueued(input.modality, model.route, "resume")) + return model.route.resume(model, token, execute) + }, + generate: (request, options) => { + const route = request.model.route + if (route.kind !== "queued") return route.generate(request, execute) + return start(request).pipe(Effect.flatMap((generation) => generation.await(options))) + }, + stream: (request, options) => { + const route = request.model.route + if (route.kind === "stream") return route.stream(request, execute) + if (route.kind === "queued") + return Stream.unwrap( + start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))), + ) + return Stream.fromIterableEffect(Effect.map(route.generate(request, execute), input.responseEvents)) + }, + } +} + +/** One modality's layer and service accessors over `operations`. */ export const make = , Event, Response>( service: Context.Service>, - input: { - readonly modality: string - /** A completed response expanded into the streaming event shape. */ - readonly responseEvents: (response: Response) => ReadonlyArray - }, + input: Input, ) => ({ responseEvents: input.responseEvents, layer: Layer.effect( service, Effect.gen(function* () { const executor = yield* RequestExecutor.Service - const notQueued = (route: MediaRoute.AnyRoute, operation: string) => - new AIError({ - reason: new UnsupportedOperationError({ - operation: `${input.modality}.${operation}`, - provider: route.provider, - route: route.id, - message: `${route.provider}/${route.id} is not a queued route; use generate or stream`, - }), - }) - const start = (request: Req) => { - const route = request.model.route - if (route.kind !== "queued") return Effect.fail(notQueued(route, "start")) - return route.start(request, executor.execute) - } - return service.of({ - start, - resume: (model, token) => { - if (model.route.kind !== "queued") return Effect.fail(notQueued(model.route, "resume")) - return model.route.resume(model, token, executor.execute) - }, - generate: (request, options) => { - const route = request.model.route - if (route.kind !== "queued") return route.generate(request, executor.execute) - return start(request).pipe(Effect.flatMap((generation) => generation.await(options))) - }, - stream: (request, options) => { - const route = request.model.route - if (route.kind === "stream") return route.stream(request, executor.execute) - if (route.kind === "queued") - return Stream.unwrap( - start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))), - ) - return Stream.fromIterableEffect(Effect.map(route.generate(request, executor.execute), input.responseEvents)) - }, - }) + return service.of(operations(executor.execute, input)) }), ), generate: (request: Req, options?: AwaitOptions) => service.use((client) => client.generate(request, options)), diff --git a/packages/ai/src/media.ts b/packages/ai/src/media.ts index b35da7c89cb5..9ac2ca44c291 100644 --- a/packages/ai/src/media.ts +++ b/packages/ai/src/media.ts @@ -239,6 +239,20 @@ export const AssetSchema = AssetEncoded.pipe( }), ) +/** + * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with + * `Media.image`; an asset known to be a video, audio or document is rejected. + */ +export const ImageAssetSchema = AssetInstance.check( + Schema.makeFilter( + (asset) => + asset.kind === "image" || + ((asset.source.type === "url" || asset.source.type === "ref") && asset.source.mediaType === undefined) || + `expected an image, got ${asset.mediaType}`, + ), +).pipe(Schema.brand("Media.ImageAsset")) +export type ImageAsset = typeof ImageAssetSchema.Type + const download = Effect.fn("Media.download")(function* ( source: Extract, headers: Record | undefined, @@ -330,6 +344,13 @@ export type Data = Uint8Array | ArrayBuffer | URL | string /** What file inputs accept: an `Asset` or plain `Data`. */ export type Input = Asset | Data +/** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */ +export const image = (input: Input, mediaType?: string): ImageAsset => { + const asset = make(input, mediaType) + if (!Schema.is(ImageAssetSchema)(asset)) throw invalid(`expected an image, got ${asset.mediaType}`) + return asset +} + /** * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged. diff --git a/packages/ai/src/protocols/google-interactions-video.ts b/packages/ai/src/protocols/google-interactions-video.ts index 93d15a9d7940..0f61c6a597c5 100644 --- a/packages/ai/src/protocols/google-interactions-video.ts +++ b/packages/ai/src/protocols/google-interactions-video.ts @@ -49,7 +49,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ interactionID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const Content = Schema.Struct({ @@ -128,11 +129,6 @@ const task = (request: Request) => { const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* (request: Request) { if (request.end !== undefined && request.start === undefined) return yield* route.unsupported("video.end", `${route.name} reads a lone image as the start frame; send start too`) - if (request.sound === false) - return yield* route.unsupported( - "video.sound", - `${route.name} always generates audio and has no option to turn it off`, - ) const media = yield* Effect.forEach( [request.start, request.end, ...(request.references ?? [])].filter( (asset): asset is Media.Asset => asset !== undefined, @@ -168,7 +164,7 @@ const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* ( // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(Interaction, (value) => ({ - token: { interactionID: value.id }, + token: value.id, snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status) }, })) @@ -179,7 +175,7 @@ const decodeStatus = Effect.fn("GoogleInteractionsVideo.decodeStatus")(function* context: MediaProtocol.PollContext, ) { const output = yield* decodeInteraction(response) - return { id: context.token.interactionID, status: MediaProtocol.status(STATUS, output.value.status) } + return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) } }) const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* ( @@ -189,7 +185,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* const output = yield* decodeInteraction(response) const decoded = output.value const status = MediaProtocol.status(STATUS, decoded.status) - if (status === "running") return yield* output.pending(context.token.interactionID) + if (status === "running") return yield* output.pending(context.token) const errors = decoded.errors ?? [] const codes = errors.flatMap((error) => { const code = errorCode(error.code) @@ -197,7 +193,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* }) const messages = errors.flatMap((error) => (error.message?.trim() ? [error.message.trim()] : [])) if (status === "cancelled") - return yield* output.ended("cancelled", `${route.name} interaction ${context.token.interactionID} was cancelled`) + return yield* output.ended("cancelled", `${route.name} interaction ${context.token} was cancelled`) if (status === "failed") { const message = `${route.name} generation failed${codes.length === 0 ? "" : ` (${codes.join(", ")})`}${messages.length === 0 ? "" : `: ${messages.join("\n")}`}` if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code))) @@ -250,7 +246,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* // 7. Protocol and route // --------------------------------------------------------------------------- -const interactionPath = (token: Token) => `${PATH}/${token.interactionID}` +const interactionPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}` export const protocol = MediaProtocol.queued(route, { token: Token, @@ -261,7 +257,7 @@ export const protocol = MediaProtocol.queued(rout }) export const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) + VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) export const GoogleInteractionsVideo = { protocol, diff --git a/packages/ai/src/protocols/minimax-video.ts b/packages/ai/src/protocols/minimax-video.ts index a5ff152e3d1e..aab982336fec 100644 --- a/packages/ai/src/protocols/minimax-video.ts +++ b/packages/ai/src/protocols/minimax-video.ts @@ -47,7 +47,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ taskID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const BaseResp = optionalNull( @@ -176,9 +177,7 @@ const reference = (asset: Media.Asset) => const resolution = (request: Request) => request.resolution?.toUpperCase() const fromRequest = Effect.fn("MiniMaxVideo.fromRequest")(function* (request: Request) { - // H3 always generates a soundtrack and has no field to turn it off. - if (request.sound === false) - return yield* route.unsupported("video.sound", `${route.name} always generates sound and can't be silenced`) + // H3 always generates a soundtrack and has no field for `sound`, so it isn't sent. const content = [ { type: "text", text: request.prompt }, ...(request.start === undefined ? [] : [yield* item(request.start, "first_frame")]), @@ -212,8 +211,7 @@ const hailuoFromRequest = Effect.fn("MiniMaxHailuoVideo.fromRequest")(function* `${hailuoRoute.name} takes only image (subject) references`, ) // Hailuo output is always silent and its shape follows the model or the first frame, with no field for either. - if (request.sound === true) - return yield* hailuoRoute.unsupported("video.sound", `${hailuoRoute.name} generates silent video only`) + // `sound` has nothing to send, so it isn't; an aspect ratio would change the shape the caller asked for. if (request.aspect !== undefined && request.aspect !== "auto") return yield* hailuoRoute.unsupported("video.aspect", `${hailuoRoute.name} has no aspect ratio input`) const subjects = yield* Effect.forEach(references, (asset) => @@ -241,7 +239,7 @@ const hailuoFromRequest = Effect.fn("MiniMaxHailuoVideo.fromRequest")(function* // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { taskID: value.task_id }, + token: value.task_id, snapshot: { id: value.task_id, status: "queued" }, })) @@ -253,7 +251,7 @@ const decodeStatus = Effect.fn("MiniMaxVideo.decodeStatus")(function* ( ) { const output = yield* decodeTask(response) const task = output.value.task ?? output.value - return { id: context.token.taskID, status: MediaProtocol.status(STATUS, task.status ?? "") } + return { id: context.token, status: MediaProtocol.status(STATUS, task.status ?? "") } }) const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* ( @@ -263,11 +261,11 @@ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* ( const output = yield* decodeTask(response) const task = output.value.task ?? output.value const status = MediaProtocol.status(STATUS, task.status ?? "") - if (status === "queued" || status === "running") return yield* output.pending(context.token.taskID) + if (status === "queued" || status === "running") return yield* output.pending(context.token) if (status === "failed") return yield* failed(output, route.name, task.error?.code ?? undefined, task.error?.message ?? undefined) if (status !== "completed") - return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`) + return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`) const url = task.content?.url ?? undefined if (url === undefined) return yield* output.invalid(`${route.name} completed without a video URL`) const duration = task.duration ?? undefined @@ -283,7 +281,7 @@ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* ( usage: typeof total === "number" ? { type: "seconds", seconds: total } : undefined, providerMetadata: { minimax: { - taskId: context.token.taskID, + taskId: context.token, model: task.model ?? undefined, resolution: task.resolution ?? undefined, ratio: task.ratio ?? undefined, @@ -301,7 +299,7 @@ const decodeHailuoStart = Effect.fn("MiniMaxHailuoVideo.decodeStart")(function* if (error) return yield* error const taskID = output.value.task_id ?? "" if (taskID === "") return yield* output.invalid(`${hailuoRoute.name} returned no task_id`) - return { token: { taskID }, snapshot: { id: taskID, status: "queued" as const } } + return { token: taskID, snapshot: { id: taskID, status: "queued" as const } } }) const decodeHailuoTask = hailuoRoute.decodeJson(HailuoTask) @@ -315,7 +313,7 @@ const decodeHailuoStatus = Effect.fn("MiniMaxHailuoVideo.decodeStatus")(function // A failed task also carries its reason in `base_resp`; any other non-zero code is a failed read. const error = status === "failed" ? undefined : baseError(output, output.value.base_resp) if (error) return yield* error - return { id: context.token.taskID, status } + return { id: context.token, status } }) const decodeHailuoFile = hailuoRoute.decodeJson(HailuoFile) @@ -330,7 +328,7 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function const error = baseError(output, task.base_resp) if (status === "failed") return yield* error ?? failed(output, hailuoRoute.name, undefined, undefined) if (error) return yield* error - if (status !== "completed") return yield* output.pending(context.token.taskID) + if (status !== "completed") return yield* output.pending(context.token) const fileID = task.file_id ?? "" if (fileID === "") return yield* output.invalid(`${hailuoRoute.name} completed without a file_id`) // The task names a file; its download URL takes a second lookup and is valid for one hour. @@ -349,7 +347,7 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function }), ], providerMetadata: { - minimax: { taskId: context.token.taskID, fileId: fileID }, + minimax: { taskId: context.token, fileId: fileID }, }, }) }) @@ -361,13 +359,13 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function export const protocol = MediaProtocol.queued(route, { token: Token, start: { body: { from: fromRequest }, decode: decodeStart }, - status: { path: (token) => `${STATUS_PATH}/${token.taskID}`, decode: decodeStatus }, - result: { path: (token) => `${STATUS_PATH}/${token.taskID}`, decode: decodeResult }, + status: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeStatus }, + result: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeResult }, // Cancels a queued task; MiniMax rejects it once the task is running. - cancel: { method: "DELETE", path: (token) => `${PATH}/${token.taskID}` }, + cancel: { method: "DELETE", path: (token) => `${PATH}/${encodeURIComponent(token)}` }, }) -const hailuoStatusPath = (token: Token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token.taskID)}` +const hailuoStatusPath = (token: Token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token)}` export const hailuoProtocol = MediaProtocol.queued(hailuoRoute, { token: Token, @@ -378,11 +376,11 @@ export const hailuoProtocol = MediaProtocol.queued - VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) + VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) /** Hailuo and the `*-01` models on the v1 API. */ export const hailuoModel = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute( + VideoModel.fromRoute( { protocol: hailuoProtocol, baseURL: DEFAULT_BASE_URL, path: HAILUO_PATH }, input, ) diff --git a/packages/ai/src/protocols/openrouter-video.ts b/packages/ai/src/protocols/openrouter-video.ts index 3ea10d3dc711..6df2a92364d2 100644 --- a/packages/ai/src/protocols/openrouter-video.ts +++ b/packages/ai/src/protocols/openrouter-video.ts @@ -43,7 +43,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ id: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const StartResponse = Schema.Struct({ id: Schema.String, status: optionalNull(Schema.String) }) @@ -133,7 +134,7 @@ const resolution = (value: string) => (/^\dk$/.test(value) ? value.toUpperCase() // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { id: value.id }, + token: value.id, snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status ?? "pending") }, })) @@ -144,7 +145,7 @@ const decodeStatus = Effect.fn("OpenRouterVideo.decodeStatus")(function* ( context: MediaProtocol.PollContext, ) { const output = yield* decodeJob(response) - return { id: context.token.id, status: MediaProtocol.status(STATUS, output.value.status) } + return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) } }) const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( @@ -154,7 +155,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( const output = yield* decodeJob(response) const job = output.value const status = MediaProtocol.status(STATUS, job.status) - if (status === "queued" || status === "running") return yield* output.pending(context.token.id) + if (status === "queued" || status === "running") return yield* output.pending(context.token) if (status === "failed") { const message = `${route.name} generation failed${job.error ? `: ${job.error}` : ""}` if (job.error && /content policy|moderat/i.test(job.error)) return yield* output.contentPolicy(message) @@ -163,7 +164,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( if (status !== "completed") return yield* output.ended( status, - `${route.name} job ${context.token.id} ${status}${job.error ? `: ${job.error}` : ""}`, + `${route.name} job ${context.token} ${status}${job.error ? `: ${job.error}` : ""}`, ) const urls = job.unsigned_urls ?? [] if (urls.length === 0) return yield* output.invalid(`${route.name} completed without a video URL`) @@ -183,7 +184,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( videos, providerMetadata: { openrouter: { - id: context.token.id, + id: context.token, generationId: job.generation_id ?? undefined, cost: job.usage?.cost ?? undefined, isByok: job.usage?.is_byok ?? undefined, @@ -196,7 +197,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( // 6. Protocol and route // --------------------------------------------------------------------------- -const jobPath = (token: Token) => `${PATH}/${encodeURIComponent(token.id)}` +const jobPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}` // OpenRouter has no cancel endpoint; `cancelled` only appears when it stops a job itself. export const protocol = MediaProtocol.queued(route, { @@ -207,7 +208,7 @@ export const protocol = MediaProtocol.queued(rout }) export const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) + VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) export const OpenRouterVideo = { protocol, diff --git a/packages/ai/src/protocols/seedance-video.ts b/packages/ai/src/protocols/seedance-video.ts index beafc561aba3..08563535ea01 100644 --- a/packages/ai/src/protocols/seedance-video.ts +++ b/packages/ai/src/protocols/seedance-video.ts @@ -47,7 +47,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ taskID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const StartResponse = Schema.Struct({ id: Schema.String }) @@ -194,7 +195,7 @@ const make = (provider: Provider) => { }) const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { taskID: value.id }, + token: value.id, snapshot: { id: value.id, status: "queued" }, })) @@ -205,7 +206,7 @@ const make = (provider: Provider) => { context: MediaProtocol.PollContext, ) { const output = yield* decodeTask(response) - return { id: context.token.taskID, status: MediaProtocol.status(STATUS, output.value.status) } + return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) } }) const decodeResult = Effect.fn("SeedanceVideo.decodeResult")(function* ( @@ -215,7 +216,7 @@ const make = (provider: Provider) => { const output = yield* decodeTask(response) const task = output.value const status = MediaProtocol.status(STATUS, task.status) - if (status === "queued" || status === "running") return yield* output.pending(context.token.taskID) + if (status === "queued" || status === "running") return yield* output.pending(context.token) if (status === "failed") { const code = task.error?.code ?? undefined const detail = task.error?.message ?? undefined @@ -224,9 +225,8 @@ const make = (provider: Provider) => { return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, code?.split(".")[0])) } if (status === "cancelled") - return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`) - if (status === "expired") - return yield* output.ended("expired", `${route.name} task ${context.token.taskID} expired`) + return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`) + if (status === "expired") return yield* output.ended("expired", `${route.name} task ${context.token} expired`) const videoURL = task.content?.video_url ?? undefined if (videoURL === undefined) return yield* output.invalid(`${route.name} completed without a video URL`) const duration = durationSeconds(task) @@ -254,7 +254,7 @@ const make = (provider: Provider) => { }, providerMetadata: { [provider]: { - taskId: context.token.taskID, + taskId: context.token, model: task.model ?? undefined, seed: task.seed ?? undefined, ratio: task.ratio ?? undefined, @@ -272,7 +272,7 @@ const make = (provider: Provider) => { }) }) - const taskPath = (token: Token) => `${PATH}/${token.taskID}` + const taskPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}` // DELETE cancels a queued task. Ark refuses it for a running task, and deletes the record of a finished one. const protocol = MediaProtocol.queued(route, { @@ -284,7 +284,7 @@ const make = (provider: Provider) => { }) const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute( + VideoModel.fromRoute( { protocol, baseURL: provider === "volcengine" ? VOLCENGINE_BASE_URL : BYTEPLUS_BASE_URL, diff --git a/packages/ai/src/protocols/xai-video.ts b/packages/ai/src/protocols/xai-video.ts index 8a804543ffd0..49bb43496a1c 100644 --- a/packages/ai/src/protocols/xai-video.ts +++ b/packages/ai/src/protocols/xai-video.ts @@ -36,7 +36,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ requestID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const StartResponse = Schema.Struct({ request_id: Schema.String }) @@ -132,7 +133,7 @@ const fromRequest = Effect.fn("XAIVideo.fromRequest")(function* (request: Reques // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { requestID: value.request_id }, + token: value.request_id, snapshot: { id: value.request_id, status: "running" }, })) @@ -148,7 +149,7 @@ const decodeStatus = Effect.fn("XAIVideo.decodeStatus")(function* ( ) { const output = yield* decodeVideoStatus(response) const status = MediaProtocol.status(STATUS, output.value.status) - return { id: context.token.requestID, status, progress: fraction(output.value.progress) } + return { id: context.token, status, progress: fraction(output.value.progress) } }) const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( @@ -158,7 +159,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( const output = yield* decodeVideoStatus(response) const decoded = output.value const status = MediaProtocol.status(STATUS, decoded.status) - if (status === "running") return yield* output.pending(context.token.requestID) + if (status === "running") return yield* output.pending(context.token) if (status === "failed") { const code = decoded.error?.code ?? undefined const message = decoded.error?.message ?? undefined @@ -168,8 +169,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( MediaProtocol.failure(FAILURE, code), ) } - if (status !== "completed") - return yield* output.ended("expired", `${route.name} request ${context.token.requestID} expired`) + if (status !== "completed") return yield* output.ended("expired", `${route.name} request ${context.token} expired`) // `respect_moderation: false` marks a filtered result; a URL may still be present, so only a missing one fails. const moderated = decoded.video?.respect_moderation === false const url = decoded.video?.url ?? undefined @@ -186,7 +186,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( ], providerMetadata: { xai: { - requestId: context.token.requestID, + requestId: context.token, model: decoded.model ?? undefined, respectModeration: decoded.video?.respect_moderation ?? undefined, }, @@ -198,7 +198,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( // 7. Protocol and route // --------------------------------------------------------------------------- -const statusPath = (token: Token) => `${STATUS_PATH}/${token.requestID}` +const statusPath = (token: Token) => `${STATUS_PATH}/${encodeURIComponent(token)}` export const protocol = MediaProtocol.queued(route, { token: Token, @@ -215,7 +215,7 @@ const startPath = (request: Request) => { } export const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute( + VideoModel.fromRoute( { protocol, baseURL: DEFAULT_BASE_URL, diff --git a/packages/ai/src/providers/google.ts b/packages/ai/src/providers/google.ts index 902eab299b22..a1143b5ebb03 100644 --- a/packages/ai/src/providers/google.ts +++ b/packages/ai/src/providers/google.ts @@ -74,7 +74,8 @@ export const configure = (input: Config = {}) => { interactionsRoute(input).model({ id: modelID }), image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => GoogleImages.model({ ...media, id: modelID, providerOptions }), - video: (modelID: string | ModelID) => GoogleInteractionsVideo.model({ ...media, id: modelID }), + video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + GoogleInteractionsVideo.model({ ...media, id: modelID, providerOptions }), speech: (modelID: string | ModelID) => GoogleSpeech.model({ ...media, id: modelID }), transcription: (modelID: string | ModelID) => GoogleTranscription.model({ ...media, id: modelID }), embedding: (modelID: string | ModelID, providerOptions?: ProviderOptions) => @@ -94,7 +95,10 @@ export const imageModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).image(modelID, input.providerOptions) } -export const videoModel = (modelID: string, settings?: Settings) => configure(toConfig(settings)).video(modelID) +export const videoModel = (modelID: string, settings?: Settings) => { + const input = toConfig(settings) + return configure(input).video(modelID, input.providerOptions) +} export const embeddingModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).embedding(modelID, input.providerOptions) diff --git a/packages/ai/src/providers/xai.ts b/packages/ai/src/providers/xai.ts index ef2ce340b960..6b659a2c7c0d 100644 --- a/packages/ai/src/providers/xai.ts +++ b/packages/ai/src/providers/xai.ts @@ -100,7 +100,8 @@ export const configure = (input: Config = {}) => { chat, image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => XAIImages.model({ ...media, id: modelID, providerOptions }), - video: (modelID: string | ModelID) => XAIVideo.model({ ...media, id: modelID }), + video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + XAIVideo.model({ ...media, id: modelID, providerOptions }), configure, } } @@ -114,6 +115,10 @@ export const imageModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).image(modelID, input.providerOptions) } +export const videoModel = (modelID: string, settings?: Settings) => { + const input = toConfig(settings) + return configure(input).video(modelID, input.providerOptions) +} export const responses = provider.responses export const chat = provider.chat export const image = provider.image diff --git a/packages/ai/src/providers/xai/videos.ts b/packages/ai/src/providers/xai/videos.ts new file mode 100644 index 000000000000..96689564e07d --- /dev/null +++ b/packages/ai/src/providers/xai/videos.ts @@ -0,0 +1,2 @@ +export { videoModel as model } from "../xai.js" +export type { Settings } from "../xai.js" diff --git a/packages/ai/src/public.ts b/packages/ai/src/public.ts index d38f6a6046e8..14eb9b4f24b3 100644 --- a/packages/ai/src/public.ts +++ b/packages/ai/src/public.ts @@ -109,12 +109,14 @@ export type { } from "./schema/index.js" export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageResponse } from "./image.js" export type { + ImageJob, ImageModelOptions, ImageOptions, ImageRequest, ImageRequestInput, ImageResolution, ImageRoute, + ImageStatus, } from "./image.js" export { VideoAspectRatio, VideoDuration, VideoModel, VideoModelSchema, VideoResponse } from "./video.js" export type { diff --git a/packages/ai/src/video-client.ts b/packages/ai/src/video-client.ts index 960677c86f96..9f7f6c250a6a 100644 --- a/packages/ai/src/video-client.ts +++ b/packages/ai/src/video-client.ts @@ -1,37 +1,42 @@ -import { Context, Effect, Layer } from "effect" +import { Context, Effect, Layer, Schema } from "effect" import { RequestExecutor } from "./route/executor.js" import { AIError, UnsupportedOperationError } from "./schema/index.js" import type { VideoJob, VideoModel, VideoRequest, VideoResponse, VideoStatus } from "./video.js" export interface Interface { readonly start: (request: VideoRequest) => Effect.Effect - readonly status: (model: VideoModel, token: unknown) => Effect.Effect - readonly result: (model: VideoModel, token: unknown) => Effect.Effect - readonly cancel: (model: VideoModel, token: unknown) => Effect.Effect + readonly status: (model: VideoModel, id: string) => Effect.Effect + readonly result: (model: VideoModel, id: string) => Effect.Effect + readonly cancel: (model: VideoModel, id: string) => Effect.Effect } export class VideoClientService extends Context.Service()("@opencode/VideoClient") {} export const Service = VideoClientService export type Service = VideoClientService +// A video route whose token isn't a string is a programmer defect, not a provider error. +const decodeID = (token: unknown) => Schema.decodeUnknownEffect(Schema.String)(token).pipe(Effect.orDie) + export const layer = Layer.effect( Service, Effect.gen(function* () { const executor = yield* RequestExecutor.Service - const attach = (model: VideoModel, token: unknown) => model.route.attach(model, token, executor.execute) + const attach = (model: VideoModel, id: string) => model.route.attach(model, id, executor.execute) return Service.of({ start: (request) => - request.model.route - .start(request, executor.execute) - .pipe(Effect.map((generation) => ({ id: generation.id, token: generation.token }))), - status: (model, token) => - attach(model, token).pipe( + request.model.route.start(request, executor.execute).pipe( + // The token, not the snapshot id, is what `status` and `result` decode; `VideoModel.fromRoute` makes it a string. + Effect.flatMap((generation) => decodeID(generation.token)), + Effect.map((id) => ({ id })), + ), + status: (model, id) => + attach(model, id).pipe( Effect.flatMap((route) => route.status), Effect.map((snapshot) => ({ status: snapshot.status, progress: snapshot.progress })), ), - result: (model, token) => attach(model, token).pipe(Effect.flatMap((route) => route.result)), - cancel: (model, token) => - attach(model, token).pipe( + result: (model, id) => attach(model, id).pipe(Effect.flatMap((route) => route.result)), + cancel: (model, id) => + attach(model, id).pipe( Effect.flatMap( (route) => route.cancel ?? @@ -55,7 +60,7 @@ export const VideoClient = { Service, layer, start: (request: VideoRequest) => Service.use((client) => client.start(request)), - status: (model: VideoModel, token: unknown) => Service.use((client) => client.status(model, token)), - result: (model: VideoModel, token: unknown) => Service.use((client) => client.result(model, token)), - cancel: (model: VideoModel, token: unknown) => Service.use((client) => client.cancel(model, token)), + status: (model: VideoModel, id: string) => Service.use((client) => client.status(model, id)), + result: (model: VideoModel, id: string) => Service.use((client) => client.result(model, id)), + cancel: (model: VideoModel, id: string) => Service.use((client) => client.cancel(model, id)), } as const diff --git a/packages/ai/src/video.ts b/packages/ai/src/video.ts index d97f4fae2d8f..a318e07a5b7a 100644 --- a/packages/ai/src/video.ts +++ b/packages/ai/src/video.ts @@ -19,14 +19,15 @@ import { VideoClient, Service } from "./video-client.js" export type VideoOptions = MediaModel.Options -/** Video generation is always a queued job: submit, then read its status and result by token. */ +/** Video generation is always a queued job: submit, then read its status and result by the provider's job ID. */ export type VideoRoute = MediaRoute.QueuedRoute export class VideoModel extends MediaModel { declare protected readonly _VideoModel: void - static fromRoute( - route: MediaModel.QueuedRouteInput>, VideoResponse, Token>, + /** A video route's token is the provider's job ID, so `VideoJob.id` is exactly what `status` and `result` take. */ + static fromRoute( + route: MediaModel.QueuedRouteInput>, VideoResponse, string>, input: MediaRoute.ModelInput, ) { return new VideoModel({ @@ -65,9 +66,9 @@ const VideoRequestSchema = Schema.Struct({ model: VideoModelSchema, prompt: Schema.String, /** Image the video starts on exactly. */ - start: Schema.optional(Media.AssetSchema), + start: Schema.optional(Media.ImageAssetSchema), /** Image the video ends on exactly. */ - end: Schema.optional(Media.AssetSchema), + end: Schema.optional(Media.ImageAssetSchema), /** Images, videos or audio that guide the subject or style without pinning a frame. */ references: Schema.optional(Schema.Array(Media.AssetSchema)), duration: Schema.optional(VideoDuration), @@ -92,8 +93,9 @@ export type VideoRequestInput = Omit< VideoRequest, "start" | "end" | "references" | "providerOptions" > & { - readonly start?: Media.Input - readonly end?: Media.Input + /** An image: `Media.image(...)`, or a URL, data URL, base64 string or bytes, which must not be a known non-image. */ + readonly start?: Media.ImageAsset | Media.Data + readonly end?: Media.ImageAsset | Media.Data readonly references?: ReadonlyArray readonly providerOptions?: NoInfer> } @@ -105,10 +107,10 @@ export const seconds = (duration: VideoDuration) => Duration.toSeconds(Duration. // Job, status and response // --------------------------------------------------------------------------- -/** A submitted generation. Store `token` (plain JSON) with the model to read the job later, from any process. */ +/** A submitted generation. Store `id` with the model to read the job later, from any process. */ export interface VideoJob { + /** The provider's job ID. */ readonly id: string - readonly token: unknown } export interface VideoStatus { @@ -134,8 +136,8 @@ export class VideoResponse extends Schema.Class("Video.Response") /** Normalize video request input into a plain `VideoRequest`. */ export const request = (input: VideoRequestInput): VideoRequest => ({ ...input, - start: input.start === undefined ? undefined : Media.make(input.start), - end: input.end === undefined ? undefined : Media.make(input.end), + start: input.start === undefined ? undefined : Media.image(input.start), + end: input.end === undefined ? undefined : Media.image(input.end), references: input.references?.map((reference) => Media.make(reference)), }) @@ -156,17 +158,17 @@ export function start(input: VideoRequestInput) { return requestEffect(input).pipe(Effect.flatMap((request) => VideoClient.start(request))) } -/** One status read for a stored token. */ -export const status = (model: VideoModel, token: unknown): Effect.Effect => - VideoClient.status(model, token) +/** One status read for a job ID. */ +export const status = (model: VideoModel, id: string): Effect.Effect => + VideoClient.status(model, id) /** The finished videos; fails while the job is still running, or with the provider's reason when it failed. */ -export const result = (model: VideoModel, token: unknown): Effect.Effect => - VideoClient.result(model, token) +export const result = (model: VideoModel, id: string): Effect.Effect => + VideoClient.result(model, id) /** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */ -export const cancel = (model: VideoModel, token: unknown): Effect.Effect => - VideoClient.cancel(model, token) +export const cancel = (model: VideoModel, id: string): Effect.Effect => + VideoClient.cancel(model, id) export const Video = { request, diff --git a/packages/ai/test/generation.test.ts b/packages/ai/test/generation.test.ts index 90eda9f3a632..e89222573b38 100644 --- a/packages/ai/test/generation.test.ts +++ b/packages/ai/test/generation.test.ts @@ -97,7 +97,9 @@ describe("Generation", () => { const generation = new Generation(route, "t", { id: "gen_1", status: "queued" }) const fiber = yield* Effect.forkChild( - generation.events({ poll: { interval: "1 second", timeout: "5 seconds" } }).pipe(Stream.runCollect, Effect.flip), + generation + .events({ poll: { interval: "1 second", timeout: "5 seconds" } }) + .pipe(Stream.runCollect, Effect.flip), ) yield* TestClock.adjust("6 seconds") const error = yield* Fiber.join(fiber) diff --git a/packages/ai/test/google-interactions-video.test.ts b/packages/ai/test/google-interactions-video.test.ts index 8bbad982ffec..a57253f7f7f9 100644 --- a/packages/ai/test/google-interactions-video.test.ts +++ b/packages/ai/test/google-interactions-video.test.ts @@ -9,7 +9,7 @@ const layer = (handler: Parameters[0]) => VideoClient.layer.pipe(Layer.provideMerge(dynamicResponse(handler))) const model = Google.configure({ apiKey: "test", baseURL: "https://google.test/v1beta" }).video("gemini-omni-1.2-flash") -const token = { interactionID: "v1_abc" } +const id = "v1_abc" const started = { id: "v1_abc", status: "in_progress", object: "interaction", model: "gemini-omni-1.2-flash" } // "AAAAIGZ0eXBpc29t" is the base64 of an MP4 `ftyp` box header. const completed = { @@ -65,7 +65,7 @@ describe("ai.video.start / Google Interactions", () => { ), ), ) - expect(job).toEqual({ id: "v1_abc", token }) + expect(job).toEqual({ id: "v1_abc" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://google.test/v1beta/interactions?trace=1", ]) @@ -100,8 +100,10 @@ describe("ai.video.start / Google Interactions", () => { const { body } = yield* sent({ model, prompt: "Morph", - start: Media.fromDataUrl("data:image/png;base64,AQID"), - end: Media.ref("google", "https://generativelanguage.googleapis.com/v1beta/files/last", "image/jpeg"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), + end: Media.image( + Media.ref("google", "https://generativelanguage.googleapis.com/v1beta/files/last", "image/jpeg"), + ), }) expect(body.input).toEqual([ { type: "image", data: "AQID", mime_type: "image/png" }, @@ -147,9 +149,15 @@ describe("ai.video.start / Google Interactions", () => { }), ) + it.effect("sends nothing for sound, since Omni always generates audio and has no field for it", () => + Effect.gen(function* () { + const silent = yield* sent({ model, prompt: "x", sound: false }) + expect(JSON.stringify(silent.body)).not.toContain("audio") + }), + ) + for (const rejected of [ { name: "an end frame without a start frame", input: { end: "data:image/png;base64,AQID" }, operation: "end" }, - { name: "silent video", input: { sound: false }, operation: "sound" }, ]) it.effect(`rejects ${rejected.name}, which Omni has no way to send, before sending`, () => Effect.gen(function* () { @@ -170,7 +178,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { const calls: Array = [] const statuses = yield* Effect.gen(function* () { const job = yield* ai.video.start({ model, prompt: "x" }) - const decoded: unknown = JSON.parse(JSON.stringify(job.token)) + const decoded: unknown = job.id return [yield* ai.video.status(model, decoded), yield* ai.video.status(model, decoded)] }).pipe( Effect.provide( @@ -198,7 +206,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { ["in_progress", "completed", "incomplete", "failed", "cancelled", "requires_action", "constructor"], (status) => ai.video - .status(model, token) + .status(model, id) .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: "v1_abc", status }))))), ) expect(statuses.map((value) => value.status)).toEqual([ @@ -213,17 +221,9 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { }), ) - it.effect("rejects a token from another provider", () => - Effect.gen(function* () { - const error = yield* ai.video.status(model, { requestID: "req_1" }).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidRequest") - expect(error.message).toContain("cannot resume") - }).pipe(Effect.provide(layer(() => Effect.die("a foreign token reached the network")))), - ) - it.effect("decodes the inline video with token usage and interaction metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token) + const response = yield* ai.video.result(model, id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("bytes") expect(response.video.mediaType).toBe("video/mp4") @@ -237,7 +237,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { it.effect("keeps a Files API video URI as a Google reference", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token) + const response = yield* ai.video.result(model, id) expect(response.video.source).toEqual({ type: "ref", provider: "google", @@ -272,7 +272,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { it.effect("fails a result read before the interaction finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toBe( "Google Interactions Video generation v1_abc has not finished; await it before reading the result", @@ -323,7 +323,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { ]) it.effect(`fails the result of a ${terminal.body.status} interaction as ${terminal.tag}`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -334,7 +334,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { Effect.gen(function* () { const calls: Array = [] yield* ai.video - .cancel(model, token) + .cancel(model, id) .pipe( Effect.provide( layer((input) => diff --git a/packages/ai/test/image-job.test.ts b/packages/ai/test/image-job.test.ts new file mode 100644 index 000000000000..cba227bd9e42 --- /dev/null +++ b/packages/ai/test/image-job.test.ts @@ -0,0 +1,207 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer, Schema } from "effect" +import type { HttpClientResponse } from "effect/http" +import { + ai, + ImageClient, + ImageModel, + ImageResponse, + Media, + type GenerationStatus, + type ImageRequest, +} from "../src/effect.js" +import { Google } from "../src/providers.js" +import { Auth, MediaProtocol } from "../src/route.js" +import { it } from "./lib/effect.js" +import { dynamicResponse, json, observe, settle, type Call } from "./lib/http.js" + +const layer = (handler: Parameters[0]) => + ImageClient.layer.pipe(Layer.provideMerge(dynamicResponse(handler))) + +// No shipped image protocol is queued, so this test-only one exercises the job calls over the real route machinery. +const route = MediaProtocol.identity({ id: "test-queued-image", name: "Queued Image", provider: "test" }) + +const STATUS = { pending: "running", done: "completed", failed: "failed" } as const satisfies Record< + string, + GenerationStatus +> + +const decodeJob = route.decodeJson( + Schema.Struct({ + status: Schema.String, + progress: Schema.optional(Schema.Number), + url: Schema.optional(Schema.String), + }), +) + +const decodeStatus = (response: HttpClientResponse.HttpClientResponse, context: MediaProtocol.PollContext) => + decodeJob(response).pipe( + Effect.map((output) => ({ + id: context.token, + status: MediaProtocol.status(STATUS, output.value.status), + progress: output.value.progress, + })), + ) + +const decodeResult = Effect.fn("QueuedImage.decodeResult")(function* ( + response: HttpClientResponse.HttpClientResponse, + context: MediaProtocol.PollContext, +) { + const output = yield* decodeJob(response) + const status = MediaProtocol.status(STATUS, output.value.status) + if (status === "running") return yield* output.pending(context.token) + if (status === "failed") return yield* output.ended("failed", `${route.name} generation failed`) + if (output.value.url === undefined) return yield* output.invalid(`${route.name} completed without an image URL`) + return new ImageResponse({ images: [Media.url(output.value.url, { mediaType: "image/png" })] }) +}) + +const jobPath = (id: string) => `/jobs/${encodeURIComponent(id)}` + +const protocol = (cancel: boolean) => + MediaProtocol.queued(route, { + token: Schema.String, + start: { + body: { from: (request) => Effect.succeed(MediaProtocol.json({ prompt: request.prompt })) }, + decode: route.decodeStarted(Schema.Struct({ id: Schema.String }), (value) => ({ + token: value.id, + snapshot: { id: value.id, status: "queued" }, + })), + }, + status: { path: jobPath, decode: decodeStatus }, + result: { path: jobPath, decode: decodeResult }, + cancel: cancel ? { method: "DELETE", path: jobPath } : undefined, + }) + +const queued = (cancel = true) => + ImageModel.fromRoute( + { protocol: protocol(cancel), baseURL: "https://queued.test", path: "/jobs" }, + { id: "queued-image", auth: Auth.bearer("test") }, + ) + +const model = queued() + +describe("ai.image.start / status / result / cancel", () => { + it.effect("start submits and returns the job ID without polling", () => + Effect.gen(function* () { + const calls: Array = [] + const job = yield* ai.image + .start({ model, prompt: "A lighthouse" }) + .pipe( + Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, { id: "job_1" }))))), + ) + expect(job).toEqual({ id: "job_1" }) + expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual(["POST https://queued.test/jobs"]) + expect(JSON.parse(calls[0].body)).toEqual({ prompt: "A lighthouse" }) + }), + ) + + it.effect("status reads one status per call by job ID", () => + Effect.gen(function* () { + const calls: Array = [] + const statuses = yield* Effect.all([ai.image.status(model, "job/1"), ai.image.status(model, "job/1")]).pipe( + Effect.provide( + layer((input) => + observe(calls, input).pipe( + Effect.map(({ nth }) => + json(input, nth === 1 ? { status: "pending", progress: 0.4 } : { status: "done", url: "x" }), + ), + ), + ), + ), + ) + expect(statuses).toEqual([ + { status: "running", progress: 0.4 }, + { status: "completed", progress: undefined }, + ]) + expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ + "GET https://queued.test/jobs/job%2F1", + "GET https://queued.test/jobs/job%2F1", + ]) + }), + ) + + it.effect("result fails while the job is running and returns the images once it completes", () => + Effect.gen(function* () { + const pending = yield* ai.image + .result(model, "job_1") + .pipe(Effect.flip, Effect.provide(layer((input) => Effect.succeed(json(input, { status: "pending" }))))) + expect(pending.reason._tag).toBe("InvalidRequest") + expect(pending.message).toContain("has not finished") + + const response = yield* ai.image + .result(model, "job_1") + .pipe( + Effect.provide( + layer((input) => Effect.succeed(json(input, { status: "done", url: "https://queued.test/out.png" }))), + ), + ) + expect(response.images.map((image) => image.source)).toEqual([ + { type: "url", url: "https://queued.test/out.png", mediaType: "image/png", expiresAt: undefined }, + ]) + }), + ) + + it.effect("cancel calls the provider when it has a cancel call and fails typed when it has none", () => + Effect.gen(function* () { + const calls: Array = [] + yield* ai.image + .cancel(model, "job_1") + .pipe(Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, {})))))) + expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual(["DELETE https://queued.test/jobs/job_1"]) + + const error = yield* ai.image + .cancel(queued(false), "job_1") + .pipe(Effect.flip, Effect.provide(layer(() => Effect.die("cancel reached the network")))) + expect(error.reason._tag).toBe("UnsupportedOperation") + expect("operation" in error.reason && error.reason.operation).toBe("image.cancel") + }), + ) + + it.effect("generate still polls a queued route to the result", () => + Effect.gen(function* () { + const calls: Array = [] + const response = yield* settle( + ai.image.generate({ model, prompt: "A lighthouse" }, { poll: { interval: "1 second" } }), + 5, + ).pipe( + Effect.provide( + layer((input) => + observe(calls, input).pipe( + Effect.map(({ call, nth }) => { + if (call.method === "POST") return json(input, { id: "job_1" }) + return json( + input, + nth === 1 ? { status: "pending" } : { status: "done", url: "https://queued.test/a.png" }, + ) + }), + ), + ), + ), + ) + expect(response.images).toHaveLength(1) + expect(calls[0].method).toBe("POST") + }), + ) + + it.effect("every job call fails with UnsupportedOperation on an inline route before sending", () => + Effect.gen(function* () { + const inline = Google.configure({ apiKey: "test" }).image("gemini-3.1-flash-image") + const errors = yield* Effect.all( + [ + ai.image.start({ model: inline, prompt: "A lighthouse" }), + ai.image.status(inline, "job_1"), + ai.image.result(inline, "job_1"), + ai.image.cancel(inline, "job_1"), + ].map((effect) => Effect.flip(effect)), + ) + expect(errors.map((error) => [error.reason._tag, "operation" in error.reason && error.reason.operation])).toEqual( + [ + ["UnsupportedOperation", "image.start"], + ["UnsupportedOperation", "image.status"], + ["UnsupportedOperation", "image.result"], + ["UnsupportedOperation", "image.cancel"], + ], + ) + }).pipe(Effect.provide(layer(() => Effect.die("an unsupported job call reached the network")))), + ) +}) diff --git a/packages/ai/test/image.test.ts b/packages/ai/test/image.test.ts index b44949bfdc74..155abfd86945 100644 --- a/packages/ai/test/image.test.ts +++ b/packages/ai/test/image.test.ts @@ -1095,7 +1095,6 @@ describe("Image", () => { const prompt = "A lighthouse" const errors = yield* Effect.all( [ - ai.image.start({ model: Google.configure({ apiKey: "test" }).image("gemini-3.1-flash-image"), prompt }), ai.image.generate({ model: Google.configure({ apiKey: "test" }).image("gemini-3.1-flash-image"), prompt, @@ -1106,7 +1105,6 @@ describe("Image", () => { ) expect(errors.map((error) => [error.reason._tag, "operation" in error.reason && error.reason.operation])).toEqual( [ - ["UnsupportedOperation", "image.start"], ["UnsupportedOperation", "media.n"], ["UnsupportedOperation", "media.n"], ], diff --git a/packages/ai/test/image.types.ts b/packages/ai/test/image.types.ts index c3f846de68f6..225292e142db 100644 --- a/packages/ai/test/image.types.ts +++ b/packages/ai/test/image.types.ts @@ -3,15 +3,19 @@ import { ai, ImageClient, ImageModel, + type ImageJob, type ImageModelOptions, type ImageOptions, type ImageRequest, + type ImageResponse, + type ImageStatus, Media, } from "../src/effect.js" import type { Service } from "../src/image-client.js" import { Anthropic, Google, OpenAI, XAI, ZAI } from "../src/providers.js" type Requirements = T extends Effect.Effect ? R : never +type Success = T extends Effect.Effect ? A : never type Equal = [A, B] extends [B, A] ? true : false type Assert = T @@ -178,6 +182,15 @@ const generated = ImageClient.generate(request) type GenerateRequirements = Assert, Service>> void (true satisfies GenerateRequirements) +type StartSuccess = Assert>, ImageJob>> +type StatusSuccess = Assert>, ImageStatus>> +type ResultSuccess = Assert>, ImageResponse>> +type CancelSuccess = Assert>, void>> +void (true satisfies StartSuccess) +void (true satisfies StatusSuccess) +void (true satisfies ResultSuccess) +void (true satisfies CancelSuccess) + // @ts-expect-error Image requests use `n`, not `count`. ai.image.generate({ model: openai, prompt: "A lighthouse", count: 2 }) // @ts-expect-error Exact sizes are provider options, not common fields. diff --git a/packages/ai/test/minimax-video.test.ts b/packages/ai/test/minimax-video.test.ts index 85ea449d0663..514458e913c7 100644 --- a/packages/ai/test/minimax-video.test.ts +++ b/packages/ai/test/minimax-video.test.ts @@ -11,7 +11,7 @@ const layer = (handler: Parameters[0]) => const minimax = MiniMax.configure({ apiKey: "test", baseURL: "https://minimax.test" }) const h3 = minimax.video("MiniMax-H3-Lite") const hailuo = minimax.video("MiniMax-Hailuo-02") -const token = { taskID: "task_1" } +const id = "task_1" const task = (fields: Record) => ({ task: { id: "task_1", model: "MiniMax-H3-Lite", ...fields } }) const succeeded = task({ @@ -83,7 +83,7 @@ describe("MiniMax Video / H3 start", () => { ), ), ) - expect(job).toEqual({ id: "task_1", token }) + expect(job).toEqual({ id: "task_1" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://minimax.test/v2/video_generation?trace=1", ]) @@ -136,12 +136,19 @@ describe("MiniMax Video / H3 start", () => { }), ) - it.effect("rejects silent output, which H3 can't produce, before sending", () => + it.effect("sends nothing for sound, which neither API has a field for", () => Effect.gen(function* () { - const error = yield* ai.video.start({ model: h3, prompt: "x", sound: false }).pipe(Effect.flip) - expect(error.reason._tag).toBe("UnsupportedOperation") - expect(error.message).toContain("always generates sound") - }).pipe(Effect.provide(layer(() => Effect.die("an unsupported request reached the network")))), + const requests = yield* sent([ + { model: h3, sound: false }, + { model: h3, sound: true }, + { model: hailuo, sound: true }, + ]) + expect(requests.map((request) => "generate_audio" in request.body || "sound" in request.body)).toEqual([ + false, + false, + false, + ]) + }), ) it.effect("returns MiniMax's HTTP errors typed", () => @@ -207,7 +214,7 @@ describe("MiniMax Video / Hailuo start", () => { const requests = yield* sent([ { model: hailuo, - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", references: ["https://example.test/face.png"], duration: "10 seconds", @@ -242,7 +249,6 @@ describe("MiniMax Video / Hailuo start", () => { request: { references: [Media.url("https://example.test/v.mp3", { mediaType: "audio/mpeg" })] }, tag: "UnsupportedOperation", }, - { name: "sound", request: { sound: true }, tag: "UnsupportedOperation" }, { name: "an aspect ratio", request: { aspect: "16:9" as const }, tag: "UnsupportedOperation" }, { name: "a MiniMax file reference", request: { start: Media.ref("minimax", "file_1") }, tag: "InvalidRequest" }, ]) { @@ -280,7 +286,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { it.effect("reads statuses from a JSON round-tripped token and keeps unknown ones running", () => Effect.gen(function* () { const calls: Array = [] - const raw: unknown = JSON.parse(JSON.stringify(token)) + const raw: unknown = id const statuses = yield* Effect.forEach( ["queued", "running", "succeeded", "failed", "cancelled", "warming_up", "constructor"], (status) => @@ -307,7 +313,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { it.effect("returns the finished video with duration, usage and metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(h3, token) + const response = yield* ai.video.result(h3, id) expect(response.video.source).toEqual({ type: "url", url: "https://cdn.minimax.test/out.mp4", @@ -329,14 +335,14 @@ describe("MiniMax Video / H3 status, result and cancel", () => { it.effect("reads the flat response format too", () => Effect.gen(function* () { - const response = yield* ai.video.result(h3, token) + const response = yield* ai.video.result(h3, id) expect(response.video.source).toMatchObject({ url: "https://cdn.minimax.test/out.mp4" }) }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, succeeded.task))))), ) it.effect("fails a result read before the task finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(h3, token).pipe(Effect.flip) + const error = yield* ai.video.result(h3, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toContain("has not finished") }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, task({ status: "running" })))))), @@ -384,7 +390,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { ]) { it.effect(`fails the result of ${terminal.message} with the provider body`, () => Effect.gen(function* () { - const error = yield* ai.video.result(h3, token).pipe(Effect.flip) + const error = yield* ai.video.result(h3, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -396,7 +402,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { Effect.gen(function* () { const calls: Array = [] yield* ai.video - .cancel(h3, token) + .cancel(h3, id) .pipe( Effect.provide( layer((input) => @@ -423,7 +429,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { ["Preparing", "Queueing", "Processing", "Success", "Fail", "Warming"], (status) => ai.video - .status(hailuo, token) + .status(hailuo, id) .pipe( Effect.provide( layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, hailuoTask({ status }))))), @@ -444,7 +450,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { it.effect("fails a status read that v1 answers with a non-zero base_resp", () => Effect.gen(function* () { - const error = yield* ai.video.status(hailuo, token).pipe(Effect.flip) + const error = yield* ai.video.status(hailuo, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toContain("This task_id does not exist") }).pipe( @@ -468,7 +474,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { it.effect("looks up the file's download URL, which expires after one hour", () => Effect.gen(function* () { const calls: Array = [] - const response = yield* ai.video.result(hailuo, token).pipe( + const response = yield* ai.video.result(hailuo, id).pipe( Effect.provide( layer((input) => Effect.gen(function* () { @@ -526,7 +532,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { ]) { it.effect(`fails the result with "${terminal.message}"`, () => Effect.gen(function* () { - const error = yield* ai.video.result(hailuo, token).pipe(Effect.flip) + const error = yield* ai.video.result(hailuo, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -536,7 +542,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { it.effect("fails cancel as unsupported without sending a request, since v1 has no cancel endpoint", () => Effect.gen(function* () { - const error = yield* ai.video.cancel(hailuo, token).pipe(Effect.flip) + const error = yield* ai.video.cancel(hailuo, id).pipe(Effect.flip) expect(error.reason._tag).toBe("UnsupportedOperation") expect(error.message).toContain("cancel") }).pipe(Effect.provide(layer(() => Effect.die("cancel reached the network")))), diff --git a/packages/ai/test/openrouter-video.test.ts b/packages/ai/test/openrouter-video.test.ts index ebaa13aaf889..8f15b749933c 100644 --- a/packages/ai/test/openrouter-video.test.ts +++ b/packages/ai/test/openrouter-video.test.ts @@ -10,7 +10,7 @@ const layer = (handler: Parameters[0]) => const openrouter = OpenRouter.configure({ apiKey: "test", baseURL: "https://openrouter.test/api/v1" }) const model = openrouter.video("x-ai/grok-imagine-video-1.5-lite") -const token = { id: "gen-vid-1-abc" } +const id = "gen-vid-1-abc" const started = (input: HandlerInput) => json(input, { id: "gen-vid-1-abc", @@ -36,7 +36,7 @@ describe("ai.video.start / OpenRouter", () => { .start({ model, prompt: "A red balloon floats up", - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", duration: "6 seconds", aspect: "16:9", @@ -48,7 +48,7 @@ describe("ai.video.start / OpenRouter", () => { }, }) .pipe(Effect.provide(record(calls))) - expect(job).toEqual({ id: "gen-vid-1-abc", token }) + expect(job).toEqual({ id: "gen-vid-1-abc" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual(["POST https://openrouter.test/api/v1/videos"]) expect(calls[0].headers.get("authorization")).toBe("Bearer test") expect(JSON.parse(calls[0].body)).toEqual({ @@ -151,8 +151,8 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { ["pending", "in_progress", "completed", "failed", "cancelled", "expired", "warming_up"], (status) => ai.video - .status(model, JSON.parse(JSON.stringify(token))) - .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: token.id, status }))))), + .status(model, id) + .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id, status }))))), ) expect(statuses.map((value) => value.status)).toEqual([ "queued", @@ -170,7 +170,7 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { Effect.gen(function* () { const calls: Array = [] const response = yield* Effect.gen(function* () { - const result = yield* ai.video.result(model, token) + const result = yield* ai.video.result(model, id) expect(yield* result.video.bytes()).toEqual(Uint8Array.from([1, 2, 3])) return result }).pipe( @@ -204,7 +204,7 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { it.effect("attaches no credentials to a result URL on another host", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token) + const response = yield* ai.video.result(model, id) expect(response.video.headers).toEqual({}) }).pipe( Effect.provide( @@ -217,10 +217,10 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { it.effect("fails a result read before the job finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toContain("has not finished") - }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: token.id, status: "in_progress" }))))), + }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id, status: "in_progress" }))))), ) for (const terminal of [ @@ -247,16 +247,16 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { ]) { it.effect(`fails the result of a job that ${terminal.body.status} with "${terminal.body.error}"`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) - }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: token.id, ...terminal.body }))))), + }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id, ...terminal.body }))))), ) } it.effect("fails cancel as unsupported without a request, since OpenRouter has no cancel endpoint", () => Effect.gen(function* () { - const error = yield* ai.video.cancel(model, token).pipe(Effect.flip) + const error = yield* ai.video.cancel(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe("UnsupportedOperation") }).pipe(Effect.provide(layer(() => Effect.die("cancel reached the network")))), ) diff --git a/packages/ai/test/promise.test.ts b/packages/ai/test/promise.test.ts index da8af3e306d6..98750b636c82 100644 --- a/packages/ai/test/promise.test.ts +++ b/packages/ai/test/promise.test.ts @@ -188,15 +188,16 @@ describe("AI promise client", () => { const model = xai.video("grok-imagine-video-1.5") const job = await ai.video.start({ model, prompt: "A kite" }) - expect(job).toEqual({ id: "req_1", token: { requestID: "req_1" } }) + expect(job).toEqual({ id: "req_1" }) - const token: unknown = JSON.parse(JSON.stringify(job.token)) - expect(await ai.video.status(model, token)).toEqual({ status: "running", progress: 0.5 }) - expect(await ai.video.status(model, token)).toEqual({ status: "completed" }) - const response = await ai.video.result(model, token) + // The ID is plain text: store it and read the job back from any process. + const id = job.id + expect(await ai.video.status(model, id)).toEqual({ status: "running", progress: 0.5 }) + expect(await ai.video.status(model, id)).toEqual({ status: "completed" }) + const response = await ai.video.result(model, id) expect(response.video).toBeInstanceOf(Media.Asset) expect(response.video.source).toMatchObject({ type: "url", url: "https://vidgen.x.ai/out.mp4" }) - expect(await ai.video.cancel(model, token).catch((error: unknown) => error)).toMatchObject({ + expect(await ai.video.cancel(model, id).catch((error: unknown) => error)).toMatchObject({ reason: { _tag: "UnsupportedOperation" }, }) @@ -209,6 +210,29 @@ describe("AI promise client", () => { await ai.dispose() }) + test("rejects image job calls on an inline route without a request", async () => { + const seen: Array = [] + const ai = AI.make({ layer: executor(seen) }) + const model = openai.image("gpt-image-2") + const reasons = await Promise.all( + [ + ai.image.start({ model, prompt: "A lighthouse" }), + ai.image.status(model, "job_1"), + ai.image.result(model, "job_1"), + ai.image.cancel(model, "job_1"), + ].map((call) => call.then(() => undefined).catch((error: unknown) => error)), + ) + expect(reasons).toEqual( + ["start", "status", "result", "cancel"].map((operation) => + expect.objectContaining({ + reason: expect.objectContaining({ _tag: "UnsupportedOperation", operation: `image.${operation}` }), + }), + ), + ) + expect(seen).toEqual([]) + await ai.dispose() + }) + test("forwards per-call options to generate, stream, and loop, and checks compaction support", async () => { const seen: Array = [] const ai = AI.make({ layer: executor([]) }) diff --git a/packages/ai/test/provider/google-interactions-video.recorded.test.ts b/packages/ai/test/provider/google-interactions-video.recorded.test.ts index 8706f5e3366a..a0d662bc7543 100644 --- a/packages/ai/test/provider/google-interactions-video.recorded.test.ts +++ b/packages/ai/test/provider/google-interactions-video.recorded.test.ts @@ -29,7 +29,7 @@ describe("Google Interactions Video recorded", () => { duration: "3 seconds", }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -38,7 +38,7 @@ describe("Google Interactions Video recorded", () => { ) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.mediaType).toBe("video/mp4") expect((yield* response.video.bytes()).length).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/media-entrypoints.test.ts b/packages/ai/test/provider/media-entrypoints.test.ts index fd46116cd378..4d795ec83a0b 100644 --- a/packages/ai/test/provider/media-entrypoints.test.ts +++ b/packages/ai/test/provider/media-entrypoints.test.ts @@ -561,6 +561,15 @@ const videos: ReadonlyArray> = [ auth: ["x-goog-api-key", "google-key"], provider: "google", }, + { + name: "xai", + load: async () => { + const { model } = await import("@opencode/ai/providers/xai/videos") + return model("grok-imagine-video-1.5", { ...shared, apiKey: "xai-key" }) + }, + url: "https://api.x.ai/v1/videos/generations", + auth: ["authorization", "Bearer xai-key"], + }, ] describe("video entrypoints", () => { @@ -573,6 +582,21 @@ describe("video entrypoints", () => { ) }) +describe("video entrypoint model options", () => { + // Model-level options from settings (as models.dev or config set them) become defaults on every request. + for (const entry of [ + { name: "xai", modelID: "grok-imagine-video-1.5", load: () => import("@opencode/ai/providers/xai/videos") }, + { name: "google", modelID: "gemini-omni-1.2-flash", load: () => import("@opencode/ai/providers/google/videos") }, + ]) + it.effect(`providers/${entry.name}/videos keeps provider options from settings`, () => + Effect.gen(function* () { + const { model } = yield* Effect.promise(entry.load) + const calls = yield* sentVideo(model(entry.modelID, { apiKey: "key", future_option: true })) + expect(JSON.parse(calls[0].body).future_option).toBe(true) + }), + ) +}) + describe("decision entrypoints", () => { for (const entry of decisions) it.effect(`providers/${entry.name}/decisions sends a configured request`, () => diff --git a/packages/ai/test/provider/minimax-video.recorded.test.ts b/packages/ai/test/provider/minimax-video.recorded.test.ts index c8bf453a3224..a24090bee68f 100644 --- a/packages/ai/test/provider/minimax-video.recorded.test.ts +++ b/packages/ai/test/provider/minimax-video.recorded.test.ts @@ -14,10 +14,10 @@ const recorded = recordedTests({ requires: ["MINIMAX_API_KEY"], }) -const settle = (model: VideoModel, token: unknown) => +const settle = (model: VideoModel, id: string) => Effect.gen(function* () { const observed: Array = [] - yield* ai.video.status(model, token).pipe( + yield* ai.video.status(model, id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -41,10 +41,10 @@ describe("MiniMax Video recorded", () => { resolution: "480p", duration: "4 seconds", }) - const observed = yield* settle(model, job.token) + const observed = yield* settle(model, job.id) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.info?.durationSeconds).toBe(4) @@ -68,11 +68,11 @@ describe("MiniMax Video recorded", () => { resolution: "512p", duration: "6 seconds", }) - const observed = yield* settle(model, job.token) + const observed = yield* settle(model, job.id) expect(observed.at(-1)?.status).toBe("completed") // The task names a file; the result looks up its one-hour download URL. - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.expiresAt).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/openrouter-video.recorded.test.ts b/packages/ai/test/provider/openrouter-video.recorded.test.ts index 0f5205c2e579..85ac20ad03fe 100644 --- a/packages/ai/test/provider/openrouter-video.recorded.test.ts +++ b/packages/ai/test/provider/openrouter-video.recorded.test.ts @@ -29,7 +29,7 @@ describe("OpenRouter Video recorded", () => { duration: "1 second", }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -40,7 +40,7 @@ describe("OpenRouter Video recorded", () => { expect(observed.every((status) => status.progress === undefined)).toBe(true) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.expiresAt).toBeGreaterThan(Date.parse("2026-01-01")) diff --git a/packages/ai/test/provider/seedance-video.recorded.test.ts b/packages/ai/test/provider/seedance-video.recorded.test.ts index 669abe150513..d979cfe59bc1 100644 --- a/packages/ai/test/provider/seedance-video.recorded.test.ts +++ b/packages/ai/test/provider/seedance-video.recorded.test.ts @@ -31,7 +31,7 @@ describe("Seedance Video recorded", () => { sound: false, }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -40,7 +40,7 @@ describe("Seedance Video recorded", () => { ) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.expiresAt).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/xai-video.recorded.test.ts b/packages/ai/test/provider/xai-video.recorded.test.ts index 8b6fe07e1f09..2aefc6c9e157 100644 --- a/packages/ai/test/provider/xai-video.recorded.test.ts +++ b/packages/ai/test/provider/xai-video.recorded.test.ts @@ -29,7 +29,7 @@ describe("xAI Video recorded", () => { duration: "2 seconds", }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -43,7 +43,7 @@ describe("xAI Video recorded", () => { expect(progress).toEqual([...progress].sort((a, b) => a - b)) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.info?.durationSeconds).toBe(2) diff --git a/packages/ai/test/seedance-video.test.ts b/packages/ai/test/seedance-video.test.ts index aa677c8739ed..519c14c2725d 100644 --- a/packages/ai/test/seedance-video.test.ts +++ b/packages/ai/test/seedance-video.test.ts @@ -11,7 +11,7 @@ const layer = (handler: Parameters[0]) => const model = Volcengine.configure({ apiKey: "test", baseURL: "https://ark.test/api/v3" }).video( "doubao-seedance-2-0-260128", ) -const token = { taskID: "cgt-1" } +const id = "cgt-1" const succeeded = { id: "cgt-1", model: "doubao-seedance-2-0-260128", @@ -44,7 +44,7 @@ describe("ai.video.start / Seedance", () => { .start({ model, prompt: "The kitten yawns at the camera", - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", duration: "5 seconds", aspect: "16:9", @@ -66,7 +66,7 @@ describe("ai.video.start / Seedance", () => { ), ), ) - expect(job).toEqual({ id: "cgt-1", token: { taskID: "cgt-1" } }) + expect(job).toEqual({ id: "cgt-1" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://ark.test/api/v3/contents/generations/tasks?trace=1", ]) @@ -213,7 +213,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { const calls: Array = [] const statuses = yield* Effect.gen(function* () { const job = yield* ai.video.start({ model, prompt: "x" }) - const restored: unknown = JSON.parse(JSON.stringify(job.token)) + const restored: unknown = job.id return yield* Effect.forEach([1, 2, 3], () => ai.video.status(model, restored)) }).pipe( Effect.provide( @@ -242,7 +242,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { Effect.gen(function* () { const raw = ["queued", "running", "succeeded", "failed", "cancelled", "expired", "paused", "constructor"] const statuses = yield* Effect.forEach(raw, (status) => - ai.video.status(model, token).pipe(Effect.provide(reply({ id: "cgt-1", status }))), + ai.video.status(model, id).pipe(Effect.provide(reply({ id: "cgt-1", status }))), ) expect(statuses.map((value) => value.status)).toEqual([ "queued", @@ -259,7 +259,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { it.effect("returns the video as a URL that expires 24 hours after the task finished, with usage and metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token).pipe(Effect.provide(reply(succeeded))) + const response = yield* ai.video.result(model, id).pipe(Effect.provide(reply(succeeded))) expect(response.video.source).toEqual({ type: "url", url: "https://ark-content.test/out.mp4", @@ -287,7 +287,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { it.effect("derives duration from frames, types mov output and keeps the last frame URL", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token).pipe( + const response = yield* ai.video.result(model, id).pipe( Effect.provide( reply({ status: "succeeded", @@ -315,7 +315,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { it.effect("fails a result read before the task finishes", () => Effect.gen(function* () { const errors = yield* Effect.forEach(["queued", "running"], (status) => - ai.video.result(model, token).pipe(Effect.flip, Effect.provide(reply({ id: "cgt-1", status }))), + ai.video.result(model, id).pipe(Effect.flip, Effect.provide(reply({ id: "cgt-1", status }))), ) expect(errors.map((error) => error.reason._tag)).toEqual(["InvalidRequest", "InvalidRequest"]) expect(errors[0].message).toBe( @@ -380,7 +380,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { ]) { it.effect(`fails the result of ${terminal.body.error?.code ?? terminal.body.status} tasks with the body`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip, Effect.provide(reply(terminal.body))) + const error = yield* ai.video.result(model, id).pipe(Effect.flip, Effect.provide(reply(terminal.body))) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toContain(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -392,10 +392,10 @@ describe("ai.video.status / result / cancel / Seedance", () => { Effect.gen(function* () { const calls: Array = [] yield* ai.video - .cancel(model, token) + .cancel(model, id) .pipe(Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, {})))))) const refused = yield* ai.video - .cancel(model, token) + .cancel(model, id) .pipe( Effect.flip, Effect.provide( @@ -415,12 +415,4 @@ describe("ai.video.status / result / cancel / Seedance", () => { ]) }), ) - - it.effect("rejects a token from another provider without a request", () => - Effect.gen(function* () { - const error = yield* ai.video.status(model, { requestID: "req_1" }).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidRequest") - expect(error.message).toContain("cannot resume") - }).pipe(Effect.provide(layer(() => Effect.die("a foreign token reached the network")))), - ) }) diff --git a/packages/ai/test/video.test.ts b/packages/ai/test/video.test.ts index 8e78d2e8e03d..931a40b0540e 100644 --- a/packages/ai/test/video.test.ts +++ b/packages/ai/test/video.test.ts @@ -1,7 +1,7 @@ import { describe, expect } from "bun:test" import { Effect, Fiber, Layer, Stream } from "effect" import * as TestClock from "effect/testing/TestClock" -import { Media, VideoClient, ai } from "../src/effect.js" +import { AIError, Media, VideoClient, ai } from "../src/effect.js" import { XAI } from "../src/providers.js" import { it } from "./lib/effect.js" import { dynamicResponse, json, observe, settle, type Call, type HandlerInput } from "./lib/http.js" @@ -25,7 +25,7 @@ describe("ai.video.start / xAI", () => { .start({ model, prompt: "Make the water crash down", - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", references: [ Media.ref("xai", "file_1"), @@ -51,7 +51,7 @@ describe("ai.video.start / xAI", () => { ), ), ) - expect(job).toEqual({ id: "req_1", token: { requestID: "req_1" } }) + expect(job).toEqual({ id: "req_1" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://xai.test/v1/videos/generations?trace=1", ]) @@ -123,6 +123,42 @@ describe("ai.video.start / xAI", () => { }).pipe(Effect.provide(layer(() => Effect.die("an unsupported reference reached the network")))), ) + it.effect("rejects start and end frames that are known not to be images before sending", () => + Effect.gen(function* () { + const video = yield* ai.video.start({ model, prompt: "x", start: "data:video/mp4;base64,AAAA" }).pipe(Effect.flip) + expect(video.reason._tag).toBe("InvalidRequest") + expect(video.message).toContain("expected an image, got video/mp4") + const audio = yield* ai.video + .start({ model, prompt: "x", end: Media.url("https://example.test/a.mp3", { mediaType: "audio/mpeg" }) }) + .pipe(Effect.flip) + expect(audio.reason._tag).toBe("InvalidRequest") + }).pipe(Effect.provide(layer(() => Effect.die("a non-image frame reached the network")))), + ) + + it.effect("Media.image throws a typed AIError for a known non-image", () => + Effect.sync(() => { + expect(() => Media.image("data:video/mp4;base64,AAAA")).toThrow(AIError) + expect(() => Media.image("data:video/mp4;base64,AAAA")).toThrow("expected an image, got video/mp4") + }), + ) + + it.effect("sends frames whose type it can't tell, like URLs and provider file references", () => + Effect.gen(function* () { + const calls: Array = [] + yield* ai.video + .start({ model, prompt: "x", start: "https://example.test/frame?id=7", end: Media.ref("xai", "file_1") }) + .pipe( + Effect.provide( + layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, { request_id: "r" })))), + ), + ) + expect(JSON.parse(calls[0].body)).toMatchObject({ + image: { url: "https://example.test/frame?id=7" }, + last_frame: { file_id: "file_1" }, + }) + }), + ) + it.effect("rejects durations that aren't seconds before sending", () => Effect.gen(function* () { // @ts-expect-error Durations are Effect duration strings in seconds. @@ -151,13 +187,12 @@ describe("ai.video.start / xAI", () => { // --------------------------------------------------------------------------- describe("ai.video.status / result / cancel", () => { - it.effect("reads one status per call from a JSON round-tripped token", () => + it.effect("reads one status per call by job ID", () => Effect.gen(function* () { const calls: Array = [] const statuses = yield* Effect.gen(function* () { const job = yield* ai.video.start({ model, prompt: "x" }) - const token: unknown = JSON.parse(JSON.stringify(job.token)) - return [yield* ai.video.status(model, token), yield* ai.video.status(model, token)] + return [yield* ai.video.status(model, job.id), yield* ai.video.status(model, job.id)] }).pipe( Effect.provide( layer((input) => @@ -178,28 +213,28 @@ describe("ai.video.status / result / cancel", () => { }), ) + it.effect("encodes the job ID into the request path", () => + Effect.gen(function* () { + const calls: Array = [] + yield* ai.video + .status(model, "../files?x=1") + .pipe(Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, done)))))) + expect(calls.map((call) => call.url)).toEqual(["https://xai.test/v1/videos/..%2Ffiles%3Fx%3D1"]) + }), + ) + it.effect("keeps unknown statuses running, including inherited property names", () => Effect.gen(function* () { const statuses = yield* Effect.forEach(["warming_up", "constructor"], (status) => - ai.video - .status(model, { requestID: "req_1" }) - .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { status }))))), + ai.video.status(model, "req_1").pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { status }))))), ) expect(statuses.map((value) => value.status)).toEqual(["running", "running"]) }), ) - it.effect("rejects a token from another provider", () => - Effect.gen(function* () { - const error = yield* ai.video.status(model, { operation: "models/x/operations/y" }).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidRequest") - expect(error.message).toContain("cannot resume") - }).pipe(Effect.provide(layer(() => Effect.die("a foreign token reached the network")))), - ) - it.effect("returns the finished video as an expiring URL with xAI metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, { requestID: "req_1" }) + const response = yield* ai.video.result(model, "req_1") expect(response.video.source).toEqual({ type: "url", url: "https://vidgen.x.ai/out.mp4", mediaType: "video/mp4" }) expect(response.video.info).toEqual({ durationSeconds: 10 }) expect(response.providerMetadata).toEqual({ @@ -222,7 +257,7 @@ describe("ai.video.status / result / cancel", () => { it.effect("fails a result read before the job finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(model, { requestID: "req_1" }).pipe(Effect.flip) + const error = yield* ai.video.result(model, "req_1").pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toBe("xAI Video generation req_1 has not finished; await it before reading the result") expect(error.reason.body).toBe(JSON.stringify({ status: "pending", progress: 40 })) @@ -261,7 +296,7 @@ describe("ai.video.status / result / cancel", () => { `fails the result of ${terminal.body.error?.code ?? terminal.body.status} jobs with the provider body`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, { requestID: "req_1" }).pipe(Effect.flip) + const error = yield* ai.video.result(model, "req_1").pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -272,7 +307,7 @@ describe("ai.video.status / result / cancel", () => { it.effect("returns moderated results and fails withheld videos as a content policy failure", () => Effect.gen(function* () { const flagged = yield* ai.video - .result(model, { requestID: "req_1" }) + .result(model, "req_1") .pipe( Effect.provide( layer((input) => @@ -284,7 +319,7 @@ describe("ai.video.status / result / cancel", () => { ) expect(flagged.providerMetadata).toEqual({ xai: { requestId: "req_1", respectModeration: false } }) const withheld = yield* ai.video - .result(model, { requestID: "req_1" }) + .result(model, "req_1") .pipe( Effect.flip, Effect.provide( @@ -297,7 +332,7 @@ describe("ai.video.status / result / cancel", () => { it.effect("fails cancel as unsupported without sending a request, since xAI has no cancel endpoint", () => Effect.gen(function* () { - const error = yield* ai.video.cancel(model, { requestID: "req_1" }).pipe(Effect.flip) + const error = yield* ai.video.cancel(model, "req_1").pipe(Effect.flip) expect(error.reason._tag).toBe("UnsupportedOperation") expect(error.message).toContain("cancel") }).pipe(Effect.provide(layer(() => Effect.die("cancel reached the network")))), @@ -317,8 +352,8 @@ describe("ai.video / transient read failures", () => { const calls: Array = [] const response = yield* settle( Effect.gen(function* () { - expect(yield* ai.video.status(model, { requestID: "req_1" })).toEqual({ status: "completed" }) - return yield* ai.video.result(model, { requestID: "req_1" }) + expect(yield* ai.video.status(model, "req_1")).toEqual({ status: "completed" }) + return yield* ai.video.result(model, "req_1") }), 5, ).pipe( @@ -341,7 +376,7 @@ describe("ai.video / transient read failures", () => { Effect.gen(function* () { const calls: Array = [] const fiber = yield* Effect.forkChild( - ai.video.status(model, { requestID: "req_1" }).pipe( + ai.video.status(model, "req_1").pipe( Effect.provide( layer((input) => Effect.gen(function* () { @@ -364,7 +399,7 @@ describe("ai.video / transient read failures", () => { Effect.gen(function* () { const calls: Array = [] const error = yield* ai.video - .status(model, { requestID: "req_1" }) + .status(model, "req_1") .pipe( Effect.flip, Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => failure(input, 400))))), diff --git a/packages/ai/test/video.types.ts b/packages/ai/test/video.types.ts index ad289ae77b7b..8b2962ff45fd 100644 --- a/packages/ai/test/video.types.ts +++ b/packages/ai/test/video.types.ts @@ -31,7 +31,7 @@ void invalidCustomOptions ai.video.start({ model: custom, prompt: "A kitten", - start: Media.bytes(Uint8Array.from([1]), "image/png"), + start: Media.image(Media.bytes(Uint8Array.from([1]), "image/png")), end: "data:image/png;base64,AQID", references: [Media.bytes(Uint8Array.from([1]), "image/png"), "https://example.com/voice.mp3"], duration: "8 seconds", @@ -66,6 +66,10 @@ ai.video.start({ model: Anthropic.configure({ apiKey: "test" }).model("claude-so // @ts-expect-error Image models cannot be used for video requests. ai.video.start({ model: OpenAI.configure({ apiKey: "test" }).image("gpt-image-2"), prompt: "A kitten" }) +// @ts-expect-error Start and end frames are images; a plain asset of any kind needs `Media.image(...)`. +ai.video.start({ model: xai, prompt: "A kitten", start: Media.bytes(Uint8Array.from([1]), "video/mp4") }) +ai.video.start({ model: xai, prompt: "A kitten", start: Media.image("https://example.com/first.png") }) + // @ts-expect-error Aspect ratios are `${w}:${h}` strings or "auto". ai.video.start({ model: xai, prompt: "A kitten", aspect: "wide" }) // @ts-expect-error Durations are Effect duration strings in seconds, not numbers. diff --git a/packages/app/component-tests/components-lab.spec.ts b/packages/app/component-tests/components-lab.spec.ts new file mode 100644 index 000000000000..d83e4d295fba --- /dev/null +++ b/packages/app/component-tests/components-lab.spec.ts @@ -0,0 +1,24 @@ +import { expect, story } from "../../stories/playwright/story" + +story("opens a component from the standalone catalog and previews its states", async ({ page }) => { + await page.goto("/") + await expect(page.getByRole("tree")).toBeVisible({ timeout: 30_000 }) + await page.getByRole("button", { name: /Search components/ }).click() + + const search = page.getByPlaceholder("Search components") + + await search.fill("Composer docks") + await search.press("Enter") + await page.getByText("Queue Three", { exact: true }).click() + await expect(page.getByText("Rename the Alpha export", { exact: true })).toBeVisible() +}) + +story("edits a story's state argument from the inspector", async ({ page }) => { + await page.goto("/?story=../../app/src/composer/composer-touch.stories.tsx") + await page + .getByRole("region", { name: "components-lab controls" }) + .getByRole("button", { name: "state", exact: true }) + .click() + await page.getByRole("menuitemradio", { name: "shell", exact: true }).click() + await expect(page.getByLabel("Composer state", { exact: true })).toHaveValue("shell") +}) diff --git a/packages/app/component-tests/preview-find.spec.ts b/packages/app/component-tests/preview-find.spec.ts new file mode 100644 index 000000000000..7f46e4ed128a --- /dev/null +++ b/packages/app/component-tests/preview-find.spec.ts @@ -0,0 +1,39 @@ +import { expect, sourceURL, story } from "../../stories/playwright/story" + +const fixture = sourceURL(new URL("../../gui-plugins/src/file/find.fixture.tsx", import.meta.url)) + +for (const frame of [false, true]) { + story(`preview find retains original Unicode offsets in ${frame ? "HTML" : "documents"}`, async ({ mount, page }) => { + await mount("current-session-terminal-work--user-command-completed") + await page.evaluate( + async ({ fixture, frame }) => { + const { mountPreviewFind } = await import(fixture) + mountPreviewFind(frame) + }, + { fixture, frame }, + ) + const host = page.getByTestId("preview-find-fixture") + const text = frame ? host.frameLocator("iframe").locator("p") : host.locator("p") + await expect(text).toHaveText("İx A.b a.b 𐐀") + await host.getByRole("button", { name: "Open preview find" }).click() + + for (const [query, matches] of [ + ["x", ["x"]], + ["a.b", ["A.b", "a.b"]], + ["𐐨", ["𐐀"]], + ] as const) { + await host.getByRole("textbox", { name: "Preview query" }).fill(query) + await expect(host.getByLabel("Match count")).toHaveText(String(matches.length)) + expect( + await text.evaluate((node, frame) => { + const key = frame ? "opencode-file-find" : "file-preview-find" + return [CSS.highlights.get(key), CSS.highlights.get(key + "-current")] + .flatMap((highlight) => (highlight ? Array.from(highlight, (range) => range.toString()) : [])) + .sort() + }, frame), + ).toEqual([...matches].sort()) + } + await host.getByRole("textbox", { name: "Preview query" }).fill("") + await expect(host.getByLabel("Match count")).toHaveText("0") + }) +} diff --git a/packages/app/component-tests/tooltip.spec.ts b/packages/app/component-tests/tooltip.spec.ts index b55839f0feaf..049460740765 100644 --- a/packages/app/component-tests/tooltip.spec.ts +++ b/packages/app/component-tests/tooltip.spec.ts @@ -1,49 +1,169 @@ import { expect, story } from "../../stories/playwright/story" -story("opens a neighbouring tooltip without the open delay", async ({ mount, page }) => { +story.beforeEach(async ({ page }) => { + await page.clock.install({ time: new Date("2026-01-01T00:00:00Z") }) + await page.clock.pauseAt(new Date("2026-01-01T00:00:01Z")) +}) + +story("cancels a pending hover on click and opens again on re-entry", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-button") + + const trigger = root.getByRole("button", { name: "Add" }) + + const tooltip = page.getByRole("tooltip", { name: "Add one to the count" }) + + await trigger.hover() + await page.clock.runFor(300) + await trigger.click() + await expect(root.getByRole("status")).toHaveText("Count: 1") + await expect(tooltip).toBeHidden() + await page.clock.runFor(600) + await expect(tooltip).toBeHidden() + + await page.mouse.move(0, 0) + await trigger.hover() + await page.clock.runFor(600) + await expect(tooltip).toBeVisible() +}) + +story("dismisses an open tooltip on pointerdown before the button activates", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-button") + + const tooltip = page.getByRole("tooltip", { name: "Add one to the count" }) + + await root.getByRole("button", { name: "Add" }).hover() + await page.clock.runFor(600) + await expect(tooltip).toBeVisible() + await page.mouse.down() + await expect(tooltip).toBeHidden() + await expect(root.getByRole("status")).toHaveText("Count: 0") + await page.mouse.up() + await expect(root.getByRole("status")).toHaveText("Count: 1") + await page.clock.runFor(600) + await expect(tooltip).toBeHidden() +}) + +story("shows the wrapped button's tooltip on Tab and Shift+Tab, even after a click", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-button") + + const trigger = root.getByRole("button", { name: "Add" }) + + const tooltip = page.getByRole("tooltip", { name: "Add one to the count" }) + + await page.keyboard.press("Tab") + await expect(trigger).toBeFocused() + await expect(tooltip).toBeVisible() + + await trigger.click() + await expect(tooltip).toBeHidden() + await page.keyboard.press("Tab") + await expect(root.getByRole("button", { name: "Reset" })).toBeFocused() + await page.keyboard.press("Shift+Tab") + await expect(trigger).toBeFocused() + await expect(tooltip).toBeVisible() + await page.keyboard.press("Escape") + await expect(tooltip).toBeHidden() + await expect(trigger).toBeFocused() +}) + +story("restored focus does not open a tooltip after Tab leaves the window", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-button") + + await page.keyboard.down("Tab") + await expect(root.getByRole("button", { name: "Add" })).toBeFocused() + // The page loses focus before receiving Tab's keyup. + await page.evaluate(() => window.dispatchEvent(new FocusEvent("blur"))) + await root.getByRole("button", { name: "Reset" }).focus() + await expect(page.getByRole("tooltip", { name: "Reset the count" })).toBeHidden() + await page.keyboard.up("Tab") +}) + +story.describe("touch", () => { + story.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } }) + + story("tapping the button preserves the tooltip's hover state", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-button") + + const trigger = root.getByRole("button", { name: "Add" }) + + const tooltip = page.getByRole("tooltip", { name: "Add one to the count" }) + + expect(await page.evaluate(() => matchMedia("(hover: none)").matches)).toBe(true) + await trigger.tap() + await expect(root.getByRole("status")).toHaveText("Count: 1") + await expect(tooltip).toBeHidden() + await page.clock.runFor(600) + await expect(tooltip).toBeHidden() + + await trigger.hover() + await page.clock.runFor(600) + await expect(tooltip).toBeVisible() + await trigger.tap() + await expect(root.getByRole("status")).toHaveText("Count: 2") + await expect(tooltip).toBeVisible() + }) +}) + +story("waits 600 ms on first hover and opens a neighbouring tooltip immediately", async ({ mount, page }) => { const root = await mount("ui-tooltip--appearances") + + const tooltip = page.getByRole("tooltip", { name: "Standard tooltip" }) + await root.getByText("Standard", { exact: true }).hover() - await expect(page.getByRole("tooltip", { name: "Standard tooltip" })).toBeVisible() + await page.clock.runFor(599) + await expect(tooltip).toBeHidden() + await page.clock.runFor(1) + await expect(tooltip).toBeVisible() // With timers frozen, the next tooltip can only open through the skip-delay window that closing this one starts. - await page.clock.install({ time: new Date("2026-01-01T00:00:00Z") }) - await page.clock.pauseAt(new Date("2026-01-01T00:00:01Z")) await root.getByText("Compact", { exact: true }).hover() await expect(page.getByRole("tooltip", { name: "Compact tooltip" })).toBeVisible() }) story("keeps a menu trigger's tooltip hidden when the menu closes under a still pointer", async ({ mount, page }) => { const root = await mount("ui-tooltip--with-menu") - await page.clock.install() + const trigger = root.getByRole("button", { name: "Actions" }) + const tooltip = page.getByRole("tooltip", { name: "More actions" }) + await trigger.hover() + await page.clock.runFor(600) await expect(tooltip).toBeVisible() await trigger.click() await expect(page.getByRole("menu")).toBeVisible() await expect(tooltip).toBeHidden() await page.keyboard.press("Escape") await expect(page.getByRole("menu")).toBeHidden() + // The menu restores focus in a zero-delay task after unmounting. + await page.clock.runFor(0) await expect(trigger).toBeFocused() - // The menu's closing layer hands the still pointer a fresh pointerenter, which would open the tooltip 400 ms later. - await page.clock.runFor(1000) + // The menu's closing layer can hand the still pointer a fresh pointerenter. + await page.clock.runFor(600) await expect(tooltip).toBeHidden() await page.mouse.move(0, 0) await trigger.hover() + await page.clock.runFor(600) await expect(tooltip).toBeVisible() }) story("opens a menu trigger's tooltip on the next hover after the menu closes", async ({ mount, page }) => { const root = await mount("ui-tooltip--with-menu") + const trigger = root.getByRole("button", { name: "Actions" }) + const tooltip = page.getByRole("tooltip", { name: "More actions" }) + await trigger.hover() + await page.clock.runFor(600) await expect(tooltip).toBeVisible() await trigger.click() await expect(page.getByRole("menu")).toBeVisible() await page.mouse.move(0, 0) await page.keyboard.press("Escape") await expect(page.getByRole("menu")).toBeHidden() + await page.clock.runFor(0) await expect(trigger).toBeFocused() await trigger.hover() + await page.clock.runFor(600) await expect(tooltip).toBeVisible() }) diff --git a/packages/app/e2e/regression/btw-sidebar.spec.ts b/packages/app/e2e/regression/btw-sidebar.spec.ts index 6ae47c9a64e7..0028cb75d005 100644 --- a/packages/app/e2e/regression/btw-sidebar.spec.ts +++ b/packages/app/e2e/regression/btw-sidebar.spec.ts @@ -163,6 +163,7 @@ test("keeps many long-titled side tabs usable at a narrow desktop width", async }) test("answers /btw in the side panel without admitting a prompt", async ({ page }) => { + await page.clock.install() await page.context().grantPermissions(["clipboard-read", "clipboard-write"]) const generations: { sessionID: string; prompt: string }[] = [] const prompts: unknown[] = [] @@ -228,12 +229,27 @@ test("answers /btw in the side panel without admitting a prompt", async ({ page await expect(panel.getByRole("button", { name: "Revert to here", exact: true })).toHaveCount(0) await expect(panel.getByRole("button", { name: "Copy answer", exact: true })).toHaveCount(1) await expect(panel.locator('[data-slot="text-part-meta"]')).toContainText(/\d+s/) - await panel.locator('[data-component="user-message"]').hover() - await panel.getByRole("button", { name: "Copy message", exact: true }).click() - await expect(panel.getByRole("button", { name: "Copied", exact: true })).toHaveCount(1) - await panel.locator('[data-component="text-part"]').hover() - await panel.getByRole("button", { name: "Copy answer", exact: true }).click() - await expect(panel.getByRole("button", { name: "Copied", exact: true })).toHaveCount(2) + const feedback = page.getByRole("tooltip", { name: "Copied", exact: true }) + + for (const [component, label] of [ + ["user-message", "Copy message"], + ["text-part", "Copy answer"], + ]) { + const row = panel.locator(`[data-component="${component}"]`) + + const button = row.getByRole("button", { name: label, exact: true }) + + await row.hover() + await button.click() + await expect(feedback).toBeVisible() + await page.clock.fastForward(1_000) + await expect(feedback).toHaveCSS("opacity", "1") + await expect(row.getByRole("button", { name: "Copied", exact: true })).toBeVisible() + await page.clock.fastForward(1_000) + await expect(button).toBeVisible() + await expect(page.getByRole("tooltip")).toBeHidden() + } + expect(generations).toHaveLength(1) expect(generations[0]?.sessionID).toBe(main.id) expect(generations[0]?.prompt).toContain("how does the retry loop work?") diff --git a/packages/app/e2e/regression/review.spec.ts b/packages/app/e2e/regression/review.spec.ts index f236e7eda116..cebbe9969196 100644 --- a/packages/app/e2e/regression/review.spec.ts +++ b/packages/app/e2e/regression/review.spec.ts @@ -459,7 +459,7 @@ test("context closes the side region only when its button opened it", async ({ p await expect(panel.locator("#session-side-panel-review-tab")).toHaveAttribute("aria-selected", "true") }) -test("context hides free-model cost but keeps paid-model zero cost", async ({ page }) => { +test("context hides zero cost for Go and free models but keeps paid-model cost", async ({ page }) => { const cases = [ { id: "ses_context_free", title: "Free model", model: "free", cost: 0, usage: false, text: "0" }, { id: "ses_context_paid", title: "Paid model", model: "paid", cost: 0, usage: false, text: "0·$0.00" }, @@ -468,24 +468,48 @@ test("context hides free-model cost but keeps paid-model zero cost", async ({ pa { id: "ses_context_mixed", title: "Previously paid", model: "free", cost: 1.25, usage: true, text: "2k·$1.25" }, { id: "ses_context_unknown", title: "Unknown pricing", model: "missing", cost: 0, usage: false, text: "0·$0.00" }, { id: "ses_context_output", title: "Output pricing", model: "output", cost: 0, usage: false, text: "0·$0.00" }, + { + id: "ses_context_go", + title: "Covered by Go", + providerID: "opencode-go", + model: "paid", + cost: 0, + usage: true, + text: "2k", + }, + { + id: "ses_context_go_spend", + title: "Go with charges", + providerID: "opencode-go", + model: "paid", + cost: 0.38, + usage: true, + text: "2k·$0.38", + }, // The root's model is free, but its subagent spent on a paid model: the family total shows. { id: "ses_context_family", title: "Paid subagent", model: "free", cost: 0, usage: true, text: "2k·$1.25" }, // A completed compaction resets the context until the next reply reports usage, as in the TUI. { id: "ses_context_compacted", title: "Compacted", model: "paid", cost: 1.25, usage: true, text: "0·$1.25" }, ] + const catalog = provider( + { id: "free", name: "Free", cost: { input: 0, output: 0 } }, + { id: "paid", name: "Paid", cost: { input: 1, output: 3 } }, + { id: "output", name: "Output", cost: { input: 0, output: 1 } }, + ) + await openSession(page, { name: "ContextPricing", - provider: provider( - { id: "free", name: "Free", cost: { input: 0, output: 0 } }, - { id: "paid", name: "Paid", cost: { input: 1, output: 3 } }, - { id: "output", name: "Output", cost: { input: 0, output: 1 } }, - ), + provider: { + ...catalog, + all: [...catalog.all, { ...catalog.all[0], id: "opencode-go", name: "OpenCode Go" }], + connected: [...catalog.connected, "opencode-go"], + }, sessions: [ ...cases.map((item) => ({ id: item.id, title: item.title, - model: { id: item.model, providerID: "opencode" }, + model: { id: item.model, providerID: item.providerID ?? "opencode" }, cost: item.cost, })), { @@ -504,7 +528,7 @@ test("context hides free-model cost but keeps paid-model zero cost", async ({ pa id: `msg_${item.id}`, type: "assistant", agent: "build", - model: { id: item.model, providerID: "opencode" }, + model: { id: item.model, providerID: item.providerID ?? "opencode" }, tokens: { input: 1500, output: 500, reasoning: 0, cache: { read: 0, write: 0 } }, content: [{ type: "text", text: "Done." }], time: { created: 1, completed: 2 }, @@ -533,6 +557,15 @@ test("context hides free-model cost but keeps paid-model zero cost", async ({ pa await page.locator("[data-titlebar-tab-slot]", { hasText: item.title }).click() await expectSessionTitle(page, item.title) await expect(button).toHaveText(item.text) + + if (item.providerID === "opencode-go") { + await button.click() + const panel = page.locator('[data-slot="session-usage-content"]') + + await expect(panel.getByText("OpenCode Go", { exact: true })).toBeVisible() + await expect(panel.getByText("Total Cost", { exact: true })).toBeVisible({ visible: item.cost > 0 }) + await button.click() + } } }) diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 208510ca4ad1..af31c4603a94 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -1765,6 +1765,9 @@ for (const row of [ }) } +const connectDialog = (page: Page) => + page.getByRole("dialog").filter({ has: page.getByRole("navigation", { name: "Connect steps", exact: true }) }) + const consoleIntegrations = [ { id: "opencode", @@ -1799,7 +1802,7 @@ test("providers: OpenCode Console signs in from its method list", async ({ page, await methods.getByRole("button", { name: "OpenCode Console account", exact: true }).click() await expect(await popup).toHaveURL(url) - const signIn = page.getByRole("dialog", { name: "Connecting to OpenCode Console", exact: true }) + const signIn = page.getByRole("dialog", { name: "Connect OpenCode Console", exact: true }) await expect(signIn.getByRole("group", { name: "Device code: ABCD-EFGH", exact: true })).toBeVisible() await expect(signIn.getByRole("button", { name: "Copy sign-in link", exact: true })).toBeVisible() }) @@ -1880,14 +1883,14 @@ test("providers: Back during a pending API key request does not report the provi .locator(".settings-provider-row", { hasText: "OpenRouter" }) .getByRole("button", { name: "Connect", exact: true }) .click() - const dialog = page.getByRole("dialog", { name: "Connect OpenRouter", exact: true }) + const dialog = connectDialog(page) await dialog.getByRole("button", { name: "API key", exact: true }).click() await dialog.getByPlaceholder("API key").fill("sk-late") await dialog.getByRole("button", { name: "Continue", exact: true }).click() await held.arrived await expect(dialog.getByRole("button", { name: "Continue", exact: true })).toBeDisabled() - await dialog.getByRole("button", { name: "Navigate back", exact: true }).click() + await dialog.getByRole("navigation").getByRole("button", { name: "OpenRouter", exact: true }).click() await expect(dialog.getByRole("button", { name: "Sign in", exact: true })).toBeVisible() // The server still saves the key, so its late success reloads the catalogs without leaving the method list. @@ -1925,7 +1928,7 @@ test("providers: the free tier upsell opens Go on its own, sized to its content" const container = page.locator('[data-slot="dialog-container"]') await expect(dialog.getByPlaceholder("API key")).toBeVisible() // Nothing to go back to: the upsell opened the dialog straight on Go. - await expect(dialog.getByRole("button", { name: "Navigate back", exact: true })).toHaveCount(0) + await expect(dialog.getByRole("navigation").getByRole("button")).toHaveCount(0) await expect.poll(async () => (await container.boundingBox())?.height).toBeLessThan(512) }) @@ -1982,7 +1985,7 @@ test("providers: the connect dialog lists connected providers and manages their const picker = await container.boundingBox() await openai.click() - await expect(page.getByRole("dialog", { name: "OpenAI", exact: true })).toBeVisible() + await expect(page.getByRole("dialog", { name: "Connect OpenAI", exact: true })).toBeVisible() // The provider step fits its content below the list's top edge. await expect.poll(async () => (await container.boundingBox())?.height).toBeLessThan(picker!.height) expect((await container.boundingBox())?.y).toBe(picker!.y) @@ -2010,7 +2013,7 @@ test("providers: the connect dialog lists connected providers and manages their await name.fill("Ignored") await name.press("Escape") await expect(list.getByRole("radio")).toHaveText(["Home", "Work"]) - await expect(page.getByRole("dialog", { name: "OpenAI", exact: true })).toBeVisible() + await expect(page.getByRole("dialog", { name: "Connect OpenAI", exact: true })).toBeVisible() await list.getByRole("button", { name: "Work options", exact: true }).click() await page.getByRole("menuitem", { name: "Remove", exact: true }).click() @@ -2025,7 +2028,7 @@ test("providers: the connect dialog lists connected providers and manages their await dialog.getByRole("button", { name: "Add account", exact: true }).click() await expect(dialog.getByPlaceholder("API key")).toBeVisible() - await dialog.getByRole("button", { name: "Navigate back", exact: true }).click() + await dialog.getByRole("navigation").getByRole("button", { name: "OpenAI", exact: true }).click() await expect(list).toBeVisible() }) @@ -2064,9 +2067,9 @@ test("providers: adding an account starts a lone method once", async ({ page, co await expect(dialog.getByPlaceholder("API key")).toBeVisible() expect(attempts).toEqual([]) - await dialog.getByRole("button", { name: "Navigate back", exact: true }).click() + await dialog.getByRole("navigation").getByRole("button", { name: "OpenCode Go", exact: true }).click() await expect(dialog.getByRole("radio", { name: "Go key", exact: true })).toBeVisible() - await dialog.getByRole("button", { name: "Integrations", exact: true }).click() + await dialog.getByRole("navigation").getByRole("button", { name: "Connect", exact: true }).click() await dialog.locator('[data-provider-id="github-copilot"]').click() const popup = page.waitForEvent("popup") await dialog.getByRole("button", { name: "Add account", exact: true }).click() @@ -2101,9 +2104,9 @@ test("providers: Back from a pending sign-in cancels it and lets a backdrop clic const popup = page.waitForEvent("popup") await dialog.locator('[data-provider-id="github-copilot"]').click() await popup - await expect(dialog.getByText("Waiting for authorization…", { exact: true })).toBeVisible() + await expect(dialog.getByText("Waiting for authorization", { exact: true })).toBeVisible() - await dialog.getByRole("button", { name: "Navigate back", exact: true }).click() + await dialog.getByRole("navigation").getByRole("button", { name: "Connect", exact: true }).click() await expect(dialog.locator('[data-provider-id="github-copilot"]')).toBeVisible() await expect.poll(() => cancelled).toEqual(["con_mock_1"]) @@ -2146,13 +2149,13 @@ test("providers: Back from a Console connection without models returns to its si .locator(".settings-provider-row", { hasText: "OpenCode Console" }) .getByRole("button", { name: "Connect", exact: true }) .click() - const dialog = page.getByRole("dialog", { name: "Connect OpenCode Console", exact: true }) + const dialog = connectDialog(page) const popup = page.waitForEvent("popup") await dialog.getByRole("button", { name: "OpenCode Console account", exact: true }).click() await popup await expect(page.getByRole("dialog").getByText("OpenCode connected", { exact: true })).toBeVisible() - await page.getByRole("dialog").getByRole("button", { name: "Navigate back", exact: true }).click() + await dialog.getByRole("navigation").getByRole("button", { name: "OpenCode Console", exact: true }).click() await expect(dialog.locator('[data-action="provider-connect-method"]')).toHaveText([ "OpenCode Console account", "API key (service account)", diff --git a/packages/app/e2e/regression/side-panels.spec.ts b/packages/app/e2e/regression/side-panels.spec.ts index 25de38130772..b58082aa29c8 100644 --- a/packages/app/e2e/regression/side-panels.spec.ts +++ b/packages/app/e2e/regression/side-panels.spec.ts @@ -387,3 +387,84 @@ test("the new tab view lists recently closed tabs, expands to the rest, and keep await expect(rows.first()).toContainText("closed-00.ts") await expect(recent).not.toContainText("README.md") }) + +test("Mod+F finds in Markdown and HTML previews with the code view's find bar", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }) + const directory = "C:/OpenCode/PreviewFind" + const key = `local\u0000${base64Encode(directory)}/ses_previewfind` + + const files = new Map([ + ["notes.md", "# Needle notes\n\nOne needle here.\n\nAnother **needle** there."], + ["diagram.mmd", "flowchart TD\n A[First needle] --> B[Last needle]"], + [ + "page.html", + "\nPage

First needle

Last needle

", + ], + ]) + + await openSession(page, { + name: "PreviewFind", + fileList: () => [], + fileContent: (path) => ({ type: "text", content: files.get(path.split("/").at(-1) ?? "") ?? "" }), + seed: { + panes: { ses_previewfind: { review: true } }, + storage: { + "opencode.global.dat:layout": { + sessionTabs: { + [key]: { all: ["file://notes.md", "file://diagram.mmd", "file://page.html"], active: "file://notes.md" }, + }, + }, + }, + }, + }) + + const side = page.locator('[data-pane-content="side"]') + const find = page.getByRole("textbox", { name: "Find" }) + const mod = await page.evaluate(() => (/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "Meta" : "Control")) + await side.getByText("One needle here.").click() + await page.keyboard.press(`${mod}+f`) + await expect(find).toBeFocused() + await find.fill("needle") + await expect(page.getByText("1/3", { exact: true })).toBeVisible() + await find.press("Enter") + await expect(page.getByText("2/3", { exact: true })).toBeVisible() + await find.press("Shift+Enter") + await find.press("Shift+Enter") + await expect(page.getByText("3/3", { exact: true })).toBeVisible() + await find.press("Escape") + await expect(find).toHaveCount(0) + + // A closed side panel keeps its preview mounted out of sight, so Mod+F opens no bar there. + const toggle = page.getByRole("button", { name: "Toggle review" }) + await toggle.click() + await expect(side).toBeHidden() + await page.keyboard.press(`${mod}+f`) + await expect(find).toHaveCount(0) + await toggle.click() + + // Mermaid keeps its source in a hidden code block; only the drawn labels count. + await side.getByRole("tab", { name: "diagram.mmd", exact: true }).click() + await side.locator("svg").getByText("First needle").click() + await page.keyboard.press(`${mod}+f`) + await expect(find).toBeFocused() + await find.fill("needle") + await expect(page.getByText("1/2", { exact: true })).toBeVisible() + await find.press("Escape") + await expect(find).toHaveCount(0) + + // The HTML runs in a sandboxed frame; Mod+F pressed inside it still opens the bar. + await side.getByRole("tab", { name: "page.html", exact: true }).click() + const frame = side.frameLocator('iframe[data-file-find="frame"]') + await frame.getByText("First needle").click() + // The find script goes after the doctype, even behind a comment, so the page keeps standards mode. + expect(await frame.locator("html").evaluate(() => document.compatMode)).toBe("CSS1Compat") + await page.keyboard.press(`${mod}+f`) + await expect(find).toBeFocused() + await find.fill("needle") + await expect(page.getByText("1/2", { exact: true })).toBeVisible() + await find.press("Enter") + await expect(page.getByText("2/2", { exact: true })).toBeVisible() + await expect(frame.getByText("Last needle")).toBeInViewport() + await find.press("Escape") + await expect(find).toHaveCount(0) +}) diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts index 757d427278a1..c322364f19f3 100644 --- a/packages/app/e2e/regression/tabs.spec.ts +++ b/packages/app/e2e/regression/tabs.spec.ts @@ -1864,6 +1864,91 @@ test("the Windows titlebar menu pastes through the desktop edit action", async ( await expect(page.getByRole("status", { name: "Desktop menu actions" })).toHaveText("edit.paste") }) +// #63095: hovering down the parent items left every submenu open, stacked on top of each other. Closing each one as +// soon as the pointer left it then showed no submenu until the next opened, so the menu blinked on every item. +test("the Windows titlebar menu swaps one submenu for the next as the pointer moves down its parent items", async ({ + page, +}) => { + await page.clock.install() + await mockWorkspace(page, { name: "WindowsMenu", sessions: [] }) + await page.goto(`/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER })}`) + await page.getByRole("button", { name: "OpenCode menu", exact: true }).click() + const parents = ["File", "Edit", "View"].map((name) => page.getByRole("menuitem", { name, exact: true })) + const submenus = page.locator('[role="menu"].desktop-app-menu-sub') + + // Keep the hover delay from elapsing while Playwright moves the pointer and checks the old submenu. + await holdClock(page) + + for (const [index, parent] of parents.entries()) { + const box = (await parent.boundingBox())! + // Down and to the left, away from the open submenu, so the pointer isn't heading for it. + await page.mouse.move(box.x + box.width / 2 - index * 20, box.y + box.height / 2, { steps: 4 }) + await expect(parent).toHaveAttribute("data-highlighted", "") + + if (index > 0) await expect(parents[index - 1]).toHaveAttribute("aria-expanded", "true") + await expect(parent).toHaveAttribute("aria-expanded", "false") + // Kobalte's hover delay. + await page.clock.runFor(100) + await expect(parent).toHaveAttribute("aria-expanded", "true") + await expect(submenus).toHaveCount(1) + } +}) + +// #59613: crossing the other parent items on the way to a submenu's lower items closed it and opened theirs. +test("the Windows titlebar menu keeps a submenu open while the pointer crosses other parent items to reach it", async ({ + page, +}) => { + await page.clock.install() + await mockWorkspace(page, { name: "WindowsMenu", sessions: [] }) + await page.goto(`/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER })}`) + await page.getByRole("button", { name: "OpenCode menu", exact: true }).click() + const file = page.getByRole("menuitem", { name: "File", exact: true }) + const fileBox = (await file.boundingBox())! + const from = { x: fileBox.x + fileBox.width / 2, y: fileBox.y + fileBox.height / 2 } + await page.mouse.move(from.x, from.y, { steps: 4 }) + await page.clock.runFor(100) + const closeWindow = page.getByRole("menuitem", { name: /^Close Window/ }) + const target = (await closeWindow.boundingBox())! + const to = { x: target.x + 20, y: target.y + target.height / 2 } + const steps = Math.ceil(Math.hypot(to.x - from.x, to.y - from.y) / 4) + + // A slow, straight move at 125px a second: it stays longer than the hover delay on each item it crosses, and the + // whole trip takes longer than the 300ms that Kobalte keeps the way to a submenu open. + for (let step = 1; step <= steps; step++) { + await page.mouse.move(from.x + ((to.x - from.x) * step) / steps, from.y + ((to.y - from.y) * step) / steps) + await page.clock.runFor(32) + } + + await expect(closeWindow).toHaveAttribute("data-highlighted", "") + await expect(file).toHaveAttribute("aria-expanded", "true") + await expect(page.locator('[role="menu"].desktop-app-menu-sub')).toHaveCount(1) +}) + +// Moving down the parent items while drifting right kept the way to the open submenu alive, so the highlight stayed on +// the item that opened it while the pointer crossed the next ones. +test("the Windows titlebar menu highlights each parent item the pointer drifts down across", async ({ page }) => { + await page.clock.install() + await mockWorkspace(page, { name: "WindowsMenu", sessions: [] }) + await page.goto(`/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER })}`) + await page.getByRole("button", { name: "OpenCode menu", exact: true }).click() + const view = page.getByRole("menuitem", { name: "View", exact: true }) + const box = (await view.boundingBox())! + const from = { x: box.x + box.width / 2, y: box.y + box.height / 2 } + await page.mouse.move(from.x, from.y, { steps: 4 }) + await page.clock.runFor(100) + await expect(view).toHaveAttribute("aria-expanded", "true") + const go = page.getByRole("menuitem", { name: "Go", exact: true }) + const target = (await go.boundingBox())! + + // 1px right for every 4px down, a frame at a time, until the pointer is a few pixels inside Go. + for (let step = 1; from.y + step * 4 < target.y + 8; step++) { + await page.mouse.move(from.x + step, from.y + step * 4) + await page.clock.runFor(16) + } + + await expect(go).toHaveAttribute("data-highlighted", "") +}) + test("the Windows menu shares the vertical sidebar's icon lane", async ({ page }) => { await mockWorkspace(page, { name: "WindowsMenu", diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts index cbc41f76b774..f87b30f755a3 100644 --- a/packages/app/e2e/regression/timeline-geometry.spec.ts +++ b/packages/app/e2e/regression/timeline-geometry.spec.ts @@ -890,6 +890,41 @@ test("groups consecutive sent prompts under the last one's meta line, with each await expect(first.getByRole("button", { name: "More actions" })).toHaveCount(1) }) +test("keeps the meta lines under messages reachable in the New timeline", async ({ page }) => { + await setupTimeline(page, { + settings: { newTimeline: true }, + messages: [ + userMessage([userText("Add the footer check.", { id: "prt_msg_0001_footer_text" })], { + id: "msg_0001_footer", + created: 1700000000000, + }), + assistantMessage([{ id: "prt_msg_0002_footer_text", type: "text", text: "Added the footer check." }], { + id: "msg_0002_footer", + parentID: "msg_0001_footer", + created: 1700000001000, + }), + ], + }) + + const content = page.locator("[data-timeline-virtual-content]") + const userRow = '[data-timeline-row="UserMessage"][data-message-id="msg_0001_footer"]' + const user = content.locator(userRow) + const reply = content.locator('[data-component="text-part"]', { hasText: "Added the footer check." }) + await expect(reply).toBeVisible() + + // Each virtual row clips to its measured height, so a meta line drawn below its row is cut off. + await user.locator('[data-slot="user-message-text"]').hover() + const meta = user.locator('[data-slot="user-message-copy-wrapper"]') + await expect(meta).toHaveCSS("opacity", "1") + const virtualRow = content.locator("[data-timeline-key]", { has: page.locator(userRow) }) + const metaBox = (await meta.boundingBox())! + const rowBox = (await virtualRow.boundingBox())! + expect(metaBox.y + metaBox.height).toBeLessThanOrEqual(rowBox.y + rowBox.height) + + // Hover only lands on what paints on top, so a clipped or covered Copy response never receives the pointer. + await reply.getByRole("button", { name: "Copy response" }).hover() +}) + test("leaves a long prompt unfolded while Fold long messages is off", async ({ page }) => { const text = Array.from({ length: 20 }, (_, index) => `Long line ${index + 1}`).join("\n") diff --git a/packages/app/src/components-lab/browser.tsx b/packages/app/src/components-lab/browser.tsx new file mode 100644 index 000000000000..cc876cd70fc0 --- /dev/null +++ b/packages/app/src/components-lab/browser.tsx @@ -0,0 +1,745 @@ +import { makeEventListener } from "@solid-primitives/event-listener" +import { + batch, + createEffect, + createMemo, + createResource, + createRoot, + createSignal, + ErrorBoundary, + getOwner, + on, + onCleanup, + onMount, + Show, + untrack, + type JSX, + type ParentComponent, +} from "solid-js" +import { createStore, reconcile } from "solid-js/store" +import { Dynamic, insert } from "solid-js/web" +import { DialogProvider } from "@opencode/ui/context/dialog" +import { useTheme } from "@opencode/ui/theme" +import { motionGlobals, motionTuning } from "@opencode/ui/motion-tuning" +import { choice, defineControls, matchesCombo, toolbar, type Field } from "knobs" +import { canvas, commandPalette, restyle, split, toast, type CommandPalette } from "knobs/ui" +import { Tree } from "knobs/ui/solid" +import { useLanguage } from "@/runtime/i18n/language" +import { SessionRouteFrame } from "@/session/session-frame" +import { fileName, knobArgs, labFields, stateArgs, type LabEntry, type StoryArgs } from "./catalog" +import { + createLabStageState, + INITIAL_LAB_BROWSE_STATE, + labStageIndex, + selectShouldToggleFolder, + transitionLabBrowse, + transitionLabStage, + type LabBrowseEvent, + type LabStageEffect, + type LabStageEvent, +} from "./machine" +import { applyMotionPatch, motionFields, motionScopes, motionValues, sameMotion, storyMotion } from "./motion" +import "./inspector.css" + +// How long Play holds each state at full speed. Slow motion doubles it while the motion itself runs 4× longer, so +// a transition still finishes and Play keeps moving. +const hold = 1600 + +const searchIcon = `` + +const themeIcon = `` + +const gridIcon = `` + +type Row = { id: string; label: string; detail?: string; children?: Row[] } + +type LabParams = { story?: string; view?: string } + +type LabPlugin = ParentComponent<{ file: string }> + +export function LabBrowser(props: { + params: LabParams + setParams: (patch: LabParams) => void + loadCatalog: () => Promise<{ entries: LabEntry[]; failed: number }> + workspace?: ParentComponent + plugin: LabPlugin +}) { + const language = useLanguage() + const theme = useTheme() + const [resource] = createResource(() => props.loadCatalog()) + + const catalog = () => (resource.loading ? undefined : resource.latest) + + const [scheme, setScheme] = createSignal<"dark" | "light">("dark") + let palette: CommandPalette | undefined + let toggle: ((id: string) => void) | undefined + let focusTree: ((id?: string) => void) | undefined + let browse = INITIAL_LAB_BROWSE_STATE + + const dispatchBrowse = (event: LabBrowseEvent) => { + const next = transitionLabBrowse(browse, event) + browse = next.state + next.effects.forEach(() => focusTree?.(props.params.story)) + } + + const entries = () => catalog()?.entries ?? [] + const grid = () => props.params.view === "grid" + const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === props.params.story))) + + const open = (file: string) => { + dispatchBrowse({ type: "story.opened", fromTree: stories.contains(document.activeElement) }) + props.setParams({ story: file, view: undefined }) + } + + const rows = createMemo(() => folder(entries(), [])) + + const search = () => { + if (palette?.isOpen) return palette.close() + + palette ??= commandPalette({ + hotkey: false, + recents: false, + placeholder: language.t("lab.search"), + look: { theme: scheme() }, + commands: () => + entries().map((entry) => ({ + id: entry.file, + label: entry.title.split("/").join(" / "), + hint: fileName(entry.file), + keywords: entry.states.map((state) => state.name), + run: () => open(entry.file), + })), + }) + palette.open() + } + + // The palette takes its look when it's made. + createEffect( + on( + scheme, + () => { + palette?.dispose() + palette = undefined + }, + { defer: true }, + ), + ) + + // Ahead of the app's own palette, which listens on the document. + makeEventListener( + window, + "keydown", + (event) => { + if (!matchesCombo("Mod+K", event)) return + event.preventDefault() + event.stopImmediatePropagation() + search() + }, + { capture: true }, + ) + + // A story's modal overlay (a menu or dialog open by default) sets `pointer-events: none` on the body, which would + // freeze the lab around it. The lab stays usable while it's open. + const unblock = document.createElement("style") + + unblock.textContent = "body { pointer-events: auto !important; }" + document.head.append(unblock) + + createEffect(() => theme.previewColorScheme(scheme())) + onCleanup(() => { + theme.cancelPreview() + palette?.dispose() + unblock.remove() + }) + + createEffect(() => { + const failed = catalog()?.failed + + if (failed) toast(language.plural("lab.failed", failed)) + }) + + // The story's knobs panel mounts in the inspector pane. + const inspector = pane(() => null) + + const stories = pane(() => ( + + row.detail} + label={language.t("lab.components")} + expanded={rows().map((row) => row.id)} + selection={props.params.story ? [props.params.story] : []} + // Digits pick the story's states. + typeahead={(key) => !/^[0-9]$/.test(key)} + onReady={(tree) => { + // Opens the folders down to the story in the address, and later ones picked from the palette. + createEffect(() => props.params.story && tree.reveal(props.params.story)) + toggle = (id) => tree.expand(id, !tree.isExpanded(id)) + focusTree = (id) => tree.focus(id) + }} + // Moving by keys selects as it goes, so a folder opens and closes only by a click, Enter, Space or ←/→. + onSelect={(_, primary) => { + if (!primary?.startsWith("folder:")) return primary && open(primary) + + if (selectShouldToggleFolder(browse)) toggle?.(primary) + }} + onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} + /> + + )) + + const stage = pane(() => ( + + entry.title.startsWith("UI/") || isDialogEntry(entry))} + scheme={untrack(scheme)} + onOpen={open} + plugin={props.plugin} + /> + + } + > + + {language.t("lab.pick")} + + } + > + {(entry) => ( + + )} + + + )) + + const inTree = (event: Event) => event.target instanceof Node && stories.contains(event.target) + + makeEventListener(window, "pointerdown", (event) => dispatchBrowse({ type: "pointer.down", inTree: inTree(event) }), { + capture: true, + }) + // Bubbling, so the tree's own pointerup (which completes a press on a selected row) selects first. + makeEventListener(window, "pointerup", () => dispatchBrowse({ type: "pointer.ended" })) + makeEventListener(window, "pointercancel", () => dispatchBrowse({ type: "pointer.ended" })) + makeEventListener( + window, + "keydown", + (event) => dispatchBrowse({ type: "key.down", key: event.key, inTree: inTree(event) }), + { capture: true }, + ) + makeEventListener(window, "keyup", () => dispatchBrowse({ type: "key.ended" })) + makeEventListener(window, "blur", () => dispatchBrowse({ type: "window.blurred" })) + makeEventListener(stage, "focusin", () => dispatchBrowse({ type: "stage.focused" })) + + let element!: HTMLDivElement + + onMount(() => { + const layout = split(element, { + theme: "dark", + storage: null, + panes: [ + { + id: "stories", + size: 260, + min: 200, + max: 420, + collapsible: true, + title: language.t("lab.components"), + element: stories, + actions: [ + { label: language.t("lab.search"), icon: searchIcon, shortcut: "Mod+K", run: search }, + { + label: language.t("lab.grid"), + icon: gridIcon, + run: () => props.setParams({ view: grid() ? undefined : "grid" }), + }, + { + label: language.t("lab.theme"), + icon: themeIcon, + run: () => setScheme(scheme() === "dark" ? "light" : "dark"), + }, + ], + }, + { id: "stage", min: 360, element: stage }, + { id: "inspector", size: 300, min: 260, max: 460, collapsible: true, title: "", element: inspector }, + ], + }) + + createEffect(() => layout.pane("stories").title(language.t("lab.components"), entries().length)) + createEffect(() => layout.pane("inspector").title(selected()?.title.split("/").join(" / ") ?? "")) + createEffect(on(scheme, (next) => restyle(layout.element, { theme: next }), { defer: true })) + onCleanup(() => layout.dispose()) + }) + + return ( + +
+ + ) +} + +/** One story on the app's background, with its args and states as a knobs panel in the inspector. */ +function Stage(props: { + entry: LabEntry + inspector: HTMLElement + scheme: "dark" | "light" + workspace?: ParentComponent + plugin: LabPlugin +}) { + const Workspace: ParentComponent = props.workspace ?? ((props) => props.children) + + const language = useLanguage() + const entry = props.entry + const fields = labFields(entry) + const names = entry.states.map((state) => state.name) + const [args, setArgs] = createStore(stateArgs(entry, 0)) + const [stageState, setStageState] = createSignal(createLabStageState(names)) + const index = createMemo(() => labStageIndex(stageState())) + const [canvas, setCanvas] = createSignal() + const component = entry.component + const fallback = component && ((values: StoryArgs) => ) + // Switching to a state that shares the current render function keeps the mounted instance, so its transitions play. + const render = () => entry.states[index()]?.render ?? entry.render ?? fallback + let timer: ReturnType | undefined + + // A state is a variant: its chip, a digit, `[` and `]` and Play all apply it, so the panel shows where it is. + const preset = (next: number): void => store.preset(next === 0 ? "default" : (names[next] ?? "default")) + + // One batch, so a state with its own render function never renders with the previous state's args. + const dispatch = (event: LabStageEvent) => + batch(() => { + const next = transitionLabStage(untrack(stageState), event) + setStageState(next.state) + next.effects.forEach(perform) + }) + + const perform = (effect: LabStageEffect) => { + if (effect.type === "timer.schedule") { + clearTimeout(timer) + timer = setTimeout( + () => dispatch({ type: "tick", attempt: effect.attempt }), + (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, + ) + + return + } + + if (effect.type === "timer.clear") return clearTimeout(timer) + + if (effect.type === "state.apply") { + setArgs(reconcile(stateArgs(entry, effect.index))) + + if (effect.preset === "now") preset(effect.index) + + // Undo or a reset moved the state: bring the other knobs to the state's args too. + if (effect.preset === "later") + queueMicrotask(() => { + if (untrack(stageState).status !== "disposed") preset(effect.index) + }) + + return + } + + // Coalesced: a story registers its replay buttons one by one. + if (effect.type === "motion.queue") return queueMicrotask(() => dispatch({ type: "motion.flushed" })) + const next = storyMotion(entry.motion) + + if (!sameMotion(next, motion)) return setShown(next) + store.sync(motionValues(motion)) + } + + const [first, ...rest] = names + + const states: { [key: string]: Field } = + first === undefined || rest.length === 0 + ? {} + : { + // Story args can themselves be named `state` (e.g. the touch composer) or `play`. + "lab.preset": choice(first, [first, ...rest], { variants: true }), + "lab.playback": toolbar( + [ + { + id: "previous", + label: language.t("lab.previous"), + icon: "M200 48 80 128l120 80ZM48 48h16v160H48Z", + run: () => dispatch({ type: "step", delta: -1 }), + }, + { id: "play", label: language.t("lab.play"), icon: "play", run: () => dispatch({ type: "play" }) }, + { id: "pause", label: language.t("lab.pause"), icon: "pause", run: () => dispatch({ type: "pause" }) }, + { + id: "next", + label: language.t("lab.next"), + icon: "M56 48l120 80-120 80ZM192 48h16v160h-16Z", + run: () => dispatch({ type: "step", delta: 1 }), + }, + ], + { labels: false, label: language.t("lab.play") }, + ), + } + + // The story's Knobs join its args here, so the inspector is the one place for its controls. Registering a knob or a + // replay button (as the story mounts) rebuilds it where it was. + let motion = storyMotion(entry.motion) + const [shown, setShown] = createSignal(motion, { equals: sameMotion }) + + const inspect = () => { + const scopes = motionScopes(motion) + + return defineControls( + "components-lab", + { ...states, ...fields, ...motionFields(motion) }, + { + storage: null, + persist: "none", + // Beta is a production build, where knobs resolves its production entry: the panel mounts only when shipped. + ship: () => import("knobs/panel"), + defaultLabel: { ...(first !== undefined && { "": first }), ...scopes.defaultLabels }, + presets: Object.fromEntries( + entry.states.slice(1).map((state, offset) => [state.name, knobArgs(fields, stateArgs(entry, offset + 1))]), + ), + // A state leaves the Knobs where they are: they're the story's tuning, not part of a state. + inPresets: scopes.inPresets, + scopedPresets: scopes.scopedPresets, + onChange: (patch, values, meta) => { + applyMotionPatch(motion, patch) + + if (!("lab.preset" in patch)) { + if (meta.source !== "preset") dispatch({ type: "pause" }) + + return setArgs(Object.fromEntries(Object.entries(patch).filter(([key]) => key in fields))) + } + + dispatch({ type: "panel.state", name: String(values["lab.preset"]), fromPreset: meta.source === "preset" }) + }, + }, + ) + } + + let store!: ReturnType + + createEffect(() => { + motion = shown() + store = untrack(inspect) + store.sync(motionValues(motion)) + onCleanup( + store.mount(props.inspector, { + theme: props.scheme, + // At some pane widths automatic sizing alternates between chips and a list on every frame. + presetDisplay: "chips", + header: { title: false, buttons: ["undo", "redo", "reset"] }, + variants: false, + session: false, + empty: language.t("lab.noControls"), + hints: { digits: "always" }, + }), + ) + + // A rebuild stays on the state it was showing, and its fresh knobs show that state's args. + if (rest.length > 0) + untrack(() => { + setArgs(reconcile(stateArgs(entry, index()))) + preset(index()) + }) + }) + + onCleanup(motionTuning.subscribe(() => dispatch({ type: "motion.changed" }))) + onCleanup(() => dispatch({ type: "disposed" })) + + if (names.length > 1) { + bindPresetNumbers(props.inspector, names.length, (number) => dispatch({ type: "select", index: number - 1 })) + } + + return ( + // Contained layout makes the canvas hold its stories' dialogs, which the provider below portals into it. + // A press inside the story (its own replay buttons, a dock) stops Play rather than being undone by it. +
dispatch({ type: "pause" })} + > + + + + {(fn) => ( + + { + // A failing state does not stick: the next state or edit tries again. + createEffect(on(() => ({ ...args }), reset, { defer: true })) + + return ( +
+                        {String(error)}
+                      
+ ) + }} + > + {untrack(() => fn(args))} +
+
+ )} +
+
+
+
+ ) +} + +/** The tree under `path`: a folder for each further title segment and a row for each story, by name. */ +function folder(entries: LabEntry[], path: string[]): Row[] { + const depth = path.length + const inside = entries.filter((entry) => path.every((segment, index) => entry.title.split("/")[index] === segment)) + const names = [...new Set(inside.flatMap((entry) => entry.title.split("/").slice(depth, -1).slice(0, 1)))] + + return [ + ...names.map((name) => ({ + id: `folder:${[...path, name].join("/")}`, + label: name, + children: folder(inside, [...path, name]), + })), + ...inside.flatMap((entry) => + entry.title.split("/").length === depth + 1 + ? [ + { + id: entry.file, + label: entry.title.split("/").at(-1) ?? entry.title, + // Files may share a title; the file name tells them apart. + detail: + inside.filter((other) => other.title === entry.title).length > 1 ? fileName(entry.file) : undefined, + }, + ] + : [], + ), + ].toSorted((a, b) => a.label.localeCompare(b.label)) +} + +// knobs' split takes each pane's content as a node; Solid keeps it reactive where it sits. +/** The library's stories on a canvas that pans and zooms, each in its first state; clicking one opens it on its own. */ +function Grid(props: { + entries: LabEntry[] + scheme: "dark" | "light" + onOpen: (file: string) => void + plugin: LabPlugin +}) { + const language = useLanguage() + const owner = getOwner() + let element!: HTMLDivElement + + onMount(() => { + const visibility = new Map void>() + + const observer = new IntersectionObserver( + (entries) => batch(() => entries.forEach((entry) => visibility.get(entry.target)?.(entry.isIntersecting))), + { root: element }, + ) + + const board = canvas(element, { + theme: props.scheme, + label: language.t("lab.grid"), + // Neighbours share the library's folder: actions, forms, overlays, then app dialogs. + items: props.entries + .toSorted((a, b) => folderOf(a).localeCompare(folderOf(b))) + .map((entry) => { + const size = tileSize(entry) + + return { + id: entry.file, + title: entry.title.split("/").at(-1), + w: size.w, + h: size.h, + render: (card: HTMLElement) => + createRoot((dispose) => { + // The shell keeps its size and hit target as previews enter and leave the viewport. + card.dataset.labStory = entry.file + const [visible, setVisible] = createSignal(false) + visibility.set(card, setVisible) + observer.observe(card) + insert(card, () => ( + + + + )) + onCleanup(() => { + observer.unobserve(card) + visibility.delete(card) + }) + + return dispose + }, owner ?? undefined), + } + }), + }) + + // The canvas captures the pointer to pan, so a card never sees its click: a press that ends where it began opens + // the story it began on. + let press: { file: string; x: number; y: number } | undefined + + const down = (event: PointerEvent) => { + const file = event.target instanceof Element ? event.target.closest("[data-lab-story]") : null + + press = file?.dataset.labStory ? { file: file.dataset.labStory, x: event.clientX, y: event.clientY } : undefined + } + + const up = (event: PointerEvent) => { + if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) props.onOpen(press.file) + press = undefined + } + + element.addEventListener("pointerdown", down, true) + window.addEventListener("pointerup", up, true) + onCleanup(() => { + element.removeEventListener("pointerdown", down, true) + window.removeEventListener("pointerup", up, true) + observer.disconnect() + board.dispose() + }) + }) + + return
+} + +// A story's first state at its natural size, holding its own dialogs as the stage does. +function Tile(props: { entry: LabEntry; plugin: LabPlugin }) { + const [canvas, setCanvas] = createSignal() + const component = props.entry.component + const render = props.entry.gridPreview ?? props.entry.states[0]?.render ?? props.entry.render + + return ( +
+ {/* The provider waits for the card, so a story that opens a dialog at once opens it inside. */} + + {(container) => ( +
+ + +
{String(error)}
} + > + {render + ? untrack(() => render(stateArgs(props.entry, 0))) + : component && } +
+
+
+
+ )} +
+
+ ) +} + +function isDialogEntry(entry: LabEntry) { + return entry.title.startsWith("App/Dialogs/") || entry.file.endsWith("/overlays/dialog/dialog.stories.tsx") +} + +function tileSize(entry: LabEntry) { + if (entry.fullscreen) return { w: 1120, h: 720 } + + if (isDialogEntry(entry)) return { w: 720, h: 820 } + + return { w: 320, h: 240 } +} + +function folderOf(entry: LabEntry) { + if (isDialogEntry(entry)) return `1:dialogs:${entry.title}` + + return `0:${entry.file.match(/ui\/src\/([^/]+)\//)?.[1] ?? ""}` +} + +function typing(target: EventTarget | null) { + return target instanceof HTMLElement && (target.isContentEditable || !!target.closest("input, textarea, select")) +} + +function bindPresetNumbers(inspector: HTMLElement, count: number, select: (number: number) => void) { + let pending: { number: number; timer: ReturnType } | undefined + + const clear = () => { + clearTimeout(pending?.timer) + pending = undefined + } + + const keydown = (event: KeyboardEvent) => { + if ( + event.defaultPrevented || + event.isComposing || + event.metaKey || + event.ctrlKey || + event.altKey || + event.shiftKey || + typing(event.target) || + !/^[0-9]$/.test(event.key) + ) + return clear() + + if (!pending && (event.key === "0" || Number(event.key) > count)) return + + event.preventDefault() + event.stopPropagation() + + if (event.repeat) return + + const number = (pending?.number ?? 0) * 10 + Number(event.key) + clear() + + if (number > count) return + + if (number * 10 > count) return select(number) + + // A prefix can be a preset on its own. Wait for the next digit before mounting a story that might take focus. + pending = { + number, + timer: setTimeout(() => { + pending = undefined + select(number) + }, 450), + } + } + + // Knobs handles single digits on a focused preset strip before the event reaches the window. + makeEventListener( + inspector, + "keydown", + (event) => { + if ( + event.target instanceof Element && + event.target.closest(".knobs-presets") && + !event.target.closest(".knobs-card") + ) + keydown(event) + }, + { capture: true }, + ) + makeEventListener(window, "keydown", keydown) + makeEventListener(window, "pointerdown", clear, { capture: true }) + makeEventListener(window, "blur", clear) + onCleanup(clear) +} + +function pane(content: () => JSX.Element) { + const element = document.createElement("div") + + element.className = "size-full" + insert(element, content) + + return element +} diff --git a/packages/app/src/components-lab/catalog.ts b/packages/app/src/components-lab/catalog.ts index 924c06874b9d..8e6510960c53 100644 --- a/packages/app/src/components-lab/catalog.ts +++ b/packages/app/src/components-lab/catalog.ts @@ -24,7 +24,7 @@ type StoryObject = { argTypes?: { [key: string]: ArgType } render?: StoryRender // `motion` names the Knobs (by id, group or card) the story uses, so the inspector shows them beside its args. - parameters?: { layout?: string; motion?: readonly string[] } + parameters?: { layout?: string; motion?: readonly string[]; gridPreview?: () => JSX.Element } } export type StoryModule = { [name: string]: StoryObject | StoryRender | string[] | undefined } @@ -40,10 +40,39 @@ export type LabEntry = { argTypes: { [key: string]: ArgType } render?: StoryRender fullscreen: boolean + gridPreview?: () => JSX.Element motion: readonly string[] states: LabState[] } +/** Loads every story file. A file that fails to import is reported rather than hiding the rest. */ +export async function loadLabCatalog( + modules: Record Promise>, + sources: Record Promise>, +) { + const files = Object.entries(modules) + + const results: PromiseSettledResult[] = [] + + // A few files at a time: hundreds of parallel module requests overflow a dev server reached through a proxy. + for (let index = 0; index < files.length; index += 8) { + const chunk = files.slice(index, index + 8).map(async ([file, load]) => { + const [module, source] = await Promise.all([load(), sources[file]?.() ?? ""]) + + return labEntry(file, module, source) + }) + + results.push(...(await Promise.allSettled(chunk))) + } + + return { + entries: results + .flatMap((result) => (result.status === "fulfilled" ? [result.value] : [])) + .toSorted((a, b) => a.title.localeCompare(b.title)), + failed: results.filter((result) => result.status === "rejected").length, + } +} + // A story file as the lab shows it. A module lists its exports alphabetically, so `source`, the file's text, gives the // order the author wrote the states in. export function labEntry(file: string, module: StoryModule, source: string): LabEntry { @@ -76,6 +105,7 @@ export function labEntry(file: string, module: StoryModule, source: string): Lab }, render: meta.render, fullscreen: meta.parameters?.layout === "fullscreen", + gridPreview: meta.parameters?.gridPreview, motion: meta.parameters?.motion ?? [], states, } diff --git a/packages/app/src/components-lab/dialog-story-runtime.tsx b/packages/app/src/components-lab/dialog-story-runtime.tsx index fb1b596567b1..23b0a41d06e1 100644 --- a/packages/app/src/components-lab/dialog-story-runtime.tsx +++ b/packages/app/src/components-lab/dialog-story-runtime.tsx @@ -204,7 +204,7 @@ const defaultModels = [ }), ] -const integrations = [ +const fixtureIntegrations = [ { id: "anthropic", name: "Anthropic", @@ -248,6 +248,149 @@ const integrations = [ methods: [{ type: "oauth", id: "copilot", label: "Sign in with GitHub" }], connections: [], }, + { + id: "xai", + name: "xAI", + methods: [ + { type: "oauth", id: "device", label: "SuperGrok Subscription" }, + { type: "key", label: "Manually enter API Key" }, + ], + connections: [], + }, + { + id: "gitlab", + name: "GitLab", + methods: [ + { + type: "oauth", + id: "pkce", + label: "Login with GitLab (OAuth)", + form: [ + { + key: "instanceUrl", + type: "string", + title: "GitLab instance URL", + description: "Use gitlab.com, or the URL of your self-managed instance.", + placeholder: "https://gitlab.com", + }, + ], + }, + ], + connections: [], + }, + { + id: "snowflake-cortex", + name: "Snowflake Cortex", + methods: [ + { + type: "oauth", + id: "browser", + label: "Login with Snowflake (External Browser)", + form: [ + { key: "account", type: "string", title: "Snowflake account", placeholder: "org-account", required: true }, + ], + }, + ], + connections: [], + }, + { + id: "amazon-bedrock", + name: "Amazon Bedrock", + methods: [ + { type: "key", label: "Bedrock API key" }, + { + type: "external", + id: "aws-profile", + label: "AWS profile (SSO or named profile)", + form: [ + { + key: "profile", + type: "string", + title: "AWS profile", + description: "Profiles from ~/.aws/config.", + required: true, + custom: true, + options: [ + { value: "default", label: "default" }, + { value: "work-sso", label: "work-sso", description: "SSO · us-east-1" }, + ], + }, + ], + }, + ], + connections: [], + }, + { + id: "acme-search", + name: "Acme Search", + methods: [ + { + type: "key", + label: "API key", + form: [ + { + key: "sources", + type: "multiselect", + title: "Sources to search", + minItems: 1, + custom: true, + options: [ + { value: "web", label: "Web" }, + { value: "news", label: "News", description: "Articles from the last 30 days" }, + { value: "code", label: "Code" }, + ], + }, + { key: "safe", type: "boolean", title: "Use safe search?", default: true }, + ], + }, + ], + connections: [], + }, + { + id: "acme-cloud", + name: "Acme Cloud", + methods: [ + { + type: "oauth", + id: "browser", + label: "Sign in", + form: [ + { + key: "terms", + type: "external", + url: "https://acme.example/terms", + title: "Accept the Acme terms", + description: "Open the link, accept the terms, then come back.", + }, + ], + }, + ], + connections: [], + }, + { + id: "acme-cli", + name: "Acme CLI", + methods: [{ type: "command", id: "login", label: "Log in", command: ["acme", "login"] }], + connections: [], + }, + { + id: "acme-code", + name: "Acme Code", + methods: [{ type: "oauth", id: "code", label: "Acme account" }], + connections: [], + }, + { + id: "acme-broken", + name: "Acme Broken", + methods: [{ type: "oauth", id: "browser", label: "Sign in" }], + connections: [], + }, + { + id: "claude-agent", + name: "Claude Agent", + methods: [{ type: "external", id: "claude-login", label: "Claude Code login (claude auth login)" }], + connections: [], + }, { id: "google", name: "Google", @@ -353,9 +496,19 @@ function findMatchingPaths(root: string, query: string, type: string | null) { type DialogStoryRuntimeOptions = { servers?: ServerConnection.Any[] + platform?: Platform + /** Replaces fixture integrations with the same id. */ + integrations?: IntegrationInfo[] } -function createStoryFetch(): typeof fetch { +const REDIRECT_PASTE = ["openai", "gitlab", "snowflake-cortex"] + +export function createStoryFetch(overrides: IntegrationInfo[] = []): typeof fetch { + const integrations = [ + ...overrides, + ...fixtureIntegrations.filter((item) => !overrides.some((override) => override.id === item.id)), + ] + const encoder = new TextEncoder() const handler = async (input: RequestInfo | URL, init?: RequestInit) => { @@ -471,13 +624,46 @@ function createStoryFetch(): typeof fetch { if (rest[1] === "connect" && rest[2] === "oauth" && rest.length === 3 && method === "POST") { const now = Date.now() + if (integrationID === "acme-broken") + return errorResponse("InvalidRequestError", "The Acme sign-in service is unavailable. Try again later.", 400) + return jsonResponse({ location, data: { attemptID: "con_story_1", - url: "https://opencode.ai/auth/authorize", + // Device sign-ins show a code; some browser sign-ins also take the redirect URL pasted from another device. + url: + integrationID === "github-copilot" || integrationID === "xai" + ? "https://example.test/device?user_code=KBSC-TK37" + : integrationID === "opencode" + ? "https://opencode.ai/auth/device?user_code=WXYZ-2345" + : "https://opencode.ai/auth/authorize", instructions: "", - mode: "auto", + mode: integrationID === "acme-code" ? "code" : "auto", + paste: REDIRECT_PASTE.includes(integrationID) ? true : undefined, + time: { created: now, expires: now + 600_000 }, + }, + }) + } + + if (rest[1] === "connect" && rest[2] === "command" && rest.length === 3 && method === "POST") { + const now = Date.now() + + return jsonResponse({ + location, + data: { attemptID: "con_story_cmd", time: { created: now, expires: now + 600_000 } }, + }) + } + + if (rest[1] === "connect" && rest[2] === "command" && rest[3] && method === "GET") { + const now = Date.now() + + return jsonResponse({ + location, + data: { + status: "pending", + message: + "$ acme login\nOpening https://acme.example/device in your browser…\nWaiting for you to approve this device.", time: { created: now, expires: now + 600_000 }, }, }) @@ -541,7 +727,7 @@ function createStoryFetch(): typeof fetch { return Object.assign(handler, { preconnect: globalThis.fetch.preconnect }) } -function createMemoryStorage() { +export function createMemoryStorage() { const namespaces = new Map>() const bucket = (name = "default") => { @@ -574,15 +760,13 @@ function createMemoryStorage() { export function DialogStoryRuntime(props: ParentProps) { const servers = () => props.servers ?? [STORY_SERVER] - const storage = createMemoryStorage() - - const platform: Platform = { + const platform: Platform = props.platform ?? { platform: "web", openExternal() {}, restart: async () => {}, notify: async () => {}, - storage, - fetch: createStoryFetch(), + storage: createMemoryStorage(), + fetch: createStoryFetch(props.integrations), } const client = new QueryClient({ diff --git a/packages/app/src/components-lab/inspector.css b/packages/app/src/components-lab/inspector.css new file mode 100644 index 000000000000..3085e0a849a6 --- /dev/null +++ b/packages/app/src/components-lab/inspector.css @@ -0,0 +1,28 @@ +.knobs-panel.knobs-inline[data-controls="components-lab"] { + border-radius: 0; +} + +.knobs-panel[data-controls="components-lab"] .knobs-presets-track { + counter-reset: lab-preset; +} + +.knobs-panel[data-controls="components-lab"] .knobs-preset-chip { + counter-increment: lab-preset; + padding-inline-start: 30px; + text-align: start; +} + +.knobs-panel[data-controls="components-lab"] .knobs-preset-key { + display: none; +} + +.knobs-panel[data-controls="components-lab"] .knobs-preset-chip::before { + content: counter(lab-preset); + position: absolute; + inset-inline-start: 6px; + inline-size: 2ch; + text-align: end; + color: var(--_k-fg-3); + font-size: var(--_k-text-meta); + font-variant-numeric: tabular-nums; +} diff --git a/packages/app/src/components-lab/lab.tsx b/packages/app/src/components-lab/lab.tsx index 4e90eb06fbb4..811acb7d9370 100644 --- a/packages/app/src/components-lab/lab.tsx +++ b/packages/app/src/components-lab/lab.tsx @@ -1,30 +1,5 @@ -import { makeEventListener } from "@solid-primitives/event-listener" import { useSearchParams } from "@solidjs/router" -import { - batch, - createEffect, - createMemo, - createResource, - createRoot, - createSignal, - ErrorBoundary, - getOwner, - on, - onCleanup, - onMount, - Show, - untrack, - type JSX, -} from "solid-js" -import { createStore, reconcile } from "solid-js/store" -import { Dynamic, insert } from "solid-js/web" -import { DialogProvider } from "@opencode/ui/context/dialog" -import { useTheme } from "@opencode/ui/theme" -import { motionGlobals, motionTuning } from "@opencode/ui/motion-tuning" -import { choice, defineControls, matchesCombo, toolbar, type Field } from "knobs" -import { canvas, commandPalette, restyle, split, toast, type CommandPalette } from "knobs/ui" -import { Tree } from "knobs/ui/solid" -import { useLanguage } from "@/runtime/i18n/language" +import { createMemo, Show, type ParentProps } from "solid-js" import { CommentsProvider } from "@/composer/comments" import { ComposerPersistenceProvider } from "@/composer/persistence" import { ModelsProvider } from "@/providers/models/models" @@ -33,42 +8,11 @@ import { ServerProvider, useServer } from "@/runtime/server/current" import { ServerConnection, useServers } from "@/runtime/server/registry" import { isServerHealthy } from "@/runtime/server/health-machine" import { useGlobal } from "@/runtime/server/runtime" -import { SessionRouteFrame } from "@/session/session-frame" import { SessionUIProvider } from "@/shell/routes/session-ui-provider" import { FileProvider } from "@/workspaces/files/model" import { LocationProvider } from "@/workspaces/location" -import { - fileName, - knobArgs, - labEntry, - labFields, - stateArgs, - type LabEntry, - type StoryArgs, - type StoryModule, -} from "./catalog" -import { - createLabStageState, - INITIAL_LAB_BROWSE_STATE, - labStageIndex, - selectShouldToggleFolder, - transitionLabBrowse, - transitionLabStage, - type LabBrowseEvent, - type LabStageEffect, - type LabStageEvent, -} from "./machine" -import { applyMotionPatch, motionFields, motionScopes, motionValues, sameMotion, storyMotion } from "./motion" - -// How long Play holds each state at full speed. Slow motion doubles it while the motion itself runs 4× longer, so -// a transition still finishes and Play keeps moving. -const hold = 1600 - -const searchIcon = `` - -const themeIcon = `` - -const gridIcon = `` +import { LabBrowser } from "./browser" +import { loadLabCatalog, type StoryModule } from "./catalog" // Standalone stories mount fixture runtimes that must not access the live app's storage. // Vite needs the patterns as literals in each call. @@ -92,446 +36,17 @@ const sources = import.meta.glob( { query: "?raw", import: "default" }, ) -/** Loads every story file. A file that fails to import is reported rather than hiding the rest. */ -async function loadCatalog() { - const files = Object.entries(modules) - const results: PromiseSettledResult[] = [] - - // A few files at a time: hundreds of parallel module requests overflow a dev server reached through a proxy. - for (let index = 0; index < files.length; index += 8) { - const chunk = files.slice(index, index + 8).map(async ([file, load]) => { - const [module, source] = await Promise.all([load(), sources[file]?.() ?? ""]) - - return labEntry(file, module, source) - }) - - results.push(...(await Promise.allSettled(chunk))) - } - - return { - entries: results - .flatMap((result) => (result.status === "fulfilled" ? [result.value] : [])) - .toSorted((a, b) => a.title.localeCompare(b.title)), - failed: results.filter((result) => result.status === "rejected").length, - } -} - -type Row = { id: string; label: string; detail?: string; children?: Row[] } - -/** The development components lab: every story file in knobs' workspace, rendered with the app's providers and theme. */ export default function ComponentsLab() { - const language = useLanguage() - const theme = useTheme() const [params, setParams] = useSearchParams<{ story?: string; view?: string }>() - const [catalog] = createResource(loadCatalog) - const [scheme, setScheme] = createSignal<"dark" | "light">("dark") - let palette: CommandPalette | undefined - let toggle: ((id: string) => void) | undefined - let focusTree: ((id?: string) => void) | undefined - let browse = INITIAL_LAB_BROWSE_STATE - - const dispatchBrowse = (event: LabBrowseEvent) => { - const next = transitionLabBrowse(browse, event) - browse = next.state - next.effects.forEach(() => focusTree?.(params.story)) - } - - const entries = () => catalog()?.entries ?? [] - const grid = () => params.view === "grid" - const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === params.story))) - - const open = (file: string) => { - dispatchBrowse({ type: "story.opened", fromTree: stories.contains(document.activeElement) }) - setParams({ story: file, view: undefined }) - } - - const rows = createMemo(() => folder(entries(), [])) - - const search = () => { - if (palette?.isOpen) return palette.close() - - palette ??= commandPalette({ - hotkey: false, - recents: false, - placeholder: language.t("lab.search"), - look: { theme: scheme() }, - commands: () => - entries().map((entry) => ({ - id: entry.file, - label: entry.title.split("/").join(" / "), - hint: fileName(entry.file), - keywords: entry.states.map((state) => state.name), - run: () => open(entry.file), - })), - }) - palette.open() - } - - // The palette takes its look when it's made. - createEffect( - on( - scheme, - () => { - palette?.dispose() - palette = undefined - }, - { defer: true }, - ), - ) - - // Ahead of the app's own palette, which listens on the document. - makeEventListener( - window, - "keydown", - (event) => { - if (!matchesCombo("Mod+K", event)) return - event.preventDefault() - event.stopImmediatePropagation() - search() - }, - { capture: true }, - ) - - // A story's modal overlay (a menu or dialog open by default) sets `pointer-events: none` on the body, which would - // freeze the lab around it. The lab stays usable while it's open. - const unblock = document.createElement("style") - - unblock.textContent = "body { pointer-events: auto !important; }" - document.head.append(unblock) - - createEffect(() => theme.previewColorScheme(scheme())) - onCleanup(() => { - theme.cancelPreview() - palette?.dispose() - unblock.remove() - }) - - createEffect(() => { - const failed = catalog()?.failed - - if (failed) toast(language.plural("lab.failed", failed)) - }) - - // The story's knobs panel mounts in the inspector pane. - const inspector = pane(() => null) - - const stories = pane(() => ( - - row.detail} - label={language.t("lab.components")} - expanded={rows().map((row) => row.id)} - selection={params.story ? [params.story] : []} - // Digits pick the story's states. - typeahead={(key) => !/^[1-9]$/.test(key)} - onReady={(tree) => { - // Opens the folders down to the story in the address, and later ones picked from the palette. - createEffect(() => params.story && tree.reveal(params.story)) - toggle = (id) => tree.expand(id, !tree.isExpanded(id)) - focusTree = (id) => tree.focus(id) - }} - // Moving by keys selects as it goes, so a folder opens and closes only by a click, Enter, Space or ←/→. - onSelect={(_, primary) => { - if (!primary?.startsWith("folder:")) return primary && open(primary) - - if (selectShouldToggleFolder(browse)) toggle?.(primary) - }} - onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} - /> - - )) - - const stage = pane(() => ( - entry.title.startsWith("UI/") || isDialogEntry(entry))} - scheme={untrack(scheme)} - onOpen={open} - /> - } - > - - {language.t("lab.pick")} -
- } - > - {(entry) => } - - - )) - - const inTree = (event: Event) => event.target instanceof Node && stories.contains(event.target) - - makeEventListener(window, "pointerdown", (event) => dispatchBrowse({ type: "pointer.down", inTree: inTree(event) }), { - capture: true, - }) - // Bubbling, so the tree's own pointerup (which completes a press on a selected row) selects first. - makeEventListener(window, "pointerup", () => dispatchBrowse({ type: "pointer.ended" })) - makeEventListener(window, "pointercancel", () => dispatchBrowse({ type: "pointer.ended" })) - makeEventListener( - window, - "keydown", - (event) => dispatchBrowse({ type: "key.down", key: event.key, inTree: inTree(event) }), - { capture: true }, - ) - makeEventListener(window, "keyup", () => dispatchBrowse({ type: "key.ended" })) - makeEventListener(window, "blur", () => dispatchBrowse({ type: "window.blurred" })) - makeEventListener(stage, "focusin", () => dispatchBrowse({ type: "stage.focused" })) - - let element!: HTMLDivElement - - onMount(() => { - const layout = split(element, { - theme: "dark", - storage: null, - panes: [ - { - id: "stories", - size: 260, - min: 200, - max: 420, - collapsible: true, - title: language.t("lab.components"), - element: stories, - actions: [ - { label: language.t("lab.search"), icon: searchIcon, shortcut: "Mod+K", run: search }, - { - label: language.t("lab.grid"), - icon: gridIcon, - run: () => setParams({ view: grid() ? undefined : "grid" }), - }, - { - label: language.t("lab.theme"), - icon: themeIcon, - run: () => setScheme(scheme() === "dark" ? "light" : "dark"), - }, - ], - }, - { id: "stage", min: 360, element: stage }, - { id: "inspector", size: 300, min: 260, max: 460, collapsible: true, title: "", element: inspector }, - ], - }) - - createEffect(() => layout.pane("stories").title(language.t("lab.components"), entries().length)) - createEffect(() => layout.pane("inspector").title(selected()?.title.split("/").join(" / ") ?? "")) - createEffect(on(scheme, (next) => restyle(layout.element, { theme: next }), { defer: true })) - onCleanup(() => layout.dispose()) - }) return ( - -
- - ) -} - -/** One story on the app's background, with its args and states as a knobs panel in the inspector. */ -function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" | "light" }) { - const language = useLanguage() - const entry = props.entry - const fields = labFields(entry) - const names = entry.states.map((state) => state.name) - const [args, setArgs] = createStore(stateArgs(entry, 0)) - const [stageState, setStageState] = createSignal(createLabStageState(names)) - const index = createMemo(() => labStageIndex(stageState())) - const [canvas, setCanvas] = createSignal() - const component = entry.component - const fallback = component && ((values: StoryArgs) => ) - // Switching to a state that shares the current render function keeps the mounted instance, so its transitions play. - const render = () => entry.states[index()]?.render ?? entry.render ?? fallback - let timer: ReturnType | undefined - - // A state is a variant: its chip, a digit, `[` and `]` and Play all apply it, so the panel shows where it is. - const preset = (next: number): void => store.preset(next === 0 ? "default" : (names[next] ?? "default")) - - // One batch, so a state with its own render function never renders with the previous state's args. - const dispatch = (event: LabStageEvent) => - batch(() => { - const next = transitionLabStage(untrack(stageState), event) - setStageState(next.state) - next.effects.forEach(perform) - }) - - const perform = (effect: LabStageEffect) => { - if (effect.type === "timer.schedule") { - clearTimeout(timer) - timer = setTimeout( - () => dispatch({ type: "tick", attempt: effect.attempt }), - (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, - ) - - return - } - - if (effect.type === "timer.clear") return clearTimeout(timer) - - if (effect.type === "state.apply") { - setArgs(reconcile(stateArgs(entry, effect.index))) - - if (effect.preset === "now") preset(effect.index) - - // Undo or a reset moved the state: bring the other knobs to the state's args too. - if (effect.preset === "later") - queueMicrotask(() => { - if (untrack(stageState).status !== "disposed") preset(effect.index) - }) - - return - } - - // Coalesced: a story registers its replay buttons one by one. - if (effect.type === "motion.queue") return queueMicrotask(() => dispatch({ type: "motion.flushed" })) - const next = storyMotion(entry.motion) - - if (!sameMotion(next, motion)) return setShown(next) - store.sync(motionValues(motion)) - } - - const [first, ...rest] = names - - const states: { [key: string]: Field } = - first === undefined || rest.length === 0 - ? {} - : { - state: choice(first, [first, ...rest], { variants: true }), - play: toolbar( - [ - { - id: "previous", - label: language.t("lab.previous"), - icon: "M200 48 80 128l120 80ZM48 48h16v160H48Z", - run: () => dispatch({ type: "step", delta: -1 }), - }, - { id: "play", label: language.t("lab.play"), icon: "play", run: () => dispatch({ type: "play" }) }, - { id: "pause", label: language.t("lab.pause"), icon: "pause", run: () => dispatch({ type: "pause" }) }, - { - id: "next", - label: language.t("lab.next"), - icon: "M56 48l120 80-120 80ZM192 48h16v160h-16Z", - run: () => dispatch({ type: "step", delta: 1 }), - }, - ], - { labels: false }, - ), - } - - // The story's Knobs join its args here, so the inspector is the one place for its controls. Registering a knob or a - // replay button (as the story mounts) rebuilds it where it was. - let motion = storyMotion(entry.motion) - const [shown, setShown] = createSignal(motion, { equals: sameMotion }) - - const inspect = () => { - const scopes = motionScopes(motion) - - return defineControls( - "components-lab", - { ...states, ...fields, ...motionFields(motion) }, - { - storage: null, - persist: "none", - // Beta is a production build, where knobs resolves its production entry: the panel mounts only when shipped. - ship: () => import("knobs/panel"), - defaultLabel: { ...(first !== undefined && { "": first }), ...scopes.defaultLabels }, - presets: Object.fromEntries( - entry.states.slice(1).map((state, offset) => [state.name, knobArgs(fields, stateArgs(entry, offset + 1))]), - ), - // A state leaves the Knobs where they are: they're the story's tuning, not part of a state. - inPresets: scopes.inPresets, - scopedPresets: scopes.scopedPresets, - onChange: (patch, values, meta) => { - applyMotionPatch(motion, patch) - - if (!("state" in patch)) { - if (meta.source !== "preset") dispatch({ type: "pause" }) - - return setArgs(Object.fromEntries(Object.entries(patch).filter(([key]) => key in fields))) - } - - dispatch({ type: "panel.state", name: String(values.state), fromPreset: meta.source === "preset" }) - }, - }, - ) - } - - let store!: ReturnType - - createEffect(() => { - motion = shown() - store = untrack(inspect) - store.sync(motionValues(motion)) - onCleanup( - store.mount(props.inspector, { - theme: props.scheme, - header: { title: false, buttons: ["undo", "redo", "reset"] }, - variants: false, - session: false, - empty: language.t("lab.noControls"), - hints: { digits: "always" }, - }), - ) - - // A rebuild stays on the state it was showing, and its fresh knobs show that state's args. - if (rest.length > 0) - untrack(() => { - setArgs(reconcile(stateArgs(entry, index()))) - preset(index()) - }) - }) - - onCleanup(motionTuning.subscribe(() => dispatch({ type: "motion.changed" }))) - onCleanup(() => dispatch({ type: "disposed" })) - - makeEventListener(window, "keydown", (event) => { - const digit = Number(event.key) - - if (names.length < 2 || !Number.isInteger(digit) || digit < 1 || digit > Math.min(9, names.length)) return - - if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || typing(event.target)) return - event.preventDefault() - dispatch({ type: "select", index: digit - 1 }) - }) - - return ( - // Contained layout makes the canvas hold its stories' dialogs, which the provider below portals into it. - // A press inside the story (its own replay buttons, a dock) stops Play rather than being undone by it. -
dispatch({ type: "pause" })} - > - - - - {(fn) => ( - - { - // A failing state does not stick: the next state or edit tries again. - createEffect(on(() => ({ ...args }), reset, { defer: true })) - - return ( -
-                        {String(error)}
-                      
- ) - }} - > - {untrack(() => fn(args))} -
-
- )} -
-
-
-
+ loadLabCatalog(modules, sources)} + workspace={Workspace} + plugin={Plugin} + /> ) } @@ -539,7 +54,7 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" * The provider stack of a draft session in the first project of the first healthy server, so a story that reads the * server, models, location or composer state renders as it does in the app. Without a server, stories render bare. */ -function Workspace(props: { children: JSX.Element }) { +function Workspace(props: ParentProps) { const servers = useServers() const global = useGlobal() @@ -561,7 +76,7 @@ function Workspace(props: { children: JSX.Element }) { ) } -function Project(props: { children: JSX.Element }) { +function Project(props: ParentProps) { const server = useServer() // The list puts the most recently active project first, and on a busy server that changes every few seconds. The @@ -592,164 +107,8 @@ function Project(props: { children: JSX.Element }) { } // A story of a plugin renders as its contributions do: inside that plugin's context from the app's host. -function Plugin(props: { file: string; children: JSX.Element }) { +function Plugin(props: ParentProps<{ file: string }>) { const id = props.file.match(/gui-plugins\/src\/([^/]+)\//)?.[1] return id ? {() => props.children} : props.children } - -/** The tree under `path`: a folder for each further title segment and a row for each story, by name. */ -function folder(entries: LabEntry[], path: string[]): Row[] { - const depth = path.length - const inside = entries.filter((entry) => path.every((segment, index) => entry.title.split("/")[index] === segment)) - const names = [...new Set(inside.flatMap((entry) => entry.title.split("/").slice(depth, -1).slice(0, 1)))] - - return [ - ...names.map((name) => ({ - id: `folder:${[...path, name].join("/")}`, - label: name, - children: folder(inside, [...path, name]), - })), - ...inside.flatMap((entry) => - entry.title.split("/").length === depth + 1 - ? [ - { - id: entry.file, - label: entry.title.split("/").at(-1) ?? entry.title, - // Files may share a title; the file name tells them apart. - detail: - inside.filter((other) => other.title === entry.title).length > 1 ? fileName(entry.file) : undefined, - }, - ] - : [], - ), - ].toSorted((a, b) => a.label.localeCompare(b.label)) -} - -// knobs' split takes each pane's content as a node; Solid keeps it reactive where it sits. -/** The library's stories on a canvas that pans and zooms, each in its first state; clicking one opens it on its own. */ -function Grid(props: { entries: LabEntry[]; scheme: "dark" | "light"; onOpen: (file: string) => void }) { - const language = useLanguage() - const owner = getOwner() - let element!: HTMLDivElement - - onMount(() => { - const board = canvas(element, { - theme: props.scheme, - label: language.t("lab.grid"), - // Neighbours share the library's folder: actions, forms, overlays, then app dialogs. - items: props.entries - .toSorted((a, b) => folderOf(a).localeCompare(folderOf(b))) - .map((entry) => { - const size = tileSize(entry) - - return { - id: entry.file, - title: entry.title.split("/").at(-1), - w: size.w, - h: size.h, - render: (card: HTMLElement) => - createRoot((dispose) => { - insert(card, () => ) - - return dispose - }, owner ?? undefined), - } - }), - }) - - // The canvas captures the pointer to pan, so a card never sees its click: a press that ends where it began opens - // the story it began on. - let press: { file: string; x: number; y: number } | undefined - - const down = (event: PointerEvent) => { - const file = event.target instanceof Element ? event.target.closest("[data-lab-story]") : null - - press = file?.dataset.labStory ? { file: file.dataset.labStory, x: event.clientX, y: event.clientY } : undefined - } - - const up = (event: PointerEvent) => { - if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) props.onOpen(press.file) - press = undefined - } - - element.addEventListener("pointerdown", down, true) - window.addEventListener("pointerup", up, true) - onCleanup(() => { - element.removeEventListener("pointerdown", down, true) - window.removeEventListener("pointerup", up, true) - board.dispose() - }) - }) - - return
-} - -// A story's first state at its natural size, holding its own dialogs as the stage does. -function Tile(props: { entry: LabEntry }) { - const [canvas, setCanvas] = createSignal() - const component = props.entry.component - const render = props.entry.states[0]?.render ?? props.entry.render - - return ( -
- {/* The provider waits for the card, so a story that opens a dialog at once opens it inside. */} - - {(container) => ( -
- - -
{String(error)}
} - > - {render - ? untrack(() => render(stateArgs(props.entry, 0))) - : component && } -
-
-
-
- )} -
-
- ) -} - -function isDialogEntry(entry: LabEntry) { - return entry.title.startsWith("App/Dialogs/") || entry.file.endsWith("/overlays/dialog/dialog.stories.tsx") -} - -function tileSize(entry: LabEntry) { - if (entry.fullscreen) return { w: 1120, h: 720 } - - if (isDialogEntry(entry)) return { w: 720, h: 820 } - - return { w: 320, h: 240 } -} - -function folderOf(entry: LabEntry) { - if (isDialogEntry(entry)) return `1:dialogs:${entry.title}` - - return `0:${entry.file.match(/ui\/src\/([^/]+)\//)?.[1] ?? ""}` -} - -function typing(target: EventTarget | null) { - return target instanceof HTMLElement && (target.isContentEditable || !!target.closest("input, textarea, select")) -} - -function pane(content: () => JSX.Element) { - const element = document.createElement("div") - - element.className = "size-full" - insert(element, content) - - return element -} diff --git a/packages/app/src/composer/composer-touch.stories.tsx b/packages/app/src/composer/composer-touch.stories.tsx index f2491b38cd16..61dad183d34d 100644 --- a/packages/app/src/composer/composer-touch.stories.tsx +++ b/packages/app/src/composer/composer-touch.stories.tsx @@ -1,4 +1,4 @@ -import { For, Show, createMemo, onCleanup, onMount } from "solid-js" +import { For, Show, createEffect, createMemo, on, onCleanup, onMount } from "solid-js" import { createStore } from "solid-js/store" import type { ModelSelection } from "@/providers/models/selection" import { STORY_MODEL } from "@opencode/session-ui/storybook" @@ -22,6 +22,7 @@ const states = [ { id: "shell", name: "Shell command" }, { id: "sending", name: "Sending" }, { id: "suggestions", name: "Slash suggestions open" }, + { id: "context", name: "Context suggestions open" }, ] as const type State = (typeof states)[number]["id"] @@ -37,6 +38,7 @@ const drafts: Record = { shell: "bun test composer", sending: "Ship it", suggestions: "", + context: "", } const selectedModel = { @@ -75,6 +77,7 @@ const context: ComposerSuggestion[] = [ { id: "file:src/composer/editor/editor.tsx", kind: "file", + recent: true, label: "src/composer/editor/editor.tsx", path: "src/composer/editor/editor.tsx", mention: { @@ -191,7 +194,11 @@ function TouchComposer(props: { state: State }) { const model = { ...editor, model: { selection, paid: true, loading: false } } satisfies ComposerModel - onMount(() => props.state === "suggestions" && editor.openCommands()) + onMount(() => { + if (props.state === "suggestions") editor.openCommands() + + if (props.state === "context") editor.openContext() + }) return ( <> @@ -227,6 +234,13 @@ function TouchComposer(props: { state: State }) { function TouchStates(props: { state: State }) { const [view, setView] = createStore({ state: props.state, generation: 0 }) + createEffect( + on( + () => props.state, + (state) => setView("state", state), + { defer: true }, + ), + ) const touch = matchMedia("(hover: none) and (pointer: coarse)") const [device, setDevice] = createStore({ touch: touch.matches }) const sync = () => setDevice("touch", touch.matches) diff --git a/packages/app/src/composer/composer.stories.tsx b/packages/app/src/composer/composer.stories.tsx index 5ebd3ec95951..fc13a2d72c1b 100644 --- a/packages/app/src/composer/composer.stories.tsx +++ b/packages/app/src/composer/composer.stories.tsx @@ -5,7 +5,7 @@ import { STORY_MODEL, emptySessionDocument, pendingAndQueuedDocument } from "@op import { Composer } from "./composer" import type { ComposerModel } from "./model" import { createComposerEditor } from "./editor/interaction" -import type { ComposerPersistedState, ComposerSuggestion } from "./types" +import type { ComposerHistory, ComposerPersistedState, ComposerSuggestion } from "./types" import { buildPromptRequest } from "./request" import { promptLength } from "./prompt-parts" import { SessionPreview } from "@/session/story-model" @@ -52,16 +52,17 @@ function ComposerStory(props: { comments?: ComposerPersistedState["context"]["items"] working?: boolean stopping?: boolean + sending?: boolean suggestions?: "command" | "context" | "none" failure?: boolean label?: string inspectRequest?: boolean continueOnStop?: boolean longLabels?: boolean - alternate?: "queue" | "steer" + alternate?: "none" | "queue" | "steer" manySuggestions?: boolean history?: boolean - manyHistory?: boolean + many?: boolean /** File search waits for the story's "Return files" button, like a slow server. */ fileSearch?: boolean suggestionBoundary?: () => HTMLElement | undefined @@ -163,51 +164,53 @@ function ComposerStory(props: { signal?.addEventListener("abort", () => setFileSearch("pending", undefined), { once: true }) }) }, - history: props.history - ? { - entries: (mode) => - mode === "shell" - ? [{ prompt: text("bun typecheck") }] - : [ - { prompt: text("Explain the latest changes") }, - { - prompt: [ - ...text("Review the composer layout\nKeep keyboard navigation accessible"), - { - type: "path", - id: "history-layout", - filename: "layout.png", - mime: "image/png", - path: "C:/shots/layout.png", - }, - ], - metadata: "review", - }, - { prompt: text("Run the focused tests") }, - ...(props.manyHistory - ? Array.from({ length: 16 }, (_, index) => ({ prompt: text(`Earlier prompt ${index + 1}`) })) - : []), - ], - add() {}, - capture: () => (draft.context.items.some((item) => item.key === "history-comment") ? "review" : undefined), - restore: (metadata) => - setDraft( - "context", - "items", - metadata === "review" - ? [ + get history(): ComposerHistory | undefined { + if (!props.history && !props.many) return undefined + + return { + entries: (mode) => + mode === "shell" + ? [{ prompt: text("bun typecheck") }] + : [ + { prompt: text("Explain the latest changes") }, + { + prompt: [ + ...text("Review the composer layout\nKeep keyboard navigation accessible"), { - type: "file", - key: "history-comment", - path: "src/composer.tsx", - selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 }, - comment: "Keep the search separate from the draft", + type: "path", + id: "history-layout", + filename: "layout.png", + mime: "image/png", + path: "C:/shots/layout.png", }, - ] - : [], - ), - } - : undefined, + ], + metadata: "review", + }, + { prompt: text("Run the focused tests") }, + ...(props.many + ? Array.from({ length: 16 }, (_, index) => ({ prompt: text(`Earlier prompt ${index + 1}`) })) + : []), + ], + add() {}, + capture: () => (draft.context.items.some((item) => item.key === "history-comment") ? "review" : undefined), + restore: (metadata) => + setDraft( + "context", + "items", + metadata === "review" + ? [ + { + type: "file", + key: "history-comment", + path: "src/composer.tsx", + selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 }, + comment: "Keep the search separate from the draft", + }, + ] + : [], + ), + } + }, readImage: async () => pixel, view: { placeholder: () => "Ask anything, / for commands, @ for context...", @@ -231,20 +234,25 @@ function ComposerStory(props: { submit: { stopping: () => !!props.stopping, working: () => !!props.working, - queue: props.alternate - ? { - count: () => 0, - delivery: () => (props.alternate === "queue" ? "steer" : "queue"), - alternate: () => props.alternate, - editing: () => undefined, - confirmEdit() {}, - undoing: () => false, - cancelEdit() {}, - editFirst: () => false, - first() {}, - steerFirst() {}, - } - : undefined, + busy: () => !!props.sending, + get queue() { + const alternate = props.alternate + + if (!alternate || alternate === "none") return undefined + + return { + count: () => 0, + delivery: () => (alternate === "queue" ? "steer" : "queue"), + alternate: () => alternate, + editing: () => undefined, + confirmEdit() {}, + undoing: () => false, + cancelEdit() {}, + editFirst: () => false, + first() {}, + steerFirst() {}, + } + }, onSubmit: () => { const value = draft.prompt.map((part) => ("content" in part ? part.content : `[${part.filename}]`)).join("") @@ -324,7 +332,7 @@ function ComposerStory(props: { return (
{story.activity} @@ -370,8 +378,11 @@ type FlowArgs = { working: boolean stopping: boolean failure: boolean + sending: boolean label: string suggestions: "command" | "context" | "none" + alternate: "none" | "queue" | "steer" + many: boolean } export default { @@ -379,8 +390,20 @@ export default { component: Composer, parameters: { layout: "centered" }, // States that only change the composer's props share this render, so moving between them keeps one composer. - args: { working: false, stopping: false, failure: false, label: "Ready", suggestions: "none" }, - argTypes: { suggestions: { control: "select", options: ["none", "command", "context"] } }, + args: { + working: false, + stopping: false, + failure: false, + sending: false, + label: "Ready", + suggestions: "none", + alternate: "none", + many: false, + }, + argTypes: { + suggestions: { control: "select", options: ["none", "command", "context"] }, + alternate: { control: "select", options: ["none", "queue", "steer"] }, + }, render: (args: FlowArgs) => , } @@ -388,9 +411,9 @@ export const EmptyDraft = {} export const PromptHistory = { args: { many: false }, - render: (args: { many: boolean }) => ( + render: (args: FlowArgs) => (
- +
), } @@ -400,8 +423,9 @@ export const TextDraft = { args: { prompt: text("Explain this change") } } export const MultilineDraft = { args: { prompt: text("Review the implementation\nThen run the focused tests") } } export const MixedAttachments = { - render: () => ( + render: (args: FlowArgs) => ( ( + render: (args: FlowArgs) => ( } +export const SlowFileSearch = { render: (args: FlowArgs) => } -function ConstrainedCommandSuggestionsStory() { +function ConstrainedCommandSuggestionsStory(props: FlowArgs) { let boundary: HTMLDivElement | undefined return (
- boundary} /> + boundary} />
) } -export const ConstrainedCommandSuggestions = { render: () => } +export const ConstrainedCommandSuggestions = { + args: { suggestions: "command" }, + render: (args: FlowArgs) => , +} export const DetachedCommandSuggestionBoundary = { - render: () => { + args: { suggestions: "command" }, + render: (args: FlowArgs) => { const detached = document.createElement("div") - return detached} /> + return detached} /> }, } @@ -507,6 +536,8 @@ export const SteeringFollowUp = { args: { prompt: text("Use this correction at t export const FailedSubmissionRestoration = { args: { prompt: text("Preserve this draft on failure"), failure: true } } +export const Sending = { args: { prompt: text("Run the focused tests"), sending: true } } + export const NewSessionFirstPrompt = { args: { prompt: text("Create the Session and implement the change"), label: "New Session draft" }, } @@ -522,48 +553,45 @@ export const RightToLeft = { export const NarrowLayout = { parameters: { viewport: { defaultViewport: "mobile1" } }, - render: () => ( + args: { prompt: text("Verify the narrow Composer") }, + render: (args: FlowArgs) => (
- +
), } export const ToolbarOverflow = { - args: { alternate: "queue" }, - argTypes: { alternate: { control: "select", options: ["none", "queue", "steer"] } }, - render: (args: { alternate: "none" | "queue" | "steer" }) => ( + args: { alternate: "queue", working: true, prompt: text("Keep all controls reachable when the toolbar overflows") }, + render: (args: FlowArgs) => (
- +
), } export const DemoFirstClassSkillIDs = { name: "Demo: First-class skill IDs", - render: () => ( + args: { suggestions: "context", label: "Select a skill from the context menu" }, + render: (args: FlowArgs) => ( - + ), } export const DemoStructuredCustomCommand = { name: "Demo: Structured custom command", - render: () => ( + render: (args: FlowArgs) => ( , + args: { label: "Composer is ready", prompt: text("Continue with the resolved Session selection") }, + render: (args: FlowArgs) => , } export const DemoContinueOnStop = { name: "Demo: Continue on Stop", - render: () => ( + args: { working: true, stopping: true, label: "Session execution is running" }, + render: (args: FlowArgs) => ( - + ), } @@ -695,7 +725,7 @@ function ServerStatusDemo() { ) } -function SelectionPrecedenceDemo() { +function SelectionPrecedenceDemo(props: FlowArgs) { const [store, setStore] = createStore({ durable: true }) const selection = createMemo(() => @@ -728,7 +758,7 @@ function SelectionPrecedenceDemo() { > {store.durable ? "Remove durable Session state" : "Restore durable Session state"} - +
) diff --git a/packages/app/src/home/home.standalone.stories.tsx b/packages/app/src/home/home.standalone.stories.tsx new file mode 100644 index 000000000000..a39b8ab969dd --- /dev/null +++ b/packages/app/src/home/home.standalone.stories.tsx @@ -0,0 +1,260 @@ +import type { SessionInfo } from "@opencode/client/promise" +import { createEffect, createMemo, on, onCleanup, Show } from "solid-js" +import { createStore } from "solid-js/store" +import { DialogStoryRuntime, STORY_PROJECTS, STORY_SERVER } from "@/components-lab/dialog-story-runtime" +import { normalizeProjectInfo } from "@/runtime/server/global-sync/utils" +import { useServer } from "@/runtime/server/current" +import { useLanguage } from "@/runtime/i18n/language" +import { SettingsSurfaceProvider } from "@/settings/surface" +import type { HomeController } from "./model" +import { createHomeProjectsController } from "./projects/controller" +import { HomeView } from "./route" +import { groupSessions, type HomeSessionsController } from "./sessions/controller" +import type { HomeSessionsListView } from "./sessions/load-machine" +import { buildHomeSessionRecords, homeSessionLocation } from "./sessions/records" +import { createHomeSessionSearchController } from "./sessions/search" + +const scenarios = ["populated", "loading", "empty", "offline"] as const + +type HomeArgs = { scenario: (typeof scenarios)[number]; project: string; search: string } + +const projects = STORY_PROJECTS.map(normalizeProjectInfo) + +function recentSessions(): SessionInfo[] { + const titles = [ + [0, 0, "Review the session location picker"], + [1, 0, "Document the worktree setup steps"], + [2, 0, "Update the release notes page"], + [0, 1, "Keep search focused when switching projects"], + [1, 1, "Review the provider setup guide"], + [2, 4, "Polish mobile navigation"], + ] as const + + return titles.map(([index, daysAgo, title], i) => { + const project = projects[index] + + const day = new Date() + day.setDate(day.getDate() - daysAgo) + day.setHours(10, 30 - i, 0, 0) + + return { + id: `ses_home_${i}`, + projectID: project.id, + title, + location: { directory: project.worktree }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: +day, updated: +day }, + } + }) +} + +function HomeStory(props: HomeArgs) { + const server = useServer() + + const language = useLanguage() + + const [state, setState] = createStore<{ + directory?: string + scenario: HomeArgs["scenario"] + activity: string + visible: typeof projects + sessions: SessionInfo[] + }>({ + scenario: props.scenario, + activity: "", + visible: projects, + sessions: recentSessions(), + }) + + const visible = () => state.visible + + const directory = () => state.directory + + const setDirectory = (value?: string) => setState("directory", value) + + const setActivity = (value: string) => setState("activity", value) + + const selected = createMemo(() => visible().find((project) => project.worktree === directory())) + + createEffect( + on( + () => props.scenario, + (next) => { + setState({ scenario: next, visible: projects, sessions: recentSessions(), activity: "" }) + }, + ), + ) + createEffect( + on( + () => props.project, + (name) => setDirectory(projects.find((item) => item.name === name)?.worktree), + ), + ) + + const home: HomeController = { + selection: { + value: () => ({ server: server.key, directory: directory() }), + focusServer: () => setDirectory(undefined), + }, + server: { + list: () => [STORY_SERVER], + focused: () => STORY_SERVER, + health: () => (state.scenario === "offline" ? { type: "unreachable" } : { type: "healthy" }), + label: () => "This computer", + context: () => server.ctx, + focusedContext: () => server.ctx, + focusedSync: () => server.ctx.sync, + }, + project: { + list: visible, + forServer: visible, + selected, + newSession: () => selected() ?? visible()[0], + select: (_, next) => setDirectory(directory() === next ? undefined : next), + add: (_, directories) => { + const added = projects.filter((item) => directories.includes(item.worktree)) + setState("visible", (items) => [ + ...items, + ...added.filter((project) => !items.some((item) => item.id === project.id)), + ]) + setDirectory(added[0]?.worktree) + }, + openNewSession: () => setActivity(`New session in ${selected()?.name ?? visible()[0]?.name}`), + openProjectNewSession: (_, path) => setActivity(`New session in ${path}`), + openProjectSession: (_, _path, session) => setActivity(`Opened ${session.title}`), + }, + } + + const navigation = createHomeProjectsController(home) + + const records = createMemo(() => + buildHomeSessionRecords({ + sessions: () => (state.scenario === "populated" ? state.sessions : []), + projectDirectories: () => { + const project = selected() + + return project && [project.worktree, ...project.sandboxes] + }, + projects: visible, + }), + ) + + const listView = (): HomeSessionsListView => { + if (state.scenario === "offline") return { status: "unavailable", reason: "offline" } + + if (state.scenario === "loading") return { status: "loading", skeleton: true } + + return { status: "ready", revealing: false } + } + + const recent: HomeSessionsController = { + copy: { language }, + platform: { desktop: true }, + tab: { isOpen: () => false }, + location: { value: (record) => homeSessionLocation(record.session.location.directory, "main"), sync() {} }, + data: { + listView, + records, + groups: createMemo(() => groupSessions(records(), language)), + searchRecords: records, + loading: () => state.scenario === "loading", + retry: () => setState("scenario", "populated"), + }, + session: { + server: () => server.key, + canCreate: () => visible().length > 0 && state.scenario !== "offline", + showProjectName: () => !selected(), + lookup: async (id) => records().find((record) => record.session.id === id), + create: home.project.openNewSession, + open: (session) => setActivity(`Opened ${session.title}`), + archive: async () => {}, + rename: async (_, session, title) => { + setState("sessions", (item) => item.id === session.id, "title", title) + + return true + }, + export: (_, session) => setActivity(`Export ${session.title}`), + exporting: () => false, + showDelete: async (_, session) => setActivity(`Delete ${session.title}`), + }, + } + + const search = createHomeSessionSearchController(home, recent) + + createEffect( + on( + () => props.search, + (value) => { + search.query.close() + + if (!value || value === "none") return + + // The inspector selects a preset on pointerdown. Let Home finish handling that outside press before opening search. + const frame = requestAnimationFrame(() => { + search.query.input(value) + search.query.focus() + }) + + onCleanup(() => cancelAnimationFrame(frame)) + }, + ), + ) + + return ( +
+ setActivity("Opened settings"), help: () => setActivity("Opened help") }, + project: { + ...navigation.project, + openNewSession: home.project.openProjectNewSession, + edit: (_, project) => setActivity(`Edit ${project.name}`), + hide: (_, project) => { + setState("visible", (items) => items.filter((item) => item.worktree !== project.worktree)) + + if (directory() === project.worktree) setDirectory(undefined) + }, + }, + }} + sessions={recent} + search={search} + /> + + {state.activity} + +
+ ) +} + +export default { + title: "App/Home", + id: "app-home", + parameters: { layout: "fullscreen" }, + args: { scenario: "populated", project: "all", search: "none" }, + argTypes: { + scenario: { control: "select", options: scenarios }, + project: { control: "select", options: ["all", ...projects.map((project) => project.name)] }, + search: { control: "select", options: ["none", "review", "worktree", "billing"] }, + }, + render: (args: HomeArgs) => ( + + + + + + ), +} + +export const Populated = {} + +export const ProjectFilter = { args: { project: "docs" } } + +export const SessionSearch = { args: { search: "review" } } + +export const Loading = { args: { scenario: "loading" } } + +export const Empty = { args: { scenario: "empty" } } + +export const Offline = { args: { scenario: "offline" } } diff --git a/packages/app/src/home/route.tsx b/packages/app/src/home/route.tsx index 6626e90f8f77..de440b56f5e8 100644 --- a/packages/app/src/home/route.tsx +++ b/packages/app/src/home/route.tsx @@ -1,6 +1,7 @@ import { ScrollView } from "@opencode/ui/scroll-view" import { createMediaQuery } from "@solid-primitives/media" -import { Show } from "solid-js" +import { onMount, Show } from "solid-js" +import { useLayout } from "@/shell/state/layout" import { createHomeController } from "./model" import { createHomeProjectsController } from "./projects/controller" import { HomeUtilityNav } from "./projects/view" @@ -11,12 +12,27 @@ import { createHomeSessionsController } from "./sessions/controller" import { HomeSessions } from "./sessions/region" export function Home() { - const mobile = createMediaQuery("(max-width: 767px)") + const layout = useLayout() const home = createHomeController() const projects = createHomeProjectsController(home) const sessions = createHomeSessionsController(home) const search = createHomeSessionSearchController(home, sessions) - const scroll = createHomeScrollController(sessions.data.groups) + + onMount(() => { + if (layout.home.searchFocus.take()) search.query.focus() + }) + + return +} + +export function HomeView(props: { + projects: ReturnType + sessions: ReturnType + search: ReturnType +}) { + const mobile = createMediaQuery("(max-width: 767px)") + + const scroll = createHomeScrollController(props.sessions.data.groups) return (
- +
- + - +
diff --git a/packages/app/src/home/sessions/controller.tsx b/packages/app/src/home/sessions/controller.tsx index fffbb8039416..58dfeb214c53 100644 --- a/packages/app/src/home/sessions/controller.tsx +++ b/packages/app/src/home/sessions/controller.tsx @@ -658,7 +658,10 @@ function localDay(date: Date) { return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate() } -function groupSessions(records: HomeSessionRecord[], language: ReturnType): HomeSessionGroup[] { +export function groupSessions( + records: HomeSessionRecord[], + language: ReturnType, +): HomeSessionGroup[] { const now = new Date() const today = localDay(now) const yesterday = localDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)) diff --git a/packages/app/src/home/sessions/delete-dialog.stories.tsx b/packages/app/src/home/sessions/delete-dialog.stories.tsx index ae2718e85fb9..fd05ff5f2fd7 100644 --- a/packages/app/src/home/sessions/delete-dialog.stories.tsx +++ b/packages/app/src/home/sessions/delete-dialog.stories.tsx @@ -6,7 +6,9 @@ import { createStore } from "solid-js/store" import { useLanguage } from "@/runtime/i18n/language" import { sessionTitle } from "@/session/title" -function DeleteSessionStory(props: { sessionTitle?: string }) { +type Args = { sessionTitle: string; deleting: boolean } + +function DeleteSessionStory(props: Args) { const dialog = useDialog() const language = useLanguage() @@ -20,16 +22,17 @@ function DeleteSessionStory(props: { sessionTitle?: string }) { - - - - -
+ + {(code) => ( +
+
{language.t("provider.connect.console.deviceCode")}
+
+ + {(character) => ( + + )} + +
+
+ )} +

{language.t("provider.connect.console.copyFailed")}

+ + + + {language.t(props.code ? "provider.connect.console.waiting" : "provider.connect.console.openingBrowser")} + +
) } diff --git a/packages/app/src/providers/connect/controller.ts b/packages/app/src/providers/connect/controller.ts index 1381400b6522..fdeac8676108 100644 --- a/packages/app/src/providers/connect/controller.ts +++ b/packages/app/src/providers/connect/controller.ts @@ -24,6 +24,7 @@ import { selectProviderDialogView, transitionProviderDialog, type ProviderAccounts, + type ProviderBackTarget, type ProviderDialogEffect, type ProviderDialogEvent, } from "./dialog-machine" @@ -638,7 +639,7 @@ export function createProviderDialogController(options: { dispatch({ type: "provider.selected", provider: id, fromPicker: true, accounts: accountsOf(id) }), input: (event: ProviderConnectEvent) => dispatch({ type: "connect.input", event }), rename: accountActions.rename, - back: () => dispatch({ type: "back" }), + navigate: (target: ProviderBackTarget) => dispatch({ type: "navigate", target }), checkClaude: () => { const id = provider() diff --git a/packages/app/src/providers/connect/dialog-machine.test.ts b/packages/app/src/providers/connect/dialog-machine.test.ts index 997a5a3c5f70..4e152d80afb4 100644 --- a/packages/app/src/providers/connect/dialog-machine.test.ts +++ b/packages/app/src/providers/connect/dialog-machine.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test" import { createProviderDialogState, + providerBackTarget, selectProviderDialogView, transitionProviderDialog, type ProviderAccounts, @@ -56,6 +57,12 @@ const selected = (provider: string, fromPicker: boolean, list = none): ProviderD accounts: list, }) +// Clicks the nearest linked breadcrumb, the way the header goes back one step. +const goBack = (state: ProviderDialogState): ProviderDialogEvent => ({ + type: "navigate", + target: providerBackTarget(state) ?? "picker", +}) + function provider(state: ProviderDialogState) { if (state.status !== "provider") throw new Error(`expected a provider step, got ${state.status}`) @@ -180,7 +187,7 @@ test("Back from a pending OAuth sign-in to the provider list allows backdrop dis const waiting = waitingOAuth("github-copilot") expect(selectProviderDialogView(waiting.state).preventBackdropDismiss).toBe(true) - const back = replay([{ type: "back" }], waiting.state) + const back = replay([goBack(waiting.state)], waiting.state) expect(back.state.status).toBe("picker") expect(selectProviderDialogView(back.state).preventBackdropDismiss).toBe(false) @@ -197,11 +204,14 @@ test("Back from a Console connection without models returns to the sign-in metho }) expect(types(empty.effects)).toEqual(["connected.notify", "models.reveal", "toast.connected"]) - const methods = replay([{ type: "back" }], empty.state) + const methods = replay([goBack(empty.state)], empty.state) expect(selectProviderDialogView(methods.state).body).toEqual({ kind: "methods" }) - expect(selectProviderDialogView(methods.state).canBack).toBe(true) + expect(selectProviderDialogView(methods.state).crumbs).toEqual([ + { kind: "root", target: "picker" }, + { kind: "provider", target: undefined }, + ]) - expect(replay([{ type: "back" }], methods.state).state.status).toBe("picker") + expect(replay([goBack(methods.state)], methods.state).state.status).toBe("picker") }) test("Back from a failed Console refresh returns to the sign-in methods", () => { @@ -220,14 +230,17 @@ test("Back from a failed Console refresh returns to the sign-in methods", () => ) expect(selectProviderDialogView(failed.state).body).toEqual({ kind: "failed" }) - expect(selectProviderDialogView(failed.state).title).toBe("console-error") + expect(selectProviderDialogView(failed.state).crumbs).toEqual([ + { kind: "root", target: "picker" }, + { kind: "provider", target: "methods" }, + ]) - expect(selectProviderDialogView(replay([{ type: "back" }], failed.state).state).body).toEqual({ kind: "methods" }) + expect(selectProviderDialogView(replay([goBack(failed.state)], failed.state).state).body).toEqual({ kind: "methods" }) }) test("Back during the Console workspace wait stops the wait", () => { const refreshing = refreshingConsole() - const back = replay([{ type: "back" }], refreshing.state) + const back = replay([goBack(refreshing.state)], refreshing.state) expect(back.effects).toContainEqual({ type: "settle.cancel" }) expect(selectProviderDialogView(back.state).body).toEqual({ kind: "methods" }) @@ -239,9 +252,12 @@ test("Back from a Claude Agent check started from Add account returns to the acc const started = replay([{ type: "claude.check", replacing: ["cred_1"] }], setup.state) const start = connectEffect(started.effects, "start") - expect(selectProviderDialogView(started.state).canBack).toBe(true) + expect(selectProviderDialogView(started.state).crumbs).toEqual([ + { kind: "root", target: "picker" }, + { kind: "provider", target: "accounts" }, + ]) - const back = replay([{ type: "back" }], started.state) + const back = replay([goBack(started.state)], started.state) expect(selectProviderDialogView(back.state).frame).toBe("accounts") // The server still saves the connection, so its late result only reloads the catalogs. @@ -267,7 +283,7 @@ test("leaving a Claude Agent check ignores its late confirmation", () => { const session = provider(confirming.state).session expect(confirming.effects).toContainEqual({ type: "claude.confirm", session, check }) - const back = replay([{ type: "back" }], confirming.state) + const back = replay([goBack(confirming.state)], confirming.state) expect(back.state.status).toBe("picker") expect(back.effects).toContainEqual({ type: "claude.timer.stop" }) @@ -348,7 +364,7 @@ test("a second Remove click sends one request, and a late final removal after Ba expect(second.state).toBe(removing.state) expect(second.effects).toEqual([]) - const back = replay([{ type: "back" }], removing.state) + const back = replay([goBack(removing.state)], removing.state) const late = replay( [ @@ -389,7 +405,7 @@ test("removing the last account closes the dialog once the removal settles", () ) expect(settled.effects).toEqual([{ type: "dialog.close" }]) - expect(replay([{ type: "back" }], settled.state).state).toBe(settled.state) + expect(replay([goBack(settled.state)], settled.state).state).toBe(settled.state) }) test("a switch that settles after another switch started is ignored", () => { @@ -431,7 +447,7 @@ test("a credential saved after the dialog moved to another provider only reloads const submit = connectEffect(submitting.effects, "submit") const session = provider(submitting.state).session - const other = replay([{ type: "back" }, selected("anthropic", true)], submitting.state) + const other = replay([goBack(submitting.state), selected("anthropic", true)], submitting.state) const late = replay( [ @@ -526,7 +542,7 @@ test("a connection without models closes the dialog", () => { expect(types(done.effects)).toEqual(["connected.notify", "models.reveal", "toast.connected", "dialog.close"]) // The key form stays while the dialog animates out, and takes no more input. expect(selectProviderDialogView(done.state).body).toEqual({ kind: "key" }) - expect(replay([{ type: "back" }], done.state).state).toBe(done.state) + expect(replay([goBack(done.state)], done.state).state).toBe(done.state) }) test("confirming a model closes once and keeps the outcome through disposal", () => { @@ -598,15 +614,18 @@ test("a lone method waits on the accounts list and starts once Add account is ch expect(types(added.effects)).toEqual(["connect.start"]) // Back from the lone method goes straight to the accounts list. - expect(selectProviderDialogView(replay([{ type: "back" }], added.state).state).frame).toBe("accounts") + expect(selectProviderDialogView(replay([goBack(added.state)], added.state).state).frame).toBe("accounts") }) test("a standalone dialog has no way back to the provider list", () => { const opened = replay([selected("opencode-go", false)], createProviderDialogState({ standalone: true })) const entering = replay([loaded(opened.state, [key])], opened.state) - expect(selectProviderDialogView(entering.state).canBack).toBe(false) - expect(replay([{ type: "back" }], entering.state).state).toBe(entering.state) + expect(selectProviderDialogView(entering.state).crumbs).toEqual([ + { kind: "root", target: undefined }, + { kind: "provider", target: undefined }, + ]) + expect(replay([goBack(entering.state)], entering.state).state).toBe(entering.state) }) test("the Console sign-in link copy result belongs to its attempt", () => { diff --git a/packages/app/src/providers/connect/dialog-machine.ts b/packages/app/src/providers/connect/dialog-machine.ts index 8ee1773f11af..9c929cc3c6dd 100644 --- a/packages/app/src/providers/connect/dialog-machine.ts +++ b/packages/app/src/providers/connect/dialog-machine.ts @@ -146,7 +146,8 @@ export type ProviderDialogEvent = | { readonly type: "model.selected"; readonly modelKey: string } | { readonly type: "group.collapsed"; readonly providerID: string; readonly collapsed: boolean } | { readonly type: "model.confirmed"; readonly selection: ModelChoice } - | { readonly type: "back" } + /** A breadcrumb in the header: the provider list, or the provider's accounts or sign-in methods. */ + | { readonly type: "navigate"; readonly target: ProviderBackTarget } | { readonly type: "disposed" } export type ProviderDialogEffect = @@ -255,7 +256,11 @@ export function transitionProviderDialog( if (event.type === "provider.cleared") return toPicker(state) - if (event.type === "back") return back(state) + if (event.type === "navigate") { + if (event.target === "picker") return toPicker(state) + + return event.target === providerBackTarget(state) ? back(state) : unchanged(state) + } if (event.type === "accounts.synced") return synced(state, event.accounts) @@ -338,7 +343,10 @@ export function providerBackTarget(state: ProviderDialogState): ProviderBackTarg /** Which dialog shell the step uses: the searchable list, the model choice, or a provider step. */ export type ProviderDialogFrame = "picker" | "models" | "accounts" | "provider" -export type ProviderDialogTitle = "connect" | "console-error" | "console-sign-in" | "anthropic-max" +/** The header path of a provider step: the provider list, then the provider. A crumb with a `target` links back. */ +export type ProviderDialogCrumb = + | { readonly kind: "root"; readonly target?: "picker" } + | { readonly kind: "provider"; readonly target?: "accounts" | "methods" } export type ProviderDialogBody = | { readonly kind: "picker" } @@ -361,7 +369,6 @@ export function selectProviderDialogView(state: ProviderDialogState) { const connect = step && "connect" in step ? selectProviderConnectView(step.connect) : undefined const target = providerBackTarget(state) const body = selectBody(state, connect) - const isConsole = provider?.provider === CONSOLE_INTEGRATION const frame: ProviderDialogFrame = !step ? "picker" @@ -374,17 +381,7 @@ export function selectProviderDialogView(state: ProviderDialogState) { frame, connect, body, - canBack: target !== undefined, - title: ((): ProviderDialogTitle => { - if (isConsole && connect?.status === "failed") return "console-error" - - if (body.kind === "console-sign-in") return "console-sign-in" - - if (provider?.provider === "anthropic" && connect?.method?.label?.toLowerCase().includes("max")) - return "anthropic-max" - - return "connect" - })(), + crumbs: crumbs(state, target), // Closing on a stray backdrop click would abandon a sign-in the user is finishing in the browser. preventBackdropDismiss: !!provider && !provider.closed && !!connect?.authorizing, completed: state.completed, @@ -394,6 +391,15 @@ export function selectProviderDialogView(state: ProviderDialogState) { export type ProviderDialogView = ReturnType +function crumbs(state: ProviderDialogState, target: ProviderBackTarget | undefined): readonly ProviderDialogCrumb[] { + if (state.status !== "provider" || state.step.kind === "models") return [] + + return [ + { kind: "root", target: state.standalone ? undefined : "picker" }, + { kind: "provider", target: target === "picker" ? undefined : target }, + ] +} + function selectBody( state: ProviderDialogState, connect: ReturnType | undefined, diff --git a/packages/app/src/providers/connect/dialog.standalone.stories.tsx b/packages/app/src/providers/connect/dialog.standalone.stories.tsx index d6467de964b8..211ae47ed8d6 100644 --- a/packages/app/src/providers/connect/dialog.standalone.stories.tsx +++ b/packages/app/src/providers/connect/dialog.standalone.stories.tsx @@ -1,7 +1,9 @@ import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" import { onMount } from "solid-js" -import { DialogStoryRuntime, STORY_DIRECTORY } from "@/components-lab/dialog-story-runtime" +import type { IntegrationInfo } from "@opencode/client/promise" +import type { ServerConnection } from "@/runtime/server/registry" +import { DialogStoryRuntime, STORY_DIRECTORY, STORY_LOCKED_SERVER } from "@/components-lab/dialog-story-runtime" import { DialogConnectProvider, useProviderConnectController } from "./dialog" function ConnectProviderDialogStory() { @@ -37,14 +39,42 @@ function ProviderConnectionDialogStory(props: { provider: string }) { ) } -function renderConnection(provider: string) { - return () => ( - - - - ) +function renderConnection( + provider: string, + options: { integrations?: IntegrationInfo[]; servers?: ServerConnection.Any[] } = {}, +) { + return () => { + return ( + + + + ) + } } +const REMOTE_SERVER: ServerConnection.Http = { + type: "http", + displayName: "Dev box", + http: { url: "http://devbox.local:4096" }, +} + +const claudeWithProblem = (message: string): IntegrationInfo[] => [ + { + id: "claude-agent", + name: "Claude Agent", + methods: [{ type: "external", id: "claude-login", label: "Claude Code login (claude auth login)" }], + connections: [ + { + type: "credential", + id: "cred_claude", + label: "Claude Code", + method: "external", + status: { status: "needs_auth", message, url: "https://code.claude.com/docs/en/setup" }, + }, + ], + }, +] + export default { title: "App/Dialogs/Connect Provider", id: "app-dialog-connect-provider", @@ -62,6 +92,21 @@ export const ChooseMethod = { render: renderConnection("opencode"), } +/** OpenCode Console through a remote server: pick "API key (service account)" to see the note on a form. */ +export const ConsoleRemote = { render: renderConnection("opencode", { servers: [REMOTE_SERVER] }) } + +// Console with only its browser sign-in, so the story starts on the device code. +const consoleAccountOnly: IntegrationInfo[] = [ + { + id: "opencode", + name: "OpenCode Console", + methods: [{ type: "oauth", id: "console", label: "OpenCode Console account" }], + connections: [], + }, +] + +export const ConsoleSignIn = { render: renderConnection("opencode", { integrations: consoleAccountOnly }) } + export const ApiKey = { render: renderConnection("openrouter"), } @@ -69,3 +114,74 @@ export const ApiKey = { export const LoginMethods = { render: renderConnection("openai"), } + +export const ClaudeAgentSetup = { render: renderConnection("claude-agent") } + +export const ClaudeAgentNotInstalled = { + render: renderConnection("claude-agent", { + integrations: claudeWithProblem("Claude Code is not installed. Install it, then run `claude auth login`."), + }), +} + +export const ClaudeAgentNotSignedIn = { + render: renderConnection("claude-agent", { + integrations: claudeWithProblem("Claude Code is not logged in. Run `claude auth login` in a terminal."), + }), +} + +/** A device sign-in with a confirmation code. */ +export const AwaitingBrowser = { render: renderConnection("github-copilot") } + +/** A choice between a device sign-in and an API key. */ +export const DeviceOrApiKey = { render: renderConnection("xai") } + +// OpenAI with only its ChatGPT method, so the story opens straight on the sign-in. +const chatgptOnly: IntegrationInfo[] = [ + { + id: "openai", + name: "OpenAI", + methods: [{ type: "oauth", id: "chatgpt", label: "ChatGPT Plus / Pro" }], + connections: [], + }, +] + +/** A browser sign-in that also takes a pasted redirect URL. */ +export const RedirectPaste = { render: renderConnection("openai", { integrations: chatgptOnly }) } + +/** The same sign-in through a remote server, where the paste field starts open. */ +export const RedirectPasteRemote = { + render: renderConnection("openai", { integrations: chatgptOnly, servers: [REMOTE_SERVER] }), +} + +/** A text question before the sign-in, then a browser sign-in with redirect paste. */ +export const TextQuestion = { render: renderConnection("gitlab") } + +/** A required text question. Continue with an empty field to see the error. */ +export const RequiredTextQuestion = { render: renderConnection("snowflake-cortex") } + +/** Pick "AWS profile": a choice question with a custom answer, for an external credential. */ +export const ChoiceQuestion = { render: renderConnection("amazon-bedrock") } + +/** A multiselect question with a custom item, then a yes/no question, then the API key. */ +export const MultiselectQuestion = { render: renderConnection("acme-search") } + +/** A link the user opens and confirms before the sign-in. */ +export const ExternalLinkQuestion = { render: renderConnection("acme-cloud") } + +/** A sign-in that runs a command and shows its output. */ +export const Command = { render: renderConnection("acme-cli") } + +/** A sign-in that asks for the authorization code the browser shows. */ +export const PasteCode = { render: renderConnection("acme-code") } + +/** A sign-in the server fails to start. */ +export const Failed = { render: renderConnection("acme-broken") } + +// The fixture refuses requests to this server. Submitting a sample service key shows the real error and retry. +export const LockedRemoteServer = { + render: () => ( + + + + ), +} diff --git a/packages/app/src/providers/connect/dialog.tsx b/packages/app/src/providers/connect/dialog.tsx index 732aef8625de..052ed41c51c9 100644 --- a/packages/app/src/providers/connect/dialog.tsx +++ b/packages/app/src/providers/connect/dialog.tsx @@ -5,10 +5,11 @@ import { Icon } from "@opencode/ui/icon" import { RadioGroup, RadioItem } from "@opencode/ui/radio" import { Checkbox } from "@opencode/ui/checkbox" import { Loader } from "@opencode/ui/loader" -import { TextField } from "@opencode/ui/text-field" +import { Field } from "@opencode/ui/field" import { DialogBody, DialogHeader, DialogTitle, DialogTitleGroup, Dialog } from "@opencode/ui/dialog" import { RedirectPasteForm } from "@opencode/ui/redirect-paste" import { TextInput } from "@opencode/ui/text-input" +import { Tooltip } from "@opencode/ui/tooltip" import { type Component, createMemo, createUniqueId, For, type JSX, Match, onMount, Show, Switch } from "solid-js" import { createStore } from "solid-js/store" import { useParams } from "@solidjs/router" @@ -31,12 +32,15 @@ import { CONSOLE_INTEGRATION, type ProviderDialogBody, type ProviderDialogFrame import { connectMethods, selectProviderConnectView, type ProviderConnectMethod } from "./machine" import type { ProviderFormInput, ProviderFormView } from "./form-machine" import { ConsoleAuthorization } from "./console" +import { StepActions, WaitingButton } from "./step-actions" import { DialogChatGPTPlanWelcome } from "./chatgpt-welcome" -import { authServerName, RemoteAuthNotice } from "./remote" +import { authServerName } from "./remote" import { providerAccounts } from "@/settings/providers/accounts" import { AccountNameInput } from "@/settings/providers/account-name" import { IconButton } from "@opencode/ui/icon-button" import { Menu } from "@opencode/ui/menu" +import { writeClipboard } from "@opencode/session-ui/copy" +import { showToast } from "@/shell/notifications/toast" import "@/shell/search-list.css" import "./models.css" @@ -103,23 +107,12 @@ export const DialogConnectProvider: Component<{ let focusHost: HTMLDivElement | undefined const holdFocus = () => focusHost?.focus({ preventScroll: true }) - const title = () => { - const name = controller.providerName() - const kind = view().title + const providerName = () => + consoleSelected() ? language.t("provider.connect.opencode.name") : controller.providerName() - if (kind === "console-error") return language.t("provider.connect.opencode.errorTitle") - - if (kind === "console-sign-in") - return language.t( - view().provider === "opencode-go" ? "provider.connect.console.titleGo" : "provider.connect.console.title", - ) - - if (kind === "anthropic-max") return language.t("provider.connect.title.anthropicProMax") - - return language.t("provider.connect.title", { - provider: consoleSelected() ? language.t("provider.connect.opencode.name") : name, - }) - } + // A Console sign-in through another server is stored on that server, so the header names it. + const sdk = useServerSDK() + const remoteServer = () => (consoleSelected() && frame() !== "picker" ? authServerName(sdk.server) : undefined) return ( @@ -161,40 +157,87 @@ export const DialogConnectProvider: Component<{
)} - -
- - - - - {controller.providerName()} -
-
{(provider) => ( -
- - - - - {title()} -
+ <> + + {/* The breadcrumb shows where the dialog is; the dialog itself is named for what it does. */} +
+ {language.t("provider.connect.title", { provider: providerName() })} +
+ )}
@@ -204,17 +247,31 @@ export const DialogConnectProvider: Component<{ /> + + {(server) => ( + + + {language.t("provider.connect.remote.label", { server: server() })} + + )} + {/* Outside the scrolling content, so it can reach across the body's padding without scrolling sideways. */} -
+
, value: ProviderConnectMethod) => + value.type === "key" ? (value.label ?? language.t("provider.connect.method.apiKey")) : value.label + +const METHOD_ICON = { + oauth: "window-cursor", + key: "keyboard", + command: "terminal", + external: "server", +} as const satisfies Record + // The TUI's integration groups and order, with connected integrations pulled up into their own group first. const POPULAR: readonly string[] = connectPopular @@ -320,11 +390,11 @@ function ProviderPicker(props: { directory?: string; onSelect: (provider: string return (
- )} @@ -573,7 +674,7 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont const options = () => optionRows(step().field) return ( -
+
send({ type: "custom.text.changed", value: event.currentTarget.value })} /> - @@ -619,21 +721,22 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont {(message) =>
{message()}
}
- + + +
) }} {(step) => ( -
+
- queueMicrotask(() => input.focus())} - type="text" - label={language.t("ui.messagePart.option.typeOwnAnswer")} - hideLabel + class="!w-full" + appearance="large" + aria-label={language.t("ui.messagePart.option.typeOwnAnswer")} placeholder={step().placeholder ?? language.t("ui.question.custom.placeholder")} value={step().customText} - onChange={(value) => send({ type: "custom.text.changed", value })} + onInput={(event) => send({ type: "custom.text.changed", value: event.currentTarget.value })} />
-
+ + + + + - - - -
+
)} @@ -687,35 +790,41 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont event.preventDefault() send({ type: "step.submitted" }) }} - class="flex w-full flex-col items-start gap-4" + class="flex w-full flex-col items-start gap-5" > - queueMicrotask(() => input.focus({ preventScroll: true }))} - class="!w-full" - type="text" - inputMode={step().numeric ? "decimal" : undefined} - aria-label={step().title} - placeholder={step().placeholder} - value={step().text} - invalid={step().error !== undefined} - autocomplete="off" - spellcheck={false} - onInput={(event) => send({ type: "text.changed", value: event.currentTarget.value })} - /> - + + {step().title} + + {(description) => ( + + {description()} + + )} + + queueMicrotask(() => input.focus({ preventScroll: true }))} + class="!w-full" + appearance="large" + type="text" + inputMode={step().numeric ? "decimal" : undefined} + placeholder={step().placeholder} + value={step().text} + invalid={step().error !== undefined} + autocomplete="off" + spellcheck={false} + onInput={(event) => send({ type: "text.changed", value: event.currentTarget.value })} + /> + + + + + )} - - {(message) => ( - - )} -
) @@ -724,15 +833,26 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont function MethodSelection() { return (
+

+ {language.t("provider.connect.methods.description", { provider: name() })} +

{(item, index) => ( )} @@ -742,7 +862,7 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont function CommandView() { return ( -
+
{(output) => (
           )}
         
-        {language.t("provider.connect.command.waiting")}
+        
+          {language.t("provider.connect.command.waiting")}
+        
       
) } @@ -767,20 +889,26 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont ) } + function ErrorLine(input: { children: JSX.Element }) { + return ( +
+ + {input.children} +
+ ) + } + function ErrorRow() { return ( -
-
- - - {isConsole - ? connect().error - : language.t("provider.connect.status.failed", { error: connect().error ?? "" })} - -
- +
+ + {isConsole ? connect().error : language.t("provider.connect.status.failed", { error: connect().error ?? "" })} + + + +
) } @@ -805,155 +933,187 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont props.controller.input({ type: "entry.submitted", value: value instanceof File || value === null ? "" : value }) } + function EntryField(input: { + name: string + label: string + placeholder: string + ref: (el: HTMLInputElement) => void + }) { + const errorID = createUniqueId() + + return ( +
+ + + {(error) => ( + + )} + +
+ ) + } + function ApiAuthView() { let apiKey: HTMLInputElement | undefined - const errorID = createUniqueId() onMount(() => { apiKey?.focus({ preventScroll: true }) }) return ( -
+
submitEntry(event, "apiKey")} class={STEP_CLASS}>

{isConsole ? language.t("provider.connect.console.serviceKeyDescription") : language.t("provider.connect.apiKey.description", { provider: name() })}

- submitEntry(event, "apiKey")} class="flex flex-col items-start gap-5 self-stretch"> - - - {(error) => ( - - )} - + (apiKey = el)} + /> + - -
+ + ) } function OAuthCodeView() { let codeInput: HTMLInputElement | undefined - const errorID = createUniqueId() onMount(() => { codeInput?.focus({ preventScroll: true }) }) return ( -
-
{language.t("provider.connect.oauth.code.description", { provider: name() })}
- -
submitEntry(event, "code")} class="flex flex-col items-start gap-5 self-stretch"> - - - {(error) => ( - - )} - - + -
-
+ + ) } function OAuthAutoView() { + const pasteOpen = () => connect().paste?.open ?? onRemote + // Stays up while the URL is being sent; once the server takes it, the sign-in is back to waiting. + const pasteSendable = () => !connect().paste?.locked || connect().paste?.submitting + return ( -
-
- {language.t( - connect().paste - ? "provider.connect.oauth.auto.paste.description" - : "provider.connect.oauth.auto.description", - { provider: name() }, - )} -
- {language.t("provider.connect.status.waiting")} -
- -
+
+

{language.t("provider.connect.oauth.auto.description", { provider: name() })}

{(value) => ( - + )} + + {language.t("provider.connect.oauth.browserFailed")} + {(paste) => ( - props.controller.input({ type: "paste.changed", value })} - onSubmit={() => props.controller.input({ type: "paste.submitted" })} - /> +
+ + +
+

{language.t("provider.connect.oauth.paste.description")}

+ props.controller.input({ type: "paste.changed", value })} + onSubmit={() => props.controller.input({ type: "paste.submitted" })} + /> +
+
+
)}
+ + + {language.t("provider.connect.status.waiting")}} + > + + +
) } @@ -979,7 +1139,7 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont +
{language.t("dialog.provider.accounts.removeConfirm", { account: account.label })} @@ -1000,11 +1160,11 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont
} > -
+
+
props.controller.chooseAccount(account)} > @@ -1087,7 +1247,7 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont -
+
) } @@ -1193,7 +1354,7 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont } return ( -
+

{language.t("provider.connect.models.description")}

@@ -1265,7 +1426,7 @@ function ProviderSteps(props: { provider: string; controller: ProviderDialogCont
+ ) +} diff --git a/packages/app/src/providers/models/manage.standalone.stories.tsx b/packages/app/src/providers/models/manage.standalone.stories.tsx index b0f1f5f59297..927f510d0f6f 100644 --- a/packages/app/src/providers/models/manage.standalone.stories.tsx +++ b/packages/app/src/providers/models/manage.standalone.stories.tsx @@ -1,13 +1,36 @@ import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" -import { onMount } from "solid-js" +import { createEffect, on, onMount } from "solid-js" import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" import { DialogManageModels } from "./manage" -function ManageModelsStory() { +function ManageModelsStory(props: { query: string }) { const dialog = useDialog() - const open = () => void dialog.show(() => ) + // The dialog owns its filter. Send inspector edits through the same field as keyboard input. + const open = () => + void dialog.show(() => { + let host!: HTMLDivElement + + createEffect( + on( + () => props.query, + (query) => { + const field = host.querySelector('input[type="search"]') + + if (!field || field.value === query) return + field.value = query + field.dispatchEvent(new InputEvent("input", { bubbles: true })) + }, + ), + ) + + return ( +
+ +
+ ) + }) onMount(open) @@ -21,12 +44,16 @@ function ManageModelsStory() { export default { title: "App/Dialogs/Manage Models", id: "app-dialog-manage-models", -} - -export const Default = { - render: () => ( + args: { query: "" }, + render: (args: { query: string }) => ( - + ), } + +export const Default = {} + +export const ProviderSearch = { args: { query: "anthropic" } } + +export const NoMatches = { args: { query: "missing-model-xyz" } } diff --git a/packages/app/src/providers/models/select-dialog.standalone.stories.tsx b/packages/app/src/providers/models/select-dialog.standalone.stories.tsx index 1e822b4cba19..c525a3bda67b 100644 --- a/packages/app/src/providers/models/select-dialog.standalone.stories.tsx +++ b/packages/app/src/providers/models/select-dialog.standalone.stories.tsx @@ -101,11 +101,11 @@ const models: StoryModel[] = [ const keyOf = (model: StoryModel) => `${model.provider.id}:${model.id}` -function SelectorStory(props: { favorite?: boolean }) { +function SelectorStory(props: { favorite?: boolean; provider?: string; empty?: boolean }) { const dialog = useDialog() const [store, setStore] = createStore<{ current: string; favorite: string[]; variant?: string }>({ - current: "opencode:claude-opus-5-5", + current: props.empty ? "" : "opencode:claude-opus-5-5", favorite: props.favorite ? ["anthropic:claude-sonnet-5"] : [], }) @@ -128,7 +128,7 @@ function SelectorStory(props: { favorite?: boolean }) { setStore("favorite", (ids) => (ids.includes(id) ? ids.filter((entry) => entry !== id) : [id, ...ids])) }, }, - list: () => models, + list: () => (props.empty ? [] : models), cycle() {}, set: (key: { providerID: string; modelID: string } | undefined) => { if (key) setStore("current", `${key.providerID}:${key.modelID}`) @@ -144,14 +144,14 @@ function SelectorStory(props: { favorite?: boolean }) { }, } satisfies ModelSelection - const open = () => void dialog.show(() => ) + const open = () => void dialog.show(() => ) onMount(open) return (
) @@ -177,3 +177,19 @@ export const Favorites = { ), } + +export const ProviderOnly = { + render: () => ( + + + + ), +} + +export const NoModels = { + render: () => ( + + + + ), +} diff --git a/packages/app/src/providers/models/unpaid.standalone.stories.tsx b/packages/app/src/providers/models/unpaid.standalone.stories.tsx index e37304c26db0..f0d9444739c8 100644 --- a/packages/app/src/providers/models/unpaid.standalone.stories.tsx +++ b/packages/app/src/providers/models/unpaid.standalone.stories.tsx @@ -1,9 +1,10 @@ -// @ts-nocheck import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" -import { createSignal, onMount } from "solid-js" -import { DialogSelectModelUnpaid } from "./unpaid" +import { createMemo, createSignal, onMount } from "solid-js" import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" +import { isFreeModel } from "./models" +import { useLocal, type ModelSelection } from "@/providers/models/selection" +import { DialogSelectModelUnpaid } from "./unpaid" const names = [ "MiMo V2.5 Free", @@ -14,30 +15,38 @@ const names = [ "Big Pickle", ] -function SelectModelWithoutProviders(props) { +function SelectModelWithoutProviders(props: { count: number }) { const dialog = useDialog() - const models = names.map((name, index) => ({ - id: name.toLowerCase().replaceAll(" ", "-"), - name, - provider: { id: "opencode", name: "OpenCode" }, - cost: { input: 0, output: 0 }, - limit: { context: 128_000 }, - capabilities: { - reasoning: index !== 5, - input: { text: true, image: false, audio: false, video: false, pdf: false }, - }, - })) + const local = useLocal() + + const models = createMemo(() => { + const free = local.model.list().find(isFreeModel) + + if (!free) return [] + + return names.slice(0, props.count).map((name, index) => ({ + ...free, + id: name.toLowerCase().replaceAll(" ", "-"), + name, + provider: { ...free.provider, name: "OpenCode" }, + limit: { ...free.limit, context: 128_000 }, + capabilities: { + ...free.capabilities, + reasoning: index !== 5, + input: { text: true, image: false, audio: false, video: false, pdf: false }, + }, + })) + }) - const [current, setCurrent] = createSignal(models[2]) + const [selected, setSelected] = createSignal("deepseek-v4-flash-free") const model = { - list: () => models.slice(0, props.count), - current, - set(value) { - setCurrent(models.find((item) => item.id === value?.modelID)) - }, - } + ...local.model, + list: models, + current: () => models().find((item) => item.id === selected()), + set: (key) => setSelected(key?.modelID), + } satisfies ModelSelection const open = () => dialog.show(() => ) @@ -54,13 +63,14 @@ export default { title: "App/Dialogs/Select Model", id: "app-dialog-select-model", args: { count: names.length }, - argTypes: { count: { control: { type: "range", min: 1, max: names.length, step: 1 } } }, -} - -export const WithoutProviders = { - render: (args) => ( + argTypes: { count: { control: { type: "range", min: 0, max: names.length, step: 1 } } }, + render: (args: { count: number }) => ( ), } + +export const WithoutProviders = {} + +export const NoFreeModels = { args: { count: 0 } } diff --git a/packages/app/src/runtime/i18n/am.ts b/packages/app/src/runtime/i18n/am.ts index ba27f69ae91b..5a4ee37f668a 100644 --- a/packages/app/src/runtime/i18n/am.ts +++ b/packages/app/src/runtime/i18n/am.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "{{provider}} አገናኝ", "provider.connect.method.apiKey": "API ቁልፍ", "provider.connect.status.inProgress": "ፍቃድ በሂደት ላይ…", - "provider.connect.status.waiting": "ፈቀዳን በመጠበቅ ላይ…", + "provider.connect.status.waiting": "ፈቀዳን በመጠበቅ ላይ", "provider.connect.status.failed": "ፍቃድ መስጠት አልተሳካም፡ {{error}}", "provider.connect.apiKey.description": "መለያዎን ለማገናኘት የ{{provider}} API ቁልፍዎን ያስገቡ እና {{provider}} ሞዴሎችን በOpenCode ይጠቀሙ።", @@ -796,7 +796,6 @@ export const dict = { "workspace.delete.location": "አካባቢ", "command.session.location.cycle": "የክፍለ ጊዜውን መገኛ ቀይር", "dialog.provider.anthropic.note": "የAPI ቁልፍ በመጠቀም ወደ Claude ሞዴሎች ቀጥተኛ መዳረሻ", - "provider.connect.title.anthropicProMax": "በAnthropic ግባ", "prompt.toast.uploading.cancelFile": "የ{{filename}} ስቀላን ሰርዝ", "prompt.toast.uploadFailed.title": "ስቀላው አልተሳካም", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/ar.ts b/packages/app/src/runtime/i18n/ar.ts index b611a3b1ee7b..192db0fcbe3f 100644 --- a/packages/app/src/runtime/i18n/ar.ts +++ b/packages/app/src/runtime/i18n/ar.ts @@ -153,7 +153,7 @@ export const dict = { "provider.connect.title": "الاتصال بـ {{provider}}", "provider.connect.method.apiKey": "مفتاح API", "provider.connect.status.inProgress": "جارٍ التفويض…", - "provider.connect.status.waiting": "في انتظار التفويض…", + "provider.connect.status.waiting": "في انتظار التفويض", "provider.connect.status.failed": "فشل التفويض: {{error}}", "provider.connect.apiKey.description": "أدخل مفتاح API الخاص بـ {{provider}} لتوصيل حسابك واستخدام نماذج {{provider}} في OpenCode.", @@ -874,7 +874,6 @@ export const dict = { "command.session.location.cycle": "التنقل بين مواقع الجلسة", "dialog.provider.anthropic.note": "وصول مباشر إلى نماذج Claude عبر مفتاح API", - "provider.connect.title.anthropicProMax": "تسجيل الدخول باستخدام Anthropic", "prompt.toast.uploading.percent": "\u2068{{percent}}\u2069%", "prompt.toast.uploading.cancelFile": "إلغاء رفع \u2068{{filename}}\u2069", "prompt.toast.uploadFailed.title": "فشل الرفع", diff --git a/packages/app/src/runtime/i18n/az.ts b/packages/app/src/runtime/i18n/az.ts index 437beb48a6f8..1da391e70161 100644 --- a/packages/app/src/runtime/i18n/az.ts +++ b/packages/app/src/runtime/i18n/az.ts @@ -150,7 +150,7 @@ export const dict = { "provider.connect.title": "{{provider}} provayderini qoş", "provider.connect.method.apiKey": "API açarı", "provider.connect.status.inProgress": "Avtorizasiya davam edir…", - "provider.connect.status.waiting": "Avtorizasiya gözlənilir…", + "provider.connect.status.waiting": "Avtorizasiya gözlənilir", "provider.connect.status.failed": "Avtorizasiya uğursuz oldu: {{error}}", "provider.connect.apiKey.description": "Hesabınızı qoşmaq və OpenCode-da {{provider}} modellərindən istifadə etmək üçün {{provider}} API açarınızı daxil edin.", @@ -826,7 +826,6 @@ export const dict = { "workspace.delete.location": "Yer", "command.session.location.cycle": "Sessiyanın yerini dəyiş", "dialog.provider.anthropic.note": "API açarı ilə Claude modellərinə birbaşa giriş", - "provider.connect.title.anthropicProMax": "Anthropic ilə daxil olun", "prompt.toast.uploading.cancelFile": "{{filename}} faylının yüklənməsini ləğv et", "prompt.toast.uploadFailed.title": "Yükləmə alınmadı", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/bg.ts b/packages/app/src/runtime/i18n/bg.ts index 477a0364d2e4..fbd14d7a029f 100644 --- a/packages/app/src/runtime/i18n/bg.ts +++ b/packages/app/src/runtime/i18n/bg.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Свържете {{provider}}", "provider.connect.method.apiKey": "API ключ", "provider.connect.status.inProgress": "В ход е оторизация…", - "provider.connect.status.waiting": "Чака се оторизация…", + "provider.connect.status.waiting": "Чака се оторизация", "provider.connect.status.failed": "Упълномощаването е неуспешно: {{error}}", "provider.connect.apiKey.description": "Въведете своя {{provider}} API ключ, за да свържете акаунта си и да използвате {{provider}} модели в OpenCode.", @@ -826,7 +826,6 @@ export const dict = { "workspace.delete.location": "Местоположение", "command.session.location.cycle": "Смяна на местоположението на сесията", "dialog.provider.anthropic.note": "Директен достъп до моделите Claude чрез API ключ", - "provider.connect.title.anthropicProMax": "Вход с Anthropic", "prompt.toast.uploading.cancelFile": "Отказ от качването на {{filename}}", "prompt.toast.uploadFailed.title": "Качването е неуспешно", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/bn.ts b/packages/app/src/runtime/i18n/bn.ts index 447feb12030e..5d64e0d4b668 100644 --- a/packages/app/src/runtime/i18n/bn.ts +++ b/packages/app/src/runtime/i18n/bn.ts @@ -153,7 +153,7 @@ export const dict = { "provider.connect.title": "{{provider}} সংযোগ করুন", "provider.connect.method.apiKey": "API কী", "provider.connect.status.inProgress": "অনুমোদন চলছে…", - "provider.connect.status.waiting": "অনুমোদনের জন্য অপেক্ষা করা হচ্ছে…", + "provider.connect.status.waiting": "অনুমোদনের জন্য অপেক্ষা করা হচ্ছে", "provider.connect.status.failed": "অনুমোদন ব্যর্থ হয়েছে: {{error}}", "provider.connect.apiKey.description": "আপনার অ্যাকাউন্ট সংযোগ করতে আপনার {{provider}} API কী লিখুন এবং OpenCode-এ {{provider}} মডেলগুলি ব্যবহার করুন৷", @@ -824,7 +824,6 @@ export const dict = { "command.session.location.cycle": "সেশনের অবস্থান পর্যায়ক্রমে বদলান", "dialog.provider.anthropic.note": "API কী-এর মাধ্যমে Claude মডেলে সরাসরি অ্যাক্সেস", - "provider.connect.title.anthropicProMax": "Anthropic দিয়ে লগ ইন করুন", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "{{filename}}-এর আপলোড বাতিল করুন", "prompt.toast.uploadFailed.title": "আপলোড ব্যর্থ হয়েছে", diff --git a/packages/app/src/runtime/i18n/br.ts b/packages/app/src/runtime/i18n/br.ts index 33681e23de63..38fddb4ee31e 100644 --- a/packages/app/src/runtime/i18n/br.ts +++ b/packages/app/src/runtime/i18n/br.ts @@ -367,7 +367,7 @@ export const dict = { "provider.connect.title": "Conectar {{provider}}", "provider.connect.method.apiKey": "Chave de API", "provider.connect.status.inProgress": "Autorização em andamento…", - "provider.connect.status.waiting": "Aguardando autorização…", + "provider.connect.status.waiting": "Aguardando autorização", "provider.connect.status.failed": "Autorização falhou: {{error}}", "provider.connect.apiKey.description": "Digite sua chave de API do {{provider}} para conectar sua conta e usar modelos do {{provider}} no OpenCode.", @@ -851,7 +851,6 @@ export const dict = { "session.background.runningCount.many": "{{count}} de itens em execução em segundo plano", "command.session.location.cycle": "Alternar local da sessão", "dialog.provider.anthropic.note": "Acesso direto aos modelos Claude por chave de API", - "provider.connect.title.anthropicProMax": "Entrar com a Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Cancelar envio de {{filename}}", "prompt.toast.uploadFailed.title": "Falha no envio", diff --git a/packages/app/src/runtime/i18n/bs.ts b/packages/app/src/runtime/i18n/bs.ts index 2ad66f5b03de..dbfe6c32fece 100644 --- a/packages/app/src/runtime/i18n/bs.ts +++ b/packages/app/src/runtime/i18n/bs.ts @@ -159,11 +159,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Pogledaj još više od 70 provajdera", "dialog.provider.viewAll": "Prikaži više provajdera", - "provider.connect.title": "Poveži {{provider}}", + "provider.connect.method.apiKey": "API ključ", "provider.connect.status.inProgress": "Autorizacija je u toku…", - "provider.connect.status.waiting": "Čekanje na autorizaciju…", + "provider.connect.status.waiting": "Čekanje na autorizaciju", "provider.connect.status.failed": "Autorizacija nije uspjela: {{error}}", "provider.connect.apiKey.description": "Unesi svoj {{provider}} API ključ da povežeš račun i koristiš {{provider}} modele u OpenCode-u.", @@ -894,7 +894,6 @@ export const dict = { "workspace.delete.location": "Lokacija", "command.session.location.cycle": "Promijeni lokaciju sesije", "dialog.provider.anthropic.note": "Direktan pristup Claude modelima putem API ključa", - "provider.connect.title.anthropicProMax": "Prijava putem Anthropic-a", "prompt.toast.uploading.cancelFile": "Otkaži otpremanje datoteke {{filename}}", "prompt.toast.uploadFailed.title": "Otpremanje nije uspjelo", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/ca.ts b/packages/app/src/runtime/i18n/ca.ts index f29a74b56045..d724c03d18d6 100644 --- a/packages/app/src/runtime/i18n/ca.ts +++ b/packages/app/src/runtime/i18n/ca.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "Connecta {{provider}}", "provider.connect.method.apiKey": "tecla API.", "provider.connect.status.inProgress": "Autorització en curs…", - "provider.connect.status.waiting": "Esperant l'autorització…", + "provider.connect.status.waiting": "Esperant l'autorització", "provider.connect.status.failed": "L'autorització ha fallat: {{error}}", "provider.connect.apiKey.description": "Introduïu la clau API de {{provider}} per connectar el compte i utilitzar els models de {{provider}} a OpenCode.", @@ -844,7 +844,6 @@ export const dict = { "toast.migration.progress.working.progress": "S'estan migrant dades {{current}}/{{total}}", "command.session.location.cycle": "Canvia la ubicació de la sessió", "dialog.provider.anthropic.note": "Accés directe als models Claude mitjançant una clau d’API", - "provider.connect.title.anthropicProMax": "Inicia la sessió amb Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Cancel·la la pujada de {{filename}}", "prompt.toast.uploadFailed.title": "Ha fallat la pujada", diff --git a/packages/app/src/runtime/i18n/cs.ts b/packages/app/src/runtime/i18n/cs.ts index 63b0cbc969b2..983ee1c4c3f1 100644 --- a/packages/app/src/runtime/i18n/cs.ts +++ b/packages/app/src/runtime/i18n/cs.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "Připojit {{provider}}", "provider.connect.method.apiKey": "API klíč", "provider.connect.status.inProgress": "Probíhá autorizace…", - "provider.connect.status.waiting": "Čekání na autorizaci…", + "provider.connect.status.waiting": "Čekání na autorizaci", "provider.connect.status.failed": "Autorizace se nezdařila: {{error}}", "provider.connect.apiKey.description": "Zadejte klíč API služby {{provider}}, připojte účet a používejte modely {{provider}} v OpenCode.", @@ -844,7 +844,6 @@ export const dict = { "workspace.delete.location": "Umístění", "command.session.location.cycle": "Přepnout umístění relace", "dialog.provider.anthropic.note": "Přímý přístup k modelům Claude pomocí klíče API", - "provider.connect.title.anthropicProMax": "Přihlásit se přes Anthropic", "prompt.toast.uploading.cancelFile": "Zrušit nahrávání souboru {{filename}}", "prompt.toast.uploadFailed.title": "Nahrávání se nezdařilo", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/da.ts b/packages/app/src/runtime/i18n/da.ts index c007447a7625..7214b10c153b 100644 --- a/packages/app/src/runtime/i18n/da.ts +++ b/packages/app/src/runtime/i18n/da.ts @@ -290,11 +290,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Se mere end 70 yderligere udbydere", "dialog.provider.viewAll": "Vis flere udbydere", - "provider.connect.title": "Forbind {{provider}}", + "provider.connect.method.apiKey": "API-nøgle", "provider.connect.status.inProgress": "Godkendelse i gang…", - "provider.connect.status.waiting": "Venter på godkendelse…", + "provider.connect.status.waiting": "Venter på godkendelse", "provider.connect.status.failed": "Godkendelse mislykkedes: {{error}}", "provider.connect.apiKey.description": "Indtast din API-nøgle til {{provider}} for at forbinde din konto og bruge modeller fra {{provider}} i OpenCode.", @@ -881,7 +881,6 @@ export const dict = { "session.background.moveInline": "Tryk på {{keybind}} for at flytte igangværende arbejde til baggrunden", "command.session.location.cycle": "Skift mellem sessionsplaceringer", "dialog.provider.anthropic.note": "Direkte adgang til Claude-modeller via API-nøgle", - "provider.connect.title.anthropicProMax": "Log ind med Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Annuller upload af {{filename}}", "prompt.toast.uploadFailed.title": "Upload mislykkedes", diff --git a/packages/app/src/runtime/i18n/de.ts b/packages/app/src/runtime/i18n/de.ts index a68fec1f7b5c..8d643fc62fdf 100644 --- a/packages/app/src/runtime/i18n/de.ts +++ b/packages/app/src/runtime/i18n/de.ts @@ -299,7 +299,7 @@ export const dict = { "provider.connect.title": "{{provider}} verbinden", "provider.connect.method.apiKey": "API-Schlüssel", "provider.connect.status.inProgress": "Autorisierung läuft…", - "provider.connect.status.waiting": "Warten auf Autorisierung…", + "provider.connect.status.waiting": "Warten auf Autorisierung", "provider.connect.status.failed": "Autorisierung fehlgeschlagen: {{error}}", "provider.connect.apiKey.description": "Geben Sie Ihren API-Schlüssel für {{provider}} ein, um Ihr Konto zu verbinden und {{provider}}-Modelle in OpenCode zu nutzen.", @@ -846,7 +846,6 @@ export const dict = { "session.background.moveInline": "Drücken Sie {{keybind}}, um laufende Arbeit in den Hintergrund zu verschieben", "command.session.location.cycle": "Sitzungsort wechseln", "dialog.provider.anthropic.note": "Direkter Zugriff auf Claude-Modelle per API-Schlüssel", - "provider.connect.title.anthropicProMax": "Bei Anthropic anmelden", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Upload von {{filename}} abbrechen", "prompt.toast.uploadFailed.title": "Upload fehlgeschlagen", diff --git a/packages/app/src/runtime/i18n/dv.ts b/packages/app/src/runtime/i18n/dv.ts index 8b7ffe976f0b..45a43e05d3e5 100644 --- a/packages/app/src/runtime/i18n/dv.ts +++ b/packages/app/src/runtime/i18n/dv.ts @@ -150,10 +150,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "އިތުރު 70+ ޕްރޮވައިޑަރުން ބައްލަވާށެވެ", "dialog.provider.viewAll": "އިތުރު ޕްރޮވައިޑަރުން ދައްކާށެވެ", "provider.connect.title": "\u2068{{provider}}\u2069 ގުޅުވާށެވެ", - "provider.connect.title.anthropicProMax": "Anthropic އާއެކު ލޮގިން ވާށެވެ", "provider.connect.method.apiKey": "API ކީ އެވެ", "provider.connect.status.inProgress": "ހުއްދަ ދިނުމުގެ މަސައްކަތް ކުރިއަށްދާ…", - "provider.connect.status.waiting": "ހުއްދައަށް އިންތިޒާރު ކުރަމުން…", + "provider.connect.status.waiting": "ހުއްދައަށް އިންތިޒާރު ކުރަމުން", "provider.connect.status.failed": "ހުއްދަ ދިނުން ނާކާމިޔާބު: \u2068{{error}}\u2069", "provider.connect.apiKey.description": "ތިބާގެ އެކައުންޓް ގުޅުވައި، OpenCode ގައި \u2068{{provider}}\u2069 މޮޑެލްތައް ބޭނުންކުރުމަށް \u2068{{provider}}\u2069 API ކީ ލިޔުއްވާ.", diff --git a/packages/app/src/runtime/i18n/dz.ts b/packages/app/src/runtime/i18n/dz.ts index 3460ed4c0292..1db280b8a01f 100644 --- a/packages/app/src/runtime/i18n/dz.ts +++ b/packages/app/src/runtime/i18n/dz.ts @@ -836,7 +836,6 @@ export const dict = { "toast.migration.progress.working.progress": "གནད་སྡུད་གནས་སྤོ་འབད་དོ་ {{current}}/{{total}}", "command.session.location.cycle": "ལཱ་ཡུན་གྱི་ས་གནས་སོར།", "dialog.provider.anthropic.note": "API ལྡེ་མིག་བརྒྱུད་དེ་ Claude དཔེ་ཚད་ཚུ་ལུ་ཐད་ཀར་འཛུལ་སྤྱོད།", - "provider.connect.title.anthropicProMax": "Anthropic ཐོག་ལས་ནང་བསྐྱོད།", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "{{filename}} སྐྱེལ་བཙུགས་འབད་ནི་ཆ་མེད་བཏང་།", "prompt.toast.uploadFailed.title": "སྐྱེལ་བཙུགས་འཐུས་ཤོར།", diff --git a/packages/app/src/runtime/i18n/el.ts b/packages/app/src/runtime/i18n/el.ts index f32a2a07ed7f..621668f16975 100644 --- a/packages/app/src/runtime/i18n/el.ts +++ b/packages/app/src/runtime/i18n/el.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Σύνδεση {{provider}}", "provider.connect.method.apiKey": "API κλειδί", "provider.connect.status.inProgress": "Εξουσιοδότηση σε εξέλιξη…", - "provider.connect.status.waiting": "Αναμονή για εξουσιοδότηση…", + "provider.connect.status.waiting": "Αναμονή για εξουσιοδότηση", "provider.connect.status.failed": "Η εξουσιοδότηση απέτυχε: {{error}}", "provider.connect.apiKey.description": "Εισαγάγετε το κλειδί {{provider}} API για να συνδέσετε τον λογαριασμό σας και χρησιμοποιήστε μοντέλα {{provider}} στο OpenCode.", @@ -840,7 +840,6 @@ export const dict = { "toast.migration.progress.working.progress": "Μεταφορά δεδομένων {{current}}/{{total}}", "command.session.location.cycle": "Εναλλαγή τοποθεσίας συνεδρίας", "dialog.provider.anthropic.note": "Άμεση πρόσβαση στα μοντέλα Claude μέσω κλειδιού API", - "provider.connect.title.anthropicProMax": "Σύνδεση με το Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Ακύρωση μεταφόρτωσης του {{filename}}", "prompt.toast.uploadFailed.title": "Η μεταφόρτωση απέτυχε", diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 83361ec2419b..5334a20f97a9 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -180,21 +180,21 @@ export const dict = { "dialog.provider.accounts.removeConfirm": "Remove {{account}}?", "dialog.provider.accounts.remove": "Remove", "dialog.provider.accounts.options": "{{account}} options", - + "provider.connect.copyFailed": "Couldn't copy to the clipboard", "provider.connect.title": "Connect {{provider}}", + + "provider.connect.breadcrumb.root": "Connect", + "provider.connect.breadcrumb.label": "Connect steps", + "provider.connect.methods.description": "Choose how to connect {{provider}}.", "provider.connect.opencode.name": "OpenCode Console", "provider.connect.opencode.freeName": "OpenCode Free", - "provider.connect.opencode.errorTitle": "Connect to OpenCode", - "provider.connect.console.title": "Connecting to OpenCode Console", - "provider.connect.console.titleGo": "Connecting to OpenCode Go", "provider.connect.console.retry": "Try again", "provider.connect.console.serviceKeyDescription": "Connect using a service-account API key from OpenCode Console.", "provider.connect.console.instructions": "Continue in your browser. Confirm the code shown there matches the one below.", "provider.connect.console.deviceCode": "Device code", "provider.connect.console.deviceCode.label": "Device code: {{code}}", - "provider.connect.console.waiting": "Waiting for confirmation…", - "provider.connect.console.browserHint": "Browser didn't open?", + "provider.connect.console.waiting": "Waiting for confirmation", "provider.connect.console.copyLink": "Copy sign-in link", "provider.connect.console.linkCopied": "Sign-in link copied", "provider.connect.console.copyFailed": "Couldn't copy the sign-in link. Open Console again to continue.", @@ -224,12 +224,11 @@ export const dict = { "Your account is connected, but this Console workspace has no available models. Check its setup in Console, then refresh.", "provider.connect.console.modelsLoading": "Your models are still loading. Refresh to check again.", "provider.connect.console.refresh": "Refresh models", - "provider.connect.console.openingBrowser": "Opening browser…", - "provider.connect.remote.title": "Connecting on “{{server}}”", + "provider.connect.console.openingBrowser": "Opening browser", + "provider.connect.remote.label": "on {{server}}", "provider.connect.remote.description": "Your OpenCode credentials will be stored on this server. Models will be available through this server.", - "provider.connect.title.anthropicProMax": "Login with Anthropic", - "provider.connect.command.waiting": "Waiting for command to finish…", + "provider.connect.command.waiting": "Waiting for command to finish", "provider.connect.command.expired": "Authentication expired", "provider.connect.form.required": "Answer required", "provider.connect.form.number": "Expected a number", @@ -238,7 +237,6 @@ export const dict = { "provider.connect.form.skip": "Skip", "provider.connect.form.add": "Add", "provider.connect.form.open": "Open link", - "provider.connect.form.openAgain": "Open link again", "provider.connect.form.finished": "I finished", "provider.connect.form.browserFailed": "We couldn't open your browser. Open the link below, then select I finished.", "provider.connect.form.selectOne": "Select at least one option", @@ -246,7 +244,7 @@ export const dict = { "provider.connect.form.maxItems": "Select at most {{count}}", "provider.connect.method.apiKey": "API key", "provider.connect.status.inProgress": "Authorization in progress…", - "provider.connect.status.waiting": "Waiting for authorization…", + "provider.connect.status.waiting": "Waiting for authorization", "provider.connect.status.failed": "Authorization failed: {{error}}", "provider.connect.apiKey.description": "Enter your {{provider}} API key to connect your account and use {{provider}} models in OpenCode.", @@ -258,15 +256,15 @@ export const dict = { "provider.connect.oauth.code.required": "Authorization code is required", "provider.connect.oauth.code.invalid": "Invalid authorization code", "provider.connect.oauth.auto.confirmationCode": "Confirmation code", - "provider.connect.oauth.auto.confirmationCode.description": - "Check that your browser shows the same code before you authorize.", "provider.connect.oauth.auto.description": "Your browser opens so you can sign in to {{provider}}. Come back here when you are done.", - "provider.connect.oauth.auto.paste.description": - "Your browser opens so you can sign in to {{provider}}. If it can't reach the machine running OpenCode, paste the URL it was redirected to below.", "provider.connect.oauth.code.description": "Your browser opens so you can sign in to {{provider}}. Paste the authorization code it gives you below.", "provider.connect.oauth.openBrowser": "Open browser", + "provider.connect.oauth.browserFailed": "We couldn't open your browser. Select Open browser to try again.", + "provider.connect.oauth.paste.toggle": "Signing in from another device?", + "provider.connect.oauth.paste.description": + "If your browser can't reach the machine running OpenCode, paste the URL it was redirected to.", "provider.connect.oauth.expired": "Authorization expired", "provider.connect.toast.connected.title": "{{provider}} connected", "provider.connect.toast.connected.description": "{{provider}} models are now available to use.", diff --git a/packages/app/src/runtime/i18n/es.ts b/packages/app/src/runtime/i18n/es.ts index 1d1a54c1efec..720b10bf5969 100644 --- a/packages/app/src/runtime/i18n/es.ts +++ b/packages/app/src/runtime/i18n/es.ts @@ -375,11 +375,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Ver más de 70 proveedores", "dialog.provider.viewAll": "Ver más proveedores", - "provider.connect.title": "Conectar {{provider}}", + "provider.connect.method.apiKey": "Clave API", "provider.connect.status.inProgress": "Autorización en progreso…", - "provider.connect.status.waiting": "Esperando autorización…", + "provider.connect.status.waiting": "Esperando autorización", "provider.connect.status.failed": "Autorización fallida: {{error}}", "provider.connect.apiKey.description": "Introduce tu clave API de {{provider}} para conectar tu cuenta y usar modelos de {{provider}} en OpenCode.", @@ -907,7 +907,6 @@ export const dict = { "session.background.runningCount.many": "{{count}} de elementos en curso en segundo plano", "command.session.location.cycle": "Cambiar la ubicación de la sesión", "dialog.provider.anthropic.note": "Acceso directo a los modelos Claude mediante una clave de API", - "provider.connect.title.anthropicProMax": "Iniciar sesión con Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Cancelar carga de {{filename}}", "prompt.toast.uploadFailed.title": "Error al cargar", diff --git a/packages/app/src/runtime/i18n/et.ts b/packages/app/src/runtime/i18n/et.ts index 0c19cf12e397..faa00241bcea 100644 --- a/packages/app/src/runtime/i18n/et.ts +++ b/packages/app/src/runtime/i18n/et.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "Ühenda {{provider}}", "provider.connect.method.apiKey": "API klahv", "provider.connect.status.inProgress": "Autoriseerimine on pooleli…", - "provider.connect.status.waiting": "Autoriseerimise ootel…", + "provider.connect.status.waiting": "Autoriseerimise ootel", "provider.connect.status.failed": "Autoriseerimine ebaõnnestus: {{error}}", "provider.connect.apiKey.description": "Sisestage {{provider}} API võti, et ühendada konto ja kasutada {{provider}} mudeleid OpenCode'is.", @@ -812,7 +812,6 @@ export const dict = { "toast.migration.progress.working.progress": "Andmete üleviimine {{current}}/{{total}}", "command.session.location.cycle": "Vaheta seansi asukohta", "dialog.provider.anthropic.note": "Otsejuurdepääs Claude’i mudelitele API-võtmega", - "provider.connect.title.anthropicProMax": "Logi Anthropicuga sisse", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Tühista faili {{filename}} üleslaadimine", "prompt.toast.uploadFailed.title": "Üleslaadimine nurjus", diff --git a/packages/app/src/runtime/i18n/fa.ts b/packages/app/src/runtime/i18n/fa.ts index 0727b9e749a1..11307638aff4 100644 --- a/packages/app/src/runtime/i18n/fa.ts +++ b/packages/app/src/runtime/i18n/fa.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "{{provider}} را وصل کنید", "provider.connect.method.apiKey": "کلید API", "provider.connect.status.inProgress": "مجوز در حال انجام است…", - "provider.connect.status.waiting": "در انتظار مجوز…", + "provider.connect.status.waiting": "در انتظار مجوز", "provider.connect.status.failed": "مجوز انجام نشد: {{error}}", "provider.connect.apiKey.description": "کلید API سرویس {{provider}} را وارد کنید تا حساب شما متصل شود و بتوانید از مدل‌های {{provider}} در OpenCode استفاده کنید.", @@ -819,7 +819,6 @@ export const dict = { "command.session.location.cycle": "جابجایی چرخشی مکان نشست", "dialog.provider.anthropic.note": "دسترسی مستقیم به مدل‌های Claude از طریق کلید API", - "provider.connect.title.anthropicProMax": "ورود با Anthropic", "prompt.toast.uploading.percent": "\u2068{{percent}}\u2069٪", "prompt.toast.uploading.cancelFile": "لغو بارگذاری \u2068{{filename}}\u2069", "prompt.toast.uploadFailed.title": "بارگذاری ناموفق بود", diff --git a/packages/app/src/runtime/i18n/fi.ts b/packages/app/src/runtime/i18n/fi.ts index deee417b678d..ce4b7c372cc8 100644 --- a/packages/app/src/runtime/i18n/fi.ts +++ b/packages/app/src/runtime/i18n/fi.ts @@ -282,7 +282,7 @@ export const dict = { "provider.connect.title": "Yhdistä {{provider}}", "provider.connect.method.apiKey": "API-avain", "provider.connect.status.inProgress": "Valtuutus käynnissä…", - "provider.connect.status.waiting": "Odotetaan valtuutusta…", + "provider.connect.status.waiting": "Odotetaan valtuutusta", "provider.connect.status.failed": "Valtuutus epäonnistui: {{error}}", "provider.connect.apiKey.description": "Anna {{provider}}-API-avaimesi yhdistääksesi tilisi ja käyttääksesi {{provider}}-malleja OpenCodessa.", @@ -821,7 +821,6 @@ export const dict = { "session.background.moveInline": "Siirrä käynnissä oleva työ taustalle painamalla {{keybind}}", "command.session.location.cycle": "Vaihda istunnon sijaintia", "dialog.provider.anthropic.note": "Suora pääsy Claude-malleihin API-avaimella", - "provider.connect.title.anthropicProMax": "Kirjaudu sisään Anthropiciin", "prompt.toast.uploading.percent": "{{percent}} %", "prompt.toast.uploading.cancelFile": "Peru tiedoston {{filename}} lähetys", "prompt.toast.uploadFailed.title": "Lähetys epäonnistui", diff --git a/packages/app/src/runtime/i18n/fo.ts b/packages/app/src/runtime/i18n/fo.ts index 057c38af6810..f0024f0489b5 100644 --- a/packages/app/src/runtime/i18n/fo.ts +++ b/packages/app/src/runtime/i18n/fo.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "Samband {{provider}}", "provider.connect.method.apiKey": "API lykil", "provider.connect.status.inProgress": "Heimild í gongd…", - "provider.connect.status.waiting": "Bíða eftir heimild…", + "provider.connect.status.waiting": "Bíða eftir heimild", "provider.connect.status.failed": "Heimild miseydnaðist: {{error}}", "provider.connect.apiKey.description": "Skriva {{provider}} API-lykilin fyri at knýta kontuna saman og brúka {{provider}}-modell í OpenCode.", @@ -816,7 +816,6 @@ export const dict = { "toast.migration.progress.working.progress": "Flyta dátur {{current}}/{{total}}", "command.session.location.cycle": "Skift staðseting fyri setuna", "dialog.provider.anthropic.note": "Beinleiðis atgongd til Claude-modellar við API-lykli", - "provider.connect.title.anthropicProMax": "Rita inn við Anthropic", "prompt.toast.uploading.percent": "{{percent}} %", "prompt.toast.uploading.cancelFile": "Ógilda uppsendingina av {{filename}}", "prompt.toast.uploadFailed.title": "Uppsending miseydnaðist", diff --git a/packages/app/src/runtime/i18n/fr.ts b/packages/app/src/runtime/i18n/fr.ts index 5e54556c6699..718b52f81a88 100644 --- a/packages/app/src/runtime/i18n/fr.ts +++ b/packages/app/src/runtime/i18n/fr.ts @@ -371,7 +371,7 @@ export const dict = { "provider.connect.title": "Connecter {{provider}}", "provider.connect.method.apiKey": "Clé API", "provider.connect.status.inProgress": "Autorisation en cours…", - "provider.connect.status.waiting": "En attente d'autorisation…", + "provider.connect.status.waiting": "En attente d'autorisation", "provider.connect.status.failed": "Échec de l'autorisation : {{error}}", "provider.connect.apiKey.description": "Entrez votre clé API {{provider}} pour connecter votre compte et utiliser les modèles {{provider}} dans OpenCode.", @@ -859,7 +859,6 @@ export const dict = { "session.background.runningCount.many": "{{count}} de tâches en cours d'exécution en arrière-plan", "command.session.location.cycle": "Changer l’emplacement de la session", "dialog.provider.anthropic.note": "Accès direct aux modèles Claude avec une clé API", - "provider.connect.title.anthropicProMax": "Se connecter avec Anthropic", "prompt.toast.uploading.percent": "{{percent}} %", "prompt.toast.uploading.cancelFile": "Annuler le téléversement de {{filename}}", "prompt.toast.uploadFailed.title": "Échec du téléversement", diff --git a/packages/app/src/runtime/i18n/he.ts b/packages/app/src/runtime/i18n/he.ts index 98f68effdcb3..e5706338dc12 100644 --- a/packages/app/src/runtime/i18n/he.ts +++ b/packages/app/src/runtime/i18n/he.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "חבר את {{provider}}", "provider.connect.method.apiKey": "מפתח API", "provider.connect.status.inProgress": "האישור מתבצע…", - "provider.connect.status.waiting": "ממתין לאישור…", + "provider.connect.status.waiting": "ממתין לאישור", "provider.connect.status.failed": "ההרשאה נכשלה: {{error}}", "provider.connect.apiKey.description": "הזן את מפתח ה-API של {{provider}} כדי לחבר את החשבון ולהשתמש במודלים של {{provider}} ב-OpenCode.", @@ -818,7 +818,6 @@ export const dict = { "command.session.location.cycle": "מעבר מחזורי בין מיקומי ההפעלה", "dialog.provider.anthropic.note": "גישה ישירה לדגמי Claude באמצעות מפתח API", - "provider.connect.title.anthropicProMax": "התחברות באמצעות Anthropic", "prompt.toast.uploading.percent": "\u2068{{percent}}\u2069%", "prompt.toast.uploading.cancelFile": "ביטול ההעלאה של \u2068{{filename}}\u2069", "prompt.toast.uploadFailed.title": "ההעלאה נכשלה", diff --git a/packages/app/src/runtime/i18n/hi.ts b/packages/app/src/runtime/i18n/hi.ts index 9b1c552a3ed8..eca6d50281bf 100644 --- a/packages/app/src/runtime/i18n/hi.ts +++ b/packages/app/src/runtime/i18n/hi.ts @@ -154,7 +154,7 @@ export const dict = { "provider.connect.title": "{{provider}} कनेक्ट करें", "provider.connect.method.apiKey": "API कुंजी", "provider.connect.status.inProgress": "प्राधिकरण प्रगति पर है…", - "provider.connect.status.waiting": "प्राधिकरण की प्रतीक्षा हो रही है…", + "provider.connect.status.waiting": "प्राधिकरण की प्रतीक्षा हो रही है", "provider.connect.status.failed": "प्राधिकरण विफल: {{error}}", "provider.connect.apiKey.description": "अपने खाते को कनेक्ट करने के लिए अपनी {{provider}} API कुंजी दर्ज करें और OpenCode में {{provider}} मॉडल का उपयोग करें।", @@ -826,7 +826,6 @@ export const dict = { "command.session.location.cycle": "सेशन की लोकेशन क्रम से बदलें", "dialog.provider.anthropic.note": "API कुंजी के माध्यम से Claude मॉडल का सीधा ऐक्सेस", - "provider.connect.title.anthropicProMax": "Anthropic से लॉग इन करें", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "{{filename}} का अपलोड रद्द करें", "prompt.toast.uploadFailed.title": "अपलोड विफल रहा", diff --git a/packages/app/src/runtime/i18n/hr.ts b/packages/app/src/runtime/i18n/hr.ts index ab857f6e41fc..9a7530d3ddd5 100644 --- a/packages/app/src/runtime/i18n/hr.ts +++ b/packages/app/src/runtime/i18n/hr.ts @@ -161,7 +161,7 @@ export const dict = { "provider.connect.title": "Povežite {{provider}}", "provider.connect.method.apiKey": "Ključ API", "provider.connect.status.inProgress": "Autorizacija u tijeku…", - "provider.connect.status.waiting": "Čeka se autorizacija…", + "provider.connect.status.waiting": "Čeka se autorizacija", "provider.connect.status.failed": "Autorizacija nije uspjela: {{error}}", "provider.connect.apiKey.description": "Enter vaš {{provider}} API ključ za povezivanje vašeg računa i korištenje {{provider}} modela u OpenCode.", @@ -838,7 +838,6 @@ export const dict = { "workspace.delete.location": "Lokacija", "command.session.location.cycle": "Promijeni lokaciju sesije", "dialog.provider.anthropic.note": "Izravan pristup modelima Claude putem API ključa", - "provider.connect.title.anthropicProMax": "Prijava putem Anthropic-a", "prompt.toast.uploading.cancelFile": "Otkaži prijenos datoteke {{filename}}", "prompt.toast.uploadFailed.title": "Prijenos nije uspio", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/hu.ts b/packages/app/src/runtime/i18n/hu.ts index 34caa21d6449..fbde90757b80 100644 --- a/packages/app/src/runtime/i18n/hu.ts +++ b/packages/app/src/runtime/i18n/hu.ts @@ -161,7 +161,7 @@ export const dict = { "provider.connect.title": "Csatlakoztassa a {{provider}}-t", "provider.connect.method.apiKey": "API kulcs", "provider.connect.status.inProgress": "Az engedélyezés folyamatban…", - "provider.connect.status.waiting": "Várakozás az engedélyezésre…", + "provider.connect.status.waiting": "Várakozás az engedélyezésre", "provider.connect.status.failed": "Az engedélyezés sikertelen: {{error}}", "provider.connect.apiKey.description": "Enter az Ön {{provider}} API kulcsa fiókja összekapcsolásához és a {{provider}} modellek használatához a OpenCode-ben.", @@ -832,7 +832,6 @@ export const dict = { "toast.migration.progress.working.progress": "Adatok migrálása {{current}}/{{total}}", "command.session.location.cycle": "Munkamenet helyének váltása", "dialog.provider.anthropic.note": "Közvetlen hozzáférés a Claude-modellekhez API-kulccsal", - "provider.connect.title.anthropicProMax": "Bejelentkezés az Anthropic használatával", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "A(z) {{filename}} feltöltésének megszakítása", "prompt.toast.uploadFailed.title": "A feltöltés sikertelen", diff --git a/packages/app/src/runtime/i18n/hy.ts b/packages/app/src/runtime/i18n/hy.ts index 2e09b9701ab5..2a1c97c4354b 100644 --- a/packages/app/src/runtime/i18n/hy.ts +++ b/packages/app/src/runtime/i18n/hy.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Միացեք {{provider}}", "provider.connect.method.apiKey": "API բանալի", "provider.connect.status.inProgress": "Լիազորումն ընթացքի մեջ է…", - "provider.connect.status.waiting": "Սպասում է թույլտվության…", + "provider.connect.status.waiting": "Սպասում է թույլտվության", "provider.connect.status.failed": "Լիազորումը ձախողվեց՝ {{error}}", "provider.connect.apiKey.description": "Մուտքագրեք ձեր {{provider}} API բանալին՝ ձեր հաշիվը միացնելու և OpenCode-ում {{provider}} մոդելներ օգտագործելու համար։", @@ -819,7 +819,6 @@ export const dict = { "workspace.delete.location": "Տեղանք", "command.session.location.cycle": "Փոխել աշխատաշրջանի տեղադրությունը", "dialog.provider.anthropic.note": "Ուղղակի հասանելիություն Claude մոդելներին API բանալիով", - "provider.connect.title.anthropicProMax": "Մուտք գործել Anthropic-ով", "prompt.toast.uploading.cancelFile": "Չեղարկել {{filename}} ֆայլի վերբեռնումը", "prompt.toast.uploadFailed.title": "Վերբեռնումը ձախողվեց", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/id.ts b/packages/app/src/runtime/i18n/id.ts index 6547f56c27c5..cecf1a723bc6 100644 --- a/packages/app/src/runtime/i18n/id.ts +++ b/packages/app/src/runtime/i18n/id.ts @@ -162,12 +162,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Lihat 70+ penyedia lainnya", "dialog.provider.viewAll": "Tampilkan lebih banyak penyedia", - "provider.connect.title": "Hubungkan {{provider}}", - "provider.connect.title.anthropicProMax": "Masuk dengan Anthropic", + "provider.connect.method.apiKey": "Kunci API", "provider.connect.status.inProgress": "Otorisasi sedang berlangsung…", - "provider.connect.status.waiting": "Menunggu otorisasi…", + "provider.connect.status.waiting": "Menunggu otorisasi", "provider.connect.status.failed": "Otorisasi gagal: {{error}}", "provider.connect.apiKey.description": "Masukkan kunci API {{provider}} untuk menghubungkan akun Anda dan gunakan model {{provider}} di OpenCode.", diff --git a/packages/app/src/runtime/i18n/is.ts b/packages/app/src/runtime/i18n/is.ts index fc8da152d1f7..e5b2cf49d140 100644 --- a/packages/app/src/runtime/i18n/is.ts +++ b/packages/app/src/runtime/i18n/is.ts @@ -161,7 +161,7 @@ export const dict = { "provider.connect.title": "Tengdu {{provider}}", "provider.connect.method.apiKey": "API lykill", "provider.connect.status.inProgress": "Heimild í gangi…", - "provider.connect.status.waiting": "Bíður eftir heimild…", + "provider.connect.status.waiting": "Bíður eftir heimild", "provider.connect.status.failed": "Heimild mistókst: {{error}}", "provider.connect.apiKey.description": "Sláðu inn API-lykilinn þinn fyrir {{provider}} til að tengja reikninginn og nota líkön frá {{provider}} í OpenCode.", @@ -821,7 +821,6 @@ export const dict = { "toast.migration.progress.working.progress": "Flytja gögn {{current}}/{{total}}", "command.session.location.cycle": "Skipta um staðsetningu setu", "dialog.provider.anthropic.note": "Beinn aðgangur að Claude-líkönum með API-lykli", - "provider.connect.title.anthropicProMax": "Skrá inn með Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Hætta við upphleðslu á {{filename}}", "prompt.toast.uploadFailed.title": "Upphleðsla mistókst", diff --git a/packages/app/src/runtime/i18n/it.ts b/packages/app/src/runtime/i18n/it.ts index 1950a6189654..07d3bd73df7f 100644 --- a/packages/app/src/runtime/i18n/it.ts +++ b/packages/app/src/runtime/i18n/it.ts @@ -303,7 +303,7 @@ export const dict = { "provider.connect.title": "Connetti {{provider}}", "provider.connect.method.apiKey": "Chiave API", "provider.connect.status.inProgress": "Autorizzazione in corso…", - "provider.connect.status.waiting": "In attesa di autorizzazione…", + "provider.connect.status.waiting": "In attesa di autorizzazione", "provider.connect.status.failed": "Autorizzazione fallita: {{error}}", "provider.connect.apiKey.description": "Inserisci la chiave API di {{provider}} per connettere il tuo account e utilizzare i modelli {{provider}} in OpenCode.", @@ -845,7 +845,6 @@ export const dict = { "session.background.runningCount.many": "{{count}} di elementi in esecuzione in background", "command.session.location.cycle": "Cambia la posizione della sessione", "dialog.provider.anthropic.note": "Accesso diretto ai modelli Claude tramite chiave API", - "provider.connect.title.anthropicProMax": "Accedi con Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Annulla il caricamento di {{filename}}", "prompt.toast.uploadFailed.title": "Caricamento non riuscito", diff --git a/packages/app/src/runtime/i18n/ja.ts b/packages/app/src/runtime/i18n/ja.ts index 5b6a7c842fd4..14ec52804eb2 100644 --- a/packages/app/src/runtime/i18n/ja.ts +++ b/packages/app/src/runtime/i18n/ja.ts @@ -153,10 +153,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "その他70以上のプロバイダーを見る", "dialog.provider.viewAll": "さらにプロバイダーを表示", "provider.connect.title": "{{provider}}を接続", - "provider.connect.title.anthropicProMax": "Anthropicにログイン", "provider.connect.method.apiKey": "APIキー", "provider.connect.status.inProgress": "認証中…", - "provider.connect.status.waiting": "認証を待機中…", + "provider.connect.status.waiting": "認証を待機中", "provider.connect.status.failed": "認証に失敗しました: {{error}}", "provider.connect.apiKey.description": "{{provider}}のAPIキーを入力してアカウントを接続し、OpenCodeで{{provider}}モデルを使用します。", diff --git a/packages/app/src/runtime/i18n/ka.ts b/packages/app/src/runtime/i18n/ka.ts index 63bc04865c53..00d6ba2a27fc 100644 --- a/packages/app/src/runtime/i18n/ka.ts +++ b/packages/app/src/runtime/i18n/ka.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "დაკავშირება {{provider}}", "provider.connect.method.apiKey": "API გასაღები", "provider.connect.status.inProgress": "ავტორიზაცია მიმდინარეობს…", - "provider.connect.status.waiting": "ველოდები ავტორიზაციას…", + "provider.connect.status.waiting": "ველოდები ავტორიზაციას", "provider.connect.status.failed": "ავტორიზაცია ვერ მოხერხდა: {{error}}", "provider.connect.apiKey.description": "შეიყვანეთ თქვენი {{provider}} API გასაღები თქვენი ანგარიშის დასაკავშირებლად და გამოიყენეთ {{provider}} მოდელები OpenCode-ში.", @@ -820,7 +820,6 @@ export const dict = { "workspace.delete.location": "მდებარეობა", "command.session.location.cycle": "სესიის მდებარეობის შეცვლა", "dialog.provider.anthropic.note": "Claude-ის მოდელებზე პირდაპირი წვდომა API გასაღებით", - "provider.connect.title.anthropicProMax": "Anthropic-ით შესვლა", "prompt.toast.uploading.cancelFile": "{{filename}} ფაილის ატვირთვის გაუქმება", "prompt.toast.uploadFailed.title": "ატვირთვა ვერ მოხერხდა", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/km.ts b/packages/app/src/runtime/i18n/km.ts index 77985dd8a268..00f5c9f5675b 100644 --- a/packages/app/src/runtime/i18n/km.ts +++ b/packages/app/src/runtime/i18n/km.ts @@ -148,10 +148,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "មើលអ្នកផ្តល់សេវា 70+ ទៀត។", "dialog.provider.viewAll": "បង្ហាញអ្នកផ្តល់សេវាបន្ថែម", "provider.connect.title": "ភ្ជាប់ {{provider}}", - "provider.connect.title.anthropicProMax": "ចូលដោយប្រើ Anthropic", "provider.connect.method.apiKey": "សោ API", "provider.connect.status.inProgress": "ការអនុញ្ញាតកំពុងដំណើរការ…", - "provider.connect.status.waiting": "រង់ចាំការអនុញ្ញាត…", + "provider.connect.status.waiting": "រង់ចាំការអនុញ្ញាត", "provider.connect.status.failed": "ការអនុញ្ញាតបានបរាជ័យ៖ {{error}}", "provider.connect.apiKey.description": "បញ្ចូល {{provider}} API key របស់អ្នក ដើម្បីភ្ជាប់គណនីរបស់អ្នក ហើយប្រើម៉ូដែល {{provider}} នៅក្នុង OpenCode។", diff --git a/packages/app/src/runtime/i18n/ko.ts b/packages/app/src/runtime/i18n/ko.ts index e1d5cc62a98e..e88951c48f45 100644 --- a/packages/app/src/runtime/i18n/ko.ts +++ b/packages/app/src/runtime/i18n/ko.ts @@ -86,10 +86,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "70개 이상의 공급자 더 보기", "dialog.provider.viewAll": "더 많은 공급자 보기", "provider.connect.title": "{{provider}} 연결", - "provider.connect.title.anthropicProMax": "Anthropic에 로그인", "provider.connect.method.apiKey": "API 키", "provider.connect.status.inProgress": "인증 진행 중…", - "provider.connect.status.waiting": "인증 대기 중…", + "provider.connect.status.waiting": "인증 대기 중", "provider.connect.status.failed": "인증 실패: {{error}}", "provider.connect.apiKey.description": "{{provider}} API 키를 입력하여 계정을 연결하고 OpenCode에서 {{provider}} 모델을 사용하세요.", diff --git a/packages/app/src/runtime/i18n/lo.ts b/packages/app/src/runtime/i18n/lo.ts index c6fac5b5526d..e78da8195b48 100644 --- a/packages/app/src/runtime/i18n/lo.ts +++ b/packages/app/src/runtime/i18n/lo.ts @@ -148,10 +148,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "ເບິ່ງ 70+ ຜູ້ໃຫ້ບໍລິການເພີ່ມເຕີມ", "dialog.provider.viewAll": "ສະແດງຜູ້ໃຫ້ບໍລິການເພີ່ມເຕີມ", "provider.connect.title": "ເຊື່ອມຕໍ່ {{provider}}", - "provider.connect.title.anthropicProMax": "ເຂົ້າສູ່ລະບົບດ້ວຍ Anthropic", "provider.connect.method.apiKey": "ລະຫັດ API", "provider.connect.status.inProgress": "ກໍາລັງດໍາເນີນຢູ່…", - "provider.connect.status.waiting": "ລໍຖ້າການອະນຸຍາດ…", + "provider.connect.status.waiting": "ລໍຖ້າການອະນຸຍາດ", "provider.connect.status.failed": "ການອະນຸຍາດລົ້ມເຫລວ: {{error}}", "provider.connect.apiKey.description": "ໃສ່ລະຫັດ API {{provider}} ຂອງທ່ານເພື່ອເຊື່ອມຕໍ່ບັນຊີຂອງທ່ານ ແລະໃຊ້ຕົວແບບ {{provider}} ໃນ OpenCode.", diff --git a/packages/app/src/runtime/i18n/lt.ts b/packages/app/src/runtime/i18n/lt.ts index 800fd3f24a1e..7a5409052b72 100644 --- a/packages/app/src/runtime/i18n/lt.ts +++ b/packages/app/src/runtime/i18n/lt.ts @@ -161,7 +161,7 @@ export const dict = { "provider.connect.title": "Prijunkite {{provider}}", "provider.connect.method.apiKey": "API raktas", "provider.connect.status.inProgress": "Vykdoma prieigos teisė…", - "provider.connect.status.waiting": "Laukiama įgaliojimo…", + "provider.connect.status.waiting": "Laukiama įgaliojimo", "provider.connect.status.failed": "Autorizacija nepavyko: {{error}}", "provider.connect.apiKey.description": "Įveskite {{provider}} API raktą, kad susietumėte paskyrą ir naudotumėte {{provider}} modelius programoje OpenCode.", @@ -851,7 +851,6 @@ export const dict = { "toast.migration.progress.working.progress": "Perkeliami duomenys {{current}}/{{total}}", "command.session.location.cycle": "Keisti seanso vietą", "dialog.provider.anthropic.note": "Tiesioginė prieiga prie „Claude“ modelių naudojant API raktą", - "provider.connect.title.anthropicProMax": "Prisijungti naudojant „Anthropic“", "prompt.toast.uploading.percent": "{{percent}} %", "prompt.toast.uploading.cancelFile": "Atšaukti failo {{filename}} įkėlimą", "prompt.toast.uploadFailed.title": "Įkelti nepavyko", diff --git a/packages/app/src/runtime/i18n/lv.ts b/packages/app/src/runtime/i18n/lv.ts index d6ba20a4e0ed..d15cbac06d77 100644 --- a/packages/app/src/runtime/i18n/lv.ts +++ b/packages/app/src/runtime/i18n/lv.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "Savienot {{provider}}", "provider.connect.method.apiKey": "API atslēga", "provider.connect.status.inProgress": "Notiek autorizācija…", - "provider.connect.status.waiting": "Gaida autorizāciju…", + "provider.connect.status.waiting": "Gaida autorizāciju", "provider.connect.status.failed": "Autorizācija neizdevās: {{error}}", "provider.connect.apiKey.description": "Ievadiet savu {{provider}} API atslēgu, lai savienotu kontu un izmantotu {{provider}} modeļus OpenCode.", @@ -835,7 +835,6 @@ export const dict = { "toast.migration.progress.working.progress": "Notiek datu migrēšana {{current}}/{{total}}", "command.session.location.cycle": "Mainīt sesijas atrašanās vietu", "dialog.provider.anthropic.note": "Tieša piekļuve Claude modeļiem, izmantojot API atslēgu", - "provider.connect.title.anthropicProMax": "Pieteikties, izmantojot Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Atcelt faila {{filename}} augšupielādi", "prompt.toast.uploadFailed.title": "Augšupielāde neizdevās", diff --git a/packages/app/src/runtime/i18n/mk.ts b/packages/app/src/runtime/i18n/mk.ts index 0f6745c5d657..a32f6ff41c9c 100644 --- a/packages/app/src/runtime/i18n/mk.ts +++ b/packages/app/src/runtime/i18n/mk.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Поврзете се {{provider}}", "provider.connect.method.apiKey": "клуч API", "provider.connect.status.inProgress": "Овластувањето е во тек…", - "provider.connect.status.waiting": "Се чека овластување…", + "provider.connect.status.waiting": "Се чека овластување", "provider.connect.status.failed": "Овластувањето не успеа: {{error}}", "provider.connect.apiKey.description": "Внесете го вашиот клуч {{provider}} API за да ја поврзете вашата сметка и да користите {{provider}} модели во OpenCode.", @@ -824,7 +824,6 @@ export const dict = { "workspace.delete.location": "Локација", "command.session.location.cycle": "Смени ја локацијата на сесијата", "dialog.provider.anthropic.note": "Директен пристап до моделите Claude преку API-клуч", - "provider.connect.title.anthropicProMax": "Најави се со Anthropic", "prompt.toast.uploading.cancelFile": "Откажи го поставувањето на {{filename}}", "prompt.toast.uploadFailed.title": "Поставувањето не успеа", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/mn.ts b/packages/app/src/runtime/i18n/mn.ts index cd4cde4c7cf1..59e95eb8c478 100644 --- a/packages/app/src/runtime/i18n/mn.ts +++ b/packages/app/src/runtime/i18n/mn.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Холбох {{provider}}", "provider.connect.method.apiKey": "API түлхүүр", "provider.connect.status.inProgress": "Зөвшөөрөл хийгдэж байна…", - "provider.connect.status.waiting": "Зөвшөөрөл хүлээж байна…", + "provider.connect.status.waiting": "Зөвшөөрөл хүлээж байна", "provider.connect.status.failed": "Зөвшөөрөл амжилтгүй болсон: {{error}}", "provider.connect.apiKey.description": "Бүртгэлээ холбохын тулд {{provider}} API түлхүүрээ оруулаад OpenCode-д {{provider}} загварыг ашиглана уу.", @@ -823,7 +823,6 @@ export const dict = { "workspace.delete.location": "Байршил", "command.session.location.cycle": "Сешний байршлыг солих", "dialog.provider.anthropic.note": "API түлхүүрээр Claude загваруудад шууд хандах", - "provider.connect.title.anthropicProMax": "Anthropic-оор нэвтрэх", "prompt.toast.uploading.cancelFile": "{{filename}} файлын байршуулалтыг цуцлах", "prompt.toast.uploadFailed.title": "Байршуулж чадсангүй", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/ms.ts b/packages/app/src/runtime/i18n/ms.ts index 34126b9cf00b..502172332821 100644 --- a/packages/app/src/runtime/i18n/ms.ts +++ b/packages/app/src/runtime/i18n/ms.ts @@ -148,10 +148,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Lihat 70+ lagi penyedia", "dialog.provider.viewAll": "Tunjukkan lebih banyak penyedia", "provider.connect.title": "Sambungkan {{provider}}", - "provider.connect.title.anthropicProMax": "Log masuk dengan Anthropic", "provider.connect.method.apiKey": "Kunci API", "provider.connect.status.inProgress": "Kebenaran sedang diproses…", - "provider.connect.status.waiting": "Menunggu kebenaran…", + "provider.connect.status.waiting": "Menunggu kebenaran", "provider.connect.status.failed": "Kebenaran gagal: {{error}}", "provider.connect.apiKey.description": "Masukkan kunci API {{provider}} anda untuk menghubungkan akaun anda dan menggunakan model {{provider}} dalam OpenCode.", diff --git a/packages/app/src/runtime/i18n/my.ts b/packages/app/src/runtime/i18n/my.ts index 0b08253185f2..1e26acb5cf69 100644 --- a/packages/app/src/runtime/i18n/my.ts +++ b/packages/app/src/runtime/i18n/my.ts @@ -149,10 +149,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "နောက်ထပ်ပံ့ပိုးပေးသူ 70+ ကိုကြည့်ပါ။", "dialog.provider.viewAll": "နောက်ထပ်ဝန်ဆောင်မှုပေးသူများကို ပြပါ။", "provider.connect.title": "{{provider}} ကို ချိတ်ဆက်ပါ။", - "provider.connect.title.anthropicProMax": "Anthropic ဖြင့် အကောင့်ဝင်ပါ", "provider.connect.method.apiKey": "API သော့", "provider.connect.status.inProgress": "ခွင့်ပြုချက် လုပ်ဆောင်နေသည်…", - "provider.connect.status.waiting": "ခွင့်ပြုချက်ကို စောင့်ဆိုင်းနေသည်…", + "provider.connect.status.waiting": "ခွင့်ပြုချက်ကို စောင့်ဆိုင်းနေသည်", "provider.connect.status.failed": "ခွင့်ပြုချက် မအောင်မြင်ပါ- {{error}}", "provider.connect.apiKey.description": "သင့်အကောင့်ကို ချိတ်ဆက်ရန်နှင့် OpenCode တွင် {{provider}} မော်ဒယ်များကို အသုံးပြုရန် သင်၏ {{provider}} API သော့ကို ထည့်သွင်းပါ။", diff --git a/packages/app/src/runtime/i18n/ne.ts b/packages/app/src/runtime/i18n/ne.ts index 9f7c98909520..99d47739e1e1 100644 --- a/packages/app/src/runtime/i18n/ne.ts +++ b/packages/app/src/runtime/i18n/ne.ts @@ -153,7 +153,7 @@ export const dict = { "provider.connect.title": "जडान गर्नुहोस् {{provider}}", "provider.connect.method.apiKey": "API कुञ्जी", "provider.connect.status.inProgress": "प्राधिकरण जारी छ…", - "provider.connect.status.waiting": "प्राधिकरणको लागि पर्खँदै…", + "provider.connect.status.waiting": "प्राधिकरणको लागि पर्खँदै", "provider.connect.status.failed": "प्राधिकरण असफल भयो: {{error}}", "provider.connect.apiKey.description": "आफ्नो खाता जडान गर्न आफ्नो {{provider}} API कुञ्जी प्रविष्ट गर्नुहोस् र OpenCode मा {{provider}} मोडेलहरू प्रयोग गर्नुहोस्।", @@ -825,7 +825,6 @@ export const dict = { "command.session.location.cycle": "सेसनको स्थान क्रमशः बदल्नुहोस्", "dialog.provider.anthropic.note": "API कुञ्जीमार्फत Claude मोडेलहरूमा प्रत्यक्ष पहुँच", - "provider.connect.title.anthropicProMax": "Anthropic मार्फत लगइन गर्नुहोस्", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "{{filename}} को अपलोड रद्द गर्नुहोस्", "prompt.toast.uploadFailed.title": "अपलोड असफल भयो", diff --git a/packages/app/src/runtime/i18n/nl.ts b/packages/app/src/runtime/i18n/nl.ts index afb416012707..39025144fc20 100644 --- a/packages/app/src/runtime/i18n/nl.ts +++ b/packages/app/src/runtime/i18n/nl.ts @@ -354,7 +354,7 @@ export const dict = { "provider.connect.title": "Verbinding maken met {{provider}}", "provider.connect.method.apiKey": "API-sleutel", "provider.connect.status.inProgress": "Autorisatie in behandeling…", - "provider.connect.status.waiting": "Wachten op autorisatie…", + "provider.connect.status.waiting": "Wachten op autorisatie", "provider.connect.status.failed": "Autorisatie mislukt: {{error}}", "provider.connect.apiKey.description": "Voer je {{provider}}-API-sleutel in om je account te koppelen en {{provider}}-modellen in OpenCode te gebruiken.", @@ -831,7 +831,6 @@ export const dict = { "session.background.moveInline": "Druk op {{keybind}} om actief werk naar de achtergrond te verplaatsen", "command.session.location.cycle": "Sessielocatie wisselen", "dialog.provider.anthropic.note": "Directe toegang tot Claude-modellen via een API-sleutel", - "provider.connect.title.anthropicProMax": "Inloggen met Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Upload van {{filename}} annuleren", "prompt.toast.uploadFailed.title": "Upload mislukt", diff --git a/packages/app/src/runtime/i18n/no.ts b/packages/app/src/runtime/i18n/no.ts index e3004fad5909..5d0c3c358261 100644 --- a/packages/app/src/runtime/i18n/no.ts +++ b/packages/app/src/runtime/i18n/no.ts @@ -356,11 +356,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Se over 70 flere leverandører", "dialog.provider.viewAll": "Vis flere leverandører", - "provider.connect.title": "Koble til {{provider}}", + "provider.connect.method.apiKey": "API-nøkkel", "provider.connect.status.inProgress": "Autorisering pågår…", - "provider.connect.status.waiting": "Venter på autorisering…", + "provider.connect.status.waiting": "Venter på autorisering", "provider.connect.status.failed": "Autorisering mislyktes: {{error}}", "provider.connect.apiKey.description": "Skriv inn API-nøkkelen din for {{provider}} for å koble til kontoen din og bruke {{provider}}-modeller i OpenCode.", @@ -888,7 +888,6 @@ export const dict = { "session.background.moveInline": "Trykk på {{keybind}} for å flytte pågående arbeid til bakgrunnen", "command.session.location.cycle": "Bytt øktplassering", "dialog.provider.anthropic.note": "Direkte tilgang til Claude-modeller via API-nøkkel", - "provider.connect.title.anthropicProMax": "Logg på med Anthropic", "prompt.toast.uploading.percent": "{{percent}} %", "prompt.toast.uploading.cancelFile": "Avbryt opplasting av {{filename}}", "prompt.toast.uploadFailed.title": "Opplasting mislyktes", diff --git a/packages/app/src/runtime/i18n/pa.ts b/packages/app/src/runtime/i18n/pa.ts index 42b7deda7b41..046f2f3804a8 100644 --- a/packages/app/src/runtime/i18n/pa.ts +++ b/packages/app/src/runtime/i18n/pa.ts @@ -153,10 +153,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "70+ ہور پرووائیڈر ویکھو", "dialog.provider.viewAll": "ہور پرووائیڈر وکھاؤ", "provider.connect.title": "\u2068{{provider}}\u2069 نال جڑو", - "provider.connect.title.anthropicProMax": "Anthropic دے نال لاگ ان کرو", "provider.connect.method.apiKey": "API کلید", "provider.connect.status.inProgress": "اختیار دیندے پئے آں…", - "provider.connect.status.waiting": "اختیار ملن دی اڈیک اے…", + "provider.connect.status.waiting": "اختیار ملن دی اڈیک اے", "provider.connect.status.failed": "اختیار نئیں مل سکیا: \u2068{{error}}\u2069", "provider.connect.apiKey.description": "اپنے اکاؤنٹ نوں جوڑن لئی اپنی \u2068{{provider}}\u2069 API کلید درج کرو تے OpenCode وچ \u2068{{provider}}\u2069 ماڈل ورتو۔", diff --git a/packages/app/src/runtime/i18n/pl.ts b/packages/app/src/runtime/i18n/pl.ts index 56f0548a6b03..c8693d872eff 100644 --- a/packages/app/src/runtime/i18n/pl.ts +++ b/packages/app/src/runtime/i18n/pl.ts @@ -153,7 +153,7 @@ export const dict = { "provider.connect.title": "Połącz {{provider}}", "provider.connect.method.apiKey": "Klucz API", "provider.connect.status.inProgress": "Autoryzacja w toku…", - "provider.connect.status.waiting": "Oczekiwanie na autoryzację…", + "provider.connect.status.waiting": "Oczekiwanie na autoryzację", "provider.connect.status.failed": "Autoryzacja nie powiodła się: {{error}}", "provider.connect.apiKey.description": "Wprowadź swój klucz API {{provider}}, aby połączyć konto i używać modeli {{provider}} w OpenCode.", @@ -858,7 +858,6 @@ export const dict = { "Spowoduje to trwałe usunięcie {{count}} drzew roboczych bez powiązanych sesji.", "command.session.location.cycle": "Zmień lokalizację sesji", "dialog.provider.anthropic.note": "Bezpośredni dostęp do modeli Claude za pomocą klucza API", - "provider.connect.title.anthropicProMax": "Zaloguj się przez Anthropic", "prompt.toast.uploading.cancelFile": "Anuluj przesyłanie pliku {{filename}}", "prompt.toast.uploadFailed.title": "Przesyłanie nie powiodło się", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/ro.ts b/packages/app/src/runtime/i18n/ro.ts index 2313851c63bf..5ef98a5d0a0d 100644 --- a/packages/app/src/runtime/i18n/ro.ts +++ b/packages/app/src/runtime/i18n/ro.ts @@ -148,7 +148,7 @@ export const dict = { "provider.connect.title": "Conectează {{provider}}", "provider.connect.method.apiKey": "Cheie API", "provider.connect.status.inProgress": "Autorizare în curs…", - "provider.connect.status.waiting": "Se așteaptă autorizarea…", + "provider.connect.status.waiting": "Se așteaptă autorizarea", "provider.connect.status.failed": "Autorizare eșuată: {{error}}", "provider.connect.apiKey.description": "Introdu cheia API {{provider}} pentru a-ți conecta contul și a folosi modelele {{provider}} în OpenCode.", @@ -835,7 +835,6 @@ export const dict = { "toast.migration.progress.working.progress": "Migrarea datelor {{current}}/{{total}}", "command.session.location.cycle": "Schimbă locația sesiunii", "dialog.provider.anthropic.note": "Acces direct la modelele Claude prin cheia API", - "provider.connect.title.anthropicProMax": "Autentificare cu Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Anulează încărcarea fișierului {{filename}}", "prompt.toast.uploadFailed.title": "Încărcarea a eșuat", diff --git a/packages/app/src/runtime/i18n/ru.ts b/packages/app/src/runtime/i18n/ru.ts index cd494bee79e9..b85c86cc98e3 100644 --- a/packages/app/src/runtime/i18n/ru.ts +++ b/packages/app/src/runtime/i18n/ru.ts @@ -159,11 +159,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Посмотреть ещё более 70 провайдеров", "dialog.provider.viewAll": "Показать больше провайдеров", - "provider.connect.title": "Подключить {{provider}}", + "provider.connect.method.apiKey": "Ключ API", "provider.connect.status.inProgress": "Авторизация…", - "provider.connect.status.waiting": "Ожидание авторизации…", + "provider.connect.status.waiting": "Ожидание авторизации", "provider.connect.status.failed": "Ошибка авторизации: {{error}}", "provider.connect.apiKey.description": "Введите ключ API {{provider}}, чтобы подключить аккаунт и использовать модели {{provider}} в OpenCode.", @@ -913,7 +913,6 @@ export const dict = { "Это навсегда удалит {{count}} рабочих деревьев без связанных сессий.", "command.session.location.cycle": "Сменить расположение сеанса", "dialog.provider.anthropic.note": "Прямой доступ к моделям Claude по API-ключу", - "provider.connect.title.anthropicProMax": "Войти через Anthropic", "prompt.toast.uploading.cancelFile": "Отменить загрузку файла {{filename}}", "prompt.toast.uploadFailed.title": "Не удалось загрузить файл", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/si.ts b/packages/app/src/runtime/i18n/si.ts index 9a771c6a2dee..209c83b43357 100644 --- a/packages/app/src/runtime/i18n/si.ts +++ b/packages/app/src/runtime/i18n/si.ts @@ -152,7 +152,7 @@ export const dict = { "provider.connect.title": "{{provider}} සම්බන්ධ කරන්න", "provider.connect.method.apiKey": "API යතුර", "provider.connect.status.inProgress": "අවසරය ක්‍රියාත්මක වෙමින් පවතී…", - "provider.connect.status.waiting": "අවසරය සඳහා රැඳී සිටිමින්…", + "provider.connect.status.waiting": "අවසරය සඳහා රැඳී සිටිමින්", "provider.connect.status.failed": "අවසරය අසාර්ථක විය: {{error}}", "provider.connect.apiKey.description": "ඔබගේ ගිණුම සම්බන්ධ කිරීමට ඔබගේ {{provider}} API යතුර ඇතුලත් කරන්න සහ OpenCode හි {{provider}} මාදිලි භාවිතා කරන්න.", @@ -820,7 +820,6 @@ export const dict = { "command.session.location.cycle": "සැසි ස්ථානය මාරුවෙන් මාරුවට වෙනස් කරන්න", "dialog.provider.anthropic.note": "API යතුරක් හරහා Claude මාදිලි වෙත සෘජු ප්‍රවේශය", - "provider.connect.title.anthropicProMax": "Anthropic සමඟ පිවිසෙන්න", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "{{filename}} ගොනුව උඩුගත කිරීම අවලංගු කරන්න", "prompt.toast.uploadFailed.title": "උඩුගත කිරීම අසාර්ථකයි", diff --git a/packages/app/src/runtime/i18n/sk.ts b/packages/app/src/runtime/i18n/sk.ts index d679074aef0f..05d51fea267e 100644 --- a/packages/app/src/runtime/i18n/sk.ts +++ b/packages/app/src/runtime/i18n/sk.ts @@ -174,7 +174,7 @@ export const dict = { "provider.connect.title": "Pripojiť {{provider}}", "provider.connect.method.apiKey": "API kľúč", "provider.connect.status.inProgress": "Prebieha autorizácia…", - "provider.connect.status.waiting": "Čaká sa na autorizáciu…", + "provider.connect.status.waiting": "Čaká sa na autorizáciu", "provider.connect.status.failed": "Autorizácia zlyhala: {{error}}", "provider.connect.apiKey.description": "Zadajte svoj API kľúč {{provider}}, aby ste prepojili svoj účet a mohli používať modely {{provider}} v OpenCode.", @@ -844,7 +844,6 @@ export const dict = { "workspace.delete.location": "Umiestnenie", "command.session.location.cycle": "Prepnúť umiestnenie relácie", "dialog.provider.anthropic.note": "Priamy prístup k modelom Claude pomocou kľúča API", - "provider.connect.title.anthropicProMax": "Prihlásiť sa cez Anthropic", "prompt.toast.uploading.cancelFile": "Zrušiť nahrávanie súboru {{filename}}", "prompt.toast.uploadFailed.title": "Nahrávanie zlyhalo", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/sl.ts b/packages/app/src/runtime/i18n/sl.ts index 900cac3c193d..6f4556d20768 100644 --- a/packages/app/src/runtime/i18n/sl.ts +++ b/packages/app/src/runtime/i18n/sl.ts @@ -174,7 +174,7 @@ export const dict = { "provider.connect.title": "Povežite {{provider}}", "provider.connect.method.apiKey": "Ključ API", "provider.connect.status.inProgress": "Avtorizacija v teku…", - "provider.connect.status.waiting": "Čakanje na avtorizacijo …", + "provider.connect.status.waiting": "Čakanje na avtorizacijo", "provider.connect.status.failed": "Avtorizacija ni uspela: {{error}}", "provider.connect.apiKey.description": "Vnesite ključ API ponudnika {{provider}}, da povežete račun in uporabljate modele {{provider}} v OpenCode.", @@ -844,7 +844,6 @@ export const dict = { "workspace.delete.location": "Lokacija", "command.session.location.cycle": "Zamenjaj lokacijo seje", "dialog.provider.anthropic.note": "Neposreden dostop do modelov Claude s ključem API", - "provider.connect.title.anthropicProMax": "Prijava prek Anthropic", "prompt.toast.uploading.cancelFile": "Prekliči nalaganje datoteke {{filename}}", "prompt.toast.uploadFailed.title": "Nalaganje ni uspelo", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/sq.ts b/packages/app/src/runtime/i18n/sq.ts index b9cbb184dd7f..0cffba4d1843 100644 --- a/packages/app/src/runtime/i18n/sq.ts +++ b/packages/app/src/runtime/i18n/sq.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Lidhni {{provider}}", "provider.connect.method.apiKey": "Tasti API", "provider.connect.status.inProgress": "Autorizimi në proces…", - "provider.connect.status.waiting": "Në pritje të autorizimit…", + "provider.connect.status.waiting": "Në pritje të autorizimit", "provider.connect.status.failed": "Autorizimi dështoi: {{error}}", "provider.connect.apiKey.description": "Futni çelësin API të {{provider}} për të lidhur llogarinë dhe për të përdorur modelet {{provider}} në OpenCode.", @@ -822,7 +822,6 @@ export const dict = { "toast.migration.progress.working.progress": "Migrimi i të dhënave {{current}}/{{total}}", "command.session.location.cycle": "Ndrysho vendndodhjen e sesionit", "dialog.provider.anthropic.note": "Qasje e drejtpërdrejtë te modelet Claude përmes çelësit API", - "provider.connect.title.anthropicProMax": "Hyr me Anthropic", "prompt.toast.uploading.percent": "{{percent}}%", "prompt.toast.uploading.cancelFile": "Anulo ngarkimin e {{filename}}", "prompt.toast.uploadFailed.title": "Ngarkimi dështoi", diff --git a/packages/app/src/runtime/i18n/sr.ts b/packages/app/src/runtime/i18n/sr.ts index 0af207f57e8e..4cafd59b5504 100644 --- a/packages/app/src/runtime/i18n/sr.ts +++ b/packages/app/src/runtime/i18n/sr.ts @@ -162,7 +162,7 @@ export const dict = { "provider.connect.title": "Повежи {{provider}}", "provider.connect.method.apiKey": "API кључ", "provider.connect.status.inProgress": "Ауторизација је у току…", - "provider.connect.status.waiting": "Чека се ауторизација…", + "provider.connect.status.waiting": "Чека се ауторизација", "provider.connect.status.failed": "Ауторизација није успела: {{error}}", "provider.connect.apiKey.description": "Унесите свој {{provider}} API кључ да бисте повезали свој налог и користили {{provider}} моделе у OpenCode.", @@ -831,7 +831,6 @@ export const dict = { "workspace.delete.location": "Локација", "command.session.location.cycle": "Промени локацију сесије", "dialog.provider.anthropic.note": "Директан приступ Claude моделима путем API кључа", - "provider.connect.title.anthropicProMax": "Пријави се преко Anthropic-а", "prompt.toast.uploading.cancelFile": "Откажи отпремање датотеке {{filename}}", "prompt.toast.uploadFailed.title": "Отпремање није успело", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/sv.ts b/packages/app/src/runtime/i18n/sv.ts index b95f8dd25a76..10e181f93543 100644 --- a/packages/app/src/runtime/i18n/sv.ts +++ b/packages/app/src/runtime/i18n/sv.ts @@ -348,7 +348,7 @@ export const dict = { "provider.connect.title": "Anslut {{provider}}", "provider.connect.method.apiKey": "API-nyckel", "provider.connect.status.inProgress": "Auktorisering pågår…", - "provider.connect.status.waiting": "Väntar på auktorisering…", + "provider.connect.status.waiting": "Väntar på auktorisering", "provider.connect.status.failed": "Auktorisering misslyckades: {{error}}", "provider.connect.apiKey.description": "Ange din {{provider}}-API-nyckel för att ansluta ditt konto och använda {{provider}}-modeller i OpenCode.", @@ -821,7 +821,6 @@ export const dict = { "session.background.moveInline": "Tryck på {{keybind}} för att flytta pågående arbete till bakgrunden", "command.session.location.cycle": "Växla sessionsplats", "dialog.provider.anthropic.note": "Direktåtkomst till Claude-modeller via API-nyckel", - "provider.connect.title.anthropicProMax": "Logga in med Anthropic", "prompt.toast.uploading.percent": "{{percent}} %", "prompt.toast.uploading.cancelFile": "Avbryt uppladdningen av {{filename}}", "prompt.toast.uploadFailed.title": "Uppladdningen misslyckades", diff --git a/packages/app/src/runtime/i18n/tg.ts b/packages/app/src/runtime/i18n/tg.ts index 86eb11a0eee5..09acd9a85ca8 100644 --- a/packages/app/src/runtime/i18n/tg.ts +++ b/packages/app/src/runtime/i18n/tg.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "Пайвастшавӣ {{provider}}", "provider.connect.method.apiKey": "API калид", "provider.connect.status.inProgress": "Иҷозатдиҳӣ идома дорад…", - "provider.connect.status.waiting": "Мунтазири иҷозат…", + "provider.connect.status.waiting": "Мунтазири иҷозат", "provider.connect.status.failed": "Иҷозат дода нашуд: {{error}}", "provider.connect.apiKey.description": "Барои пайваст кардани ҳисоби худ калиди {{provider}} API-ро ворид кунед ва моделҳои {{provider}}-ро дар OpenCode истифода баред.", @@ -829,7 +829,6 @@ export const dict = { "workspace.delete.location": "Ҷойгиршавӣ", "command.session.location.cycle": "Ҷойгиршавии сессияро иваз кунед", "dialog.provider.anthropic.note": "Дастрасии мустақим ба моделҳои Claude тавассути калиди API", - "provider.connect.title.anthropicProMax": "Бо Anthropic ворид шавед", "prompt.toast.uploading.cancelFile": "Боркунии файли {{filename}}-ро бекор кунед", "prompt.toast.uploadFailed.title": "Боркунӣ ноком шуд", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/th.ts b/packages/app/src/runtime/i18n/th.ts index 194977598fb4..6e7b1f354103 100644 --- a/packages/app/src/runtime/i18n/th.ts +++ b/packages/app/src/runtime/i18n/th.ts @@ -161,12 +161,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "ดูผู้ให้บริการเพิ่มเติมกว่า 70 ราย", "dialog.provider.viewAll": "แสดงผู้ให้บริการเพิ่มเติม", - "provider.connect.title": "เชื่อมต่อ {{provider}}", - "provider.connect.title.anthropicProMax": "เข้าสู่ระบบ Anthropic", + "provider.connect.method.apiKey": "คีย์ API", "provider.connect.status.inProgress": "กำลังอนุญาต…", - "provider.connect.status.waiting": "รอการอนุญาต…", + "provider.connect.status.waiting": "รอการอนุญาต", "provider.connect.status.failed": "การอนุญาตล้มเหลว: {{error}}", "provider.connect.apiKey.description": "ป้อนคีย์ API ของ {{provider}} เพื่อเชื่อมต่อบัญชีและใช้โมเดล {{provider}} ใน OpenCode", diff --git a/packages/app/src/runtime/i18n/tk.ts b/packages/app/src/runtime/i18n/tk.ts index c3f0c74dadbe..deb1ce00d685 100644 --- a/packages/app/src/runtime/i18n/tk.ts +++ b/packages/app/src/runtime/i18n/tk.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "{{provider}} birikdiriň", "provider.connect.method.apiKey": "API açary", "provider.connect.status.inProgress": "Ygtyýarnama dowam edýär …", - "provider.connect.status.waiting": "Ygtyýarnama garaşýarys …", + "provider.connect.status.waiting": "Ygtyýarnama garaşýarys", "provider.connect.status.failed": "Ygtyýarnama şowsuz: {{error}}", "provider.connect.apiKey.description": "Hasabyňyzy birikdirmek we OpenCode-da {{provider}} modellerini ulanmak üçin {{provider}} API açaryňyzy giriziň.", @@ -815,7 +815,6 @@ export const dict = { "workspace.delete.location": "Ýerleşiş", "command.session.location.cycle": "Sessiýanyň ýerleşýän ýerini üýtget", "dialog.provider.anthropic.note": "API açary bilen Claude modellerine göni giriş", - "provider.connect.title.anthropicProMax": "Anthropic arkaly giriň", "prompt.toast.uploading.cancelFile": "{{filename}} faýlynyň ýüklenmegini ýatyr", "prompt.toast.uploadFailed.title": "Ýükleme şowsuz boldy", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/tr.ts b/packages/app/src/runtime/i18n/tr.ts index e8dea6e6f0c8..6b047ea66077 100644 --- a/packages/app/src/runtime/i18n/tr.ts +++ b/packages/app/src/runtime/i18n/tr.ts @@ -171,11 +171,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "70'ten fazla sağlayıcı daha görüntüle", "dialog.provider.viewAll": "Daha fazla sağlayıcı göster", - "provider.connect.title": "{{provider}} bağla", + "provider.connect.method.apiKey": "API anahtarı", "provider.connect.status.inProgress": "Yetkilendirme devam ediyor…", - "provider.connect.status.waiting": "Yetkilendirme bekleniyor…", + "provider.connect.status.waiting": "Yetkilendirme bekleniyor", "provider.connect.status.failed": "Yetkilendirme başarısız: {{error}}", "provider.connect.apiKey.description": "{{provider}} hesabınızı bağlamak ve OpenCode'da {{provider}} modellerini kullanmak için API anahtarınızı girin.", @@ -895,7 +895,6 @@ export const dict = { "toast.migration.progress.working.progress": "Veriler taşınıyor {{current}}/{{total}}", "command.session.location.cycle": "Oturum konumunu değiştir", "dialog.provider.anthropic.note": "API anahtarıyla Claude modellerine doğrudan erişim", - "provider.connect.title.anthropicProMax": "Anthropic ile giriş yap", "prompt.toast.uploading.percent": "%{{percent}}", "prompt.toast.uploading.cancelFile": "{{filename}} yüklemesini iptal et", "prompt.toast.uploadFailed.title": "Yükleme başarısız", diff --git a/packages/app/src/runtime/i18n/uk.ts b/packages/app/src/runtime/i18n/uk.ts index c3c7b9a01b45..5d9082e8de3d 100644 --- a/packages/app/src/runtime/i18n/uk.ts +++ b/packages/app/src/runtime/i18n/uk.ts @@ -186,11 +186,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Переглянути ще понад 70 провайдерів", "dialog.provider.viewAll": "Показати більше провайдерів", - "provider.connect.title": "Підключити {{provider}}", + "provider.connect.method.apiKey": "Ключ API", "provider.connect.status.inProgress": "Авторизація виконується…", - "provider.connect.status.waiting": "Очікування авторизації…", + "provider.connect.status.waiting": "Очікування авторизації", "provider.connect.status.failed": "Авторизація не вдалася: {{error}}", "provider.connect.apiKey.description": "Введіть ключ API {{provider}}, щоб підключити обліковий запис і використовувати моделі {{provider}} у OpenCode.", @@ -912,7 +912,6 @@ export const dict = { "workspace.delete.location": "Розташування", "command.session.location.cycle": "Змінити розташування сеансу", "dialog.provider.anthropic.note": "Прямий доступ до моделей Claude за допомогою ключа API", - "provider.connect.title.anthropicProMax": "Увійти через Anthropic", "prompt.toast.uploading.cancelFile": "Скасувати завантаження файлу {{filename}}", "prompt.toast.uploadFailed.title": "Не вдалося завантажити файл", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/ur.ts b/packages/app/src/runtime/i18n/ur.ts index 897ed4cfd683..f1cac074fcd2 100644 --- a/packages/app/src/runtime/i18n/ur.ts +++ b/packages/app/src/runtime/i18n/ur.ts @@ -154,10 +154,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "مزید 70 فراہم کنندگان دیکھیں", "dialog.provider.viewAll": "مزید فراہم کنندگان دکھائیں۔", "provider.connect.title": "\u2068{{provider}}\u2069 سے منسلک ہوں", - "provider.connect.title.anthropicProMax": "Anthropic کے ساتھ لاگ ان کریں", "provider.connect.method.apiKey": "API کلید", "provider.connect.status.inProgress": "اجازت حاصل کی جا رہی ہے…", - "provider.connect.status.waiting": "اجازت کا انتظار ہے…", + "provider.connect.status.waiting": "اجازت کا انتظار ہے", "provider.connect.status.failed": "اجازت حاصل نہیں ہو سکی: \u2068{{error}}\u2069", "provider.connect.apiKey.description": "اپنا اکاؤنٹ منسلک کرنے اور OpenCode میں \u2068{{provider}}\u2069 ماڈلز استعمال کرنے کے لیے اپنی \u2068{{provider}}\u2069 API کلید درج کریں۔", diff --git a/packages/app/src/runtime/i18n/uz.ts b/packages/app/src/runtime/i18n/uz.ts index 3f7a69d85810..8efef2d52f2c 100644 --- a/packages/app/src/runtime/i18n/uz.ts +++ b/packages/app/src/runtime/i18n/uz.ts @@ -149,7 +149,7 @@ export const dict = { "provider.connect.title": "{{provider}} ni ulang", "provider.connect.method.apiKey": "API kaliti", "provider.connect.status.inProgress": "Avtorizatsiya davom etmoqda…", - "provider.connect.status.waiting": "Avtorizatsiya kutilmoqda…", + "provider.connect.status.waiting": "Avtorizatsiya kutilmoqda", "provider.connect.status.failed": "Avtorizatsiya amalga oshmadi: {{error}}", "provider.connect.apiKey.description": "Hisobingizni ulash va OpenCode’da {{provider}} modellaridan foydalanish uchun {{provider}} API kalitini kiriting.", @@ -826,7 +826,6 @@ export const dict = { "workspace.delete.location": "Joylashuv", "command.session.location.cycle": "Sessiya joylashuvini almashtirish", "dialog.provider.anthropic.note": "API kaliti orqali Claude modellariga bevosita kirish", - "provider.connect.title.anthropicProMax": "Anthropic orqali kirish", "prompt.toast.uploading.cancelFile": "{{filename}} faylini yuklashni bekor qilish", "prompt.toast.uploadFailed.title": "Yuklash amalga oshmadi", "prompt.toast.uploading.percent": "{{percent}}%", diff --git a/packages/app/src/runtime/i18n/vi.ts b/packages/app/src/runtime/i18n/vi.ts index 9734339b967b..2e68e1a7d389 100644 --- a/packages/app/src/runtime/i18n/vi.ts +++ b/packages/app/src/runtime/i18n/vi.ts @@ -153,10 +153,9 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "Xem hơn 70 nhà cung cấp khác", "dialog.provider.viewAll": "Hiển thị thêm nhà cung cấp", "provider.connect.title": "Kết nối {{provider}}", - "provider.connect.title.anthropicProMax": "Đăng nhập bằng Anthropic", "provider.connect.method.apiKey": "Khóa API", "provider.connect.status.inProgress": "Đang ủy quyền…", - "provider.connect.status.waiting": "Đang chờ ủy quyền…", + "provider.connect.status.waiting": "Đang chờ ủy quyền", "provider.connect.status.failed": "Ủy quyền thất bại: {{error}}", "provider.connect.apiKey.description": "Nhập khóa API {{provider}} để kết nối tài khoản và sử dụng các mô hình {{provider}} trong OpenCode.", diff --git a/packages/app/src/runtime/i18n/zh.ts b/packages/app/src/runtime/i18n/zh.ts index 5a74cec90be2..62a3d92be2f4 100644 --- a/packages/app/src/runtime/i18n/zh.ts +++ b/packages/app/src/runtime/i18n/zh.ts @@ -181,12 +181,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "查看另外 70 多个提供商", "dialog.provider.viewAll": "查看更多提供商", - "provider.connect.title": "连接 {{provider}}", - "provider.connect.title.anthropicProMax": "登录 Anthropic", + "provider.connect.method.apiKey": "API 密钥", "provider.connect.status.inProgress": "正在授权…", - "provider.connect.status.waiting": "等待授权…", + "provider.connect.status.waiting": "等待授权", "provider.connect.status.failed": "授权失败:{{error}}", "provider.connect.apiKey.description": "输入你的 {{provider}} API 密钥以连接账户,并在 OpenCode 中使用 {{provider}} 模型。", diff --git a/packages/app/src/runtime/i18n/zht.ts b/packages/app/src/runtime/i18n/zht.ts index 1281637d2c8f..8cf25daaafd3 100644 --- a/packages/app/src/runtime/i18n/zht.ts +++ b/packages/app/src/runtime/i18n/zht.ts @@ -165,12 +165,11 @@ export const dict = { "dialog.model.unpaid.viewMoreProviders": "查看另外 70 多個提供者", "dialog.provider.viewAll": "查看更多提供者", - "provider.connect.title": "連線 {{provider}}", - "provider.connect.title.anthropicProMax": "登入 Anthropic", + "provider.connect.method.apiKey": "API 金鑰", "provider.connect.status.inProgress": "正在授權…", - "provider.connect.status.waiting": "等待授權…", + "provider.connect.status.waiting": "等待授權", "provider.connect.status.failed": "授權失敗: {{error}}", "provider.connect.apiKey.description": "輸入你的 {{provider}} API 金鑰以連線帳戶,並在 OpenCode 中使用 {{provider}} 模型。", diff --git a/packages/app/src/runtime/plugin/dialogs.stories.tsx b/packages/app/src/runtime/plugin/dialogs.stories.tsx index 0017cdc8751c..2f757a46a69a 100644 --- a/packages/app/src/runtime/plugin/dialogs.stories.tsx +++ b/packages/app/src/runtime/plugin/dialogs.stories.tsx @@ -4,28 +4,33 @@ import { onMount } from "solid-js" import { createStore } from "solid-js/store" import { PluginSelectDialog } from "./dialogs" -function PluginSelectStory() { +type Args = { optionCount: number; grouped: boolean; descriptions: boolean } + +function PluginSelectStory(props: Args) { const dialog = useDialog() + const [store, setStore] = createStore({ selected: "Nothing selected" }) + const destinations = [ + { title: "Design notes", description: "Research and references", group: "Recent", value: "design" }, + { title: "Project roadmap", description: "Upcoming milestones", group: "Recent", value: "roadmap" }, + { title: "Engineering", description: "Implementation and architecture", group: "Teams", value: "engineering" }, + { title: "Product", description: "Planning and feedback", group: "Teams", value: "product" }, + { title: "Support", description: "Customer questions", group: "Teams", value: "support" }, + ] + const open = () => dialog.show(() => ( ({ + ...item, + group: props.grouped ? item.group : undefined, + description: props.descriptions ? item.description : undefined, + })), }} done={(value) => { setStore("selected", value ?? "Selection dismissed") @@ -49,8 +54,13 @@ function PluginSelectStory() { export default { title: "App/Dialogs/Plugin Selection", id: "app-dialog-plugin-selection", + args: { optionCount: 5, grouped: true, descriptions: true } satisfies Args, + argTypes: { optionCount: { control: { type: "range", min: 0, max: 5, step: 1 } } }, + render: (args: Args) => , } -export const Default = { - render: () => , -} +export const Default = {} + +export const TitlesOnly = { args: { grouped: false, descriptions: false } } + +export const NoDestinations = { args: { optionCount: 0 } } diff --git a/packages/app/src/runtime/plugin/titlebar-items.stories.tsx b/packages/app/src/runtime/plugin/titlebar-items.stories.tsx index 83e3400d4bed..90ec690d5949 100644 --- a/packages/app/src/runtime/plugin/titlebar-items.stories.tsx +++ b/packages/app/src/runtime/plugin/titlebar-items.stories.tsx @@ -1,58 +1,97 @@ -import { For } from "solid-js" +import { createEffect, createSignal, For, Show } from "solid-js" import type { TitlebarItem } from "@opencode/plugin/gui" import { TitlebarItems } from "./titlebar-items" -const catalogs = import.meta.glob<{ default: Record }>( - "../../../../gui-plugins/src/updater/i18n/*.ts", - { eager: true }, -) +type Labels = { "status.label": string; "action.installRestart": string; "action.installing": string } + +const catalogs = import.meta.glob<{ default: Labels }>("../../../../gui-plugins/src/updater/i18n/*.ts", { eager: true }) const rtl = new Set(["ar", "dv", "fa", "he", "ur"]) const locales = Object.entries(catalogs) .map(([file, module]) => ({ locale: file.split("/").pop()!.replace(".ts", ""), - label: module.default["status.label"]!, + labels: module.default, })) .sort((a, b) => a.locale.localeCompare(b.locale)) -const items = (label: string) => { - const item: TitlebarItem = { id: "update", label, run: () => {} } +const actions = ["label only", "install", "installing", "toggle off", "toggle on"] as const - return { ids: () => [item.id], item: () => item } -} +type Args = { locale: string; layout: string; action: (typeof actions)[number]; label: string } export default { title: "App/Titlebar/Items", id: "app-titlebar-items", component: TitlebarItems, -} - -/** The update pill in every updater locale; hover or focus a pill to expand its label. */ -export const UpdateLabels = { - render: () => ( + args: { locale: "all", layout: "both", action: "label only", label: "" }, + argTypes: { + locale: { options: ["all", ...locales.map((entry) => entry.locale)] }, + layout: { options: ["both", "horizontal", "vertical"] }, + action: { options: actions }, + }, + render: (args: Args) => (
- - {(entry) => ( -
- {entry.locale} -
-
- -
-
-
- + args.locale === "all" || args.locale === entry.locale)}> + {(entry) => { + const [action, setAction] = createSignal(args.action) + createEffect(() => setAction(args.action)) + + const toggle = () => action() === "toggle on" || action() === "toggle off" + + const item = (): TitlebarItem => ({ + id: "update", + label: args.label || entry.labels["status.label"], + get title() { + if (action() === "installing") return entry.labels["action.installing"] + + if (action() === "install") return entry.labels["action.installRestart"] + }, + busy: action() === "installing", + icon: toggle() ? "terminal" : undefined, + pressed: toggle() ? action() === "toggle on" : undefined, + run: () => { + if (action() === "install") return setAction("installing") + + if (toggle()) setAction(action() === "toggle on" ? "toggle off" : "toggle on") + }, + }) + + const items = { ids: () => ["update"], item } + + return ( +
+ {entry.locale} + +
+
+ +
+
+
+ +
+ +
+
-
- )} + ) + }}
), } + +/** The update pill in every updater locale; hover or focus a pill to expand its label. */ +export const UpdateLabels = {} + +export const ReadyToInstall = { args: { locale: "en", action: "install", layout: "horizontal" } } + +export const Installing = { args: { locale: "en", action: "installing" } } + +export const Pressed = { args: { locale: "en", layout: "vertical", action: "toggle on", label: "Terminal" } } diff --git a/packages/app/src/servers/registry/row.stories.tsx b/packages/app/src/servers/registry/row.stories.tsx index ae5e419ac1df..f69f31c8f855 100644 --- a/packages/app/src/servers/registry/row.stories.tsx +++ b/packages/app/src/servers/registry/row.stories.tsx @@ -15,12 +15,14 @@ const states: { label: string; health?: ServerHealth }[] = [ { label: "Not checked" }, ] -export default { title: "App/Servers/Health indicator", id: "app-server-health" } - -export const States = { - render: () => ( +export default { + title: "App/Servers/Health indicator", + id: "app-server-health", + args: { health: "All" }, + argTypes: { health: { options: ["All", ...states.map((state) => state.label)] } }, + render: (args: { health: string }) => (
- + args.health === "All" || args.health === state.label)}> {(state) => (
@@ -33,3 +35,17 @@ export const States = {
), } + +export const States = {} + +export const Authentication = { args: { health: "Waiting for sign-in" } } + +export const Connecting = { args: { health: "Connecting" } } + +export const Connected = { args: { health: "Connected" } } + +export const Unreachable = { args: { health: "Failed" } } + +export const Incompatible = { args: { health: "Incompatible" } } + +export const Unknown = { args: { health: "Not checked" } } diff --git a/packages/app/src/session/commands/fork-dialog.stories.tsx b/packages/app/src/session/commands/fork-dialog.stories.tsx index ebea73c255d4..ef467f69f91b 100644 --- a/packages/app/src/session/commands/fork-dialog.stories.tsx +++ b/packages/app/src/session/commands/fork-dialog.stories.tsx @@ -4,8 +4,11 @@ import { onMount } from "solid-js" import { createStore } from "solid-js/store" import { ForkDialog } from "./fork-dialog" -function ForkDialogStory() { +type Args = { messageCount: number; forking: boolean } + +function ForkDialogStory(props: Args) { const dialog = useDialog() + const [store, setStore] = createStore({ selected: "No message selected" }) const messages = [ @@ -28,7 +31,9 @@ function ForkDialogStory() { const open = () => dialog.show(() => ( 0} + pendingMessageID={props.forking && props.messageCount > 0 ? messages[0].id : undefined} onSelect={(messageID) => { setStore("selected", messageID) dialog.close() @@ -51,8 +56,13 @@ function ForkDialogStory() { export default { title: "App/Dialogs/Fork Session", id: "app-dialog-fork-session", + args: { messageCount: 8, forking: false } satisfies Args, + argTypes: { messageCount: { control: { type: "range", min: 0, max: 8, step: 1 } } }, + render: (args: Args) => , } -export const Default = { - render: () => , -} +export const Default = {} + +export const NoMessages = { args: { messageCount: 0 } } + +export const Forking = { args: { forking: true } } diff --git a/packages/app/src/session/commands/jump-to-message.stories.tsx b/packages/app/src/session/commands/jump-to-message.stories.tsx index ea0fb8b8fbb9..7dd4c60c1195 100644 --- a/packages/app/src/session/commands/jump-to-message.stories.tsx +++ b/packages/app/src/session/commands/jump-to-message.stories.tsx @@ -1,10 +1,18 @@ import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" import { Keybind } from "@opencode/ui/keybind" -import { For, onMount, Show } from "solid-js" +import { createEffect, createSignal, For, on, onMount, Show } from "solid-js" import { useLanguage } from "@/runtime/i18n/language" import { formatKeybindParts, matchKeybind, parseKeybind } from "@/shell/commands/command" import { JumpToMessage } from "./jump-to-message" +import { + selectJumpHistory, + selectJumpOpening, + selectJumpStatus, + transitionJumpToMessage, + type JumpToMessageEvent, + type JumpToMessageState, +} from "./jump-to-message-machine" const shortcut = "mod+alt+g" @@ -48,12 +56,28 @@ const turns = [ reply, })) -function SessionStory(props: { query?: string; empty?: boolean; failed?: boolean }) { +const scenes = ["browse", "closed", "empty", "loading", "failed", "paged", "opening", "openFailed"] as const + +type Args = { scene: (typeof scenes)[number]; query: string } + +const recent = turns.slice(4) + +const older = turns.slice(0, 4) + +function snapshot(scene: Args["scene"], history: typeof turns): JumpToMessageState { + if (scene === "loading" || scene === "failed") return { status: scene, attempt: 1 } + + if (scene === "opening") return { status: "opening", history, target: older[0]!.id, attempt: 2 } + + return { status: "ready", history, failed: scene === "openFailed", attempt: 1 } +} + +function SessionStory(props: Args) { const language = useLanguage() const dialog = useDialog() - const prompts = () => (props.empty ? [] : turns) + const [prompts, setPrompts] = createSignal(turns) const bubbles = new Map() @@ -61,30 +85,78 @@ function SessionStory(props: { query?: string; empty?: boolean; failed?: boolean let transcript!: HTMLDivElement - const open = (query = "") => - dialog.show(() => ( - dialog.close() : undefined} - onClose={() => dialog.close()} - onJump={(prompt) => { - dialog.close() - const bubble = bubbles.get(prompt.id) - bubble?.focus({ preventScroll: true }) - bubble?.scrollIntoView({ block: "center", inline: "nearest" }) - }} - /> - )) + const open = () => + dialog.show(() => { + const history = prompts() === recent ? older : [] + + const [state, setState] = createSignal(snapshot(props.scene, history)) + + const status = () => { + const note = selectJumpStatus(state()) + + return note && language.t(`dialog.jump.${note}`) + } + + const dispatch = (event: JumpToMessageEvent) => { + const next = transitionJumpToMessage(state(), event) + setState(next.state) + + for (const effect of next.effects) { + if (effect.type === "history.load") dispatch({ type: "history.loaded", attempt: effect.attempt, history }) + + if (effect.type === "open.load") { + setPrompts(turns) + dispatch({ type: "opened", attempt: effect.attempt }) + } + + if (effect.type === "jump") { + dialog.close() + const bubble = bubbles.get(effect.id) + bubble?.focus({ preventScroll: true }) + bubble?.scrollIntoView({ block: "center", inline: "nearest" }) + } + } + } + + const [query, setQuery] = createSignal(props.query) + createEffect(() => setQuery(props.query)) + + return ( + dispatch({ type: "retry" }) : undefined} + onClose={() => dialog.close()} + onJump={(row) => + dispatch({ type: "selected", id: row.id, loaded: prompts().some((turn) => turn.id === row.id) }) + } + /> + ) + }) onMount(() => { transcript.scrollTop = transcript.scrollHeight session.focus({ preventScroll: true }) - - void open(props.query) }) + createEffect( + on([() => props.scene, () => props.query], ([scene], previous) => { + if (previous?.[0] === scene) { + if (!dialog.active && scene !== "closed") void open() + + return + } + + setPrompts(scene === "empty" ? [] : scene === "browse" || scene === "closed" ? turns : recent) + + if (scene === "closed") return dialog.close() + void open() + }), + ) + return (
, + args: { scene: "browse", query: "" }, + argTypes: { scene: { options: scenes } }, parameters: { layout: "fullscreen" }, } -export const Browse = { render: () => } +export const Browse = {} + +export const MultilineMatch = { args: { query: "loading dock" } } -export const MultilineMatch = { render: () => } +export const Empty = { args: { scene: "empty" } } -export const Empty = { render: () => } +export const HistoryFailed = { args: { scene: "failed" } } -export const HistoryFailed = { render: () => } +export const NoMatches = { args: { query: "missing bookmark" } } -export const NoMatches = { render: () => } +export const MixedDirection = { args: { query: "ليلى" } } diff --git a/packages/app/src/session/commands/jump-to-message.tsx b/packages/app/src/session/commands/jump-to-message.tsx index 0eb8ff7d6397..f63a28f4bc7a 100644 --- a/packages/app/src/session/commands/jump-to-message.tsx +++ b/packages/app/src/session/commands/jump-to-message.tsx @@ -16,6 +16,8 @@ export type JumpPrompt = { id: string; text: string; created: number } export function JumpToMessage(props: { prompts: JumpPrompt[] initialQuery?: string + query?: string + onQuery?: (value: string) => void status?: string opening?: boolean onJump: (prompt: JumpPrompt) => void @@ -24,7 +26,14 @@ export function JumpToMessage(props: { }) { const language = useLanguage() - const [query, setQuery] = createSignal(props.initialQuery ?? "") + const [localQuery, setLocalQuery] = createSignal(props.initialQuery ?? "") + + const query = () => props.query ?? localQuery() + + const setQuery = (value: string) => { + if (props.query === undefined) setLocalQuery(value) + props.onQuery?.(value) + } const timestamp = createMemo( () => diff --git a/packages/app/src/session/composer/activity-chips.stories.tsx b/packages/app/src/session/composer/activity-chips.stories.tsx index c65b17ab7dc3..24196d58074a 100644 --- a/packages/app/src/session/composer/activity-chips.stories.tsx +++ b/packages/app/src/session/composer/activity-chips.stories.tsx @@ -9,8 +9,7 @@ import { subagentReport, } from "@opencode/session-ui/storybook" import { timelinePresets } from "@opencode/session-ui/timeline/detail" -import { createEffect, createMemo, on, onCleanup, onMount } from "solid-js" -import { createStore } from "solid-js/store" +import { createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js" import { SessionPreview } from "@/session/story-model" import type { SessionActivityItem } from "./activity-chips" @@ -188,16 +187,26 @@ function liveDocument(stage: Stage): SessionDocument { } // Scripted with `activity-story-stage` events on `document` so a recording can step through the work. -function LiveActivity() { - const [story, setStory] = createStore({ stage: 0 }) - const stage = createMemo(() => stages[story.stage]) - const value = createMemo(() => liveDocument(stage())) +function LiveActivity(props: PreviewArgs) { + const [recorded, setRecorded] = createSignal() + const value = createMemo(() => liveDocument(recorded() ?? stages[props.stage] ?? stages[0])) + + createEffect( + on( + () => [props.stage, props.subagents, props.shells], + () => setRecorded(undefined), + { defer: true }, + ), + ) onMount(() => { const step = (event: Event) => { if (!(event instanceof CustomEvent)) return - setStory("stage", Number(event.detail)) + const stage = stages[Number(event.detail)] + + if (!stage) return + setRecorded(stage) pin("smooth") } @@ -213,12 +222,12 @@ function LiveActivity() { document={value()} timelineDetail={timelineDetail} activity={{ - subagents: subagents - .slice(stage().finished, stage().started) - .map((_, index) => subagentItem(index + stage().finished)), - shells: shells - .slice(stage().finishedShells, stage().shells) - .map((_, index) => shellItem(index + stage().finishedShells)), + subagents: Array.from({ length: recorded()?.started ?? props.subagents }, (_, index) => + subagentItem(index), + ).slice(recorded()?.finished ?? 0), + shells: Array.from({ length: recorded()?.shells ?? props.shells }, (_, index) => shellItem(index)).slice( + recorded()?.finishedShells ?? 0, + ), onOpen: (item) => { // The preview has no child route, so show the launch in its timeline. const part = document.querySelector( @@ -268,4 +277,4 @@ export const SubagentsAndShells = { args: { stage: 4, subagents: 2, shells: 2 } export const ManySubagents = { args: { stage: 4, subagents: 12, shells: 2 } } -export const Live = { render: () => } +export const Live = { render: (args: PreviewArgs) => } diff --git a/packages/app/src/session/composer/composer-docks.stories.tsx b/packages/app/src/session/composer/composer-docks.stories.tsx index 08956b435966..f11579ceb764 100644 --- a/packages/app/src/session/composer/composer-docks.stories.tsx +++ b/packages/app/src/session/composer/composer-docks.stories.tsx @@ -21,7 +21,9 @@ import { SubagentBar } from "./subagent-bar" type DockArgs = { question: boolean permission: boolean + responding: boolean websearch: boolean + providers: "ready" | "loading" | "loadFailed" | "empty" queue: number subagent: boolean } @@ -64,16 +66,25 @@ function ComposerDocksPreview(props: DockArgs) { const dequeue = (id: string) => setState("rows", (rows) => rows.filter((index) => `queued_${index}` !== id)) + // Keep a dismissed request closed when an unrelated inspector field changes. + for (const key of ["question", "permission", "websearch", "subagent"] as const) { + createEffect( + on( + () => props[key], + (value) => setState(key, value), + { defer: true }, + ), + ) + } + createEffect( on( - () => [props.question, props.permission, props.websearch, props.queue, props.subagent] as const, - ([question, permission, websearch, queue, subagent]) => { - setState({ question, permission, websearch, subagent }) - queueTo(queue) - }, + () => props.providers, + (value) => setState("providers", value), { defer: true }, ), ) + createEffect(on(() => props.queue, queueTo, { defer: true })) const replay = (id: string, label: string, run: () => void) => onCleanup(motionTuning.action({ id: `docks.${id}`, label, group: "Composer", subsection: "Docks", run })) @@ -115,25 +126,28 @@ function ComposerDocksPreview(props: DockArgs) { state.question ? { ...activeQuestionRequest, id: `${activeQuestionRequest.id}:${state.revision}` } : undefined, websearch: { request: () => (state.websearch ? websearchRequest : undefined), - options: () => [ - { value: "exa", label: "Exa" }, - { value: "parallel", label: "Parallel" }, - ], + options: () => + state.providers !== "ready" + ? [] + : [ + { value: "exa", label: "Exa" }, + { value: "parallel", label: "Parallel" }, + ], selected: () => state.searchProvider, specific: () => false, - loading: () => false, - loadFailed: () => false, + loading: () => state.providers === "loading", + loadFailed: () => state.providers === "loadFailed", failed: () => false, optionUnavailable: () => false, sending: () => false, connected: () => true, select: (value) => setState("searchProvider", value), - retry() {}, + retry: () => setState("providers", "ready"), submit: async () => void setState("websearch", false), } satisfies WebSearchRequestModel, elicitationRequest: () => undefined, - permissionRequest: () => (state.permission ? activePermissionRequest : undefined), - permissionResponding: () => false, + permissionRequest: () => (state.permission ? activePermissionRequest : undefined), + permissionResponding: () => props.responding, decide: () => { deciding = true setState("permission", false) @@ -217,8 +231,17 @@ export default { }, argTypes: { queue: { control: { type: "range", min: 0, max: 4, step: 1 } }, + providers: { options: ["ready", "loading", "loadFailed", "empty"] }, }, - args: { question: false, permission: false, websearch: false, queue: 0, subagent: false } satisfies DockArgs, + args: { + question: false, + permission: false, + responding: false, + websearch: false, + providers: "ready", + queue: 0, + subagent: false, + } satisfies DockArgs, render: (args: DockArgs) => , } @@ -234,6 +257,10 @@ export const QuestionAndPermission = { args: { question: true, permission: true export const WebSearch = { args: { websearch: true } } +export const WebSearchRetry = { args: { websearch: true, providers: "loadFailed" } } + +export const PermissionResponding = { args: { permission: true, responding: true } } + export const Subagent = { args: { subagent: true } } // Opens a question, then answers it and dismisses the next one: the closes a reviewer should watch. diff --git a/packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx b/packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx new file mode 100644 index 000000000000..7bb60338e721 --- /dev/null +++ b/packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx @@ -0,0 +1,45 @@ +import { Show } from "solid-js" +import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" +import { SessionFreeLimitPanel } from "./free-limit-panel" +import { RecoverySession, RestoredComposer } from "./recovery-story" + +type Args = { reset: "today" | "tomorrow" | "unknown"; paid: boolean } + +function LimitStory(props: Args) { + const resetAt = () => { + if (props.reset === "unknown") return null + const at = new Date() + + if (props.reset === "tomorrow") at.setDate(at.getDate() + 1) + + return at.setHours(23, 59, 59, 999) + } + + return ( + + undefined} />}> + + + + ) +} + +export default { + title: "OpenCode/Session/Free limit", + id: "session-free-limit", + args: { reset: "today", paid: false } satisfies Args, + argTypes: { reset: { options: ["today", "tomorrow", "unknown"] } }, + render: (args: Args) => ( + + + + ), +} + +export const LimitReached = {} + +export const NextDayReset = { args: { reset: "tomorrow" } } + +export const UnknownReset = { args: { reset: "unknown" } } + +export const PaidProviderConnected = { args: { paid: true } } diff --git a/packages/app/src/session/composer/location-missing.standalone.stories.tsx b/packages/app/src/session/composer/location-missing.standalone.stories.tsx new file mode 100644 index 000000000000..6613c575c361 --- /dev/null +++ b/packages/app/src/session/composer/location-missing.standalone.stories.tsx @@ -0,0 +1,142 @@ +import type { SessionInfo, SessionMoveInput, WorktreeDirectory } from "@opencode/client/promise" +import { Button } from "@opencode/ui/button" +import { createSignal, onMount, Show } from "solid-js" +import { + createMemoryStorage, + createStoryFetch, + DialogStoryRuntime, + STORY_DIRECTORY, + STORY_PROJECTS, +} from "@/components-lab/dialog-story-runtime" +import type { Platform } from "@/runtime/platform/platform" +import { useData } from "@/runtime/server/current" +import { ToastRegion } from "@/shell/notifications/toast" +import { SessionLocationMissing } from "./location-missing" +import { RecoverySession, RestoredComposer } from "./recovery-story" + +const worktrees: WorktreeDirectory[] = ["timeline", "review", "settings"].map((name) => ({ + directory: `${STORY_DIRECTORY}-${name}`, + strategy: "git", +})) + +type Args = { directory: string; git: boolean; worktrees: "available" | "none"; failFirstMove: boolean } + +function RecoveryStory(props: Args) { + const session: SessionInfo = { + id: "ses_missing", + projectID: STORY_PROJECTS[0].id, + location: { directory: props.directory }, + title: "Timeline fixtures", + time: { created: 1, updated: 2 }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } + + const fallback = createStoryFetch() + + let failed = false + + const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + + const path = new URL(request.url).pathname + + if (path === "/api/project") + return Response.json(STORY_PROJECTS.map((p) => ({ ...p, vcs: props.git ? "git" : undefined }))) + + if (path === "/api/worktree" && request.method === "POST") + return Response.json({ directory: `${STORY_DIRECTORY}-new` }) + + if (path === "/api/worktree") return Response.json(props.worktrees === "available" ? worktrees : []) + + if (path === `/api/session/${session.id}/move`) { + if (props.failFirstMove && !failed) { + failed = true + + return new Response("The checkout is busy", { status: 503 }) + } + + const body: Pick = await request.json() + session.location.directory = body.directory + + return new Response(null, { status: 204 }) + } + + if (path === `/api/session/${session.id}`) return Response.json({ data: session }) + + return fallback(input, init) + } + + const platform: Platform = { + platform: "web", + openExternal() {}, + notify: async () => {}, + restart: async () => {}, + storage: createMemoryStorage(), + fetch: Object.assign(fetcher, { preconnect: fallback.preconnect }), + } + + return ( + + + + ) +} + +function RecoveryDock(props: { session: SessionInfo; directory: string }) { + const data = useData() + + onMount(() => void data.project.sync()) + + const destination = () => data.session.get(props.session.id)?.location.directory + + return ( + + + } + > + Session moved to {destination()} + + + + + ) +} + +function Replay(props: Args) { + const [revision, setRevision] = createSignal(0) + + return ( +
+ + {(args) => } + + +
+ ) +} + +export default { + title: "OpenCode/Session/Missing location", + id: "session-missing-location", + args: { directory: `${STORY_DIRECTORY}-old`, git: true, worktrees: "available", failFirstMove: false } satisfies Args, + argTypes: { worktrees: { options: ["available", "none"] } }, + render: (args: Args) => , +} + +export const MissingWorktree = {} + +export const DirectoryOnly = { args: { git: false } } + +export const NoWorktrees = { args: { worktrees: "none" } } + +export const RetryMove = { args: { failFirstMove: true } } diff --git a/packages/app/src/session/composer/queue-panel.stories.tsx b/packages/app/src/session/composer/queue-panel.stories.tsx index 8a55dd733caa..f862d5e873ea 100644 --- a/packages/app/src/session/composer/queue-panel.stories.tsx +++ b/packages/app/src/session/composer/queue-panel.stories.tsx @@ -1,3 +1,5 @@ +import { createEffect, on } from "solid-js" +import { createStore } from "solid-js/store" import { SessionQueuePanel } from "./queue-panel" import type { SessionQueueView } from "./queue" @@ -10,27 +12,58 @@ const prompts = [ "Remove the unused Alpha helper", ] -const view = (count: () => number): SessionQueueView => ({ - rows: () => prompts.slice(0, count()).map((text, index) => ({ id: `queued_${index}`, text, attachments: 0 })), - editing: () => undefined, - working: () => true, - busy: () => false, - steer: async () => undefined, - remove: async () => undefined, - undo: () => undefined, - edit: () => false, - reorder: async () => undefined, -}) +const plainRows = prompts.map((text, index) => ({ id: `queued_${index}`, text, attachments: 0 })) + +const contextRows = [ + { id: "quote", text: "Update the queue context", attachments: 1 }, + { id: "notes", text: "Compare the reference notes", attachments: 2 }, + { id: "file", text: "Keep the queue compact", attachments: 1 }, + { id: "context-only", text: "", attachments: 2 }, + ...plainRows.slice(4), +] + +type QueueArgs = { count: number; context: boolean; working: boolean; pending: boolean } + +function QueuePreview(props: QueueArgs) { + const rows = () => (props.context ? contextRows : plainRows).slice(0, props.count) + const [state, setState] = createStore<{ rows: typeof plainRows; editing?: string }>({ rows: rows() }) + const remove = (id: string) => setState("rows", (rows) => rows.filter((row) => row.id !== id)) + + createEffect(on(rows, (rows) => setState({ rows, editing: undefined }), { defer: true })) + + const queue: SessionQueueView = { + rows: () => state.rows.map((row, index) => ({ ...row, pending: props.pending && index === 0 })), + editing: () => state.editing, + working: () => props.working, + busy: () => props.pending, + steer: async (id) => remove(id), + remove: async (id) => remove(id), + undo: remove, + edit: (id) => { + if (props.pending) return false + setState("editing", id) + + return true + }, + reorder: async (ids) => + void setState( + "rows", + ids.flatMap((id) => state.rows.filter((row) => row.id === id)), + ), + } + + return ( +
+ +
+ ) +} export default { title: "OpenCode/Session/Queue panel", id: "session-queue-panel", - render: (args: { count: number }) => ( -
- args.count)} /> -
- ), - args: { count: 3 }, + render: (args: QueueArgs) => , + args: { count: 3, context: false, working: true, pending: false }, argTypes: { count: { control: { type: "range", min: 0, max: prompts.length, step: 1 } } }, parameters: { layout: "centered", @@ -46,20 +79,8 @@ export const Short = { args: { count: 3 } } export const Scrolling = { args: { count: 6 } } -export const WithContext = { - render: () => ( -
- 0), - rows: () => [ - { id: "quote", text: "Update the queue context", attachments: 1 }, - { id: "notes", text: "Compare the reference notes", attachments: 2 }, - { id: "file", text: "Keep the queue compact", attachments: 1 }, - { id: "context-only", text: "", attachments: 2 }, - ], - }} - /> -
- ), -} +export const WithContext = { args: { count: 4, context: true } } + +export const Parked = { args: { working: false } } + +export const PendingAdmission = { args: { pending: true } } diff --git a/packages/app/src/session/composer/recovery-story.tsx b/packages/app/src/session/composer/recovery-story.tsx new file mode 100644 index 000000000000..eb435beae5db --- /dev/null +++ b/packages/app/src/session/composer/recovery-story.tsx @@ -0,0 +1,38 @@ +import { CurrentSessionProviders, pendingAndQueuedDocument } from "@opencode/session-ui/storybook" +import { SessionTimeline } from "@opencode/session-ui/timeline" +import { createSignal, type ParentProps } from "solid-js" +import { Composer } from "@/composer/composer" +import { createPromptController } from "@/session/story-model" + +export function RecoverySession(props: ParentProps) { + return ( +
+
+ + + +
+ {props.children} +
+ ) +} + +export function RestoredComposer() { + const [activity, setActivity] = createSignal("") + + const prompt = createPromptController({ + initial: "Continue with the timeline fixtures.", + placeholder: "Ask anything", + status: () => ({ type: "idle" }), + onActivity: setActivity, + onSubmit: (text) => setActivity(`Sent locally: ${text}`), + onStop() {}, + }) + + return ( +
+ + {activity()} +
+ ) +} diff --git a/packages/app/src/session/composer/todo-pill.stories.tsx b/packages/app/src/session/composer/todo-pill.stories.tsx index 88b3067bd1fb..22c28ba3466b 100644 --- a/packages/app/src/session/composer/todo-pill.stories.tsx +++ b/packages/app/src/session/composer/todo-pill.stories.tsx @@ -5,7 +5,7 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { createMemo, onMount } from "solid-js" import { SessionPreview } from "@/session/story-model" import type { SessionActivityItem } from "./activity-chips" -import { sessionTodos, type Todo } from "./todos" +import { sessionTodos, todoFinished, type Todo } from "./todos" const timelineDetail = timelinePresets[2].value @@ -19,7 +19,7 @@ const plan = [ "Run the app typecheck", ] -type Scenario = "plan" | "cancelled" | "parallel" +type Scenario = "plan" | "cancelled" | "parallel" | "pending" // `progress` todos are done, the next one is in progress and the rest are pending. `cancelled` drops the last todo, // and `parallel` runs the two after `progress` at once. @@ -29,7 +29,7 @@ const todosAt = (progress: number, scenario: Scenario): Todo[] => status: index < progress ? "completed" - : index === progress || (scenario === "parallel" && index === progress + 1) + : (scenario !== "pending" && index === progress) || (scenario === "parallel" && index === progress + 1) ? "in_progress" : scenario === "cancelled" && index === plan.length - 1 ? "cancelled" @@ -100,6 +100,7 @@ type PreviewArgs = { progress: number; scenario: Scenario; open: boolean; activi function Preview(props: PreviewArgs) { const value = createMemo(() => document(todosAt(props.progress, props.scenario))) + const todos = createMemo(() => sessionTodos(value().messages)) onMount(() => setTimeout(() => { @@ -115,7 +116,7 @@ function Preview(props: PreviewArgs) { document={value()} timelineDetail={timelineDetail} activity={props.activity ? activity : undefined} - todos={{ items: sessionTodos(value().messages), open: props.open }} + todos={todos().every(todoFinished) ? undefined : { items: todos(), open: props.open }} /> ) } @@ -127,7 +128,7 @@ export default { args: { progress: 3, scenario: "plan", open: false, activity: true }, argTypes: { progress: { control: { type: "range", min: 0, max: 7, step: 1 } }, - scenario: { control: { type: "select" }, options: ["plan", "cancelled", "parallel"] }, + scenario: { control: { type: "select" }, options: ["plan", "cancelled", "parallel", "pending"] }, open: { control: { type: "boolean" } }, activity: { control: { type: "boolean" } }, }, @@ -151,3 +152,7 @@ export const WithoutActivity = { args: { activity: false } } export const Cancelled = { args: { scenario: "cancelled", open: true } } export const SeveralInProgress = { args: { scenario: "parallel", open: true } } + +export const PendingPlan = { args: { scenario: "pending", progress: 0 } } + +export const FinishedPlan = { args: { progress: plan.length } } diff --git a/packages/app/src/session/header/session-header-actions.stories.tsx b/packages/app/src/session/header/session-header-actions.stories.tsx index a436090425cb..413d6a6eaf5e 100644 --- a/packages/app/src/session/header/session-header-actions.stories.tsx +++ b/packages/app/src/session/header/session-header-actions.stories.tsx @@ -1,24 +1,33 @@ -import { createSignal } from "solid-js" -import { SessionHeaderActions } from "./session-header-actions" +import { createEffect, createSignal } from "solid-js" +import { useLanguage } from "@/runtime/i18n/language" +import { formatKeybindParts } from "@/shell/commands/command" +import { reviewGlyphFill, SessionHeaderActions } from "./session-header-actions" + +type Args = { opened: boolean; visible: boolean; label: string; keybind: string; panelGlyph: boolean } export default { title: "App/Session/Header actions", id: "app-session-header-actions", component: SessionHeaderActions, -} + args: { opened: false, visible: true, label: "Toggle review", keybind: "", panelGlyph: false }, + render: (args: Args) => { + const language = useLanguage() -export const ReviewToggle = { - render: () => { - const [opened, setOpened] = createSignal(false) + const [opened, setOpened] = createSignal(args.opened) + createEffect(() => setOpened(args.opened)) + + const glyph = (fill: SVGPathElement) => + createEffect(() => fill.setAttribute("transform", reviewGlyphFill(Number(opened())))) return (
setOpened(!opened()), }} /> @@ -26,3 +35,11 @@ export const ReviewToggle = { ) }, } + +export const ReviewToggle = {} + +export const Opened = { args: { opened: true } } + +export const PanelGlyph = { args: { panelGlyph: true, keybind: "mod+shift+r" } } + +export const Hidden = { args: { visible: false } } diff --git a/packages/app/src/session/question-switch.stories.tsx b/packages/app/src/session/question-switch.stories.tsx index aaaead6a8068..e4b27550b93e 100644 --- a/packages/app/src/session/question-switch.stories.tsx +++ b/packages/app/src/session/question-switch.stories.tsx @@ -353,3 +353,28 @@ export const LongPrompt = { /> ), } + +export const FreeResponse = { + render: () => ( + + ), +} diff --git a/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx b/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx new file mode 100644 index 000000000000..fa2210efa293 --- /dev/null +++ b/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx @@ -0,0 +1,88 @@ +import { Button } from "@opencode/ui/button" +import { createSignal, Show } from "solid-js" +import { DialogStoryRuntime, STORY_LOCKED_SERVER, STORY_SERVER } from "@/components-lab/dialog-story-runtime" +import { ServerProvider } from "@/runtime/server/current" +import type { ServerConnection } from "@/runtime/server/registry" +import { ServerSignedOutPanel, ServerUnavailablePanel } from "./server-unavailable-panel" + +const reasons = ["unreachable", "incompatible", "signedOutHttp", "signedOutPlugin", "signedOutManaged"] as const + +type Args = { reason: (typeof reasons)[number]; closable: boolean } + +function PanelStory(props: Args) { + const [outcome, setOutcome] = createSignal("") + + const plugin: ServerConnection.Plugin = { + type: "plugin", + key: "story:studio", + plugin: "story", + displayName: "Build workstation", + managed: true, + status: { type: props.reason === "incompatible" ? "incompatible" : "stopped" }, + authenticate: () => false, + connect: + props.reason === "signedOutManaged" + ? undefined + : async () => { + setOutcome("Signed in to the build workstation") + + return true + }, + } + + const reason = () => (props.reason === "incompatible" ? "incompatible" : "unreachable") + + return ( + +
+ + {outcome()} + +
+ } + > + } + > + + setOutcome("Session tab closed") : undefined} + /> + + + +
+ + ) +} + +export default { + title: "OpenCode/Session/Server unavailable", + id: "session-server-unavailable", + args: { reason: "unreachable", closable: true } satisfies Args, + argTypes: { reason: { options: reasons } }, + render: (args: Args) => ( + + {(reason) => } + + ), +} + +export const Unreachable = {} + +export const Incompatible = { args: { reason: "incompatible" } } + +export const Draft = { args: { closable: false } } + +export const SignedOut = { args: { reason: "signedOutHttp" } } + +export const PluginSignIn = { args: { reason: "signedOutPlugin" } } + +export const NoSignInAction = { args: { reason: "signedOutManaged" } } diff --git a/packages/app/src/session/session-identity-header.tsx b/packages/app/src/session/session-identity-header.tsx index ed7786e2781b..626388c35d7c 100644 --- a/packages/app/src/session/session-identity-header.tsx +++ b/packages/app/src/session/session-identity-header.tsx @@ -435,7 +435,8 @@ export function SessionLocation(props: { - + {/* A child's lineage follows, whose buttons pad 6px; a title pads 4px. */} + ) @@ -499,21 +500,20 @@ export function SessionAncestorTrail(props: { data-slot={ancestor.direct ? "session-title-parent" : "session-title-ancestor"} data-session-id={ancestor.id} title={ancestor.title} - class="max-w-[min(200px,40vw)] shrink-0 truncate text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:text-v2-text-text-muted" - classList={{ "ps-1": index() === 0 }} + class="h-7 max-w-[min(200px,40vw)] shrink-0 truncate rounded-[6px] px-1.5 text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:bg-v2-overlay-simple-overlay-hover hover:text-v2-text-text-muted focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:text-v2-text-text-muted focus-visible:outline-none" onClick={() => open(props.sessionID, ancestor.id)} > {ancestor.title} - + )}
- +
) diff --git a/packages/app/src/session/session-screen.stories.tsx b/packages/app/src/session/session-screen.stories.tsx index 4386d68f68b4..c0b632546b5e 100644 --- a/packages/app/src/session/session-screen.stories.tsx +++ b/packages/app/src/session/session-screen.stories.tsx @@ -15,6 +15,7 @@ import { terminalPassedDocument, } from "@opencode/session-ui/storybook" import { SessionPreview } from "./story-model" +import type { SubagentStatus } from "./composer/subagent-bar" const description = "opencode · modular-session-ui" @@ -307,21 +308,33 @@ export const ChildSessionNoOutcome = { ), } -export const ChildSessionDone = { - render: () => ( +function finishedChild(title: string, status: Exclude) { + return ( - ), + ) +} + +export const ChildSessionDone = { + render: () => finishedChild("Inspect a finished child Session", "succeeded"), +} + +export const ChildSessionFailed = { + render: () => finishedChild("Inspect a failed child Session", "failed"), +} + +export const ChildSessionInterrupted = { + render: () => finishedChild("Inspect an interrupted child Session", "interrupted"), } export const MobileLayout = { diff --git a/packages/app/src/session/timeline/background-work.stories.tsx b/packages/app/src/session/timeline/background-work.stories.tsx index 8bbed9ce36cd..183cd9c8cc40 100644 --- a/packages/app/src/session/timeline/background-work.stories.tsx +++ b/packages/app/src/session/timeline/background-work.stories.tsx @@ -3,6 +3,7 @@ import { BackgroundMoveHint } from "./message-timeline" export default { title: "OpenCode/Session/Background work", id: "session-background-work", + args: { keybind: "Ctrl+B" }, parameters: { docs: { description: { @@ -13,9 +14,14 @@ export default { } export const InlineMoveHint = { - render: () => ( + render: (args: { keybind: string }) => (
- + key.trim()) + .filter(Boolean)} + />
), } diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index 8f498fe8ea6a..591a7b843b3f 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -513,7 +513,7 @@ function MessageTimelineView( // The lane keeps its height while empty, so Working and the hint come and go without moving the rows around it. // The bottom lane also keeps its height while live status moves into the Activity row, so the tail the activity pill // floats in never closes and a pinned timeline does not shift when input waits. - const activity = (live: () => boolean) => ( + const activity = (live: () => boolean, inRow = false) => (
@@ -567,7 +568,7 @@ function MessageTimelineView( // row: Working hides and returns several times in one step, and each change would move that input 36px. const shown = createMemo((was) => was || working() || backgroundHintPresence.present(), false) - return {activity(() => true)} + return {activity(() => true, true)} }} )} diff --git a/packages/app/src/session/timeline/search-bar.stories.tsx b/packages/app/src/session/timeline/search-bar.stories.tsx new file mode 100644 index 000000000000..9ae8a2a2b6f1 --- /dev/null +++ b/packages/app/src/session/timeline/search-bar.stories.tsx @@ -0,0 +1,122 @@ +import type { SessionMessageInfo } from "@opencode/client/promise" +import type { SessionDocument } from "@opencode/session-ui/document" +import { CurrentSessionProviders, emptySessionDocument, STORY_MODEL, STORY_TIME } from "@opencode/session-ui/storybook" +import { SessionTimeline } from "@opencode/session-ui/timeline" +import { Button } from "@opencode/ui/button" +import { createEffect, createSignal, on, Show } from "solid-js" +import { TimelineSearchBar } from "./search-bar" +import { createTranscriptSearch } from "./search-controller" + +const turns = [ + [ + "Which trail is open on Saturday?", + "The lake trail opens at nine. The bridge on the north shore is closed for repairs.", + ], + [ + "Is there a way around the bridge?", + "Take the footpath past the boat house. It joins the south shore near the picnic tables.", + ], + [ + "How far is it from the station?", + "About three kilometres. There’s a drinking fountain at the entrance and a bike rack by the gate.", + ], + [ + "Where should we eat?", + "For lunch by the water, follow the trail to the orchard. The last trail marker points to a bench under the apple trees.", + ], +] + +const transcript: SessionDocument = { + ...emptySessionDocument, + messages: turns.flatMap(([question, answer], index): SessionMessageInfo[] => [ + { id: `prompt_${index}`, type: "user", text: question, time: { created: STORY_TIME + index * 60_000 } }, + { + id: `answer_${index}`, + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: [{ type: "text", text: answer }], + time: { created: STORY_TIME + index * 60_000 + 1000, completed: STORY_TIME + index * 60_000 + 2000 }, + }, + ]), +} + +type Args = { query: string; open: boolean; empty: boolean } + +function FindStory(props: Args) { + const document = () => (props.empty ? emptySessionDocument : transcript) + + const [scroll, setScroll] = createSignal() + + // This timeline mounts every row eagerly. The search controller can seek directly to each matching range. + const search = createTranscriptSearch({ + sessionID: () => document().sessionID, + messages: () => document().messages, + scrollRef: scroll, + revealMessage() {}, + pauseAutoScroll() {}, + }) + + createEffect( + on([() => props.open, () => props.query], ([open, query]) => { + if (!open) return search.query.close() + search.query.open() + search.query.setValue(query) + }), + ) + + return ( +
{ + if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return + event.preventDefault() + search.query.open() + }} + > +
+

A walk along the south shore

+ + Find in conversation + + } + > + + +
+
+ + No messages in this session.

} + > + +
+
+
+

+ Enter for the next match · Shift+Enter for the previous match · Escape to close +

+
+ ) +} + +export default { + title: "OpenCode/Session/Find in transcript", + id: "session-transcript-find", + args: { query: "trail", open: true, empty: false } satisfies Args, + render: (args: Args) => , +} + +export const Matches = {} + +export const NoMatches = { args: { query: "waterfall" } } + +export const EmptyQuery = { args: { query: "" } } + +export const EmptyTranscript = { args: { empty: true } } + +export const Closed = { args: { open: false } } diff --git a/packages/app/src/session/timeline/search-controller.ts b/packages/app/src/session/timeline/search-controller.ts index ec869a94e2fc..b3b440b736f6 100644 --- a/packages/app/src/session/timeline/search-controller.ts +++ b/packages/app/src/session/timeline/search-controller.ts @@ -1,3 +1,4 @@ +import type { SessionMessageInfo } from "@opencode/client/promise" import { useCommand } from "@/shell/commands/command" import { useLanguage } from "@/runtime/i18n/language" import { useData } from "@/runtime/server/current" @@ -103,15 +104,36 @@ function applyHighlights( CSS.highlights.set(HIGHLIGHT_ACTIVE, new Highlight(...active)) } -export function createTimelineSearchController(input: { +type TimelineSearchInput = { sessionID: () => string | undefined scrollRef: () => HTMLDivElement | undefined revealMessage: (id: string, partID?: string) => void pauseAutoScroll: () => void -}) { +} + +export function createTimelineSearchController(input: TimelineSearchInput) { const command = useCommand() - const language = useLanguage() const data = useData() + + const controller = createTranscriptSearch({ ...input, messages: (id) => data.session.message.list(id) }) + + command.register("session.search", () => [ + { + id: "session.search", + title: controller.query.placeholder(), + keybind: "mod+f", + hidden: true, + onSelect: controller.query.open, + }, + ]) + + return controller +} + +export function createTranscriptSearch( + input: TimelineSearchInput & { messages: (id: string) => readonly SessionMessageInfo[] }, +) { + const language = useLanguage() const [searchState, setSearchState] = createSignal(createTimelineSearchState()) const view = createMemo(() => timelineSearchView(searchState())) const visible = createMemo(() => view().visible) @@ -124,7 +146,7 @@ export function createTimelineSearchController(input: { let seekFrame: number | undefined const searchableParts = (sessionID: string | undefined) => - sessionID ? extractSearchableParts(data.session.message.list(sessionID)) : NO_PARTS + sessionID ? extractSearchableParts(input.messages(sessionID)) : NO_PARTS // Reads the transcript only while a query exists, so a closed or empty Find bar costs nothing while a reply // streams, and typing reuses the lowercased parts. @@ -186,16 +208,6 @@ export function createTimelineSearchController(input: { onCleanup(() => dispatch({ type: "disposed" })) - command.register("session.search", () => [ - { - id: "session.search", - title: language.t("session.search.placeholder"), - keybind: "mod+f", - hidden: true, - onSelect: open, - }, - ]) - function open() { dispatch({ type: "open", sessionID: untrack(input.sessionID) }) } diff --git a/packages/app/src/session/timeline/sources.stories.tsx b/packages/app/src/session/timeline/sources.stories.tsx index 064904ff9792..c354caec7769 100644 --- a/packages/app/src/session/timeline/sources.stories.tsx +++ b/packages/app/src/session/timeline/sources.stories.tsx @@ -10,7 +10,7 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { Icon } from "@opencode/ui/icon" import { IconButton } from "@opencode/ui/icon-button" import { Tabs } from "@opencode/ui/tabs" -import { createEffect, createMemo, on, onMount, Show, type ParentProps } from "solid-js" +import { createEffect, createMemo, on, onCleanup, Show, type ParentProps } from "solid-js" import { createStore } from "solid-js/store" import { useLanguage } from "@/runtime/i18n/language" import { SessionPreview } from "@/session/story-model" @@ -252,7 +252,12 @@ function Sources(props: SourcesArgs) { timelineDetail={timelineDetail} side={ - setState("panel", false)}> + setState("panel", false)} + > {}} /> @@ -264,16 +269,24 @@ function Sources(props: SourcesArgs) { // The side panel's frame around the real panel: the strip with the real tab title, as the side region draws it. // `expand` opens the first search with results once it shows. -function Side(props: ParentProps<{ expand: boolean; count: number; onClose: () => void }>) { +function Side(props: ParentProps<{ turn: Turn; expand: boolean; count: number; onClose: () => void }>) { const language = useLanguage() let el: HTMLDivElement | undefined - onMount(() => { - if (!props.expand) return - requestAnimationFrame(() => - el?.querySelector('[data-slot="sources-step-row"][aria-expanded="false"]')?.click(), - ) - }) + createEffect( + on( + () => [props.turn, props.expand] as const, + ([, expand]) => { + const frame = requestAnimationFrame(() => { + const row = el?.querySelector('[data-slot="sources-step-row"][aria-expanded]') + + if (row && row.getAttribute("aria-expanded") !== String(expand)) row.click() + }) + + onCleanup(() => cancelAnimationFrame(frame)) + }, + ), + ) return ( diff --git a/packages/app/src/settings/shell.standalone.stories.tsx b/packages/app/src/settings/shell.standalone.stories.tsx index dfff34049533..c0ca4d9c26e6 100644 --- a/packages/app/src/settings/shell.standalone.stories.tsx +++ b/packages/app/src/settings/shell.standalone.stories.tsx @@ -1,15 +1,20 @@ import { createMemoryHistory, MemoryRouter, Route } from "@solidjs/router" -import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" +import { DialogStoryRuntime, STORY_LOCKED_SERVER, STORY_SERVER } from "@/components-lab/dialog-story-runtime" +import { ServerConnection } from "@/runtime/server/registry" import { SettingsScreen } from "@/settings/shell" import { SettingsSurfaceProvider, type SettingsRootTab } from "@/settings/surface" import { LayoutProvider } from "@/shell/state/layout" -function SettingsStory(props: { tab: SettingsRootTab }) { +function SettingsStory(props: { tab: SettingsRootTab; locked?: boolean }) { const history = createMemoryHistory() - history.set({ value: `/settings?tab=${props.tab}`, replace: true, scroll: false }) + + const query = new URLSearchParams({ tab: props.tab }) + + if (props.locked) query.set("server", ServerConnection.key(STORY_LOCKED_SERVER)) + history.set({ value: `/settings?${query}`, replace: true, scroll: false }) return ( - +
, } + +export const UnavailableServer = { render: () => } diff --git a/packages/app/src/settings/timeline-detail.stories.tsx b/packages/app/src/settings/timeline-detail.stories.tsx index 1f0cc52edf36..1bf4de43ee74 100644 --- a/packages/app/src/settings/timeline-detail.stories.tsx +++ b/packages/app/src/settings/timeline-detail.stories.tsx @@ -9,32 +9,46 @@ import "./settings.css" export default { title: "OpenCode/Settings/Timeline detail", id: "settings-timeline-detail", + args: { preset: "compact" }, + argTypes: { preset: { options: [...timelinePresets.map((preset) => preset.id), "custom"] } }, + render: (args: { preset: string }) => ( + + {(preset) => } + + ), } -export const Interactive = { - render: () => { - const [state, setState] = createStore<{ value: TimelineDetail; visible: boolean }>({ - value: structuredClone(timelinePresets[2].value), - visible: true, - }) +function Preview(props: { preset: string }) { + const [state, setState] = createStore<{ value: TimelineDetail; visible: boolean }>({ + value: structuredClone( + timelinePresets.find((preset) => preset.id === props.preset)?.value ?? { + ...timelinePresets[2].value, + shell: { placement: "separate", details: "collapsed" }, + }, + ), + visible: true, + }) - return ( -
- - -
- setState("value", value)} /> -
-
-
- - - -
- ) - }, + return ( +
+ + +
+ setState("value", value)} /> +
+
+
+ + + +
+ ) } + +export const Interactive = {} + +export const Custom = { args: { preset: "custom" } } diff --git a/packages/app/src/shell/commands/dialog.standalone.stories.tsx b/packages/app/src/shell/commands/dialog.standalone.stories.tsx index 138e54a54754..68b0f6b4f8c9 100644 --- a/packages/app/src/shell/commands/dialog.standalone.stories.tsx +++ b/packages/app/src/shell/commands/dialog.standalone.stories.tsx @@ -13,7 +13,9 @@ import { useTabs } from "@/shell/tabs/tabs" import { CommandPaletteView, matchesCommandPaletteEntry } from "./dialog" import { createCommandPaletteFileEntry, type CommandPaletteEntry } from "./palette" -function CommandPaletteStory(props: { query?: string }) { +type Scenario = { query?: string; fileSearch?: "pending" | "failed" } + +function CommandPaletteStory(props: Scenario) { const dialog = useDialog() const language = useLanguage() @@ -171,27 +173,44 @@ function CommandPaletteStory(props: { query?: string }) { ] } + const findFiles = async (query: string, signal: AbortSignal): Promise => { + if (!query) return [] + + if (props.fileSearch === "failed") throw new Error("File search unavailable") + + if (props.fileSearch === "pending") { + return new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })) + } + + return files().filter((entry) => matchesCommandPaletteEntry(entry, query)) + } + const open = () => { tabs.addSessionTab({ server: serverKey, sessionId: "ses_story_1" }) - void dialog.show(() => ( - (query ? files().filter((entry) => matchesCommandPaletteEntry(entry, query)) : [])]} - highlight={() => {}} - select={() => dialog.close()} - close={() => dialog.close()} - /> - )) - - if (!props.query) return - const initial = props.query - queueMicrotask(() => { - const input = document.querySelector(".command-palette input[role='combobox']") - - if (!input) return - input.value = initial - input.dispatchEvent(new InputEvent("input", { bubbles: true })) + void dialog.show(() => { + let host!: HTMLDivElement + + onMount(() => { + if (!props.query) return + const input = host.querySelector('input[role="combobox"]') + + if (!input) return + input.value = props.query + input.dispatchEvent(new InputEvent("input", { bubbles: true })) + }) + + return ( +
+ {}} + select={() => dialog.close()} + close={() => dialog.close()} + /> +
+ ) }) } @@ -209,18 +228,20 @@ export default { id: "app-dialog-command-palette", } -export const Default = { +const story = (scenario: Scenario = {}) => ({ render: () => ( - + ), -} +}) -export const Searching = { - render: () => ( - - - - ), -} +export const Default = story() + +export const Searching = story({ query: "model" }) + +export const NoResults = story({ query: "changelog.md" }) + +export const SearchingFiles = story({ query: "changelog.md", fileSearch: "pending" }) + +export const FileSearchFailed = story({ query: "changelog.md", fileSearch: "failed" }) diff --git a/packages/app/src/shell/titlebar/inbox-card.stories.tsx b/packages/app/src/shell/titlebar/inbox-card.stories.tsx index 0a20fda4ebf9..f115f2d8e0fc 100644 --- a/packages/app/src/shell/titlebar/inbox-card.stories.tsx +++ b/packages/app/src/shell/titlebar/inbox-card.stories.tsx @@ -1,11 +1,15 @@ import { Button } from "@opencode/ui/button" +import { Menu } from "@opencode/ui/menu" import { createEffect, For, on, Show } from "solid-js" import { createStore } from "solid-js/store" +import { useLanguage } from "@/runtime/i18n/language" import { InboxSessionCard } from "./inbox" import type { InboxStatus } from "./inbox-model" const now = Date.UTC(2026, 10, 3, 12) +const statuses = ["done", "ready", "working", "approval", "input", "failed"] as const satisfies readonly InboxStatus[] + function SessionCardStory(props: { status: InboxStatus selected: boolean @@ -17,9 +21,21 @@ function SessionCardStory(props: { project: string projectKnown: boolean ageMinutes: number + ageSeconds: number + timestampKnown: boolean + readAction: boolean width: number }) { - const [state, setState] = createStore({ selected: props.selected, archived: props.archived, removed: false }) + const language = useLanguage() + + const initial = () => ({ selected: props.selected, archived: props.archived, removed: false, status: props.status }) + + const [state, setState] = createStore(initial()) + + const toggleRead = () => { + if (state.status !== "ready") return setState("status", "ready") + setState("status", props.status === "failed" ? "failed" : "done") + } createEffect( on( @@ -30,8 +46,9 @@ function SessionCardStory(props: { () => props.projectKnown, () => props.selected, () => props.archived, + () => props.readAction, ], - () => setState({ selected: props.selected, archived: props.archived, removed: false }), + () => setState(initial()), ), ) @@ -50,27 +67,34 @@ function SessionCardStory(props: { } directory={props.worktree ? "/workspace/opencode/worktrees/tooltip-status" : "/workspace/opencode"} title={props.title} - status={props.status} + status={state.status} selected={state.selected} archived={state.archived} server={props.remote ? "Build server · build.example.internal" : undefined} branch={props.branch || undefined} worktree={props.worktree} now={now} - since={now - props.ageMinutes * 60_000} + since={props.timestampKnown ? now - props.ageMinutes * 60_000 - props.ageSeconds * 1000 : undefined} onOpen={() => setState("selected", true)} + actions={ + + + {language.t(state.status === "ready" ? "session.markUnread" : "session.markRead")} + + + + } onArchive={() => setState("archived", true)} onUnarchive={() => setState("archived", false)} onDelete={() => setState("removed", true)} />
- @@ -95,12 +119,16 @@ export default { project: "opencode", projectKnown: true, ageMinutes: 41, + ageSeconds: 0, + timestampKnown: true, + readAction: false, width: 280, }, argTypes: { - status: { control: "select", options: ["done", "ready", "working", "approval", "input", "failed"] }, + status: { control: "select", options: statuses }, width: { control: { type: "range", min: 136, max: 640, step: 8 } }, ageMinutes: { control: { type: "range", min: 0, max: 10_080, step: 1 } }, + ageSeconds: { control: { type: "range", min: 0, max: 59, step: 1 } }, }, parameters: { docs: { @@ -150,7 +178,7 @@ export const Narrow = { args: { width: 136, remote: true } } export const AllStates = { render: (args: Parameters[0]) => (
- + status !== args.status)]}> {(status) => (
{status} @@ -161,3 +189,9 @@ export const AllStates = {
), } + +export const JustStarted = { args: { status: "working", ageMinutes: 0, ageSeconds: 12 } } + +export const UnknownAge = { args: { status: "working", timestampKnown: false } } + +export const MarkAsRead = { args: { readAction: true } } diff --git a/packages/app/src/shell/titlebar/inbox-list.stories.tsx b/packages/app/src/shell/titlebar/inbox-list.stories.tsx index e42ecb8f5c6c..989d9de69b98 100644 --- a/packages/app/src/shell/titlebar/inbox-list.stories.tsx +++ b/packages/app/src/shell/titlebar/inbox-list.stories.tsx @@ -29,6 +29,9 @@ function SessionListStory(props: { height: number currentArchived: boolean neverRun: boolean + loading: boolean + announcement: string + recentExpanded: boolean }) { const language = useLanguage() @@ -38,12 +41,13 @@ function SessionListStory(props: { archived: props.archived, removed: new Array(), action: "", - recentExpanded: false, + recentExpanded: props.recentExpanded, }) createEffect(() => setState("selected", props.selectedSession)) createEffect(() => setState("expanded", props.workingExpanded)) createEffect(() => setState("archived", props.archived)) + createEffect(() => setState("recentExpanded", props.recentExpanded)) const sessions = (section: "current" | "needs" | "unread" | "recent" | "working", count: number) => Array.from({ length: count }, (_, index) => { @@ -172,6 +176,8 @@ function SessionListStory(props: { style={{ width: `${props.width}px`, height: `${props.height}px` }} > @@ -236,6 +242,9 @@ export default { height: 640, currentArchived: false, neverRun: false, + loading: false, + announcement: "", + recentExpanded: false, }, argTypes: { currentCount: { control: { type: "range", min: 0, max: 1, step: 1 } }, @@ -245,7 +254,7 @@ export default { workingCount: { control: { type: "range", min: 0, max: 12, step: 1 } }, selectedSession: { control: "select", - options: ["current-0", "recent-1", "recent-0", "needs-0", "working-0", "none"], + options: ["current-0", "recent-1", "recent-0", "needs-0", "working-0", "unread-0", "none"], }, width: { control: { type: "range", min: 136, max: 640, step: 8 } }, height: { control: { type: "range", min: 240, max: 900, step: 20 } }, @@ -312,3 +321,9 @@ export const Dense = { args: { needsCount: 4, recentCount: 10, workingCount: 5 } export const Narrow = { args: { width: 136 } } export const ShortSidebar = { args: { height: 360 } } + +export const Loading = { args: { loading: true } } + +export const RecentExpanded = { args: { recentCount: 16, recentExpanded: true } } + +export const ArchivedOnly = { args: { needsCount: 0, unreadCount: 0, recentCount: 0, workingCount: 0 } } diff --git a/packages/app/src/shell/titlebar/navigation-story.tsx b/packages/app/src/shell/titlebar/navigation-story.tsx new file mode 100644 index 000000000000..63fff5e3474c --- /dev/null +++ b/packages/app/src/shell/titlebar/navigation-story.tsx @@ -0,0 +1,207 @@ +import type { ProjectListOutput, SessionInfo } from "@opencode/client/promise" +import { createMemoryHistory, MemoryRouter, Route } from "@solidjs/router" +import { createEffect, on, Show } from "solid-js" +import { + createMemoryStorage, + createStoryFetch, + DialogStoryRuntime, + STORY_DIRECTORY, + STORY_PROJECTS, + STORY_SERVER, +} from "@/components-lab/dialog-story-runtime" +import type { Platform } from "@/runtime/platform/platform" +import { ServerConnection } from "@/runtime/server/registry" +import { useGlobal } from "@/runtime/server/runtime" +import { tabHref, tabKey, useTabs, type Tab } from "@/shell/tabs/tabs" +import { createRouteTabSync } from "./route-sync" +import { SidebarCustomized, type SidebarStripGrouping } from "./sidebar-customized" +import type { SidebarViewState } from "./sidebar-view" +import { TitlebarTabStrip } from "./tab-strip" +import "./titlebar.css" + +const server = ServerConnection.key(STORY_SERVER) + +const projects = STORY_PROJECTS.map((project) => + project.id === "prj_docs" ? { ...project, name: "Developer documentation and integration guides" } : project, +) satisfies ProjectListOutput + +const idle = Date.UTC(2026, 10, 3, 12) + +function session(id: string, title: string, project: ProjectListOutput[number], unread = false): SessionInfo { + return { + id: `ses_${id}`, + title, + projectID: project.id, + location: { directory: project.canonical }, + time: { created: idle - 60_000, updated: idle, idle, viewed: unread ? undefined : idle }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } +} + +const sessions = [ + session("restore", "Restore workspace tabs", projects[0]), + session("guide", "Review the keyboard navigation guide for switching between project sessions", projects[1], true), + session("sidebar", "Sidebar focus order", projects[0]), + session("landing", "Landing page spacing", projects[2]), + session("contrast", "Check badge contrast", projects[0]), + session("search", "Search index refresh", projects[1]), + session("redirects", "Audit redirects", projects[2]), + session("icons", "Project icons", projects[0]), + session("examples", "Update examples", projects[1]), + session("footer", "Footer links", projects[2]), +] + +// All fetches and writes belong to one mount. The rest of the server (including the event stream) +// comes from the same fixture the standalone dialog stories use. +function navigationFetch(): typeof fetch { + const fallback = createStoryFetch() + + const records = new Map(sessions.map((item) => [item.id, structuredClone(item)])) + + const handler = async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + + const url = new URL(request.url) + + if (url.pathname === "/api/project") return Response.json(projects) + + if (url.pathname === "/api/session") { + const parent = url.searchParams.get("parentID") + + return Response.json({ data: parent && parent !== "null" ? [] : [...records.values()], cursor: {} }) + } + + const match = /^\/api\/session\/(ses_[^/]+)(?:\/(\w+))?$/.exec(url.pathname) + + if (!match) return fallback(input, init) + const record = records.get(match[1]) + + if (!record) return new Response(null, { status: 404 }) + + if (match[2] === "message") return Response.json({ data: [], cursor: {} }) + + if (match[2] === "view") record.time.viewed = record.time.idle + + if (request.method === "DELETE") records.delete(record.id) + + if (request.method === "PATCH") { + const patch: { title?: string } = await request.json() + + if (patch.title !== undefined) record.title = patch.title + } + + if (request.method !== "GET") return new Response(null, { status: 204 }) + + return Response.json({ data: match[2] ? [] : record }) + } + + return Object.assign(handler, { preconnect: fallback.preconnect }) +} + +type Preset = "sessions" | "draft" | "crowded" | "projects" | "collapsed" + +export function NavigationStory(props: { preset: Preset; width: number }) { + const draft: Tab = { type: "draft", server, directory: STORY_DIRECTORY, draftID: "navigation-draft" } + + const open = props.preset === "crowded" ? sessions : sessions.slice(0, 4) + + const tabs: Tab[] = [...open.map((item): Tab => ({ type: "session", server, sessionId: item.id })), draft] + + const view: Omit = { + grouping: "project", + ordering: "manual", + show: { recent: true, subagents: false, serverLabels: true }, + collapsed: props.preset === "collapsed" ? { [`project:${projects[0].id}`]: true } : {}, + } + + const storage = createMemoryStorage() + storage("opencode.window.navigation.dat").setItem("tabs", JSON.stringify(tabs)) + storage("opencode.global.dat").setItem("sidebar.view", JSON.stringify(view)) + + const platform: Platform = { + platform: "desktop", + windowID: "navigation", + openDirectoryPickerDialog: async () => null, + openExternal() {}, + notify: async () => {}, + restart: async () => {}, + storage, + fetch: navigationFetch(), + } + + const history = createMemoryHistory() + history.set({ value: tabHref(props.preset === "draft" ? draft : tabs[0]), replace: true, scroll: false }) + + return ( + + ( + + + + )} + /> + + ) +} + +function NavigationSurface(props: { sidebar: boolean; width: number }) { + const tabs = useTabs() + + const route = createRouteTabSync() + + const global = useGlobal() + + createEffect( + on(route.currentTab, (current) => { + if (current?.type === "session") global.serverCtx(server)?.notification.session.markRead(current.sessionId) + }), + ) + + const strip = (group?: SidebarStripGrouping) => ( + { + tabs.select(tab) + element?.scrollIntoView({ block: "nearest", inline: "nearest" }) + }} + onClose={(tab) => tabs.closeTab(tabs.store.indexOf(tab))} + onCloseTabs={(items, keep) => tabs.closeTabs(items.map(tabKey), keep)} + onReorder={tabs.reorder} + /> + ) + + return ( + + {strip()} +
+ } + > +
+ void tabs.newDraft({ server, directory: STORY_DIRECTORY })} + > + {strip} + +
+ + ) +} diff --git a/packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx b/packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx new file mode 100644 index 000000000000..ea5bbb094c09 --- /dev/null +++ b/packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx @@ -0,0 +1,16 @@ +import { NavigationStory } from "./navigation-story" + +type Args = { width: number } + +export default { + title: "App/Desktop/Project sidebar", + id: "app-desktop-project-sidebar", + args: { width: 304 }, + argTypes: { width: { control: { type: "range", min: 192, max: 480, step: 8 } } }, +} + +export const ProjectGroups = { render: (args: Args) => } + +export const CollapsedCurrentProject = { + render: (args: Args) => , +} diff --git a/packages/app/src/shell/titlebar/sidebar-view-menu.tsx b/packages/app/src/shell/titlebar/sidebar-view-menu.tsx index 7c9b81c80aee..9a898dcadb7d 100644 --- a/packages/app/src/shell/titlebar/sidebar-view-menu.tsx +++ b/packages/app/src/shell/titlebar/sidebar-view-menu.tsx @@ -1,5 +1,4 @@ import { For, Show, type JSX } from "solid-js" -import { createStore } from "solid-js/store" import { Icon } from "@opencode/ui/icon" import { IconButton } from "@opencode/ui/icon-button" import { Menu } from "@opencode/ui/menu" @@ -43,15 +42,8 @@ export function SidebarViewMenu(props: { const groupings = () => SIDEBAR_GROUPINGS.filter((value) => multiServer() || (value !== "server" && value !== "server-project")) - // Kobalte closes a submenu only when focus leaves it, and hovering a sibling trigger keeps focus in the parent - // menu, so without this every submenu hovered stays open on top of the next. - const [menu, setMenu] = createStore<{ sub: string | undefined }>({ sub: undefined }) - - const toggleSub = (key: string, open: boolean) => - setMenu("sub", (current) => (open ? key : current === key ? undefined : current)) - return ( - !open && setMenu("sub", undefined)}> + - toggleSub("grouping", open)} - > + {language.t(`sidebar.view.grouping.${props.state.grouping}`)} @@ -90,13 +76,7 @@ export function SidebarViewMenu(props: { - toggleSub("ordering", open)} - > + {language.t(`sidebar.view.ordering.${props.state.ordering}`)} @@ -123,13 +103,7 @@ export function SidebarViewMenu(props: { - toggleSub("show", open)} - > + @@ -146,13 +120,7 @@ export function SidebarViewMenu(props: { {(kind) => ( - toggleSub(`filter:${kind}`, open)} - > + 0}>{props.state.filters[kind].length} diff --git a/packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx b/packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx new file mode 100644 index 000000000000..478bdc9d2894 --- /dev/null +++ b/packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx @@ -0,0 +1,19 @@ +import { NavigationStory } from "./navigation-story" + +type Args = { width: number } + +export default { + title: "App/Desktop/Session tab strip", + id: "app-desktop-session-tab-strip", + args: { width: 880 }, + argTypes: { width: { control: { type: "range", min: 240, max: 1440, step: 8 } } }, +} + +export const SessionsAndDraft = { render: (args: Args) => } + +export const ActiveDraft = { render: (args: Args) => } + +export const Crowded = { + args: { width: 600 }, + render: (args: Args) => , +} diff --git a/packages/app/src/tips/model.ts b/packages/app/src/tips/model.ts index 284c9be99f5c..e13f055b7ca0 100644 --- a/packages/app/src/tips/model.ts +++ b/packages/app/src/tips/model.ts @@ -7,7 +7,7 @@ import { Persist, persisted } from "@/runtime/persistence/storage" import { usePlatform } from "@/runtime/platform/platform" import { ServerConnection, useServers } from "@/runtime/server/registry" import { useGlobal } from "@/runtime/server/runtime" -import { selectTip, TIP_INTERVAL_MS, type Tip } from "./queue" +import { FIRST_TIP_DELAY_MS, selectTip, TIP_INTERVAL_MS, type Tip } from "./queue" const STARTUP_DELAY = 2 * 60 * 1000 @@ -16,6 +16,7 @@ const History = Persistence.struct({ shownAt: Schema.Finite, dismissed: Persistence.array(Schema.String), dismissedAt: Schema.Finite, + firstSeen: Persistence.fallback(Schema.Finite, () => 0), }) export function createTipToasts() { @@ -79,6 +80,11 @@ export function createTipToasts() { shownAt: 0, dismissed: [], dismissedAt: 0, + firstSeen: 0, + }) + + createEffect(() => { + if (loaded() && !history.firstSeen) setHistory("firstSeen", Date.now()) }) const [tick, setTick] = createSignal(0) @@ -90,6 +96,7 @@ export function createTipToasts() { const times = [ Math.max(history.shownAt, history.dismissedAt) + TIP_INTERVAL_MS, + history.firstSeen + FIRST_TIP_DELAY_MS, ...tips.flatMap((tip) => [tip.start ?? 0, tip.end ?? 0]), ] diff --git a/packages/app/src/tips/queue.test.ts b/packages/app/src/tips/queue.test.ts index e4ecf1e52785..ae170ce9a43e 100644 --- a/packages/app/src/tips/queue.test.ts +++ b/packages/app/src/tips/queue.test.ts @@ -1,7 +1,10 @@ import { expect, test } from "bun:test" import { selectTip, type Tip } from "./queue" -const fresh = { current: "", shownAt: 0, dismissed: [], dismissedAt: 0 } +const hours = 60 * 60 * 1000 + +// Installed an hour before time 0, so the first-tip delay has already passed. +const fresh = { current: "", shownAt: 0, dismissed: [], dismissedAt: 0, firstSeen: -hours } const first: Tip = { id: "first", title: "tips.browse.title", description: "tips.browse.description" } @@ -9,7 +12,13 @@ const second: Tip = { ...first, id: "second" } const tips = [first, second] -const hours = 60 * 60 * 1000 +test("the first tip waits an hour after the app first ran", () => { + const installed = { ...fresh, firstSeen: 10 * hours } + expect(selectTip(tips, installed, 11 * hours - 1)).toBeUndefined() + expect(selectTip(tips, installed, 11 * hours)).toBe(first) + expect(selectTip(tips, { ...fresh, firstSeen: 0 }, 5 * hours)).toBeUndefined() + expect(selectTip(tips, { ...installed, dismissed: [first.id], dismissedAt: 1 }, 25 * hours)).toBe(second) +}) test("first eligible tip wins until it is handled or stops being eligible", () => { expect(selectTip(tips, fresh, 1)).toBe(first) diff --git a/packages/app/src/tips/queue.ts b/packages/app/src/tips/queue.ts index 85b781f0c550..4cefb7fd04f1 100644 --- a/packages/app/src/tips/queue.ts +++ b/packages/app/src/tips/queue.ts @@ -2,6 +2,8 @@ import type { useLanguage } from "@/runtime/i18n/language" export const TIP_INTERVAL_MS = 24 * 60 * 60 * 1000 +export const FIRST_TIP_DELAY_MS = 60 * 60 * 1000 + type Text = Parameters["t"]>[0] export type Tip = { @@ -19,6 +21,7 @@ export type TipHistory = { shownAt: number dismissed: readonly string[] dismissedAt: number + firstSeen: number } /** Array order is priority. Dates are epoch milliseconds; the end is exclusive. */ @@ -37,5 +40,7 @@ export function selectTip(tips: readonly Tip[], history: TipHistory, now: number if (last && now < last + TIP_INTERVAL_MS) return + if (!last && now < (history.firstSeen || now) + FIRST_TIP_DELAY_MS) return + return tips.find(eligible) } diff --git a/packages/app/src/usage/dialog.standalone.stories.tsx b/packages/app/src/usage/dialog.standalone.stories.tsx index ece8f56ebc88..60c03212bfbc 100644 --- a/packages/app/src/usage/dialog.standalone.stories.tsx +++ b/packages/app/src/usage/dialog.standalone.stories.tsx @@ -2,11 +2,13 @@ import type { UsageLimitsBudget, UsageLimitsInfo } from "@opencode/client/promis import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" import { onMount } from "solid-js" -import { DialogStoryRuntime, STORY_DIRECTORY } from "@/components-lab/dialog-story-runtime" +import { DialogStoryRuntime, STORY_DIRECTORY, STORY_LOCKED_SERVER } from "@/components-lab/dialog-story-runtime" import { DialogUsage, UsageDialogContent } from "./dialog" import type { CurrentModel } from "./limits" -const resetsAt = Date.UTC(2026, 10, 1) +const today = new Date() + +const resetsAt = Date.UTC(today.getUTCFullYear(), today.getUTCMonth() + 1, 1) const hour = 3_600_000 @@ -33,11 +35,11 @@ const anthropic = (spent: number) => const pool = (spent: number) => budget({ id: "pool", scope: "combined", shared: true, limit: 1_000, spent }) -const info = (budgets: UsageLimitsBudget[], go = false): UsageLimitsInfo => ({ +const info = (budgets: UsageLimitsBudget[], go?: "available" | "limited"): UsageLimitsInfo => ({ workspace: { id: "wrk_1", name: "Acme", usageURL: "https://opencode.ai/wrk_1/activity/overview" }, go: go ? { - rolling: { percent: 42, limited: false, resetsAt: Date.now() + 3 * hour }, + rolling: { percent: go === "limited" ? 100 : 42, limited: go === "limited", resetsAt: Date.now() + 3 * hour }, weekly: { percent: 18, limited: false, resetsAt: Date.now() + 100 * hour }, monthly: { percent: 7, limited: false, resetsAt: Date.now() + 500 * hour }, } @@ -82,7 +84,7 @@ export default { id: "app-dialog-usage", } -export const Default = { render: () => } +export const Default = { render: () => } export const SignedOut = { render: () => ( @@ -123,3 +125,13 @@ export const WorkspaceBudgetReached = { render: () => } export const NoBudgets = { render: () => } + +export const GoLimitReached = { render: () => } + +export const LoadFailed = { + render: () => ( + + + + ), +} diff --git a/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx b/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx index 5e15c35f50fc..a78edac3e7c5 100644 --- a/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx +++ b/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx @@ -5,7 +5,7 @@ import { createStore } from "solid-js/store" import { DialogStoryRuntime, STORY_DIRECTORY, STORY_SERVER } from "@/components-lab/dialog-story-runtime" import { DirectoryPickerDialog } from "./dialog" -function DirectoryPickerStory(props: { mode?: "directory" | "file" }) { +function DirectoryPickerStory(props: { mode?: "directory" | "file"; start?: string }) { const dialog = useDialog() const [store, setStore] = createStore({ selected: "No path selected" }) @@ -15,7 +15,7 @@ function DirectoryPickerStory(props: { mode?: "directory" | "file" }) { { const text = Array.isArray(result) ? result.join(", ") : (result ?? "Cancelled") @@ -56,3 +56,11 @@ export const SelectFile = { ), } + +export const MissingDirectory = { + render: () => ( + + + + ), +} diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 91def31eb2d1..192d3620cfb2 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2631,7 +2631,6 @@ export type ConfigEntry = media_blob?: boolean schedules?: boolean artifacts?: boolean - shell_timeout_background?: boolean console_watches?: boolean mcp_events?: boolean part_rows?: boolean diff --git a/packages/core/src/database/database.ts b/packages/core/src/database/database.ts index b18521b30841..5cf243fd028a 100644 --- a/packages/core/src/database/database.ts +++ b/packages/core/src/database/database.ts @@ -30,7 +30,9 @@ export class Service extends Context.Service()("@opencode/st // releasing a shared semaphore resumes the waiting object's fiber inside the // releasing object's I/O context, where its first storage call is rejected as // cross-object I/O. -const databaseLayer = (lock: Effect.Effect) => +// Only a database file the user opens imports their legacy auth.json; in-memory and injected databases belong to +// embedders and tests, which must not pick up the user's credentials. +const databaseLayer = (lock: Effect.Effect, legacyCredentials = false) => Layer.effect( Service, Effect.gen(function* () { @@ -48,7 +50,7 @@ const databaseLayer = (lock: Effect.Effect) => // Durable Object SQLite always enforces foreign keys and rejects the pragma. if (supportsForeignKeyToggle && !durableObject) yield* db.run("PRAGMA foreign_keys = ON") const semaphore = yield* lock - yield* semaphore.withPermit(DatabaseMigration.apply(db)) + yield* semaphore.withPermit(DatabaseMigration.apply(db, { legacyCredentials })) return { db } }).pipe(Effect.orDie), @@ -70,9 +72,10 @@ export function layer(options: Options = { path: ":memory:" }) { return Layer.unwrap( Effect.gen(function* () { const provide = (filename: string) => - databaseLayer(filename === ":memory:" ? Semaphore.make(1) : Effect.succeed(lockFor(filename))).pipe( - Layer.provide(sqliteLayer({ filename })), - ) + (filename === ":memory:" + ? databaseLayer(Semaphore.make(1)) + : databaseLayer(Effect.succeed(lockFor(filename)), true) + ).pipe(Layer.provide(sqliteLayer({ filename }))) const filename = options.path ?? ":memory:" if (filename === ":memory:") return provide(filename) const file = isAbsolute(filename) ? filename : join((yield* Global.Service).data, filename) diff --git a/packages/core/src/database/migration.ts b/packages/core/src/database/migration.ts index 9f006d1eb561..5d3512820b1a 100644 --- a/packages/core/src/database/migration.ts +++ b/packages/core/src/database/migration.ts @@ -21,7 +21,7 @@ export type Migration = { // Not serialized here: the Database layer holds a lock scoped to the database // it is bootstrapping, since two instances over one file must not race. -export function apply(db: Database) { +export function apply(db: Database, options = { legacyCredentials: true }) { return Effect.gen(function* () { // OpenCode owns the unprefixed table namespace. Embedders sharing this // database may own underscore-prefixed tables, which bootstrap ignores. @@ -36,7 +36,7 @@ export function apply(db: Database) { yield* db.transaction((tx) => Effect.gen(function* () { yield* schema.up(tx) - yield* legacyCredentials.up(tx) + if (options.legacyCredentials) yield* legacyCredentials.up(tx) yield* tx.run( sql`CREATE TABLE ${sql.identifier("migration")} (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`, ) diff --git a/packages/core/src/mime.ts b/packages/core/src/mime.ts index 15f24023fa9d..a84e94ba2844 100644 --- a/packages/core/src/mime.ts +++ b/packages/core/src/mime.ts @@ -1,10 +1,21 @@ export * as Mime from "./mime.js" export function detect(bytes: Uint8Array) { + return detectMedia(bytes) ?? (isText(bytes) ? "text/plain" : "application/octet-stream") +} + +export function detectMedia(bytes: Uint8Array) { if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png" if (startsWith(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg" - if (startsWith(bytes, [0x47, 0x49, 0x46, 0x38])) return "image/gif" - if (startsWith(bytes, [0x42, 0x4d])) return "image/bmp" + const signature = ascii(bytes, 0, 6) + if (signature === "GIF87a" || signature === "GIF89a") return "image/gif" + if (bytes.length >= 18 && startsWith(bytes, [0x42, 0x4d])) { + const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) + const pixels = header.getUint32(10, true) + const dib = header.getUint32(14, true) + // Pixels follow the 14-byte file header and a Windows or OS/2 DIB header, possibly beyond this sample. + if ([12, 16, 40, 52, 56, 64, 108, 124].includes(dib) && pixels >= 14 + dib) return "image/bmp" + } if (startsWith(bytes, [0x25, 0x50, 0x44, 0x46, 0x2d])) return "application/pdf" if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes.subarray(8), [0x57, 0x45, 0x42, 0x50])) return "image/webp" @@ -28,7 +39,7 @@ export function detect(bytes: Uint8Array) { if (brand === "M4A ") return "audio/mp4" return "video/mp4" } - return isText(bytes) ? "text/plain" : "application/octet-stream" + return undefined } export const isTextual = (mime: string) => diff --git a/packages/core/src/plugin/provider/opencode-watches.ts b/packages/core/src/plugin/provider/opencode-watches.ts index b0a6b6ac83c4..e951b4758311 100644 --- a/packages/core/src/plugin/provider/opencode-watches.ts +++ b/packages/core/src/plugin/provider/opencode-watches.ts @@ -253,7 +253,7 @@ export const make = Effect.fnUntraced(function* (ctx: Context, http: HttpClient. editor.namespace({ name: namespace, description: - "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console. The session wakes on its own when they change. A pull request it opened wakes it as each check finishes, so don't wait on CI with `gh pr checks --watch`, `gh run watch` or `sleep`.", + "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console. The session wakes on its own when they change. A pull request it opened wakes it when a check fails and once when all have finished, so don't wait on CI with `gh pr checks --watch`, `gh run watch` or `sleep`.", }) editor.add({ name: "watch", diff --git a/packages/core/src/provider.ts b/packages/core/src/provider.ts index fec21c9c463f..a5a757648c42 100644 --- a/packages/core/src/provider.ts +++ b/packages/core/src/provider.ts @@ -180,6 +180,7 @@ const builtins = new Map Promise>([ ], ["@opencode/ai/providers/xai", () => import("@opencode/ai/providers/xai")], ["@opencode/ai/providers/xai/images", () => import("@opencode/ai/providers/xai/images")], + ["@opencode/ai/providers/xai/videos", () => import("@opencode/ai/providers/xai/videos")], ["@opencode/ai/providers/zai", () => import("@opencode/ai/providers/zai")], ["@opencode/ai/providers/zai/chat", () => import("@opencode/ai/providers/zai/chat")], ["@opencode/ai/providers/zai/images", () => import("@opencode/ai/providers/zai/images")], diff --git a/packages/core/src/tool/plugin/image-generate.ts b/packages/core/src/tool/plugin/image-generate.ts index 726e35c9b395..adff3d106303 100644 --- a/packages/core/src/tool/plugin/image-generate.ts +++ b/packages/core/src/tool/plugin/image-generate.ts @@ -198,8 +198,8 @@ export const Plugin = { return yield* new ToolFailure({ message: `${source} is larger than 20 MiB.` }) return (yield* environment.files.read(target.absolute)).bytes }) - const mime = Mime.detect(bytes) - if (!INPUT_TYPES.includes(mime)) + const mime = Mime.detectMedia(bytes) + if (!mime || !INPUT_TYPES.includes(mime)) return yield* new ToolFailure({ message: `${source} is not a PNG, JPEG, WebP or GIF image.` }) return { data: Buffer.from(bytes).toString("base64"), mime, name: path.basename(source) } }) @@ -314,7 +314,8 @@ export const Plugin = { const image = result.images[0] if (!image) return yield* Effect.fail(new Error(`${ref} returned no image.`)) const bytes = Buffer.from(image.data, "base64") - const file = stem + (EXTENSIONS[Mime.detect(bytes)] ?? ".png") + const mime = Mime.detectMedia(bytes) + const file = stem + (EXTENSIONS[mime ?? "image/png"] ?? ".png") // The edit prompt covered the requested path. Replacing a different existing file needs its own // approval; a new file only has to pass the deny rules. if (target && file !== target.absolute) { diff --git a/packages/core/src/tool/plugin/read.ts b/packages/core/src/tool/plugin/read.ts index f0b04931e627..3d2e729556a3 100644 --- a/packages/core/src/tool/plugin/read.ts +++ b/packages/core/src/tool/plugin/read.ts @@ -53,6 +53,8 @@ export const Plugin = { output: Output, execute: (input, context) => { return Effect.gen(function* () { + if (input.limit === 0) + return yield* new ToolFailure({ message: "Limit must be a positive integer" }) if (Skill.isUri(input.path)) { const parsed = parseSkillUri(input.path) if (!parsed) return yield* new ToolFailure({ message: `File not found: ${input.path}` }) @@ -348,7 +350,8 @@ export const toModelContent = (path: string, offset: number | undefined, output: const start = output.type === "text-page" ? output.offset : 1 // Pages already join selected lines; a trailing newline represents a selected blank line. const text = output.type === "file" ? output.content.replace(/\n$/, "") : output.content - const lines = output.content === "" ? [] : text.split("\n") + const empty = output.type === "text-page" ? output.lineCount === 0 : output.content === "" + const lines = empty ? [] : text.split("\n") // A page that starts before the requested offset is the file's tail, returned for an offset past the end. const total = start + lines.length - 1 const pastEnd = output.type === "text-page" && offset !== undefined && start < offset diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 12b434fc9573..0fa456f60a6c 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -10,7 +10,6 @@ import { Clock, Deferred, Effect, Fiber, Option, Schema, Struct } from "effect" import { Environment } from "../../environment/index.js" import { Job } from "../../job.js" import { FileAccess } from "../../file-access.js" -import { Flag } from "../../flag.js" import { Permission } from "../../permission.js" import { NonNegativeInt } from "../../schema.js" import { Session } from "../../session.js" @@ -37,7 +36,7 @@ const OS = : process.platform === "linux" ? "Linux" : process.platform -const description = (shell?: string, autoBackground = false) => +const description = (shell?: string) => [ "Execute a shell command and return its output.", ...(shell ? [`Commands run on ${OS} using ${shell}.`] : []), @@ -45,31 +44,25 @@ const description = (shell?: string, autoBackground = false) => "Prefer dedicated tools over shell commands when possible.", "When output is large, the full result is saved to a file and a truncated preview is returned.", "Rely on automatic truncation unless filtering the output is more useful.", - autoBackground - ? "Commands still running after their timeout move to the background." - : "Commands accept an optional timeout, background commands have no timeout by default.", + "Commands still running after their timeout move to the background.", "Background commands return immediately, and you will be notified when they complete.", + "The current session ID is available in the OPENCODE_SESSION_ID environment variable.", ].join(" ") -const input = (autoBackground: boolean) => - Schema.Struct({ - command: Schema.String.annotate({ description: "Shell command string to execute" }), - workdir: Schema.optionalKey(Schema.String).annotate({ - description: - "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.", - }), - timeout: Schema.optionalKey(NonNegativeInt).annotate({ - description: autoBackground - ? `Optional timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}). When it expires, a foreground command moves to the background and a background command is stopped.` - : `Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to ${DEFAULT_TIMEOUT_MS} for foreground commands. Background commands have no timeout by default.`, - }), - background: Schema.optionalKey(Schema.Boolean).annotate({ - description: - "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.", - }), - }) - -export const Input = input(false) +export const Input = Schema.Struct({ + command: Schema.String.annotate({ description: "Shell command string to execute" }), + workdir: Schema.optionalKey(Schema.String).annotate({ + description: + "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.", + }), + timeout: Schema.optionalKey(NonNegativeInt).annotate({ + description: `Optional timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}). When it expires, a foreground command moves to the background and a background command is stopped.`, + }), + background: Schema.optionalKey(Schema.Boolean).annotate({ + description: + "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.", + }), +}) const StructuredOutput = Schema.Struct({ output: Schema.String, @@ -287,7 +280,6 @@ export const Plugin = { const shellSelect = yield* ShellSelect.Service const compatibleShell = shellSelect.resolve({ priority: "compat" }) const permission = yield* Permission.Service - const autoBackground = yield* Flag.enabled("shell_timeout_background") const prepare = Effect.fn("ShellTool.prepare")(function* (invocation: ShellCreateBefore, context: Tool.Context) { const target = yield* access.resolve({ path: invocation.cwd, kind: "directory" }) @@ -355,15 +347,12 @@ export const Plugin = { editor.add({ name, options: { codemode: false }, - description: description(undefined, autoBackground), - input: input(autoBackground), + description: description(), + input: Input, output: StructuredOutput, execute: (input, context) => { - // With timeout backgrounding, a foreground timeout of 0 falls back to the default so a call can't block - // until the command exits. - const foreground = autoBackground - ? input.timeout || DEFAULT_TIMEOUT_MS - : (input.timeout ?? DEFAULT_TIMEOUT_MS) + // A foreground timeout of 0 falls back to the default, so a call can't block until the command exits. + const foreground = input.timeout || DEFAULT_TIMEOUT_MS const timeout = input.background === true ? (input.timeout ?? 0) : foreground let finalTimeout = timeout // Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command. @@ -414,7 +403,7 @@ export const Plugin = { ), ) // A foreground timeout moves the command to the background instead of stopping it. - if (autoBackground && input.background !== true) invocation.timeout = 0 + if (input.background !== true) invocation.timeout = 0 }), ) yield* context.progress({ shellID: info.id }) @@ -435,7 +424,7 @@ export const Plugin = { const waiting = jobs.block({ id: job.id, sessionID: context.sessionID }) const blocked = - autoBackground && finalTimeout > 0 + finalTimeout > 0 ? waiting.pipe( Effect.timeoutOption(finalTimeout), Effect.flatMap((result) => @@ -498,7 +487,7 @@ export const Plugin = { Effect.gen(function* () { const tool = event.tools[name] if (!tool) return - tool.description = description(ShellSelect.name(yield* compatibleShell), autoBackground) + tool.description = description(ShellSelect.name(yield* compatibleShell)) }) yield* ctx.session.hook("context", hook) yield* ctx.session.hook("compaction", hook) diff --git a/packages/core/src/tool/read-filesystem.ts b/packages/core/src/tool/read-filesystem.ts index 11930dcba8a5..5f1a91dd3d21 100644 --- a/packages/core/src/tool/read-filesystem.ts +++ b/packages/core/src/tool/read-filesystem.ts @@ -82,6 +82,7 @@ export type FileContent = typeof FileContent.Type export class TextPage extends Schema.Class("ReadTool.TextPage")({ type: Schema.Literal("text-page"), content: Schema.String, + lineCount: NonNegativeInt, mime: Schema.String, offset: PositiveInt, truncated: Schema.Boolean, @@ -137,8 +138,8 @@ export const read = Effect.fn("ReadTool.read")(function* ( ) if (first instanceof ListPage) return first - const media = Mime.detect(first.bytes) - if (MEDIA_MIMES.has(media)) { + const media = Mime.detectMedia(first.bytes) + if (media && MEDIA_MIMES.has(media)) { if (first.info.size > MAX_MEDIA_INGEST_BYTES) return yield* new MediaIngestLimitError({ resource, maximumBytes: MAX_MEDIA_INGEST_BYTES }) const whole = yield* readFile(files, input, resource) @@ -155,13 +156,20 @@ export const read = Effect.fn("ReadTool.read")(function* ( const paged = first.info.size > MAX_READ_BYTES || page.offset !== undefined || page.limit !== undefined if (!paged) { if (first.bytes.includes(0)) return yield* new BinaryFileError({ resource }) - return { - type: "file" as const, - uri: virtual ? resource : pathToFileURL(input).href, - name: virtual ? path.posix.basename(input) : path.basename(input), - content: new TextDecoder().decode(first.bytes).split("\n").map(clampLine).join("\n"), - encoding: "utf8" as const, - mime: mimeType(input), + const lines = new TextDecoder().decode(first.bytes).split("\n") + // A final separator ends the last physical line; keep it in whole-file content. + const count = lines.at(-1) === "" ? lines.length - 1 : lines.length + if (count <= MAX_READ_LINES) { + const content = lines.map(clampLine).join("\n") + if (Buffer.byteLength(content) <= MAX_READ_BYTES) + return { + type: "file" as const, + uri: virtual ? resource : pathToFileURL(input).href, + name: virtual ? path.posix.basename(input) : path.basename(input), + content, + encoding: "utf8" as const, + mime: mimeType(input), + } } } @@ -325,6 +333,7 @@ const textPage = Effect.fnUntraced(function* ( return new TextPage({ type: "text-page", content: entries.join("\n"), + lineCount: entries.length, mime: mimeType(input), offset: from, truncated: next !== undefined, diff --git a/packages/core/test/database-migration.test.ts b/packages/core/test/database-migration.test.ts index bfdfd4adbfd1..fd3bc387e270 100644 --- a/packages/core/test/database-migration.test.ts +++ b/packages/core/test/database-migration.test.ts @@ -553,6 +553,22 @@ describe("DatabaseMigration", () => { ) }) + test("leaves legacy credentials out of in-memory databases", async () => { + await using tmp = await tmpdir() + await Bun.write( + path.join(tmp.path, "auth.json"), + JSON.stringify({ openai: { type: "oauth", refresh: "refresh", access: "access", expires: 123 } }), + ) + + const rows = await Effect.runPromise( + Database.Service.use((database) => database.db.all(sql`SELECT id FROM credential`)).pipe( + Effect.provide(Database.layer({ path: ":memory:" })), + Effect.provideService(Global.Service, Global.make({ data: tmp.path })), + ), + ) + expect(rows).toEqual([]) + }) + test("bootstraps a fresh database when the legacy credential file is malformed", async () => { await using tmp = await tmpdir() await Bun.write(path.join(tmp.path, "auth.json"), "not json") diff --git a/packages/core/test/mime.test.ts b/packages/core/test/mime.test.ts index a63f19005120..93af27cf06ee 100644 --- a/packages/core/test/mime.test.ts +++ b/packages/core/test/mime.test.ts @@ -4,6 +4,30 @@ import { Mime } from "@opencode/core/mime" const ftyp = (hex: string) => Uint8Array.from(Buffer.from(hex, "hex")) describe("Mime.detect", () => { + test.each([ + [Uint8Array.of(65), "text/plain"], + [Uint8Array.of(0xff), "application/octet-stream"], + [Uint8Array.of(0xe2, 0x82), "text/plain"], // A sample may end inside a UTF-8 character. + ] as const)("leaves samples without media headers to the text fallback: %j", (bytes, mime) => { + expect(Mime.detectMedia(bytes)).toBeUndefined() + expect(Mime.detect(bytes)).toBe(mime) + }) + + test("keeps ordinary text starting with BM as text", () => { + for (const text of ["BM", "BMW service schedule\n"]) expect(Mime.detect(Buffer.from(text))).toBe("text/plain") + }) + + test("detects Windows and OS/2 bitmaps from a prefix", () => { + // 1x1, 24-bit bitmaps with a four-byte padded pixel row. + const windows = "424d3a000000000000003600000028000000010000000100000001001800" + "00".repeat(28) + const os2 = "424d1e000000000000001a0000000c000000010001000100180000000000" + for (const hex of [windows, os2]) { + const bytes = Buffer.from(hex, "hex") + expect(Mime.detect(bytes)).toBe("image/bmp") + expect(Mime.detect(bytes.subarray(0, 18))).toBe("image/bmp") + } + }) + test("tells ISO-BMFF brands apart", () => { expect(Mime.detect(ftyp("000000206674797061766966000000004d695072617669666d6961666d696631"))).toBe("image/avif") expect(Mime.detect(ftyp("000000186674797061766973000000006d73663161766973"))).toBe("image/avif") diff --git a/packages/core/test/session-prompt.test.ts b/packages/core/test/session-prompt.test.ts index 6c50de01f379..d00ef5ebd7d5 100644 --- a/packages/core/test/session-prompt.test.ts +++ b/packages/core/test/session-prompt.test.ts @@ -843,11 +843,15 @@ describe("Session.prompt", () => { yield* setup const session = yield* Session.Service const uri = `data:video/mp2t;base64,${Buffer.from("export const value = 1\n").toString("base64")}` + const notes = Buffer.from("BMW service schedule\n").toString("base64") const message = yield* session.prompt({ sessionID, text: "Inspect this", - files: [{ uri, name: "main.ts" }], + files: [ + { uri, name: "main.ts" }, + { uri: `data:;base64,${notes}`, name: "notes" }, + ], resume: false, }) @@ -858,6 +862,7 @@ describe("Session.prompt", () => { source: { type: "inline" }, name: "main.ts", }, + { data: notes, mime: "text/plain", source: { type: "inline" }, name: "notes" }, ]) }), ) diff --git a/packages/core/test/tool-read-filesystem.test.ts b/packages/core/test/tool-read-filesystem.test.ts index f4997f9b4b27..fa38fa154b2b 100644 --- a/packages/core/test/tool-read-filesystem.test.ts +++ b/packages/core/test/tool-read-filesystem.test.ts @@ -23,6 +23,13 @@ const absolute = (value: string) => AbsolutePath.make(value) describe("ReadTool text serialization", () => { const cases = [ + { + name: "reads a partial GIF signature as text", + content: "GIF8 is text", + page: {}, + output: { type: "file", content: "GIF8 is text", encoding: "utf8" }, + model: "Read file lines.txt, lines 1-1\n1: GIF8 is text", + }, { name: "preserves a selected trailing blank line before continuation", content: "alpha\n\nomega\n", @@ -90,9 +97,30 @@ describe("ReadTool text serialization", () => { name: "preserves empty-file page output", content: "", page: { limit: 2 }, - output: { type: "text-page", content: "", offset: 1, truncated: false }, + output: { type: "text-page", content: "", lineCount: 0, offset: 1, truncated: false }, model: "Read file lines.txt, 0 lines", }, + { + name: "numbers the only blank line in a newline-only file", + content: "\n", + page: { limit: 1 }, + output: { type: "text-page", content: "", lineCount: 1, offset: 1, truncated: false }, + model: "Read file lines.txt, lines 1-1\n1: ", + }, + { + name: "numbers a single blank line before continuation", + content: "alpha\n\nomega\n", + page: { offset: 2, limit: 1 }, + output: { type: "text-page", content: "", lineCount: 1, offset: 2, truncated: true, next: 3 }, + model: "Read file lines.txt, lines 2-2\n2: \n[Output truncated. Continue reading with offset: 3]", + }, + { + name: "counts the last blank line when an offset is past EOF", + content: "alpha\n\n", + page: { offset: 9, limit: 1 }, + output: { type: "text-page", content: "", lineCount: 1, offset: 2, truncated: false }, + model: "Read file lines.txt, lines 2-2 (offset 9 is past the end; the file has 2 lines)\n2: ", + }, ] cases.forEach((input) => { @@ -105,13 +133,81 @@ describe("ReadTool text serialization", () => { const result = yield* ReadToolFileSystem.read(current.environment, file, "lines.txt", input.page) expect(result).toMatchObject(input.output) - expect(ReadTool.toModelContent("lines.txt", undefined, result)).toBe(input.model) + expect(ReadTool.toModelContent("lines.txt", input.page.offset, result)).toBe(input.model) }), ) }) }) describe("ReadToolFileSystem", () => { + it.live("applies the default line limit to small files at physical line boundaries", () => + Effect.gen(function* () { + const { environment, files, directory } = yield* fixture + const file = absolute(path.join(directory, "dense.txt")) + const read = (page?: ReadToolFileSystem.PageInput) => ReadToolFileSystem.read(environment, file, "dense.txt", page) + const prefix = "x\r\n".repeat(1_999) + for (const ending of ["last", "last\n", "last\r\n", "\n"]) { + const content = prefix + ending + yield* files.writeFileString(file, content) + expect(yield* read()).toMatchObject({ type: "file", content }) + } + + yield* files.writeFileString(file, prefix + "\r\nlast") + const page = yield* read() + expect(page.type).toBe("text-page") + if (page.type !== "text-page") return + expect(page).toMatchObject({ content: "x\n".repeat(1_999), offset: 1, next: 2_001, truncated: true }) + expect(ReadTool.toModelContent("dense.txt", undefined, page)).toEndWith( + "2000: \n[Output truncated. Continue reading with offset: 2001]", + ) + expect(yield* read({ offset: page.next })).toMatchObject({ content: "last", offset: 2_001, truncated: false }) + }), + ) + + it.live("applies the byte limit to the returned content of small files", () => + Effect.gen(function* () { + const { environment, files, directory } = yield* fixture + const file = absolute(path.join(directory, "bytes.txt")) + const read = () => ReadToolFileSystem.read(environment, file, "bytes.txt") + const exact = ("é".repeat(799) + "x\n").repeat(32) + yield* files.writeFileString(file, exact) + expect(yield* read()).toMatchObject({ type: "file", content: exact }) + + // Each truncation marker takes more bytes than the one character it replaces. + yield* files.writeFileString(file, ("x".repeat(2_001) + "\n").repeat(25) + "é".repeat(500)) + const page = yield* read() + expect(page.type).toBe("text-page") + if (page.type !== "text-page") return + expect(page).toMatchObject({ offset: 1, next: 26, truncated: true }) + expect(page.content.split("\n")).toHaveLength(25) + expect(Buffer.byteLength(page.content)).toBeLessThanOrEqual(50 * 1024) + }), + ) + + it.live("reads extensionless and renamed GIFs as images", () => + Effect.gen(function* () { + const { environment, files, directory } = yield* fixture + for (const [version, name] of [ + ["GIF87a", "pixel"], + ["GIF89a", "pixel.txt"], + ]) { + // 1x1 screen, black/white palette, one pixel and trailer. + const bytes = Buffer.concat([ + Buffer.from(version), + Buffer.from("01000100800000000000ffffff2c00000000010001000002024401003b", "hex"), + ]) + const file = absolute(path.join(directory, name)) + yield* files.writeFile(file, bytes) + expect(yield* ReadToolFileSystem.read(environment, file, name)).toMatchObject({ + type: "file", + mime: "image/gif", + encoding: "base64", + content: bytes.toString("base64"), + }) + } + }), + ) + it.effect("preserves the environment not-found error", () => Effect.gen(function* () { const { environment, directory } = yield* fixture diff --git a/packages/core/test/tool-read.test.ts b/packages/core/test/tool-read.test.ts index 48ad4f76140c..280f539997b8 100644 --- a/packages/core/test/tool-read.test.ts +++ b/packages/core/test/tool-read.test.ts @@ -223,6 +223,23 @@ describe("ReadTool", () => { }), ) + it.effect("rejects a zero limit before reading", () => + Effect.gen(function* () { + const registry = yield* Tool.Service + const result = yield* executeTool(registry, { + sessionID, + ...toolIdentity, + call: { type: "tool-call", id: "call-zero-limit", name: "read", input: { path: "README.md", limit: 0 } }, + }) + expect(result).toMatchObject({ + status: "error", + error: { message: "Limit must be a positive integer" }, + }) + expect(assertions).toEqual([]) + expect(readCalls).toEqual([]) + }), + ) + it.effect("asks for external_directory approval before reading an external absolute path", () => Effect.gen(function* () { const registry = yield* Tool.Service @@ -1130,6 +1147,7 @@ describe("ReadTool", () => { readResult = new ReadToolFileSystem.TextPage({ type: "text-page", content: "hello", + lineCount: 1, mime: "text/plain", offset: 2, truncated: true, @@ -1170,6 +1188,7 @@ describe("ReadTool", () => { readResult = new ReadToolFileSystem.TextPage({ type: "text-page", content: "nine\nten", + lineCount: 2, mime: "text/plain", offset: 9, truncated: true, diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 1c70279fb455..c25d5a36aeac 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -278,19 +278,8 @@ const progressOverflowCommand = (bytes: number, release: string) => ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }` : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; while [ ! -e '${release}' ]; do sleep 0.05; done` -const withSession = ( - directory: string, - body: (registry: Tool.Interface) => Effect.Effect, - autoBackground?: boolean, -) => +const withSession = (directory: string, body: (registry: Tool.Interface) => Effect.Effect) => Effect.gen(function* () { - if (autoBackground !== undefined) - yield* Effect.promise(() => - Bun.write( - path.join(directory, "opencode.json"), - JSON.stringify({ experimental: { shell_timeout_background: autoBackground } }), - ), - ) const sessions = yield* Session.Service const location = Location.Ref.make({ directory: AbsolutePath.make(directory) }) yield* sessions.create({ @@ -1469,125 +1458,84 @@ describe("ShellTool", () => { { timeout: 15_000 }, ) - it.live( - "reports partial output, the timeout and the exit code when a foreground command times out", - () => - withTempDir((tmp) => { - reset() - // Long enough for the command to print before it is killed. - const timeout = isWindows ? 5_000 : 500 - return withSession(tmp.path, (registry) => - executeTool(registry, call({ command: startingCommand, timeout }, "call-foreground-timeout")), - ).pipe( - Effect.andThen((settled) => - Effect.sync(() => { - expect(settled.metadata).toMatchObject({ timeout: true }) - expect(settled.output).not.toHaveProperty("timeout") - expect(settled.output).toMatchObject({ - exitCode: settled.metadata?.exit ?? null, - }) - if (!isWindows) expect(settled.output.signal).toBe("SIGTERM") - expect(settled.content).toEqual([ - { type: "text", text: "server starting" }, - Expected.text( - expect.stringMatching( - new RegExp( - `^Command timed out after ${timeout / 1_000} seconds\\. If it needs longer and isn't waiting for input, rerun with a larger timeout\\.\\nExit code: ${timedOutExit}$`, - ), - ), - ), - ]) - }), - ), - ) - }), - { timeout: 15_000 }, - ) - it.live("moves a foreground timeout to the background and delivers its original process result once", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const bus = yield* Bus.Service - const notices = yield* Queue.unbounded() - yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( - Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), - Stream.runForEach((event) => Queue.offer(notices, event.data.item.payload)), - Effect.forkScoped({ startImmediately: true }), - ) - const result = yield* executeTool( - registry, - call({ command: progressOverflowCommand(6, "release"), timeout: 10 }, "call-auto-background"), - ) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - const info = yield* shell.get(id) - expect(result.status).toBe("completed") - expect(info.pid).toBeGreaterThan(0) - expect(result.metadata).toMatchObject({ - status: "running", - shellID: id, - pid: info.pid, - truncated: false, - }) - expect(result.output).toEqual({ + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const bus = yield* Bus.Service + const notices = yield* Queue.unbounded() + yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( + Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), + Stream.runForEach((event) => Queue.offer(notices, event.data.item.payload)), + Effect.forkScoped({ startImmediately: true }), + ) + const result = yield* executeTool( + registry, + call({ command: progressOverflowCommand(6, "release"), timeout: 10 }, "call-auto-background"), + ) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + const info = yield* shell.get(id) + expect(result.status).toBe("completed") + expect(info.pid).toBeGreaterThan(0) + expect(result.metadata).toMatchObject({ + status: "running", + shellID: id, + pid: info.pid, + truncated: false, + }) + expect(result.output).toEqual({ + shellID: id, + pid: info.pid, + outputPath: info.file, + exitCode: null, + output: expect.any(String), + wallTimeSeconds: expect.any(Number), + }) + expect(result.output.wallTimeSeconds).toBeGreaterThanOrEqual(0.01) + expect(result.metadata).not.toHaveProperty("timeout") + expect(result.content?.[0]).toEqual({ + type: "text", + text: `Command moved to the background (shell ID: ${id}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}\n\nThe command did not finish within its timeout of 0.01 seconds and was moved to the background. Do not start another copy while it is running.`, + }) + expect(info.status).toBe("running") + expect((yield* shell.list()).map((item) => item.id)).toEqual([id]) + + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) + const finished = yield* shell.wait(id) + expect(finished).toMatchObject({ + status: "exited", + exit: 0, + pid: info.pid, + }) + expect(yield* Queue.take(notices)).toMatchObject({ + text: expect.stringContaining("xxxxxx"), + metadata: { + source: "shell", shellID: id, - pid: info.pid, - outputPath: info.file, - exitCode: null, - output: expect.any(String), - wallTimeSeconds: expect.any(Number), - }) - expect(result.output.wallTimeSeconds).toBeGreaterThanOrEqual(0.01) - expect(result.metadata).not.toHaveProperty("timeout") - expect(result.content?.[0]).toEqual({ - type: "text", - text: `Command moved to the background (shell ID: ${id}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}\n\nThe command did not finish within its timeout of 0.01 seconds and was moved to the background. Do not start another copy while it is running.`, - }) - expect(info.status).toBe("running") - expect((yield* shell.list()).map((item) => item.id)).toEqual([id]) - - yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) - const finished = yield* shell.wait(id) - expect(finished).toMatchObject({ - status: "exited", + state: "completed", exit: 0, - pid: info.pid, - }) - expect(yield* Queue.take(notices)).toMatchObject({ - text: expect.stringContaining("xxxxxx"), - metadata: { - source: "shell", - shellID: id, - state: "completed", - exit: 0, - }, - }) - expect(yield* Queue.size(notices)).toBe(0) - expect(yield* shell.list()).toEqual([]) - }), - true, + }, + }) + expect(yield* Queue.size(notices)).toBe(0) + expect(yield* shell.list()).toEqual([]) + }), ) }), ) - it.live("returns a fast foreground result directly with timeout backgrounding enabled", () => + it.live("returns a fast foreground result directly", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool(registry, call({ command: helloCommand, timeout: 10_000 })) - expect(result.metadata).toMatchObject({ status: "completed", exit: 0 }) - expect(result.content).toEqual([{ type: "text", text: "hello" }]) - const jobs = yield* Job.Service - expect(yield* jobs.runningBackground).toEqual([]) - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool(registry, call({ command: helloCommand, timeout: 10_000 })) + expect(result.metadata).toMatchObject({ status: "completed", exit: 0 }) + expect(result.content).toEqual([{ type: "text", text: "hello" }]) + const jobs = yield* Job.Service + expect(yield* jobs.runningBackground).toEqual([]) + }), ) }), ) @@ -1595,62 +1543,56 @@ describe("ShellTool", () => { it.live("preserves a timeout-promoted command's eventual failure", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const bus = yield* Bus.Service - const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( - Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ) - const result = yield* executeTool( - registry, - call({ command: `${progressOverflowCommand(0, "release")}; exit 7`, timeout: 10 }), - ) - const id = ID.make(String(result.metadata?.shellID)) - yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) - const shell = yield* Shell.Service - expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 7 }) - expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ - text: expect.stringContaining("Exit code: 7"), - metadata: { source: "shell", shellID: id, state: "completed", exit: 7 }, - }) - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const bus = yield* Bus.Service + const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( + Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ) + const result = yield* executeTool( + registry, + call({ command: `${progressOverflowCommand(0, "release")}; exit 7`, timeout: 10 }), + ) + const id = ID.make(String(result.metadata?.shellID)) + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) + const shell = yield* Shell.Service + expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 7 }) + expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ + text: expect.stringContaining("Exit code: 7"), + metadata: { source: "shell", shellID: id, state: "completed", exit: 7 }, + }) + }), ) }), ) - it.effect("treats a foreground timeout of zero as the default timeout with timeout backgrounding enabled", () => + it.effect("treats a foreground timeout of zero as the default timeout", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const running = yield* executeTool( - registry, - call({ command: progressOverflowCommand(0, "release"), timeout: 0 }, "call-zero-timeout"), - ).pipe(Effect.forkScoped({ startImmediately: true })) - // The wait starts only after the command spawns, so keep advancing the clock until the call returns. - const result = yield* Fiber.join(running).pipe( - Effect.raceFirst( - Effect.forever(Effect.promise(() => Bun.sleep(20)).pipe(Effect.andThen(TestClock.adjust("2 minutes")))), - ), - ) - expect(result.content?.[0]).toMatchObject({ - type: "text", - text: expect.stringContaining("did not finish within its timeout of 120 seconds"), - }) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.get(id)).status).toBe("running") - yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) - expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0 }) - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const running = yield* executeTool( + registry, + call({ command: progressOverflowCommand(0, "release"), timeout: 0 }, "call-zero-timeout"), + ).pipe(Effect.forkScoped({ startImmediately: true })) + // The wait starts only after the command spawns, so keep advancing the clock until the call returns. + const result = yield* Fiber.join(running).pipe( + Effect.raceFirst( + Effect.forever(Effect.promise(() => Bun.sleep(20)).pipe(Effect.andThen(TestClock.adjust("2 minutes")))), + ), + ) + expect(result.content?.[0]).toMatchObject({ + type: "text", + text: expect.stringContaining("did not finish within its timeout of 120 seconds"), + }) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + expect((yield* shell.get(id)).status).toBe("running") + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) + expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0 }) + }), ) }), ) @@ -1658,58 +1600,35 @@ describe("ShellTool", () => { it.live("still cancels a timeout-promoted shell through its existing job handle", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool( - registry, - call({ command: progressOverflowCommand(0, "release"), timeout: 10 }), - ) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.get(id)).status).toBe("running") - const jobs = yield* Job.Service - expect(yield* jobs.cancel(id)).toMatchObject({ id, status: "cancelled" }) - // Cancelling stops the command and keeps it, output file included. - expect((yield* shell.wait(id)).status).toBe("killed") - expect(yield* shell.list()).toEqual([]) - }), - true, - ) - }), - ) - - it.live("preserves explicit background timeout limits with timeout backgrounding disabled", () => - withTempDir((tmp) => { - reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 10 })) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.wait(id)).status).toBe("timeout") - }), - false, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool( + registry, + call({ command: progressOverflowCommand(0, "release"), timeout: 10 }), + ) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + expect((yield* shell.get(id)).status).toBe("running") + const jobs = yield* Job.Service + expect(yield* jobs.cancel(id)).toMatchObject({ id, status: "cancelled" }) + // Cancelling stops the command and keeps it, output file included. + expect((yield* shell.wait(id)).status).toBe("killed") + expect(yield* shell.list()).toEqual([]) + }), ) }), ) - it.live("stops a background command when its explicit timeout expires with timeout backgrounding enabled", () => + it.live("stops a background command when its explicit timeout expires", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 50 })) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.wait(id)).status).toBe("timeout") - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 50 })) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + expect((yield* shell.wait(id)).status).toBe("timeout") + }), ) }), ) diff --git a/packages/gui-plugins/src/browser/panel.fixture.tsx b/packages/gui-plugins/src/browser/panel.fixture.tsx index b96fa780c8c9..0c8e26f63b89 100644 --- a/packages/gui-plugins/src/browser/panel.fixture.tsx +++ b/packages/gui-plugins/src/browser/panel.fixture.tsx @@ -53,7 +53,7 @@ import { createModel } from "./model" import SessionBrowserPane from "./panel" import { BrowserPane, type PaneEvent } from "./ipc" import { pageShortcut } from "./keys" -import { refusal } from "./policy" +import { normalizeURL, refusal } from "./policy" import { type BuiltinLayout } from "@opencode/plugin/gui/builtin" /** The renderer host pieces the pane runs on, passed in by `packages/app/component-tests/browser-pane.spec.ts`. */ @@ -110,6 +110,23 @@ type PaneFixtureState = { selection: string } +export type BrowserScenario = "Page" | "Empty" | "Recent" | "Loading" | "Failed" | "Suspended" + +type ElementRect = Pick + +type StoryHost = Pick & { + scenario: BrowserScenario + Page: Component<{ url: string; zoom: number; picking: boolean; pick: (rect: ElementRect) => void }> + Frame: ParentComponent<{ + loading: boolean + finish: () => void + suspended: boolean + reconnect: () => void + external: string | undefined + comments: readonly ComposerNote[] + }> +} + // A 16px blue square, as main reports a page icon. const icon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHJlY3Qgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2IiByeD0iMyIgZmlsbD0iIzNiODJmNiIvPjwvc3ZnPg==" @@ -137,21 +154,40 @@ export function mountBrowserPane(input: PaneHost) { host.style.cssText = "position:fixed;inset:0;z-index:1000;background:#181818;color:#eee;padding:24px" document.body.appendChild(host) - function Fixture() { + const Fixture = browserPaneFixture(input) + + return render( + () => ( + + + + + + ), + host, + ) +} + +// Both hosts exercise the real model and pane. The lab draws an in-memory document where the component tests +// measure native embed layouts and captures. +export function browserPaneFixture(input: PaneHost | StoryHost) { + return function Fixture() { const language = input.useLanguage() const messages = new Map(Object.entries(browserEn)) + const scenario = "scenario" in input ? input.scenario : undefined + const [store, setStore] = createStore({ session: "Alpha", mounted: true, visible: true, - url: undefined, - loading: false, + url: scenario === "Empty" || scenario === "Recent" ? "about:blank" : undefined, + loading: scenario === "Loading", generation: 0, delayNavigation: false, pendingURL: undefined, - loadErrors: {}, - error: undefined, + loadErrors: scenario === "Failed" ? { Alpha: "ERR_CONNECTION_REFUSED" } : {}, + error: scenario === "Suspended" ? "browser.pane.suspended" : undefined, layouts: {}, covered: false, moving: false, @@ -164,7 +200,7 @@ export function mountBrowserPane(input: PaneHost) { highlights: [], comments: [], zoom: 1, - history: { visits: [] }, + history: { visits: scenario === "Recent" ? structuredClone(visits) : [] }, external: [], cookies: 3, failSite: false, @@ -223,12 +259,30 @@ export function mountBrowserPane(input: PaneHost) { } // SAFETY: the host embeds call only `embed`, `capture` and `on` on their bridge (`runtime/plugin/embeds.tsx`). - const embeds = input.createEmbeds({ - bridge: bridge as Bridge, - zoom: () => (store.selection === "zoomed" ? 1.25 : 1), - dialog: () => store.dialog, - moving: () => store.moving || input.panelMotion.panelsMoving(), - }) + const embeds: Embeds = + "createEmbeds" in input + ? input.createEmbeds({ + bridge: bridge as Bridge, + zoom: () => (store.selection === "zoomed" ? 1.25 : 1), + dialog: () => store.dialog, + moving: () => store.moving || input.panelMotion.panelsMoving(), + }) + : { + capture: async () => undefined, + View: (props) => ( +
+ + + + {props.children} +
+ ), + } const t = (key: string, params?: Readonly>>) => (messages.get(key) ?? language.t(key)).replace(/\{\{(\w+)\}\}/g, (_, name: string) => @@ -297,6 +351,9 @@ export function mountBrowserPane(input: PaneHost) { composer: { attach: (note: ComposerNote) => setStore("comments", (items) => [...items, note]) }, } as unknown as SessionScreen + const back: string[] = [] + const forward: string[] = [] + const report = (key = store.session) => { const tab = tabs.find((item) => item.title === key) @@ -308,6 +365,8 @@ export function mountBrowserPane(input: PaneHost) { { ...tab, url: store.url ?? tab.url, + canGoBack: back.length > 0, + canGoForward: forward.length > 0, loading: store.loading, generation: store.generation, loadError: store.loadErrors[key], @@ -325,6 +384,14 @@ export function mountBrowserPane(input: PaneHost) { bindings.set(value.session, value.binding) queueMicrotask(() => { report(value.session) + + // A suspended attachment reports its retained inventory once. The next interaction can reconnect it. + if (store.error === "browser.pane.suspended") { + setStore("error", undefined) + + return + } + const tab = tabs.find((item) => item.title === value.session) if (tab) emit(value.session, { type: "embed", tabID: tab.id, embed: `embed-${tab.title}` }) @@ -342,15 +409,32 @@ export function mountBrowserPane(input: PaneHost) { if (command.type === "navigate" || command.type === "reload") setStore("loadErrors", store.session, undefined) if (command.type === "navigate") { + const url = normalizeURL(command.url) + if (store.delayNavigation) { - setStore("pendingURL", command.url) + setStore("pendingURL", url) return } - setStore({ url: command.url, loading: false, generation: store.generation + 1 }) + back.push(store.url ?? current().url) + forward.length = 0 + setStore({ url, loading: false, generation: store.generation + 1 }) + } + + if (command.type === "back" || command.type === "forward") { + const stack = command.type === "back" ? back : forward + const url = stack.pop() + + if (url) { + const other = command.type === "back" ? forward : back + other.push(store.url ?? current().url) + setStore({ url, loading: false, generation: store.generation + 1 }) + } } + if (command.type === "reload") setStore({ loading: false, generation: store.generation + 1 }) + if (command.type === "stop") setStore("loading", false) report() }, @@ -437,7 +521,7 @@ export function mountBrowserPane(input: PaneHost) { const plugin = fake as unknown as Context & SetupContext const model = createModel(plugin) - const pick = () => { + const pick = (rect?: ElementRect) => { const selector = () => { if (store.selection === "fallback") return "" @@ -458,11 +542,34 @@ export function mountBrowserPane(input: PaneHost) { label: "button.primary", role: "button", name: "Save changes", - rect: { x: 48, y: store.selection === "low" ? 180 : 40, width: 160, height: 36 }, + rect: rect ?? { x: 48, y: store.selection === "low" ? 180 : 40, width: 160, height: 36 }, }, }) } + if ("Frame" in input) + return ( + + + { + setStore("loading", false) + report() + }} + suspended={model.suspended({ key: store.session })} + reconnect={() => model.command({ key: store.session }, { type: "reload", tabID: current().id })} + comments={store.comments} + external={store.external.at(-1)} + > + + {(view) => } + + + + + ) + return ( @@ -546,7 +653,7 @@ export function mountBrowserPane(input: PaneHost) { )}
- + find.setQuery(event.currentTarget.value)} /> + {find.state()?.count} + + ) + }, host) +} diff --git a/packages/gui-plugins/src/file/find.tsx b/packages/gui-plugins/src/file/find.tsx new file mode 100644 index 000000000000..43b34b075210 --- /dev/null +++ b/packages/gui-plugins/src/file/find.tsx @@ -0,0 +1,373 @@ +import { Option, Schema } from "effect" +import { createSignal, onCleanup, Show, untrack } from "solid-js" +import { makeEventListener } from "@solid-primitives/event-listener" +import { createResizeObserver } from "@solid-primitives/resize-observer" +import { createKeyed, type FileContent } from "@opencode/plugin/gui" +import { FileSearchBar } from "@opencode/session-ui/file-search" + +const HIT = "file-preview-find" + +const ACTIVE = "file-preview-find-current" + +/** Marks messages between the bar and the script it adds to an HTML preview. */ +const CHANNEL = "opencode-file-find" + +/** The open bar: what it searches, the query, and the active match out of `count`. */ +type PreviewFindState = { + target: HTMLElement + query: string + index: number + count: number + pos: { top: number; right: number } +} + +/** The marked ranges of a rendered preview, and the bar's input. */ +type PreviewFindDom = { ranges: Range[]; input?: HTMLInputElement } + +/** A frame the observer waits for, so a burst of mutations searches once. */ +type PendingFrame = { frame?: number } + +/** + * Find for previews the code view's find can't search: rendered Markdown, Mermaid and tables by their text, and HTML + * through a script added to the page, since the preview runs in a sandboxed frame. It uses the code view's bar and + * marks, so both look the same. + */ +export function createPreviewFind(input: { root: () => HTMLElement | undefined; active: () => boolean }) { + const [state, setState] = createSignal() + const local: PreviewFindDom = { ranges: [] } + + const update = (next: Partial) => { + const current = untrack(state) + + if (current) setState({ ...current, ...next }) + } + + const search = (query: string, index: number, scroll = true) => { + const current = untrack(state) + + if (!current) return + + if (current.target instanceof HTMLIFrameElement) { + update({ query, index }) + current.target.contentWindow?.postMessage({ source: CHANNEL, op: "search", query, index, marks: marks() }, "*") + + return + } + + local.ranges = query ? documentRanges(current.target, query) : [] + const at = local.ranges.length === 0 ? 0 : Math.min(index, local.ranges.length - 1) + update({ query, index: at, count: local.ranges.length }) + paint(at, scroll) + } + + const paint = (index: number, scroll: boolean) => { + if (!globalThis.CSS?.highlights) return + const active = local.ranges[index] + CSS.highlights.set(HIT, new Highlight(...local.ranges.filter((range) => range !== active))) + + if (!active) return CSS.highlights.delete(ACTIVE) + CSS.highlights.set(ACTIVE, new Highlight(active)) + + if (scroll) active.startContainer.parentElement?.scrollIntoView({ block: "center", inline: "nearest" }) + } + + // Where the code view puts its bar, so it stays put when the preview switches to the source. + const position = (el: HTMLElement) => { + const rect = el.getBoundingClientRect() + + return { top: Math.round(rect.top) - 4, right: Math.round(window.innerWidth - rect.right) + 8 } + } + + /** Opens the bar for the shown preview; false when none is showing, so the code view's find runs instead. */ + const open = () => { + const el = input.root()?.querySelector("[data-file-find]") + + // A closed side panel keeps its preview mounted but hidden; the bar would open off screen. + if (!el?.checkVisibility()) return false + const current = untrack(state) + + if (current?.target !== el) { + close() + setState({ target: el, query: current?.query ?? "", index: 0, count: 0, pos: position(el) }) + } + + search(untrack(state)?.query ?? "", 0) + requestAnimationFrame(() => { + local.input?.focus() + local.input?.select() + }) + + return true + } + + const close = () => { + const current = untrack(state) + + if (!current) return + local.ranges = [] + CSS.highlights?.delete(HIT) + CSS.highlights?.delete(ACTIVE) + + if (current.target instanceof HTMLIFrameElement) + current.target.contentWindow?.postMessage({ source: CHANNEL, op: "clear" }, "*") + setState(undefined) + } + + const next = (dir: 1 | -1) => { + const current = untrack(state) + + if (!current?.query || current.count === 0) return + const index = (current.index + dir + current.count) % current.count + + if (current.target instanceof HTMLIFrameElement) return search(current.query, index) + update({ index }) + paint(index, true) + } + + // The HTML preview's script answers searches, says when its page loaded, and passes on Mod+F pressed inside it, + // which never reaches this window's key handlers. + makeEventListener(window, "message", (event: MessageEvent) => { + const frame = input.root()?.querySelector('iframe[data-file-find="frame"]') + + if (!frame || event.source !== frame.contentWindow) return + const decoded = decodeFrameMessage(event.data) + + if (Option.isNone(decoded)) return + const data = decoded.value + + if (data.op === "shortcut") { + if (input.active()) open() + + return + } + + const current = untrack(state) + + if (current?.target !== frame) return + + if (data.op === "ready") return search(current.query, current.index) + + if (data.op === "result" && data.query === current.query) update({ count: data.count, index: data.index }) + }) + + // Keep the bar on its preview, search text that renders again, and close once the preview is gone, e.g. on a + // switch to the source, whose code view has its own find. + createKeyed( + () => state()?.target, + (el) => { + const root = input.root() + const pending: PendingFrame = {} + + const observer = new MutationObserver(() => { + if (pending.frame !== undefined) return + pending.frame = requestAnimationFrame(() => { + pending.frame = undefined + + if (!el.isConnected) return close() + + if (el instanceof HTMLIFrameElement) return + const current = untrack(state) + + // Text that renders again keeps the active match without scrolling to it. + if (current) search(current.query, current.index, false) + }) + }) + + if (root) observer.observe(root, { childList: true, subtree: true, characterData: true }) + const reposition = () => update({ pos: position(el) }) + makeEventListener(window, "resize", reposition, { passive: true }) + createResizeObserver(el, reposition) + onCleanup(() => { + observer.disconnect() + + if (pending.frame !== undefined) cancelAnimationFrame(pending.frame) + }) + }, + ) + + createKeyed(() => !input.active(), close) + + onCleanup(close) + + return { + state, + open, + close, + next, + setInput: (el: HTMLInputElement) => { + local.input = el + }, + setQuery: (query: string) => search(query, 0), + onKeyDown: (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault() + close() + + return + } + + if (event.key !== "Enter") return + event.preventDefault() + next(event.shiftKey ? -1 : 1) + }, + } +} + +export function PreviewFindBar(props: { find: ReturnType }) { + return ( + + {(state) => ( + props.find.next(-1)} + onNext={() => props.find.next(1)} + /> + )} + + ) +} + +/** + * The HTML with the find script first, after any doctype so the page keeps its rendering mode. The script runs before + * the page's own, so a Content-Security-Policy the page declares later does not block it. + */ +export function findableHtml(content: FileContent): FileContent { + if (content.type !== "text" || content.url || content.bytes) return content + const script = `` + const doctype = /^(?:\s|)*]*>/i.exec(content.content)?.[0] ?? "" + + return { ...content, content: doctype + script + content.content.slice(doctype.length) } +} + +/** The page's colors can't resolve the app's theme, so the marks travel resolved with each search. */ +function marks() { + const probe = document.createElement("span") + document.body.append(probe) + probe.style.backgroundColor = "rgb(from var(--surface-warning-base) r g b / 0.35)" + const hit = getComputedStyle(probe).backgroundColor + probe.style.backgroundColor = "rgb(from var(--surface-warning-strong) r g b / 0.55)" + const active = getComputedStyle(probe).backgroundColor + probe.remove() + + return { hit, active } +} + +/** What the HTML preview's script sends; the page's own scripts can post to this window too. */ +const decodeFrameMessage = Schema.decodeUnknownOption( + Schema.Union([ + Schema.Struct({ source: Schema.Literal(CHANNEL), op: Schema.Literals(["ready", "shortcut"]) }), + Schema.Struct({ + source: Schema.Literal(CHANNEL), + op: Schema.Literal("result"), + query: Schema.String, + count: Schema.Number, + index: Schema.Number, + }), + ]), +) + +/** Every case-insensitive occurrence of `query` in the text under `root`, in reading order. */ +function documentRanges(root: HTMLElement, query: string) { + // Matching the original text keeps Unicode case folding from shifting DOM offsets. + const needle = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu") + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT) + const ranges: Range[] = [] + + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if (!(node instanceof Text)) continue + // Text the preview hides, such as a diagram's source, can't be shown as a match. + if (!node.parentElement?.checkVisibility()) continue + + for (const match of node.data.matchAll(needle)) { + const range = document.createRange() + range.setStart(node, match.index) + range.setEnd(node, match.index + match[0].length) + ranges.push(range) + } + } + + return ranges +} + +/** + * Runs inside the HTML preview, serialized into its page, so it can use nothing from this module. It finds and marks + * text the way the bar does for other previews, and hands Mod+F back to the app. + */ +function frameFind(channel: string) { + const post = ( + message: { op: "ready" | "shortcut" } | { op: "result"; query: string; count: number; index: number }, + ) => parent.postMessage({ source: channel, ...message }, "*") + + // An adopted sheet, since a style element would fall to the page's own Content-Security-Policy. + const sheet = new CSSStyleSheet() + + window.addEventListener("message", (event) => { + const data = event.data + + if (event.source !== parent || data?.source !== channel) return + const api = CSS.highlights + + if (data.op === "clear") { + api?.delete("opencode-file-find") + api?.delete("opencode-file-find-current") + + return + } + + if (data.op !== "search") return + const query = String(data.query) + const needle = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu") + const ranges: Range[] = [] + const walker = document.createTreeWalker(document.body ?? document.documentElement, NodeFilter.SHOW_TEXT) + + for (let node = walker.nextNode(); node && query; node = walker.nextNode()) { + if (!(node instanceof Text)) continue + if (!node.parentElement?.checkVisibility()) continue + + for (const match of node.data.matchAll(needle)) { + const range = document.createRange() + range.setStart(node, match.index) + range.setEnd(node, match.index + match[0].length) + ranges.push(range) + } + } + + const index = ranges.length === 0 ? 0 : Math.min(Math.max(data.index, 0), ranges.length - 1) + const active = ranges[index] + sheet.replaceSync( + `::highlight(opencode-file-find){background-color:${data.marks?.hit}}::highlight(opencode-file-find-current){background-color:${data.marks?.active}}`, + ) + + if (!document.adoptedStyleSheets.includes(sheet)) + document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet] + + if (api) { + api.set("opencode-file-find", new Highlight(...ranges.filter((range) => range !== active))) + + if (active) api.set("opencode-file-find-current", new Highlight(active)) + else api.delete("opencode-file-find-current") + } + + active?.startContainer.parentElement?.scrollIntoView({ block: "center", inline: "nearest" }) + post({ op: "result", query, count: ranges.length, index }) + }) + + window.addEventListener( + "keydown", + (event) => { + if (event.key.toLowerCase() !== "f" || !(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return + event.preventDefault() + post({ op: "shortcut" }) + }, + true, + ) + + window.addEventListener("DOMContentLoaded", () => post({ op: "ready" })) +} diff --git a/packages/gui-plugins/src/file/view.tsx b/packages/gui-plugins/src/file/view.tsx index 2d7e61669c8f..e62ae65b82a4 100644 --- a/packages/gui-plugins/src/file/view.tsx +++ b/packages/gui-plugins/src/file/view.tsx @@ -12,6 +12,7 @@ import { createKeyed, usePlugin, type LineRange, type MountedSession, type Sessi import { artifactKind } from "@opencode/util/artifact" import ArtifactView from "./artifact-view" import { useShared } from "./context" +import { createPreviewFind, PreviewFindBar } from "./find" import { fileTabPath } from "./path" import { FILE_SCROLL_INTERACTED, @@ -71,7 +72,7 @@ function FileCommentMenu(props: { /** The code view's scroll element and the animation frame that restores or stores its scroll. */ type ScrollTarget = { element?: HTMLDivElement; frame?: number } -type FindState = { find: FileSearchHandle | null } +type FindState = { find: FileSearchHandle | null; root?: HTMLDivElement } /** The session the view shows and the one it showed before a switch, whose unsaved scroll a switch still stores. */ type ShownSessions = { current: MountedSession; previous?: MountedSession } @@ -417,7 +418,9 @@ export function SessionFileView(props: { session: MountedSession; screen: Sessio ), }) - // Mod+F finds in the shown file. + const previewFind = createPreviewFind({ root: () => state.root, active }) + + // Mod+F finds in the shown file, or in its preview. makeEventListener( window, "keydown", @@ -430,6 +433,8 @@ export function SessionFileView(props: { session: MountedSession; screen: Sessio event.preventDefault() event.stopPropagation() + + if (previewFind.open()) return // Find scrolls to its matches; the stored scroll must not pull the view back. scrollSync.interacted() state.find?.focus() @@ -523,7 +528,12 @@ export function SessionFileView(props: { session: MountedSession; screen: Sessio ) return ( -
+
(state.root = el)} + class="relative h-full min-h-0 flex flex-col" + classList={{ "mt-3": !artifact() }} + > + {(value) => ( diff --git a/packages/gui-plugins/src/pairing/dialog.stories.tsx b/packages/gui-plugins/src/pairing/dialog.stories.tsx index e763b94adb8f..addccef5bf86 100644 --- a/packages/gui-plugins/src/pairing/dialog.stories.tsx +++ b/packages/gui-plugins/src/pairing/dialog.stories.tsx @@ -2,16 +2,20 @@ import { onMount } from "solid-js" import { PairingHost, pairingRemote } from "../../../stories/mocks/gui-plugins/pairing" import PairingPage from "./page" -function PairingDialogStory(props: { mode: "ready" | "pending" | "failed" }) { - const mock = pairingRemote({ enabled: props.mode === "ready" }) +function PairingDialogStory(props: { + mode: "ready" | "pending" | "failed" + response?: "Code request fails" | "Copy fails" +}) { + const mock = pairingRemote({ + enabled: props.mode === "ready", + response: props.mode === "failed" ? "Remote change fails" : props.response, + }) const client = { ...mock.client, setRemote: (...args: Parameters) => { if (props.mode === "pending") return new Promise(() => {}) - if (props.mode === "failed") return Promise.reject(new Error("Unable to enable remote access")) - return mock.client.setRemote(...args) }, } @@ -21,7 +25,7 @@ function PairingDialogStory(props: { mode: "ready" | "pending" | "failed" }) { onMount(() => root.getElementsByTagName("button")[0].click()) return ( - +
mock.server} pairing={() => ({ status: "active", value: client, generation: 1 })} />
@@ -39,3 +43,7 @@ export const Ready = { render: () => } export const SettingUp = { render: () => } export const Failed = { render: () => } + +export const CodeRequestFailed = { render: () => } + +export const CopyFailsOnce = { render: () => } diff --git a/packages/gui-plugins/src/pairing/page.stories.tsx b/packages/gui-plugins/src/pairing/page.stories.tsx index 52b0ba69f59a..031b21f0a95b 100644 --- a/packages/gui-plugins/src/pairing/page.stories.tsx +++ b/packages/gui-plugins/src/pairing/page.stories.tsx @@ -1,46 +1,108 @@ -import { PairingHost, pairingRemote } from "../../../stories/mocks/gui-plugins/pairing" +import { createMemo, Show } from "solid-js" +import { PairingHost, pairingRemote, pairingResponses } from "../../../stories/mocks/gui-plugins/pairing" +import type { MainStatus } from "./machine" import PairingPage from "./page" -const story = (remote: { enabled: boolean; fails?: boolean; screenFails?: boolean }, main = true) => ({ - render: () => { - const mock = pairingRemote(remote) - - return ( - - mock.server} - pairing={() => - main ? { status: "active", value: mock.client, generation: 1 } : { status: "inactive", reason: "disabled" } - } - /> - - ) - }, +type Args = { + mainProcess: MainStatus["status"] + localServer: boolean + remoteAccess: boolean + keepScreenActive: boolean + response: (typeof pairingResponses)[number] + codeLifetimeSeconds: number +} + +function PairingStory(args: Args) { + const fixture = createMemo(() => + pairingRemote({ + enabled: args.remoteAccess, + screenActive: args.keepScreenActive, + response: args.response, + expiresIn: args.codeLifetimeSeconds, + }), + ) + + return ( + + {(mock) => ( + + (args.localServer ? mock.server : undefined)} + pairing={() => { + if (args.mainProcess === "pending") return { status: "pending" } + + if (args.mainProcess === "inactive") return { status: "inactive", reason: "disabled" } + + return { status: "active", value: mock.client, generation: 1 } + }} + /> + + )} + + ) +} + +// Each preset starts a fresh page. Within it, losing main or the server also reaches an already-open dialog. +const story = (args: Partial = {}) => ({ + args, + render: (props: Args) => , }) export default { - title: "Plugins/Pairing", + title: "App/Plugins/Pairing", id: "plugins-pairing", + args: { + mainProcess: "active", + localServer: true, + remoteAccess: true, + keepScreenActive: false, + response: "Normal", + codeLifetimeSeconds: 300, + } satisfies Args, + argTypes: { + mainProcess: { control: "select", options: ["active", "pending", "inactive"] satisfies Args["mainProcess"][] }, + response: { control: "select", options: pairingResponses }, + codeLifetimeSeconds: { control: { type: "range", min: 5, max: 300, step: 5 } }, + }, parameters: { docs: { description: { - component: "Settings → Pairing on desktop: pair a device from anywhere through remote access, and its QR code.", + component: + "Desktop Pairing settings. Change a switch or open Pair device to exercise setup, refresh, copy and retry using local fixtures.", }, }, }, } /** Remote access is on, so Pair device shows the QR code at once. */ -export const RemoteOn = story({ enabled: true }) +export const RemoteOn = story() /** The first pairing turns remote access on, then shows the QR code once the tunnel connects. */ -export const FirstPairing = story({ enabled: false }) +export const FirstPairing = story({ remoteAccess: false }) /** Remote access cannot be turned on, so the dialog offers to try again. */ -export const SetupFails = story({ enabled: false, fails: true }) +export const SetupFails = story({ remoteAccess: false, response: "Remote change fails" }) /** Pairing's main side is not running, so remote access cannot be turned on and pairing is unavailable. */ -export const WithoutMainProcess = story({ enabled: false }, false) +export const WithoutMainProcess = story({ remoteAccess: false, mainProcess: "inactive" }) /** The display sleep setting cannot be read at first; after the retries, Try again reads it and the switch stays enabled. */ -export const ScreenSettingFails = story({ enabled: true, screenFails: true }) +export const ScreenSettingFails = story({ response: "Screen read fails" }) + +export const MainStarting = story({ mainProcess: "pending" }) + +export const WithoutLocalServer = story({ localServer: false }) + +export const ScreenAwake = story({ keepScreenActive: true }) + +export const RemoteSettingFails = story({ remoteAccess: false, response: "Remote read fails" }) + +export const ScreenChangeFails = story({ keepScreenActive: true, response: "Screen change fails" }) + +export const TunnelConnecting = story({ response: "Tunnel connects slowly" }) + +export const CodeRequestFails = story({ response: "Code request fails" }) + +export const CopyFails = story({ response: "Copy fails" }) + +export const ExpiringCode = story({ codeLifetimeSeconds: 5 }) diff --git a/packages/gui-plugins/src/review/panel.stories.tsx b/packages/gui-plugins/src/review/panel.stories.tsx new file mode 100644 index 000000000000..d97258e2b79d --- /dev/null +++ b/packages/gui-plugins/src/review/panel.stories.tsx @@ -0,0 +1,35 @@ +import { lazy, Show, Suspense } from "solid-js" +import type { ChangesScenario } from "../../../stories/mocks/gui-plugins/workspace-panel" + +const Panel = lazy(() => import("../../../stories/mocks/gui-plugins/workspace-panel")) + +export default { + title: "App/Plugins/Review", + id: "plugins-review", + parameters: { + layout: "fullscreen", + docs: { + description: { + component: + "Select or filter a changed file, switch diff layouts, and leave a line comment. The failed working-tree read succeeds on retry.", + }, + }, + }, + args: { scenario: "Changes" }, + argTypes: { scenario: { control: "select", options: ["Changes", "Clean", "Read error", "Offline"] } }, + render: (args: { scenario: ChangesScenario }) => ( + + + {(scenario) => } + + + ), +} + +export const ChangesAndComments = {} + +export const Empty = { args: { scenario: "Clean" } } + +export const ReadError = { args: { scenario: "Read error" } } + +export const Offline = { args: { scenario: "Offline" } } diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index aea18291a4ca..6623b635d791 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -16687,9 +16687,6 @@ "artifacts": { "type": "boolean" }, - "shell_timeout_background": { - "type": "boolean" - }, "console_watches": { "type": "boolean" }, diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index f82cb806850c..3111d6f06bfd 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -15,7 +15,6 @@ export const registry = { media_blob: "Store new session media once in a deduplicated blob table instead of inline in every message row.", schedules: "Enable experimental scheduled tasks that wake a session with a prompt.", artifacts: "Enable experimental artifacts backed by pluggable providers.", - shell_timeout_background: "Move foreground shell commands to the background when their timeout expires.", console_watches: "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console, and wake sessions when they change.", mcp_events: diff --git a/packages/server/test/schema-error.test.ts b/packages/server/test/schema-error.test.ts index b0f9c213960b..fb65c5cde463 100644 --- a/packages/server/test/schema-error.test.ts +++ b/packages/server/test/schema-error.test.ts @@ -2,6 +2,7 @@ import { expect } from "bun:test" import { Generate } from "@opencode/core/generate" import { makeLocationNode } from "@opencode/util/effect/app-node" import { Effect, Layer } from "effect" +import { tmpdirScoped } from "../../core/test/fixture/tmpdir" import { it } from "../../core/test/lib/effect" import { ServerFetch } from "../src/fetch" @@ -21,8 +22,10 @@ const generate = makeLocationNode({ it.live("reports response encoding failures as server errors and request decoding failures as bad requests", () => Effect.gen(function* () { + const config = yield* tmpdirScoped() const handler = yield* ServerFetch.make( { + config: { directory: config.path, project: false }, database: { path: ":memory:" }, fs: { filewatcher: false }, models: { fetch: false }, diff --git a/packages/server/test/session-diff.test.ts b/packages/server/test/session-diff.test.ts index bafcfa07b263..e822acd4e358 100644 --- a/packages/server/test/session-diff.test.ts +++ b/packages/server/test/session-diff.test.ts @@ -55,6 +55,7 @@ it.live("serves turn diffs by user message with range validation", () => const handler = yield* ServerFetch.make( { app: { version: "test-version" }, + config: { directory: tmp.path, project: false }, database: { path: ":memory:" }, fs: { filewatcher: false }, models: { fetch: false }, diff --git a/packages/session-ui/component-tests/session-shell.spec.ts b/packages/session-ui/component-tests/session-shell.spec.ts index d209ed5bb717..c5f5f3ba0958 100644 --- a/packages/session-ui/component-tests/session-shell.spec.ts +++ b/packages/session-ui/component-tests/session-shell.spec.ts @@ -56,6 +56,22 @@ for (const [id, output] of [ }) } +for (const [outcome, label] of [ + ["nonzero", "Exit 1"], + ["timeout", "Timed out"], + ["killed", "Stopped"], +]) { + story(`shows the new timeline's user-shell ${outcome} outcome without output`, async ({ mount }) => { + const root = await mount("timeline-next-user-command--live-command", { args: { outcome, output: false } }) + const shell = root.locator('[data-component="session-shell-message"]') + await expect(shell).not.toContainText(label) + await root.getByRole("button", { name: "Complete command", exact: true }).click() + await expect(shell.getByText(label, { exact: true })).toBeVisible() + await expect(shell).toContainText("printf ready") + await expect(shell.locator('[data-slot="bash-result"]')).toHaveCount(0) + }) +} + story("copies the shell command and its output separately", async ({ mount, page }) => { const root = await mount("current-session-terminal-work--expanded-shell") const shell = root.locator('[data-component="bash-output"]') @@ -86,6 +102,8 @@ story("keeps Copied for two seconds after the latest click", async ({ mount, pag // The first click's reset falls due here, while the second click's feedback still runs. await page.clock.runFor(900) await expect(result.getByRole("button", { name: "Copied" })).toBeVisible() + await expect(page.getByRole("tooltip", { name: "Copied" })).toBeVisible() await page.clock.runFor(1_200) await expect(result.getByRole("button", { name: "Copy output", exact: true })).toBeVisible() + await expect(page.getByRole("tooltip")).toBeHidden() }) diff --git a/packages/session-ui/src/components/copy.ts b/packages/session-ui/src/components/copy.ts index e16df0856a0d..a6e42772fc1e 100644 --- a/packages/session-ui/src/components/copy.ts +++ b/packages/session-ui/src/components/copy.ts @@ -35,15 +35,23 @@ export async function writeClipboard(text: string): Promise { return copied } -/** "Copied" feedback for one copy button. Owner cleanup clears its reset timer and drops a write still in flight. */ -export function createCopyFeedback() { +/** "Copied" feedback for one copy button. Owner cleanup clears the timer and ignores a write still in flight. */ +export function createCopyFeedback(options?: { + write: (text: string) => Promise + onError: () => void +}) { + const write = options?.write ?? writeClipboard + const [state, setState] = createSignal(INITIAL_COPY_FEEDBACK_STATE) let timer: ReturnType | undefined const dispatch = (event: CopyFeedbackEvent) => { const next = transitionCopyFeedback(untrack(state), event) - if (next.state !== untrack(state)) setState(next.state) + if (next.state === untrack(state)) return + setState(next.state) + + if (event.type === "copy.failed") options?.onError() next.effects.forEach(run) } @@ -61,8 +69,8 @@ export function createCopyFeedback() { return } - void writeClipboard(effect.text).then( - (written) => dispatch({ type: written ? "copy.succeeded" : "copy.failed", attempt: effect.attempt }), + void Promise.try(() => write(effect.text)).then( + (written) => dispatch({ type: written === false ? "copy.failed" : "copy.succeeded", attempt: effect.attempt }), () => dispatch({ type: "copy.failed", attempt: effect.attempt }), ) } diff --git a/packages/session-ui/src/components/dock-prompt.stories.tsx b/packages/session-ui/src/components/dock-prompt.stories.tsx index a954c62ad120..6bdacda3abe4 100644 --- a/packages/session-ui/src/components/dock-prompt.stories.tsx +++ b/packages/session-ui/src/components/dock-prompt.stories.tsx @@ -5,6 +5,7 @@ export default { title: "OpenCode/Requests/Prompt frame", id: "components-dock-prompt", component: DockPrompt, + args: { experimental: false }, parameters: { docs: { description: { @@ -16,17 +17,19 @@ export default { } export const Question = { - render: () => ( + args: { prompt: "Which Session layout should I implement?", hint: "Select one answer" }, + render: (args: { experimental: boolean; prompt: string; hint: string }) => (
Question
-
Which Session layout should I implement?
-
Select one answer
+
{args.prompt}
+
{args.hint}
} @@ -47,9 +50,11 @@ export const Question = { } export const Permission = { - render: () => ( + args: { command: "npm publish --tag canary" }, + render: (args: { experimental: boolean; command: string }) => ( Permission required
} footer={ <> @@ -62,7 +67,7 @@ export const Permission = { } > - npm publish --tag canary + {args.command} ), } diff --git a/packages/session-ui/src/components/file-media.stories.tsx b/packages/session-ui/src/components/file-media.stories.tsx new file mode 100644 index 000000000000..3875a51283ba --- /dev/null +++ b/packages/session-ui/src/components/file-media.stories.tsx @@ -0,0 +1,112 @@ +import { Button } from "@opencode/ui/button" +import { FileComponentProvider } from "@opencode/ui/context/file" +import { createMemo, createSignal, onCleanup, Show } from "solid-js" +import audio from "@opencode/ui/audio/alert-03.mp3?inline" +import image from "../../../ui/src/assets/favicon/web-app-manifest-192x192.png?inline" +import type { PresentationFileContent, PresentationFileDiff } from "../file-presentation" +import { File } from "./file" +import { SessionReview } from "./session-review" + +const states = ["ready", "loading", "unavailable", "failed", "deleted"] as const + +type Args = { kind: "image" | "audio"; state: (typeof states)[number] } + +function MediaReview(props: Args) { + const path = props.kind === "image" ? "assets/app-icon.png" : "assets/notification.mp3" + + const payload: PresentationFileContent = { + type: "binary", + encoding: "base64", + mimeType: props.kind === "image" ? "image/png" : "audio/mpeg", + content: (props.kind === "image" ? image : audio).split(",")[1]!, + } + + // A Git LFS pointer is a text diff. Review expands it and FileMedia reads the underlying asset by path. + const pointer = (hash: string) => + `version https://git-lfs.github.com/spec/v1\noid sha256:${hash.repeat(64)}\nsize 8102\n` + + const diffs: PresentationFileDiff[] = [ + { + file: path, + status: props.state === "deleted" ? "deleted" : "modified", + before: pointer("0"), + after: props.state === "deleted" ? "" : pointer("1"), + additions: props.state === "deleted" ? 0 : 1, + deletions: props.state === "deleted" ? 3 : 1, + }, + ] + + const [state, setState] = createSignal(props.state) + + let finish: ((content?: PresentationFileContent) => void) | undefined + + onCleanup(() => finish?.()) + + const readFile = createMemo(() => { + const scenario = state() + + if (scenario === "unavailable" || scenario === "deleted") return undefined + + return async (file: string) => { + if (file !== path) return + + if (scenario === "failed") throw new Error(`Could not read ${file}`) + + if (scenario === "loading") + return new Promise((resolve) => { + finish = resolve + }) + + return payload + } + }) + + const complete = () => { + finish?.(payload) + setState("ready") + } + + return ( + +
+ + + + } + /> +
+
+ ) +} + +export default { + title: "OpenCode/Review/File media", + id: "review-file-media", + args: { kind: "image", state: "ready" } satisfies Args, + argTypes: { kind: { options: ["image", "audio"] }, state: { options: states } }, + render: (args: Args) => ( + + {(scenario) => } + + ), +} + +export const ImagePreview = {} + +export const AudioPreview = { args: { kind: "audio" } } + +export const Loading = { args: { state: "loading" } } + +export const Unavailable = { args: { state: "unavailable" } } + +export const FailedRead = { args: { state: "failed" } } + +export const Removed = { args: { state: "deleted" } } diff --git a/packages/session-ui/src/components/line-comment.stories.tsx b/packages/session-ui/src/components/line-comment.stories.tsx index e548a81b8ddd..1c93ac476ae4 100644 --- a/packages/session-ui/src/components/line-comment.stories.tsx +++ b/packages/session-ui/src/components/line-comment.stories.tsx @@ -1,4 +1,4 @@ -import { createSignal } from "solid-js" +import { createEffect, createSignal } from "solid-js" import { LineComment, LineCommentAnchor, LineCommentEditor } from "./line-comment" const docs = `### Overview @@ -30,6 +30,7 @@ export default { title: "OpenCode/Review/Line comments", id: "components-line-comment", component: LineComment, + args: { inline: false }, tags: ["autodocs"], parameters: { docs: { @@ -41,29 +42,45 @@ export default { } export const Default = { - render: () => ( -
-
12 | const total = sum(values)
-
13 | return total / values.length
- -
- ), + args: { open: true, comment: "Consider guarding against empty arrays.", selection: "L12-L13" }, + render: (args: { inline: boolean; open: boolean; comment: string; selection: string }) => { + const [open, setOpen] = createSignal(args.open) + createEffect(() => setOpen(args.open)) + + return ( +
+
12 | const total = sum(values)
+
13 | return total / values.length
+ setOpen(!open())} + /> +
+ ) + }, } export const Editor = { - render: () => { - const [value, setValue] = createSignal("Add context for this change.") + args: { comment: "Add context for this change.", selection: "L40", mentions: false }, + render: (args: { inline: boolean; comment: string; selection: string; mentions: boolean }) => { + const [value, setValue] = createSignal(args.comment) + createEffect(() => setValue(args.comment)) return (
40 | if (values.length === 0) return 0
["src/sum.ts", "src/sum.test.ts"].filter((path) => path.includes(query)) } + : undefined + } onInput={setValue} onCancel={() => setValue("")} onSubmit={(next) => setValue(next)} @@ -93,23 +116,37 @@ export const Editor = { } export const AnchorOnly = { - render: () => ( -
-
20 | const ready = true
- -
Anchor content
-
-
- ), + args: { open: false, icon: "comment" }, + argTypes: { icon: { options: ["comment", "plus"] } }, + render: (args: { inline: boolean; open: boolean; icon: "comment" | "plus" }) => { + const [open, setOpen] = createSignal(args.open) + createEffect(() => setOpen(args.open)) + + return ( +
+
20 | const ready = true
+ setOpen(!open())} + > +
Anchor content
+
+
+ ) + }, } diff --git a/packages/session-ui/src/components/markdown.stories.tsx b/packages/session-ui/src/components/markdown.stories.tsx index 0d8a145decca..d6151572b95a 100644 --- a/packages/session-ui/src/components/markdown.stories.tsx +++ b/packages/session-ui/src/components/markdown.stories.tsx @@ -1,5 +1,5 @@ import { markdown } from "@opencode/ui/storybook/fixtures" -import { createSignal, onCleanup } from "solid-js" +import { createEffect, createSignal, onCleanup } from "solid-js" import { Markdown } from "./markdown" export default { @@ -17,19 +17,19 @@ export default { } export const CompleteResponse = { - render: () => ( + args: { text: markdown }, + render: (args: { text: string }) => (
- +
), } export const CompactResult = { - render: () => ( + args: { text: "Updated the Session status and verified it.\n\n- **12 tests passed**\n- `bun typecheck` passed" }, + render: (args: { text: string }) => (
- +
), } @@ -56,54 +56,79 @@ export const Table = { const streamed = "Streaming Markdown now keeps existing elements alive while each newly arriving word fades into the response." -function StreamingMarkdown() { - const words = streamed.match(/\S+\s*/g) ?? [] +const playback = { + args: { playback: "live" }, + argTypes: { playback: { options: ["live", "partial", "complete"] } }, +} + +function StreamingMarkdown(props: { playback: string; chunks: string[]; interval: number; loop?: boolean }) { const [count, setCount] = createSignal(1) - const timer = setInterval(() => setCount((value) => Math.min(value + 1, words.length)), 180) - onCleanup(() => clearInterval(timer)) - return + createEffect(() => { + const length = props.chunks.length + + if (props.playback === "complete") return setCount(length) + + if (props.playback === "partial") return setCount(Math.ceil(length / 2)) + setCount(1) + + const timer = setInterval( + () => + setCount((value) => { + if (value < length) return value + 1 + + if (props.loop) return 1 + clearInterval(timer) + + return length + }), + props.interval, + ) + + onCleanup(() => clearInterval(timer)) + }) + + return ( + + ) } export const StreamingResponse = { - render: () => ( + ...playback, + render: (args: { playback: string }) => (
- +
), } -function StreamingInlineCodeMarkdown() { - const chunks = [ - "Updated ", - "`apps/cloud", - "flare/src/", - "editor/Cloud", - "Auth.ts:29", - "-43` and ", - "`packages/", - "session-ui/src/", - "components/markdown", - "-solid.tsx`, ", - "then verified ", - "the changes with ", - "`bun type", - "check` and ", - "`bun te", - "st`.", - ] - - const [count, setCount] = createSignal(1) - const timer = setInterval(() => setCount((value) => (value >= chunks.length ? 1 : value + 1)), 220) - onCleanup(() => clearInterval(timer)) - - return -} +const inlineCodeChunks = [ + "Updated ", + "`apps/cloud", + "flare/src/", + "editor/Cloud", + "Auth.ts:29", + "-43` and ", + "`packages/", + "session-ui/src/", + "components/markdown", + "-solid.tsx`, ", + "then verified ", + "the changes with ", + "`bun type", + "check` and ", + "`bun te", + "st`.", +] export const StreamingInlineCode = { - render: () => ( + ...playback, + render: (args: { playback: string }) => (
- +
), } @@ -122,32 +147,11 @@ const externalLinkChunks = [ ": No third-party request.", ] -function StreamingExternalLinks() { - const [count, setCount] = createSignal(1) - - const timer = setInterval(() => { - setCount((value) => { - if (value === externalLinkChunks.length) { - clearInterval(timer) - - return value - } - - return value + 1 - }) - }, 380) - - onCleanup(() => clearInterval(timer)) - - return ( - - ) -} - export const ExternalLinksStreaming = { - render: () => ( + ...playback, + render: (args: { playback: string }) => (
- +
), } diff --git a/packages/session-ui/src/components/markdown.tsx b/packages/session-ui/src/components/markdown.tsx index 099398d15e23..d0d120efb061 100644 --- a/packages/session-ui/src/components/markdown.tsx +++ b/packages/session-ui/src/components/markdown.tsx @@ -206,7 +206,7 @@ function MarkdownCopyButton(props: { labels: CodeLabels; copied: boolean }) { const label = () => (props.copied ? props.labels.copied : props.labels.copy) return ( - +
diff.file)} split={props.split} + overflow={props.overflow} + disableLineNumbers={props.disableLineNumbers} />
@@ -37,16 +41,19 @@ export default { } export const Unified = { - render: () => , + args: { split: false, empty: false, disableLineNumbers: false, overflow: "wrap" }, + argTypes: { overflow: { options: ["wrap", "scroll"] } }, + render: (args: ReviewArgs) => , } export const Split = { - render: () => , + ...Unified, + args: { ...Unified.args, split: true }, } export const UnifiedDark = { + ...Unified, globals: { theme: "dark" }, - render: () => , } const commentFile = "src/review.ts" @@ -211,11 +218,14 @@ export const LargeFile = { const padding = `// ${"unchanged ".repeat(70)}\n`.repeat(800) const before = { name: "large.ts", contents: `export const value = 'before'\n${padding}` } const after = { name: "large.ts", contents: `export const value = 'after'\n${padding}` } - const input = args.source === "metadata" ? { fileDiff: parseDiffFromFile(before, after) } : { before, after } return (
- +
) }, diff --git a/packages/session-ui/src/components/tool-count-summary.stories.tsx b/packages/session-ui/src/components/tool-count-summary.stories.tsx index e2e61497399c..ba12852fa8cd 100644 --- a/packages/session-ui/src/components/tool-count-summary.stories.tsx +++ b/packages/session-ui/src/components/tool-count-summary.stories.tsx @@ -1,4 +1,5 @@ import { Button } from "@opencode/ui/button" +import { createEffect } from "solid-js" import { createStore } from "solid-js/store" import { AnimatedCountList, type CountItem } from "./tool-count-summary" import { ToolStatusTitle } from "./tool-status-title" @@ -8,8 +9,14 @@ const text = { done: "Explored", } as const -function ContextProgress() { - const [state, setState] = createStore({ reads: 2, searches: 1, lists: 0, active: true }) +type Counts = { reads: number; searches: number; lists: number; active: boolean } + +function ContextProgress(props: Counts) { + const [state, setState] = createStore({ ...props }) + + for (const key of ["reads", "searches", "lists", "active"] as const) { + createEffect(() => setState({ [key]: props[key] })) + } const items = (): CountItem[] => [ { key: "ui.messagePart.context.read", count: state.reads }, @@ -17,7 +24,7 @@ function ContextProgress() { { key: "ui.messagePart.context.list", count: state.lists }, ] - const reset = () => setState({ reads: 2, searches: 1, lists: 0, active: true }) + const reset = () => setState({ ...props }) return (
@@ -54,6 +61,9 @@ export default { title: "OpenCode/Work/Context progress", id: "components-animated-count-list", component: AnimatedCountList, + argTypes: Object.fromEntries( + ["reads", "searches", "lists"].map((key) => [key, { control: { type: "range", min: 0, max: 100, step: 1 } }]), + ), parameters: { docs: { description: { @@ -65,19 +75,21 @@ export default { } export const Exploring = { - render: () => , + args: { reads: 2, searches: 1, lists: 0, active: true }, + render: (args: Counts) => , } export const Completed = { - render: () => ( + args: { reads: 5, searches: 3, lists: 1, active: false }, + render: (args: Counts) => ( - + diff --git a/packages/session-ui/src/components/tool-error-card.stories.tsx b/packages/session-ui/src/components/tool-error-card.stories.tsx index f2aebe8789f5..8d2cfa3a058c 100644 --- a/packages/session-ui/src/components/tool-error-card.stories.tsx +++ b/packages/session-ui/src/components/tool-error-card.stories.tsx @@ -76,6 +76,7 @@ export default { tool: samples[0].tool, error: samples[0].error, subtitle: samples[0].subtitle, + defaultOpen: false, }, argTypes: { tool: { @@ -89,16 +90,14 @@ export default { control: "text", }, }, - render: (props: { tool: string; error: string; subtitle?: string }) => { - return - }, } export const All = { - render: () => { + render: (args: { tool: string; error: string; subtitle?: string; defaultOpen: boolean }) => { return (
- + + {(item) => ( } diff --git a/packages/session-ui/src/message/message-content.tsx b/packages/session-ui/src/message/message-content.tsx index ed42197060a7..1d8e3831ea9f 100644 --- a/packages/session-ui/src/message/message-content.tsx +++ b/packages/session-ui/src/message/message-content.tsx @@ -134,17 +134,15 @@ function MetaItems(props: { items: MetaItem[]; slot: "user-message" | "text-part function MessageActionButton( props: Pick, "disabled" | "onMouseDown" | "onClick" | "aria-label"> & { - icon: "check" | "copy" + copied: boolean label: JSX.Element size?: "small" | "normal" }, ) { - const icon = () => (props.icon === "copy" ? "outline-copy" : props.icon) - return ( - + } + icon={} size={props.size ?? "normal"} variant="ghost-muted" disabled={props.disabled} @@ -1248,7 +1246,7 @@ export function AssistantTextContent(props: { data-copy-always-visible={data.copyAlwaysVisible ? "" : undefined} > event.preventDefault()} diff --git a/packages/session-ui/src/message/prompt-message.stories.tsx b/packages/session-ui/src/message/prompt-message.stories.tsx index 645342f535ad..8ca8b52b834c 100644 --- a/packages/session-ui/src/message/prompt-message.stories.tsx +++ b/packages/session-ui/src/message/prompt-message.stories.tsx @@ -1,4 +1,4 @@ -import { createMemo, For, Show } from "solid-js" +import { createEffect, createMemo, For, Show } from "solid-js" import { createStore } from "solid-js/store" import type { SessionMessageUser } from "@opencode/client/promise" import type { SessionUserActions } from "../actions" @@ -6,31 +6,26 @@ import { CurrentUserMessageDisplay } from "./message-content" import { CurrentSessionProviders } from "../storybook/current-session-story" import { CURRENT_SESSION_ID, STORY_MODEL, STORY_TIME } from "../storybook/current-session-fixtures" +const statuses = ["delivered", "starting", "steering", "stranded", "queued", "sending"] as const + +type Args = { status: (typeof statuses)[number]; voice: boolean; text: boolean; grouped: boolean; fails: boolean } + export default { title: "OpenCode/Conversation/Prompt message", id: "current-prompt-message", parameters: { layout: "fullscreen" }, + args: { status: "steering", voice: false, text: true, grouped: false, fails: false } satisfies Args, + argTypes: { status: { options: statuses } }, } export const Pending = { - render: () => { - const statuses = ["delivered", "starting", "steering", "stranded", "queued", "sending"] as const + render: (args: Args) => { + const [state, setState] = createStore({ ...args, failures: 0 }) - const [state, setState] = createStore<{ - status: (typeof statuses)[number] - voice: boolean - text: boolean - grouped: boolean - fails: boolean - failures: number - }>({ - status: "steering", - voice: false, - text: true, - grouped: false, - fails: false, - failures: 0, - }) + // Frame controls and host callbacks can still change the fixture after a panel edit. + for (const key of ["status", "voice", "text", "grouped", "fails"] as const) { + createEffect(() => setState({ [key]: args[key] })) + } // A failing host rejects, like a server error, and leaves the message as it was. const attempt = async (apply: () => void) => { @@ -146,3 +141,9 @@ export const Pending = { ) }, } + +export const SendingAttachment = { ...Pending, args: { status: "sending", text: false } } + +export const DeliveredVoice = { ...Pending, args: { status: "delivered", voice: true } } + +export const StrandedSteer = { ...Pending, args: { status: "stranded", grouped: true } } diff --git a/packages/session-ui/src/timeline-next/compaction.tsx b/packages/session-ui/src/timeline-next/compaction.tsx new file mode 100644 index 000000000000..492576dc2354 --- /dev/null +++ b/packages/session-ui/src/timeline-next/compaction.tsx @@ -0,0 +1,234 @@ +import type { SessionMessageCompaction } from "@opencode/client/promise" +import { Card } from "@opencode/ui/card" +import { useI18n } from "@opencode/ui/context/i18n" +import { createEffect, createMemo, createSignal, onCleanup, Show, untrack } from "solid-js" +import { BasicTool } from "../components/basic-tool" +import { LinkedText } from "../components/linked-text" +import { useData } from "../context" +import { + createCompactionEntranceState, + DISPOSED_COMPACTION_ENTRANCE_EVENT, + GRACE_ELAPSED_EVENT, + selectCompactionEnter, + transitionCompactionEntrance, + type CompactionEntranceEffect, + type CompactionEntranceEvent, +} from "../message/compaction-entrance-machine" +import { PacedMarkdown } from "../message/message-content" +import { Separator } from "./separator" + +/** A compaction the server admitted but has not started, drawn as the divider a started one opens with. */ +export function CompactionQueued() { + const i18n = useI18n() + + return ( +
+ +
+ ) +} + +/** + * A compaction, drawn with the timeline's own dividers: as tall as their text, with a plain line, spaced like the rows + * around them. An automatic one with background compaction on is one quiet divider instead. + */ +export function CompactionMessage(props: { message: SessionMessageCompaction; error: string }) { + const i18n = useI18n() + const data = useData() + const summary = () => (props.message.status === "failed" ? "" : props.message.summary) + + const error = () => { + if (props.message.status !== "failed") return "" + + if (props.message.error.type === "aborted" || props.message.error.type === "compaction.interrupted") return "" + + return props.error + } + + const compact = createMemo( + () => new Intl.NumberFormat(i18n.locale(), { notation: "compact", maximumFractionDigits: 1 }), + ) + + // Usage of the compaction request itself; the resulting context size only shows on the next assistant step. + const usage = () => { + if (props.message.status === "running" || !props.message.tokens) return "" + const tokens = props.message.tokens + const input = tokens.input + tokens.cache.read + tokens.cache.write + const output = tokens.output + tokens.reasoning + + if (input + output <= 0) return "" + + return i18n.t("ui.messagePart.compaction.usage", { + input: compact().format(input), + output: compact().format(output), + }) + } + + const outcome = () => { + if (props.message.status !== "failed") + return props.message.status === "completed" && props.message.native?.messages + ? "ui.messagePart.providerCompaction" + : "ui.messagePart.compaction" + + if (props.message.error.type === "aborted") return "ui.messagePart.compaction.cancelled" + + if (props.message.error.type === "compaction.interrupted") return "ui.messagePart.compaction.interrupted" + + return "ui.messagePart.compaction.failed" + } + + const label = createMemo(() => [i18n.t(outcome()), usage()].filter(Boolean).join(" · ")) + + return ( + + } + > +
+ + +
+
+ +
+
+
+ +
+ +
+
+ + + + + + + + +
+
+ ) +} + +/** + * An automatic compaction, drawn as one divider that reads Compacting, then Compacted. Its height never changes, and + * clicking it opens the summary. + */ +function QuietCompaction(props: { id: string; created: number; running: boolean; summary: string; usage: string }) { + const i18n = useI18n() + const [open, setOpen] = createSignal(false) + // A new one waits out the grace before showing Compacting; one that ends inside it, as a precomputed summary does, + // only fades in as Compacted. One already running or finished when the history loads shows without an entrance. + const initial = createCompactionEntranceState({ ageMs: Date.now() - props.created, running: props.running }) + const [entrance, setEntrance] = createSignal(initial.state) + const enter = createMemo(() => selectCompactionEnter(entrance())) + let graceTimer: ReturnType | undefined + + const runEntrance = (effect: CompactionEntranceEffect) => { + clearTimeout(graceTimer) + graceTimer = undefined + + if (effect.type === "schedule-grace") + graceTimer = setTimeout(() => dispatchEntrance(GRACE_ELAPSED_EVENT), effect.delayMs) + } + + const dispatchEntrance = (event: CompactionEntranceEvent) => { + const result = transitionCompactionEntrance(untrack(entrance), event) + setEntrance(result.state) + result.effects.forEach(runEntrance) + } + + initial.effects.forEach(runEntrance) + createEffect(() => dispatchEntrance({ type: "running.changed", running: props.running })) + onCleanup(() => dispatchEntrance(DISPOSED_COMPACTION_ENTRANCE_EVENT)) + + const expandable = () => !props.running && !!props.summary.trim() + + const label = createMemo(() => + splitEnding(i18n.t("ui.messagePart.compaction.running"), i18n.t("ui.messagePart.compaction.done")), + ) + + return ( +
+ + +
+
+
+ +
+
+ +
{props.usage}
+
+
+
+
+ ) +} + +/** Splits Compacting and Compacted at their shared stem, so only the ending changes when the compaction ends. */ +function splitEnding(running: string, done: string) { + const chars = [...running] + const others = [...done] + const at = chars.findIndex((char, index) => char !== others[index]) + const stem = chars.slice(0, at === -1 ? chars.length : at).join("") + + return { running, done, stem, ending: { running: running.slice(stem.length), done: done.slice(stem.length) } } +} diff --git a/packages/session-ui/src/timeline-next/event-row.tsx b/packages/session-ui/src/timeline-next/event-row.tsx index b612d7a39be1..b00622c01665 100644 --- a/packages/session-ui/src/timeline-next/event-row.tsx +++ b/packages/session-ui/src/timeline-next/event-row.tsx @@ -70,7 +70,8 @@ export function TimelineEventRow(props: { ) } -function TimelineEventItem(props: { event: TimelineEvent; onRevealShell?: (shellID: string) => void }) { +/** One subagent or shell an events row or an opened activity group lists: who did it and what it was. */ +export function TimelineEventItem(props: { event: TimelineEvent; onRevealShell?: (shellID: string) => void }) { const i18n = useI18n() const data = useData() diff --git a/packages/session-ui/src/timeline-next/events.ts b/packages/session-ui/src/timeline-next/events.ts index d4d159f23bbe..fbc3cf699c29 100644 --- a/packages/session-ui/src/timeline-next/events.ts +++ b/packages/session-ui/src/timeline-next/events.ts @@ -35,10 +35,12 @@ export const kindKeys = { shell: "ui.timeline.event.shells", } as const -/** How a group's label counts work it started, beside its other calls: "1 command, started 1 shell". */ +/** How a group's label counts work that runs on, beside its other calls: "1 command, started 1 shell". */ export const launchKeys = { started: { shell: "ui.timeline.activity.startedShells", subagent: "ui.timeline.activity.startedSubagents" }, ran: { shell: "ui.timeline.activity.commands", subagent: "ui.timeline.activity.subagents" }, + finished: { shell: "ui.timeline.activity.finishedShells", subagent: "ui.timeline.activity.finishedSubagents" }, + stopped: { shell: "ui.timeline.activity.stoppedShells", subagent: "ui.timeline.activity.stoppedSubagents" }, } as const // Text a call or notice carries, where it is not empty. @@ -99,6 +101,13 @@ export function noticeEvent(message: SessionMessageInfo): TimelineEvent | undefi return { ...item, verb: "finished", failed: state === "error" } } +/** Which subagent or shell an event is about, where it says. */ +export function workKey(event: TimelineEvent) { + const id = event.kind === "shell" ? event.shellID : event.sessionID + + return id ? `${event.kind}:${id}` : undefined +} + /** * A run of events as one label: each verb once, in the order it first happened, with how many of each kind, and how * many failed overall. Two finishes in a row read "Finished 2 subagents". diff --git a/packages/session-ui/src/timeline-next/projection.test.ts b/packages/session-ui/src/timeline-next/projection.test.ts index 0aa1b5280854..2f07936191f9 100644 --- a/packages/session-ui/src/timeline-next/projection.test.ts +++ b/packages/session-ui/src/timeline-next/projection.test.ts @@ -2,7 +2,8 @@ import { describe, expect, test } from "bun:test" import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise" import { Predicate } from "effect" import { createRoot } from "solid-js" -import { timelinePresets } from "../timeline/detail" +import { subagentReport } from "../storybook/current-session-fixtures" +import { timelinePresets, type TimelineDetail } from "../timeline/detail" import { createNextTimelineProjection, workedDuration } from "./projection" import { replayScript, scenarios } from "./stories/session-replay" @@ -87,6 +88,164 @@ describe("New timeline projection", () => { expect(groups).toEqual(["first", "notice", "second"]) }) + + test("a subagent's report shows above the status line before the agent takes it, and the user's input below", () => { + const steer = { id: "steer", type: "user", text: "Also check the tests", time: { created: 2 } } as const + + const messages: SessionMessageInfo[] = [ + { id: "user", type: "user", text: "Go", time: { created: 0 } }, + step("working", 1, { + content: [ + { + id: "shell", + type: "tool", + name: "shell", + state: { status: "running", input: { command: "sleep 60" }, metadata: {} }, + time: { created: 1 }, + }, + ], + }), + steer, + subagentReport("report", 3, { + childID: "child", + agent: "explore", + state: "completed", + description: "Trace the bug", + body: "Found it.", + }), + ] + + const rows = (messages: SessionMessageInfo[], pending: ReadonlySet) => + createRoot((dispose) => { + const projection = createNextTimelineProjection({ + sessionMessages: () => messages, + status: () => ({ type: "busy" }), + timelineDetail: () => detailed, + pendingInputIDs: () => pending, + }) + + const result = projection.rows().map((row) => { + if (!Predicate.isTagged(row, "AssistantPart")) return row._tag + + return row.group.type === "part" + ? row.group.ref.messageID + : row.group.refs.map((ref) => ref.messageID).join("+") + }) + + dispose() + + return result + }) + + const alone = messages.filter((message) => message !== steer) + + expect(rows(alone, new Set(["report"]))).toEqual(["UserMessage", "working", "report"]) + expect(rows(messages, new Set(["steer", "report"]))).toEqual([ + "UserMessage", + "working", + "report", + "Activity", + "TurnGap", + "UserMessage", + ]) + }) + + test("a subagent finishes in the group that started it only when nothing comes between; otherwise it reports in its own row", () => { + const launched: SessionMessageInfo[] = [ + { id: "user", type: "user", text: "Go", time: { created: 0 } }, + step("launch", 1, { + finish: "tool-calls", + content: [ + { + id: "call", + type: "tool", + name: "subagent", + state: { + status: "completed", + input: { description: "Review the diff", agent: "review" }, + content: [{ type: "text", text: "" }], + metadata: { sessionID: "child", status: "running" }, + }, + time: { created: 1, completed: 2 }, + }, + ], + time: { created: 1, completed: 2 }, + }), + ] + + const report = subagentReport("report", 4, { + childID: "child", + agent: "review", + state: "completed", + description: "Review the diff", + body: "Looks good.", + }) + + const said = step("said", 3, { + finish: "stop", + content: [{ type: "text", text: "Started a review." }], + time: { created: 3, completed: 3 }, + }) + + const groups = (messages: SessionMessageInfo[], detail: TimelineDetail) => + createRoot((dispose) => { + const projection = createNextTimelineProjection({ + sessionMessages: () => messages, + status: () => ({ type: "idle" }), + timelineDetail: () => detail, + }) + + const result = projection + .rows() + .flatMap((row) => + Predicate.isTagged(row, "AssistantPart") && row.group.type !== "part" + ? [`${row.group.type}:${row.group.refs.map((ref) => ref.messageID).join("+")}`] + : [], + ) + + dispose() + + return result + }) + + const grouped = { ...detailed, subagents: { placement: "grouped" as const } } + + expect(groups([...launched, report], grouped)).toEqual(["context:launch+report"]) + expect(groups([...launched, said, report], grouped)).toEqual(["context:launch", "events:report"]) + expect(groups([...launched, report], detailed)).toEqual(["events:launch", "events:report"]) + }) + + test("a move shows only when it changes where the session is", () => { + const moved = (id: string, created: number, from: string, to: string): SessionMessageInfo => ({ + id, + type: "location-switched", + location: { directory: to }, + previous: { location: { directory: from } }, + time: { created }, + }) + + const messages: SessionMessageInfo[] = [ + { id: "user", type: "user", text: "Go", time: { created: 0 } }, + moved("into", 1, "/repo", "/repo-worktree"), + moved("again", 2, "/repo-worktree", "/repo-worktree"), + moved("back", 3, "/repo-worktree", "/repo"), + ] + + const notices = createRoot((dispose) => { + const projection = createNextTimelineProjection({ + sessionMessages: () => messages, + status: () => ({ type: "idle" }), + timelineDetail: () => detailed, + }) + + const result = projection.rows().flatMap((row) => (Predicate.isTagged(row, "Notice") ? [row.messageID] : [])) + dispose() + + return result + }) + + expect(notices).toEqual(["into", "back"]) + }) }) describe("workedDuration", () => { diff --git a/packages/session-ui/src/timeline-next/projection.ts b/packages/session-ui/src/timeline-next/projection.ts index ff2c382cf9f0..3fd26a0206ae 100644 --- a/packages/session-ui/src/timeline-next/projection.ts +++ b/packages/session-ui/src/timeline-next/projection.ts @@ -22,15 +22,17 @@ import { type TurnThinkingPlacement, } from "../timeline/turn-phase-machine" import { errorInfo } from "./errors" -import { noticeEvent } from "./events" +import { noticeEvent, toolEvent, workKey, type TimelineEvent } from "./events" import { contentGroup, contentShows, echoesUserShell, hidesActivity, liveThinkingShows, + movedInPlace, noticePlacement, textShows, + toolRule, } from "./rules" type Notice = Exclude @@ -314,18 +316,14 @@ function constructRows(input: Input) { }), ] - // Like the TUI, a queued compaction waits after the active turn and ahead of every undelivered input: - // steers, which own turns, and synthetic notices, which ride at the end of the active one. - const pendingAt = rows.findIndex( - (row) => - input.pendingInputIDs?.has(row.userMessageID) || - (Predicate.isTagged(row, "Notice") && input.pendingInputIDs?.has(row.messageID)), - ) + // Like the TUI, a queued compaction waits after the active turn and ahead of every steer still waiting for delivery. + // Notices waiting for delivery are already in the active turn, since they report what happened. + const pendingAt = rows.findIndex((row) => input.pendingInputIDs?.has(row.userMessageID)) rows.splice( pendingAt < 0 ? rows.length : pendingAt, 0, - // Live status ends the work the model has seen, so it stays above everything still waiting for delivery. + // Live status ends the turn, so it stays above the input the user steered in, which waits for the agent to reply. ...(input.status.type !== "idle" && activeMessageID && (pendingAt >= 0 || input.queuedCompactionIDs.length > 0) ? [new TimelineRow.Activity({ userMessageID: activeMessageID })] : []), @@ -377,10 +375,14 @@ function constructTurns(input: Input) { } input.messages.forEach((message) => { - if (echoesUserShell(message, userShellIDs)) return + if (echoesUserShell(message, userShellIDs) || movedInPlace(message)) return if (isNotice(message)) { - if (current) current.entries.push({ type: "notice", message }) + // A notice still waiting for delivery, such as a subagent reporting back, already happened, so it joins the + // working turn above the status line, even when input the user steered in meanwhile waits below it. + const turn = input.pendingInputIDs?.has(message.id) ? (execution?.turn ?? current) : current + + if (turn) turn.entries.push({ type: "notice", message }) else leading.push(message) return @@ -651,6 +653,25 @@ function groupNotices( // Live status renders nothing while other feedback shows, so a group below it spaces from the content above it. const above = Predicate.isTagged(previous, "Activity") ? result.at(-2) : previous const message = Predicate.isTagged(row, "Notice") ? messageByID.get(row.messageID) : undefined + const event = message && noticeEvent(message) + + // Work that reports back right after the activity group that started it, with nothing between, finishes there. + if ( + event && + !event.failed && + Predicate.isTagged(previous, "AssistantPart") && + previous.group.type === "context" && + previous.userMessageID === row.userMessageID && + launches(previous.group, event, messageByID) + ) { + result[result.length - 1] = new TimelineRow.AssistantPart({ + ...previous, + group: { ...previous.group, refs: [...previous.group.refs, { messageID: message.id, partID: message.id }] }, + }) + + return result + } + const type = message ? noticeGroup(detail, message) : undefined const current = @@ -710,6 +731,25 @@ function joins( return previous.type === "events" && current.type === "events" && notices(previous) && notices(current) } +// Whether an activity group started the work an event is about. +function launches( + group: Exclude, + event: TimelineEvent, + messageByID: ReadonlyMap, +) { + const key = workKey(event) + + return ( + key !== undefined && + group.refs.some((ref) => { + const content = resolveContent(messageByID.get(ref.messageID), ref.partID) + const launch = content?.type === "tool" && toolRule(content).layout === "event" ? toolEvent(content) : undefined + + return launch !== undefined && workKey(launch) === key + }) + ) +} + function noticeGroup(detail: TimelineDetail, message: SessionMessageInfo) { if (noticeEvent(message)) return "events" as const diff --git a/packages/session-ui/src/timeline-next/row.tsx b/packages/session-ui/src/timeline-next/row.tsx index 4ffa71fcc230..65ff02f7ee3f 100644 --- a/packages/session-ui/src/timeline-next/row.tsx +++ b/packages/session-ui/src/timeline-next/row.tsx @@ -31,8 +31,7 @@ import { useData } from "../context" import { useSources } from "../context/sources" import { turnSources } from "../sources/sources" import { SessionReadToolGroup, SessionUserMessage } from "../message/current-message" -import { SessionCompactionMessage, SessionCompactionQueued } from "../message/message-content" -import { taskAgentName, type ContextGroupPart } from "../tools/tool-renderer" +import { taskAgentName } from "../tools/tool-renderer" import { SessionRetry } from "../components/session-retry" import { SessionError } from "../components/session-error" import type { TimelineDetail } from "../timeline/detail" @@ -48,16 +47,17 @@ import { } from "../timeline/steer-arrival-machine" import { Badge } from "@opencode/ui/badge" import { attached } from "../components/message-file" +import { CompactionMessage, CompactionQueued } from "./compaction" import { unwrapErrorMessage } from "./errors" import { TimelineEventRow } from "./event-row" import { noticeEvent, toolEvent } from "./events" import { trackNestedRails } from "./nested-rail" import { contentEntries, createNextTimelineProjection, resolveContent, workedDuration } from "./projection" -import { contentOpens, diffOpens, goal as goalMessage, thoughtOpens, toolRule, userShellOpens } from "./rules" +import { contentOpens, diffOpens, goal as goalMessage, movedInPlace, thoughtOpens, toolRule } from "./rules" import { Separator } from "./separator" import { timelineGaps } from "./spacing" import { AssistantContent } from "./tools/assistant-content" -import { ContextGroup } from "./tools/context-group" +import { ContextGroup, type ActivityGroupPart } from "./tools/context-group" import { FileGroup } from "./tools/file-group" import { PatchTool } from "./tools/patch" import { ShellMessage } from "./tools/shell" @@ -144,7 +144,9 @@ export function createNextTimelineRowRenderer(input: { const messages = input.projection.messageByID() const context = input.projection.userContextByID() - return userMessageRuns(input.projection.rows(), [...messages.values()], (id) => { + const boundaries = [...messages.values()].filter((message) => !movedInPlace(message)) + + return userMessageRuns(input.projection.rows(), boundaries, (id) => { const message = messages.get(id) const user = context.get(id) @@ -335,7 +337,7 @@ export function createNextTimelineRowRenderer(input: { const contents = indexGroupContents(group.refs) const streaming = phase(row().userMessageID).streamingReasoningRef - return group.refs.flatMap((ref) => { + return group.refs.flatMap((ref) => { const content = contents.get(ref.messageID)?.get(ref.partID) if (content?.type === "tool") { @@ -364,6 +366,9 @@ export function createNextTimelineRowRenderer(input: { ] if (ref.messageID !== ref.partID || !message) return [] + const event = noticeEvent(message) + + if (event) return [{ type: "event", id: ref.partID, event }] if (message.type !== "assistant" && message.type !== "user") return [{ type: "notice", id: ref.partID, render: () => }] @@ -402,6 +407,7 @@ export function createNextTimelineRowRenderer(input: { open={input.disclosure.value(key()) === true} onOpenChange={(open) => input.disclosure.set(key(), open)} onSizeChange={onSizeChange} + onRevealShell={input.revealPart} />
) @@ -460,6 +466,7 @@ export function createNextTimelineRowRenderer(input: { return ( input.disclosure.set(row().group.key, open)} onSizeChange={onSizeChange} @@ -811,7 +818,7 @@ export function createNextTimelineRowRenderer(input: { {(message) => (
- +
)} @@ -920,11 +927,7 @@ export function createNextTimelineRowRenderer(input: { {(message) => (
- input.disclosure.set(message().id, open)} - /> +
)}
@@ -1169,7 +1172,7 @@ export function createNextTimelineRowRenderer(input: {
- +
diff --git a/packages/session-ui/src/timeline-next/rules.test.ts b/packages/session-ui/src/timeline-next/rules.test.ts index a69a11a44541..5d33ffd7304e 100644 --- a/packages/session-ui/src/timeline-next/rules.test.ts +++ b/packages/session-ui/src/timeline-next/rules.test.ts @@ -11,7 +11,6 @@ import { thoughtOpens, toolFailed, toolStopped, - userShellOpens, } from "./rules" import { timelineStatus } from "./status" @@ -110,12 +109,10 @@ describe("echoesUserShell", () => { }) describe("details", () => { - test("shell details decide whether a command's whole output shows, for the agent's commands and the user's", () => { + test("shell details decide whether an agent's command opens to its whole output", () => { expect(contentOpens(preset("everything"), tool("shell"))).toBe(true) expect(contentOpens(preset("compact"), tool("shell"))).toBe(false) expect(contentOpens(preset("compact"), tool("execute"))).toBe(false) - expect(userShellOpens(preset("everything"))).toBe(true) - expect(userShellOpens(preset("compact"))).toBe(false) }) test("thinking details stream the live thought in view, and every finished thought starts closed", () => { diff --git a/packages/session-ui/src/timeline-next/rules.ts b/packages/session-ui/src/timeline-next/rules.ts index 506668b30b06..e18b1ed5fac8 100644 --- a/packages/session-ui/src/timeline-next/rules.ts +++ b/packages/session-ui/src/timeline-next/rules.ts @@ -189,11 +189,6 @@ export function liveThinkingShows(detail: TimelineDetail) { return detail.thinking.placement !== "hidden" } -/** A command the user ran always shows, whole where shell details expand and its last lines otherwise. */ -export function userShellOpens(detail: TimelineDetail) { - return detail.shell.details === "expanded" -} - /** The notice the agent gets about a command the user ran repeats that command's own card, so it never shows. */ export function echoesUserShell(message: SessionMessageInfo, userShellIDs: ReadonlySet) { const shellID = message.type === "synthetic" ? message.metadata?.shellID : undefined @@ -208,7 +203,7 @@ export function echoesUserShell(message: SessionMessageInfo, userShellIDs: Reado /** * Where a notice shows. What the user did and what changed the session always stands on its own. Background work - * reports its outcome as its own row, following the setting its launch follows: a subagent's the subagent setting, a + * reports its outcome as an event, following the setting its launch follows: a subagent's the subagent setting, a * shell's the shell setting. */ export function noticePlacement(detail: TimelineDetail, message: SessionMessageInfo): TimelinePlacement { @@ -236,6 +231,11 @@ export function sessionEvent(message: SessionMessageInfo) { return goal(message) } +/** A move to where the session already is changes nothing, so it shows nothing. */ +export function movedInPlace(message: SessionMessageInfo) { + return message.type === "location-switched" && message.previous?.location.directory === message.location.directory +} + /** A goal the user set, which reads as their own message. */ export function goal( message: SessionMessageInfo | undefined, diff --git a/packages/session-ui/src/timeline-next/status-line.tsx b/packages/session-ui/src/timeline-next/status-line.tsx index b7ee04e680f2..88d34a12c114 100644 --- a/packages/session-ui/src/timeline-next/status-line.tsx +++ b/packages/session-ui/src/timeline-next/status-line.tsx @@ -12,6 +12,8 @@ export function StatusLane(props: { collapsed?: boolean /** The space above the next row of the turn, so the line sits where that row will. */ spacing?: TimelineGap + /** The lane sits in a row of the timeline, which clips what reaches past it, rather than in its open tail. */ + inRow?: boolean class?: string children?: JSX.Element }) { @@ -21,6 +23,7 @@ export function StatusLane(props: { data-component="timeline-status-lane" data-collapsed={props.collapsed ? "" : undefined} data-spacing={props.spacing} + data-in-row={props.inRow ? "" : undefined} class={props.class} > diff --git a/packages/session-ui/src/timeline-next/stories/compare-renderer.stories.tsx b/packages/session-ui/src/timeline-next/stories/compare-renderer.stories.tsx index 1c105415ec6b..a8b56221de1a 100644 --- a/packages/session-ui/src/timeline-next/stories/compare-renderer.stories.tsx +++ b/packages/session-ui/src/timeline-next/stories/compare-renderer.stories.tsx @@ -1,10 +1,11 @@ import { TextShimmer } from "@opencode/ui/text-shimmer" -import { Show, createEffect, createSignal, onCleanup, onMount } from "solid-js" +import { Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js" import { BackgroundMoveHint } from "../../../../app/src/session/timeline/message-timeline" import { createStore, reconcile } from "solid-js/store" import type { SessionDocument } from "../../document" import { CurrentSessionProviders } from "../../storybook/current-session-story" -import type { TimelineDetail } from "../../timeline/detail" +import { timelinePresets, type TimelineDetail } from "../../timeline/detail" +import { terminalRunningDocument } from "../../storybook/current-session-fixtures" import { SessionTimeline } from "../../timeline/session-timeline" import { StatusLane } from "../status-line" import { NextSessionTimeline } from "./session-timeline" @@ -42,8 +43,29 @@ const padding = "px-4 md:px-6" type ScrollTo = { type: "timeline-compare:scroll-to"; anchor: string; offset: number } export const Renderer = { - render: () => { + args: { preview: "waiting" }, + argTypes: { preview: { options: ["waiting", "current", "new"] } }, + render: (args: { preview: string }) => { const [state, setState] = createStore<{ render?: Render }>({}) + + // An embedded comparison supplies the actual snapshot. In isolation the inspector can send a working turn. + const snapshot = createMemo( + () => + state.render ?? + (args.preview === "waiting" + ? undefined + : { + type: "timeline-compare:render", + document: terminalRunningDocument, + detail: timelinePresets[2].value, + activity: args.preview === "new", + lane: args.preview === "new" ? "activity" : "legacy", + turnDiffs: false, + width: 720, + status: "Working", + }), + ) + const [hint, setHint] = createSignal(false) // The offer shows once the call has blocked the turn for the build's delay, counted from when the playhead got here. @@ -112,7 +134,7 @@ export const Renderer = { data-scrollable onScroll={report} > - + {(render) => (
diff --git a/packages/session-ui/src/timeline-next/stories/compare.stories.tsx b/packages/session-ui/src/timeline-next/stories/compare.stories.tsx index 87a2e8863d0c..1e65069979fe 100644 --- a/packages/session-ui/src/timeline-next/stories/compare.stories.tsx +++ b/packages/session-ui/src/timeline-next/stories/compare.stories.tsx @@ -1,5 +1,5 @@ import type { SessionMessageInfo } from "@opencode/client/promise" -import { For, Show, createEffect, createMemo, onCleanup, onMount, type JSX } from "solid-js" +import { For, Show, createEffect, createMemo, on, onCleanup, onMount, type JSX } from "solid-js" import { createStore } from "solid-js/store" import { timelinePresets } from "../../timeline/detail" import { createNextTimelineProjection } from "../projection" @@ -59,8 +59,37 @@ const statusLabels = { working: "Working", } as const +const sessions = [...Object.keys(scenarios), ...exported.map((session) => session.name)] + +const presetIDs = timelinePresets.map((preset) => preset.id) + export const Compare = { - render: () => { + args: { + session: sessions[0]!, + preset: defaultPreset, + view: defaultView, + theme: "dark", + width: 720, + turnDiffs: false, + mix: 50, + }, + argTypes: { + session: { options: sessions }, + preset: { options: presetIDs }, + view: { options: views }, + theme: { options: ["light", "dark"] }, + width: { control: { type: "range", min: 480, max: 960, step: 240 } }, + mix: { control: { type: "range", min: 0, max: 100, step: 1 } }, + }, + render: (args: { + session: string + preset: PresetID + view: View + theme: "light" | "dark" + width: number + turnDiffs: boolean + mix: number + }) => { const query = new URLSearchParams(location.search) // Without another build to compare, the page compares this build's two timelines. const other = query.get("base") @@ -69,27 +98,44 @@ export const Compare = { const base = other ? `${other.replace(/\/$/, "")}/` : self const baseLabel = query.get("baseLabel") ?? (other ? "base" : "Current timeline") const headLabel = query.get("headLabel") ?? (other ? "head" : "New timeline") - const sessions = [...Object.keys(scenarios), ...exported.map((session) => session.name)] - - const presetIDs = timelinePresets.map((preset) => preset.id) const number = (key: string) => (query.has(key) ? Number(query.get(key)) : undefined) const [state, setState] = createStore({ - session: sessions.find((session) => session === query.get("session")) ?? sessions[0]!, - preset: presetIDs.find((preset) => preset === query.get("preset")) ?? defaultPreset, + session: sessions.find((session) => session === query.get("session")) ?? args.session, + preset: presetIDs.find((preset) => preset === query.get("preset")) ?? args.preset, next: query.get("next") !== "false", baseNext: query.get("baseNext") === "true", tick: number("step") ?? Number.MAX_SAFE_INTEGER, playing: false, - width: ([480, 720, 960] as const).find((width) => width === number("width")) ?? 720, - theme: query.get("theme") === "light" ? ("light" as const) : ("dark" as const), - turnDiffs: query.get("files") === "true", - view: views.find((view) => view === query.get("view")) ?? defaultView, - mix: 50, + width: ([480, 720, 960] as const).find((width) => width === number("width")) ?? args.width, + theme: (["light", "dark"] as const).find((theme) => theme === query.get("theme")) ?? args.theme, + turnDiffs: query.has("files") ? query.get("files") === "true" : args.turnDiffs, + view: views.find((view) => view === query.get("view")) ?? args.view, + mix: args.mix, }) + // A standalone comparison may have opened at a bookmarked setting. Only subsequent inspector edits override it. + createEffect( + on( + () => args.session, + (session) => setState({ session, tick: Number.MAX_SAFE_INTEGER, playing: false }), + { defer: true }, + ), + ) + + for (const key of ["preset", "view", "theme", "width", "turnDiffs", "mix"] as const) { + createEffect( + on( + () => args[key], + (value) => setState({ [key]: value }), + { defer: true }, + ), + ) + } + // The address follows the controls, so a link opens where it was copied. createEffect(() => { + if (query.get("id") !== "timeline-compare--compare") return const address = new URLSearchParams(location.search) address.set("session", state.session) address.set("preset", state.preset) diff --git a/packages/session-ui/src/timeline-next/stories/playground.stories.tsx b/packages/session-ui/src/timeline-next/stories/playground.stories.tsx index ea60e8ee290a..91568f2ab974 100644 --- a/packages/session-ui/src/timeline-next/stories/playground.stories.tsx +++ b/packages/session-ui/src/timeline-next/stories/playground.stories.tsx @@ -1,4 +1,4 @@ -import { For, Show, createEffect, createMemo, onCleanup } from "solid-js" +import { For, Show, createEffect, createMemo, on, onCleanup } from "solid-js" import { createStore } from "solid-js/store" import { TextShimmer } from "@opencode/ui/text-shimmer" import { CurrentSessionProviders } from "../../storybook/current-session-story" @@ -47,22 +47,54 @@ type PlaygroundMessage = { } export const Playground = { - args: { embedded: false }, - render: (args: { embedded: boolean }) => { + args: { + embedded: false, + scenario: defaultScenario, + preset: defaultPreset, + activity: true, + width: 720, + turnDiffs: false, + progress: 100, + }, + argTypes: { + scenario: { options: scenarioNames }, + preset: { options: timelinePresets.map((preset) => preset.id) }, + width: { control: { type: "range", min: 480, max: 960, step: 240 } }, + progress: { control: { type: "range", min: 0, max: 100, step: 1 } }, + }, + render: (args: { + embedded: boolean + scenario: ScenarioName + preset: PresetID + activity: boolean + width: number + turnDiffs: boolean + progress: number + }) => { const [state, setState] = createStore({ - scenario: defaultScenario, - preset: defaultPreset, - activity: true, + scenario: args.scenario, + preset: args.preset, + activity: args.activity, tick: Number.MAX_SAFE_INTEGER, playing: false, - width: 720, - turnDiffs: false, + width: args.width, + turnDiffs: args.turnDiffs, }) const script = createMemo(() => scenarios[state.scenario]) const detail = createMemo(() => timelinePresets.find((preset) => preset.id === state.preset)!.value) const total = createMemo(() => script().reduce((sum, beat) => sum + ticks(beat), 0)) const tick = createMemo(() => Math.min(state.tick, total())) + createEffect(() => setState("scenario", args.scenario)) + createEffect(() => setState("preset", args.preset)) + createEffect(() => setState("activity", args.activity)) + createEffect(() => setState("width", args.width)) + createEffect(() => setState("turnDiffs", args.turnDiffs)) + createEffect( + on([() => args.progress, () => args.scenario], () => + setState({ tick: Math.round((total() * args.progress) / 100), playing: false }), + ), + ) // The playhead is now, so live durations read like a session happening as you watch. const replay = createMemo(() => replayScript(script(), tick(), Date.now() - tick() * 1_500)) diff --git a/packages/session-ui/src/timeline-next/stories/user-command.stories.tsx b/packages/session-ui/src/timeline-next/stories/user-command.stories.tsx new file mode 100644 index 000000000000..736b0bc0d7ea --- /dev/null +++ b/packages/session-ui/src/timeline-next/stories/user-command.stories.tsx @@ -0,0 +1,55 @@ +import type { SessionMessageShell } from "@opencode/client/promise" +import { createSignal } from "solid-js" +import { DataProvider } from "../../context/data" +import { ShellMessage } from "../tools/shell" + +/** + * A command the user ran, drawn by the New timeline. It starts running and keeps how it ended in its metadata, which is + * where the row reads the exit code, a timeout, or that the command was stopped. + */ +export default { + title: "OpenCode/Timeline/Next user command", + id: "timeline-next-user-command", + component: ShellMessage, + parameters: { layout: "fullscreen" }, +} + +export const LiveCommand = { + args: { outcome: "nonzero", output: false }, + argTypes: { + outcome: { control: "select", options: ["nonzero", "timeout", "killed"] }, + output: { control: "boolean" }, + }, + render: (args: { outcome: "nonzero" | "timeout" | "killed"; output: boolean }) => { + const [message, setMessage] = createSignal({ + id: "msg_user_command", + type: "shell", + shellID: "shell_user_command", + command: "printf ready", + status: "running", + time: { created: 1 }, + }) + + return ( +
+ + + + +
+ ) + }, +} diff --git a/packages/session-ui/src/timeline-next/timeline-next.css b/packages/session-ui/src/timeline-next/timeline-next.css index 83dba6cc5847..bfae00e1812c 100644 --- a/packages/session-ui/src/timeline-next/timeline-next.css +++ b/packages/session-ui/src/timeline-next/timeline-next.css @@ -76,106 +76,12 @@ } } -/* Cut output shows its last lines, fading out at the top where it is cut. */ -[data-timeline="next"] [data-component="clamped-content"] { - &[data-clamped] { - max-height: var(--clamped-content-height, 96px); - overflow: hidden; - } - - /* The fade is the code's own background, so the cut lines fade into the block rather than through it. */ - &[data-overflow] { - position: relative; - - &::after { - content: ""; - position: absolute; - inset-inline: 0; - top: 0; - height: 20px; - background: linear-gradient(var(--clamped-content-fade), transparent); - pointer-events: none; - } - } -} - -/* A command the user ran is its command and output, always showing, with the output cut to four lines. */ -[data-timeline="next"] [data-component="shell-tool"] { - [data-slot="shell-tool-writing"] { - display: block; - font-size: 13px; - line-height: var(--line-height-compact); - color: var(--v2-text-text-muted); - } - - [data-component="bash-output"][data-clamp] { - [data-slot="bash-scroll"] { - max-height: none; - } - - [data-component="clamped-content"] { - grid-area: 1 / 1; - /* The 12px top padding and four 20px lines of output, as a plain length the clamp can read back. */ - --clamped-content-height: 92px; - --clamped-content-fade: var(--bash-section-background); - } - } -} - -/* The output's toggle sits at the end of the command line, so neither block's text is a click target. */ -[data-timeline="next"] [data-component="shell-tool"] [data-slot="bash-command"] { - /* How the command ended and the output's toggle, above the command, which shares their grid cell and comes later, - so paints over it. The inset matches the file header's toggle. */ - [data-slot="bash-actions"] { - position: relative; - z-index: 1; - grid-area: 1 / 1; - justify-self: end; - align-self: center; - display: flex; - align-items: center; - gap: 8px; - margin-inline-end: 8px; - } - - [data-slot="bash-outcome"] { - font-family: var(--v2-font-family-sans); - font-size: 13px; - font-weight: 440; - line-height: var(--line-height-compact); - letter-spacing: -0.04px; - white-space: nowrap; - color: var(--v2-text-text-muted); - - &[data-tone="danger"] { - color: var(--v2-state-fg-danger); - } - } - - [data-slot="bash-toggle-button"] { - display: flex; - align-items: center; - justify-content: center; - padding: 0; - border: 0; - background: none; - color: inherit; - cursor: default; - - &:focus-visible { - outline: 1px solid var(--v2-text-text-accent); - outline-offset: 2px; - border-radius: 2px; - } - } - - &:has([data-slot="bash-toggle"]) [data-slot="bash-pre"] { - padding-inline-end: 40px; - } - - &:has([data-slot="bash-outcome"]) [data-slot="bash-pre"] { - padding-inline-end: 120px; - } +/* A command the user ran is its command and output, always showing, as an agent's command shows once opened. */ +[data-timeline="next"] [data-component="shell-tool"] [data-slot="shell-tool-writing"] { + display: block; + font-size: 13px; + line-height: var(--line-height-compact); + color: var(--v2-text-text-muted); } /* A file's change counts follow its name, showing only the side that changed; its change bars are quieter; and its @@ -323,13 +229,15 @@ } /* An event row opens to the subagents and shells it counts, each read like a nested row and leading to its session or - to the call that ran it. */ + to the call that ran it. An opened activity group lists the ones it started or heard back from the same way. */ [data-timeline="next"] [data-component="timeline-event-list"] { display: flex; flex-direction: column; gap: 8px; padding-top: 4px; +} +[data-timeline="next"] :is([data-component="timeline-event-list"], [data-slot="context-tool-group-item"]) { [data-slot="timeline-event-item"] { display: flex; align-items: center; @@ -376,7 +284,7 @@ color: var(--v2-text-text-base); } - [data-component="tag"] { + [data-slot="timeline-event-item"] [data-component="tag"] { flex-shrink: 0; } } @@ -402,26 +310,6 @@ padding-top: var(--timeline-gap-l); } -/* The user's message actions show in the large gap below it rather than adding to it, above the row that follows so - they stay reachable. */ -[data-timeline="next"][data-timeline-row="UserMessage"] { - position: relative; - z-index: 1; - - [data-component="user-message"] { - position: relative; - } - - [data-slot="user-message-copy-wrapper"] { - position: absolute; - inset-inline: 0; - top: 100%; - height: 28px; - margin-top: 0; - padding-top: 8px; - } -} - /* Rows are as tall as their text, so the gaps between them are the gaps that show. A row's 28px click area stays: 6px of padding above and below, taken back by margins of the same size, so neighbouring click areas meet without overlapping. An open row's header ends the small gap above its first nested row. */ @@ -495,21 +383,6 @@ text-box: trim-start text; } - /* The agent's last words in a turn keep their actions in the large gap below them, as the user's message does. The - gap above the actions is their own padding, so the pointer stays over the message while it crosses to them. */ - [data-component="text-part"]:has(> [data-slot="text-part-copy-wrapper"]) { - position: relative; - - > [data-slot="text-part-copy-wrapper"] { - position: absolute; - inset-inline: 0; - top: 100%; - height: 28px; - margin-top: 0; - padding-top: 8px; - } - } - [data-component="context-tool-group-list"], [data-component="timeline-event-list"] { gap: var(--timeline-gap-s); @@ -517,6 +390,7 @@ } [data-component="context-tool-group-list"] [data-slot="context-tool-group-item"], + [data-component="context-tool-group-list"] [data-slot="timeline-event-item"], [data-component="timeline-event-list"] [data-slot="timeline-event-item"] { min-height: var(--line-height-compact); } @@ -541,11 +415,43 @@ height: calc(var(--line-height-compact) + 6px + var(--timeline-gap-s)); } } -} -[data-timeline="next"][data-timeline-row="AssistantPart"]:has([data-slot="text-part-copy-wrapper"]) { - position: relative; - z-index: 1; + /* Answers are spaced by the row gaps and trimmed to their text, as the agent's text is. */ + [data-component="question-answers"] { + gap: var(--timeline-gap-s); + padding: 0; + line-height: var(--line-height-base); + + [data-slot="question-answer-item"] { + gap: 4px; + } + + [data-slot="question-text"], + [data-slot="answer-text"] { + text-box: trim-both text; + } + } + + /* A row's action is as tall as its line, so its button never makes the row taller. */ + [data-slot="basic-tool-action"] { + height: var(--line-height-compact); + + [data-component="icon-button-v2"] { + width: 20px; + height: 20px; + } + } + + /* The quiet compaction draws the same line as the other dividers. */ + [data-component="session-compaction-message"][data-quiet] { + [data-slot="session-compaction-line"]::before { + background: var(--v2-border-border-base); + } + + [data-slot="session-compaction-summary"] { + padding-bottom: 0; + } + } } /* The live thought sits where the row it settles into will, which its frame spaces like any other row. */ @@ -581,9 +487,19 @@ --timeline-status-space: var(--timeline-gap-l); } + /* The background hint's 24px button is centred on the 16px line and reaches 4px past it. A row clips at its own + height, so in a row the lane keeps that room below the line, whether or not the hint shows, so the input waiting + below does not move when it comes and goes. */ + &[data-in-row] { + --timeline-status-hint-overflow: calc((24px - var(--line-height-compact)) / 2); + height: calc(var(--line-height-compact) + var(--timeline-status-space) + var(--timeline-status-hint-overflow)); + padding-bottom: var(--timeline-status-hint-overflow); + } + &[data-collapsed] { height: 0; padding-top: 0; + padding-bottom: 0; overflow: hidden; } diff --git a/packages/session-ui/src/timeline-next/tools/clamped-content.tsx b/packages/session-ui/src/timeline-next/tools/clamped-content.tsx deleted file mode 100644 index f37941dd695d..000000000000 --- a/packages/session-ui/src/timeline-next/tools/clamped-content.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { createEffect, createSignal, on, onCleanup, onMount, type JSX } from "solid-js" - -/** - * Output cut to its last few lines, as a command the user ran shows it, so the newest stay in view as running output - * grows. Its owner offers the control that shows the rest, so the text stays selectable. - */ -export function ClampedContent(props: { - expanded: boolean - /** Whether the content is longer than the cut, so the owner knows to offer its toggle. */ - onOverflowChange?: (overflow: boolean) => void - children: JSX.Element -}) { - const [overflow, setOverflow] = createSignal(false) - let frame: HTMLDivElement | undefined - let content: HTMLDivElement | undefined - - const measure = () => { - if (!frame || !content) return - // Measured against the cut height, so an expanded frame still knows whether it has more than the cut shows. - const limit = Number.parseFloat(getComputedStyle(frame).getPropertyValue("--clamped-content-height")) || 96 - setOverflow(content.offsetHeight > limit + 1) - - // Shifting the content rather than scrolling it keeps the fade over the frame's edge. - const shift = props.expanded ? 0 : Math.min(0, frame.clientHeight - content.offsetHeight) - - content.style.translate = shift ? `0 ${shift}px` : "" - } - - onMount(() => { - const observer = new ResizeObserver(measure) - - if (frame) observer.observe(frame) - - if (content) observer.observe(content) - onCleanup(() => observer.disconnect()) - }) - - createEffect(on(() => props.expanded, measure, { defer: true })) - createEffect(on(overflow, (value) => props.onOverflowChange?.(value))) - - return ( -
-
{props.children}
-
- ) -} diff --git a/packages/session-ui/src/timeline-next/tools/context-group.tsx b/packages/session-ui/src/timeline-next/tools/context-group.tsx index 15e761e4576a..a220bfdb3147 100644 --- a/packages/session-ui/src/timeline-next/tools/context-group.tsx +++ b/packages/session-ui/src/timeline-next/tools/context-group.tsx @@ -24,19 +24,26 @@ import { toolMetadata, type ContextGroupPart, } from "../../tools/tool-renderer" -import { kindKeys, launchKeys, summarizeEvents, toolEvent, verbKeys } from "../events" +import { TimelineEventRow } from "../event-row" +import { kindKeys, launchKeys, summarizeEvents, toolEvent, verbKeys, workKey, type TimelineEvent } from "../events" import { toolRule, toolStopped, type ToolMode } from "../rules" import { FileGroup } from "./file-group" import { ThoughtRow } from "./thought" import { ToolDisplay } from "./tool-display" +/** A part of an activity group: a call, a thought, a notice, or background work reporting back. */ +export type ActivityGroupPart = ContextGroupPart | { type: "event"; id: string; event: TimelineEvent } + +// Subagents and background work listed one after another in an opened group, as one nested events row. +type WorkRun = { type: "work"; id: string; events: TimelineEvent[] } + /** * A stretch of the agent's work folded into one row, named by what it did: "Explored 3 files · 2 commands". It only * records what happened; the status line below the turn says what is live. A stretch of thoughts alone is those * thoughts, without a group around them. */ export function ContextGroup(props: { - parts: ContextGroupPart[] + parts: ActivityGroupPart[] open: boolean onOpenChange: (open: boolean) => void onSizeChange?: () => void @@ -49,12 +56,23 @@ export function ContextGroup(props: { fileOpen?: (path: string) => boolean | undefined onFileOpenChange?: (path: string, open: boolean) => void patchGroupKey?: (tools: SessionMessageAssistantTool[]) => string + onRevealShell?: (shellID: string) => void }) { const i18n = useI18n() const tools = createMemo(() => props.parts.filter((part) => part.type === "tool")) const reasoning = createMemo(() => props.parts.flatMap((part) => (part.type === "reasoning" ? [part] : []))) const thoughtsOnly = createMemo(() => reasoning().length > 0 && reasoning().length === props.parts.length) - const activity = createMemo(() => activityLabel(tools(), i18n)) + const events = createMemo(() => [...workEvents(props.parts).values()]) + + // A group of only subagents and work reporting back reads as the events row it is, not a group around one. Until a + // call has anything to count, it stays a group, so the row never renders empty. + const workOnly = createMemo( + () => + events().length > 0 && + props.parts.every((part) => part.type === "event" || (part.type === "tool" && toolRule(part).name === "subagent")), + ) + + const activity = createMemo(() => activityLabel(tools(), events(), i18n)) const label = createMemo(() => { const value = activity() @@ -69,16 +87,51 @@ export function ContextGroup(props: { const items = createMemo(() => (props.open ? props.parts : []).reduce< - (SessionMessageAssistantTool[] | Exclude)[] + ( + | SessionMessageAssistantTool[] + | Exclude + | WorkRun + )[] >((groups, tool) => { + const previous = groups.at(-1) + + // Subagents started one after another, and work reporting back, read as one events row nested in the group: + // "Started 3 subagents". The rows keep the order things happened in, which the label does not. + if (tool.type === "event" || (tool.type === "tool" && toolRule(tool).name === "subagent")) { + // A subagent still being asked for has nothing to list yet. + const event = tool.type === "event" ? tool.event : toolEvent(tool) + + if (!event) return groups + const run = previous && !Array.isArray(previous) && previous.type === "work" ? previous : undefined + const key = tool.type === "event" ? workKey(event) : undefined + + // Work reporting back right after its launch, with nothing between, finishes the launch's row. With + // anything between, the launch and the report each keep their row. + const launch = key && run ? run.events.findIndex((item) => item.verb === "started" && workKey(item) === key) : -1 + + if (run && launch >= 0) { + run.events[launch] = { ...run.events[launch]!, verb: event.verb, failed: event.failed } + + return groups + } + + if (run) { + run.events.push(event) + + return groups + } + + groups.push({ type: "work", id: tool.id, events: [event] }) + + return groups + } + if (tool.type !== "tool") { groups.push(tool) return groups } - const previous = groups.at(-1) - if (Array.isArray(previous) && previous[0] && joins(previous[0], tool)) { previous.push(tool) @@ -136,113 +189,152 @@ export function ContextGroup(props: {
} > -
part.id).join(",")} + part.id).join(",")}> + +
+ } > - - }> - {(value) => ( - - {value().verb} - - {value().main} - - 0}> - - {value().others.join(", ")} - - - )} - -
- } +
part.id).join(",")} > -
- - {(item) => { - const group = createMemo(() => { - const value = item() - - return Array.isArray(value) ? value : undefined - }) - - const reasoning = createMemo(() => { - const value = item() - - return !Array.isArray(value) && value.type === "reasoning" ? value : undefined - }) - - const callback = createMemo(() => { - const value = item() - - return !Array.isArray(value) && - (value.type === "notice" || value.type === "shell" || value.type === "text") - ? value - : undefined - }) - - return ( - - {(part) =>
{part().render()}
} -
- } - > - {(part) => ( -
- props.onReasoningOpenChange?.(part().id, open)} - onContentRendered={props.onSizeChange} - /> -
- )} + + }> + {(value) => ( + + {value().verb} + + {value().main} - } - > - {(group) => ( -
- -
- )} -
- ) - }} -
-
- -
+ 0}> + + {value().others.join(", ")} + + + )} + +
+ } + > +
+ + {(item) => { + const group = createMemo(() => { + const value = item() + + return Array.isArray(value) ? value : undefined + }) + + const reasoning = createMemo(() => { + const value = item() + + return !Array.isArray(value) && value.type === "reasoning" ? value : undefined + }) + + const callback = createMemo(() => { + const value = item() + + return !Array.isArray(value) && + (value.type === "notice" || value.type === "shell" || value.type === "text") + ? value + : undefined + }) + + const work = createMemo(() => { + const value = item() + + return !Array.isArray(value) && value.type === "work" ? value : undefined + }) + + return ( + + {(part) =>
{part().render()}
} +
+ } + > + {(work) => ( +
+ { + props.onToolOpenChange?.(`events:${work().id}`, open) + props.onSizeChange?.() + }} + onRevealShell={props.onRevealShell} + /> +
+ )} + + } + > + {(part) => ( +
+ props.onReasoningOpenChange?.(part().id, open)} + onContentRendered={props.onSizeChange} + /> +
+ )} + + } + > + {(group) => ( +
+ +
+ )} + + ) + }} +
+
+ +
+ ) } @@ -285,6 +377,7 @@ function GroupItem(props: { props.onToolOpenChange?.(tool().id, open)} onSizeChange={props.onSizeChange} @@ -421,7 +514,7 @@ function UsedTitle(props: { label: ReturnType }) { ) } -function usedLabel(parts: ContextGroupPart[], i18n: UiI18n) { +function usedLabel(parts: ActivityGroupPart[], i18n: UiI18n) { const count = parts.filter((part) => part.type === "reasoning").length if (!count) { @@ -450,6 +543,52 @@ function usedLabel(parts: ContextGroupPart[], i18n: UiI18n) { } } +/** + * What each subagent or background shell in a group did, for its label. Work that reports back anywhere in the group + * that started it is counted once, as how it ended: "Finished", not "Started" and "Finished". + */ +function workEvents(parts: ActivityGroupPart[]) { + const launch = (part: ActivityGroupPart) => + part.type === "tool" && toolRule(part).layout === "event" ? toolEvent(part) : undefined + + const launched = new Set( + parts.flatMap((part) => { + const event = launch(part) + const key = event && workKey(event) + + return key ? [key] : [] + }), + ) + + const reports = new Map( + parts.flatMap((part) => { + const key = part.type === "event" ? workKey(part.event) : undefined + + return key && part.type === "event" ? [[key, part.event] as const] : [] + }), + ) + + return new Map( + parts.flatMap((part): [ActivityGroupPart, TimelineEvent][] => { + if (part.type === "event") { + const key = workKey(part.event) + + return key && launched.has(key) ? [] : [[part, part.event]] + } + + const event = launch(part) + + if (!event) return [] + const key = workKey(event) + const outcome = key ? reports.get(key) : undefined + + return [ + [part, outcome && event.verb === "started" ? { ...event, verb: outcome.verb, failed: outcome.failed } : event], + ] + }), + ) +} + // The most consequential work names a group: changing files over running commands, and both over reading. const modePriority: ToolMode[] = ["edit", "run", "tool", "explore"] @@ -464,25 +603,16 @@ const decodeChangedPath = Schema.decodeUnknownOption(Schema.Struct({ file: Schem /** * Names a stretch of the agent's work by its main mode, then what its other calls did: "Edited 4 files · 2 commands, - * started 1 shell". Work that runs on is counted by what was started, not among the calls that started it; a stretch of - * only that reads like an events row: "Started 2 subagents". + * started 1 shell". Work that runs on is counted by what happened to it, not among the calls that started it; a + * stretch of only that reads like an events row: "Started 2 subagents · finished 2 subagents". */ -function activityLabel(group: SessionMessageAssistantTool[], i18n: UiI18n) { +function activityLabel(group: SessionMessageAssistantTool[], events: TimelineEvent[], i18n: UiI18n) { const tools = group.filter((tool) => toolRule(tool).layout !== "event") + const launches = summarizeEvents(events).verbs - const launches = summarizeEvents( - group.flatMap((tool) => { - const event = toolRule(tool).layout === "event" ? toolEvent(tool) : undefined - - return event ? [event] : [] - }), - ).verbs - - const launched = launches.flatMap((bucket) => { - const keys = bucket.verb === "started" || bucket.verb === "ran" ? launchKeys[bucket.verb] : undefined - - return keys ? bucket.kinds.map((item) => i18n.plural(keys[item.kind], item.count)) : [] - }) + const launched = launches.flatMap((bucket) => + bucket.kinds.map((item) => i18n.plural(launchKeys[bucket.verb][item.kind], item.count)), + ) const modes = new Set(tools.map((tool) => toolRule(tool).mode)) const mode = modePriority.find((item) => modes.has(item)) @@ -542,7 +672,7 @@ function activityLabel(group: SessionMessageAssistantTool[], i18n: UiI18n) { const main = { // A few files read better by name; past that, the count says more than a list that truncates. edit: - files.length <= 3 + files.length <= 2 ? files.map((path) => getFilename(path)).join(", ") : i18n.plural("ui.timeline.activity.files", files.length), run: commands[0]!, diff --git a/packages/session-ui/src/timeline-next/tools/shell.tsx b/packages/session-ui/src/timeline-next/tools/shell.tsx index 17971b7fc158..401b7642ab14 100644 --- a/packages/session-ui/src/timeline-next/tools/shell.tsx +++ b/packages/session-ui/src/timeline-next/tools/shell.tsx @@ -2,11 +2,8 @@ import type { SessionMessageShell } from "@opencode/client/promise" import { Predicate } from "effect" import { type UiI18n, useI18n } from "@opencode/ui/context/i18n" import { Badge } from "@opencode/ui/badge" -import { Icon } from "@opencode/ui/icon" import { TextShimmer } from "@opencode/ui/text-shimmer" -import { Tooltip } from "@opencode/ui/tooltip" import { createComputed, createEffect, createMemo, createSignal, on, onCleanup, Show, untrack } from "solid-js" -import { LinkedText } from "../../components/linked-text" import { useData } from "../../context" import { createShellRunState, @@ -17,15 +14,7 @@ import { } from "../../tools/run-machine" import { createShellFollower } from "../../tools/shell-output" import { BasicTool } from "../../components/basic-tool" -import { - ConsoleCopy, - ConsoleOutput, - ShellSubmessage, - toolInput, - toolMetadata, - type ToolProps, -} from "../../tools/tool-renderer" -import { ClampedContent } from "./clamped-content" +import { ConsoleOutput, ShellSubmessage, toolInput, toolMetadata, type ToolProps } from "../../tools/tool-renderer" /** * An agent's shell call is a row of activity, as in the current timeline: Shell, then its command, cut to the row while @@ -83,14 +72,12 @@ export function ShellTool(props: ToolProps) { } /** - * A command the user ran shows as a card: its command and output, the output cut to its last lines, where a command says - * how it went, until expanded. How it ended sits on the card when it did not succeed. + * A command the user ran shows as an agent's shell call does once opened, its command and output, without the row above + * them to open it. */ function ShellCard(props: ToolProps) { const i18n = useI18n() const run = shellRun(props) - const [expanded, setExpanded] = createSignal(false) - const open = () => props.open ?? expanded() const outcome = createMemo(() => shellOutcome(props.metadata, i18n)) run.follow() @@ -107,19 +94,9 @@ function ShellCard(props: ToolProps) { } > - { - const next = !open() - - setExpanded(next) - props.onOpenChange?.(next) - }} - /> + + {(value) => {value().label}}
) } @@ -191,11 +168,7 @@ function shellOutcome(metadata: ToolProps["metadata"], i18n: UiI18n) { } /** A command the user ran. */ -export function ShellMessage(props: { - message: SessionMessageShell - open?: boolean - onOpenChange?: (open: boolean) => void -}) { +export function ShellMessage(props: { message: SessionMessageShell }) { return (
) } - -// Copy sits on the output only. The command's corner holds how the command ended, and the output's toggle once there is -// more than the cut shows. -function ShellOutput(props: { - command?: string - output: string - expanded: boolean - outcome?: { tone: "neutral" | "danger"; label: string } - onToggle: () => void -}) { - const i18n = useI18n() - const [overflow, setOverflow] = createSignal(false) - const toggleLabel = () => i18n.t(props.expanded ? "ui.common.showLess" : "ui.common.showMore") - - return ( -
-
- - {(command) => ( -
- -
- - {(outcome) => ( - - {outcome().label} - - )} - - -
- - - -
-
-
-
-
-                {command()}
-              
-
- )} -
- - {(output) => ( -
- - -
-                  
-                    
-                  
-                
-
-
- )} -
-
-
- ) -} diff --git a/packages/session-ui/src/timeline/error-card.stories.tsx b/packages/session-ui/src/timeline/error-card.stories.tsx index 0be1499ba5b1..add74dbd87a0 100644 --- a/packages/session-ui/src/timeline/error-card.stories.tsx +++ b/packages/session-ui/src/timeline/error-card.stories.tsx @@ -8,6 +8,8 @@ export default { id: "current-session-error-card", component: SessionTimeline, parameters: { layout: "fullscreen" }, + args: { width: 480 }, + argTypes: { width: { control: { type: "range", min: 320, max: 960, step: 10 } } }, } const document = { @@ -43,12 +45,12 @@ const document = { } satisfies SessionDocument export const ProviderErrors = { - render: () => ( + render: (args: { width: number }) => ( ), } @@ -89,12 +91,12 @@ const executionErrorsDocument = { } satisfies SessionDocument export const ExecutionErrors = { - render: () => ( + render: (args: { width: number }) => ( ), } @@ -121,12 +123,12 @@ const linkDocument = { } satisfies SessionDocument export const LinkedError = { - render: () => ( + render: (args: { width: number }) => ( ), } diff --git a/packages/session-ui/src/timeline/error-spacing.stories.tsx b/packages/session-ui/src/timeline/error-spacing.stories.tsx index 43e322856b47..36f94252af4b 100644 --- a/packages/session-ui/src/timeline/error-spacing.stories.tsx +++ b/packages/session-ui/src/timeline/error-spacing.stories.tsx @@ -56,12 +56,14 @@ const document = { } satisfies SessionDocument export const ErrorAndUpdates = { - render: () => ( + args: { preset: "detailed" }, + argTypes: { preset: { options: timelinePresets.map((preset) => preset.id) } }, + render: (args: { preset: string }) => (
preset.id === "detailed")!.value} + timelineDetail={timelinePresets.find((preset) => preset.id === args.preset)!.value} />
diff --git a/packages/session-ui/src/timeline/file-changes.stories.tsx b/packages/session-ui/src/timeline/file-changes.stories.tsx index d0c47e7fd24b..430b2c60a17d 100644 --- a/packages/session-ui/src/timeline/file-changes.stories.tsx +++ b/packages/session-ui/src/timeline/file-changes.stories.tsx @@ -1,5 +1,6 @@ import { createTwoFilesPatch } from "diff" -import { createMemo, createSignal, untrack } from "solid-js" +import { createEffect, createMemo, createSignal, untrack } from "solid-js" +import { Dynamic } from "solid-js/web" import { createStore } from "solid-js/store" import type { TurnDiffSource, TurnDiffState } from "../context/data" import { CurrentSessionProviders, CurrentSessionTimelineStory } from "../storybook/current-session-story" @@ -317,8 +318,11 @@ const fileScenarios = { } export const AppendingToolCalls = { - render: () => { - const [state, setState] = createStore({ calls: 0 }) + args: { calls: 0 }, + argTypes: { calls: { control: { type: "range", min: 0, max: 12, step: 1 } } }, + render: (args: { calls: number }) => { + const [state, setState] = createStore({ calls: args.calls }) + createEffect(() => setState("calls", args.calls)) const files = ["src/a.ts", "src/b.ts"].map((file) => ({ ...storyPatchFile(file), @@ -367,8 +371,9 @@ export const AppendingToolCalls = { export const ChangingFiles = { args: { scenario: "streaming" }, argTypes: { scenario: { control: "select", options: Object.keys(fileScenarios) } }, - // SAFETY: the scenario control only offers fileScenarios keys. - render: (args: { scenario: string }) => fileScenarios[args.scenario as keyof typeof fileScenarios].render(), + render: (args: { scenario: keyof typeof fileScenarios }) => ( + + ), } export const CreatedANewFile = { @@ -384,15 +389,16 @@ export const CreatedANewFile = { } export const FileToolFallbacks = { - args: { tool: "edit", empty: false, forceOpen: false, controlled: true }, + args: { tool: "edit", empty: false, forceOpen: false, controlled: true, completed: false }, argTypes: { tool: { control: "select", options: ["edit", "write"] }, empty: { control: "boolean" }, forceOpen: { control: "boolean" }, controlled: { control: "boolean" }, }, - render: (args: { tool: string; empty: boolean; forceOpen: boolean; controlled: boolean }) => { - const [state, setState] = createStore({ completed: false, open: false }) + render: (args: { tool: string; empty: boolean; forceOpen: boolean; controlled: boolean; completed: boolean }) => { + const [state, setState] = createStore({ completed: args.completed, open: false }) + createEffect(() => setState("completed", args.completed)) return (
diff --git a/packages/session-ui/src/timeline/mermaid.stories.tsx b/packages/session-ui/src/timeline/mermaid.stories.tsx index a65df19a8ba3..9a3ec8110c9c 100644 --- a/packages/session-ui/src/timeline/mermaid.stories.tsx +++ b/packages/session-ui/src/timeline/mermaid.stories.tsx @@ -1,4 +1,4 @@ -import { createMemo, createSignal } from "solid-js" +import { createEffect, createMemo, createSignal } from "solid-js" import type { SessionDocument } from "../document" import { CURRENT_SESSION_ID, STORY_MODEL, STORY_TIME } from "../storybook/current-session-fixtures" import { CurrentSessionProviders } from "../storybook/current-session-story" @@ -79,6 +79,7 @@ function StateGraphTimeline() { function MermaidTimeline(props: { streaming: boolean }) { const [completed, setCompleted] = createSignal(!props.streaming) + createEffect(() => setCompleted(!props.streaming)) const document = createMemo( (): SessionDocument => ({ diff --git a/packages/session-ui/src/timeline/research-and-agents.stories.tsx b/packages/session-ui/src/timeline/research-and-agents.stories.tsx index 86e85d9fdd32..95c3eca66746 100644 --- a/packages/session-ui/src/timeline/research-and-agents.stories.tsx +++ b/packages/session-ui/src/timeline/research-and-agents.stories.tsx @@ -1,5 +1,6 @@ import type { SessionMessageAssistant, SessionMessageAssistantTool } from "@opencode/client/promise" import { createMemo } from "solid-js" +import { Dynamic } from "solid-js/web" import { createStore } from "solid-js/store" import type { SessionDocument } from "../document" import { CurrentSessionProviders, CurrentSessionTimelineStory } from "../storybook/current-session-story" @@ -14,7 +15,7 @@ import { webResearchDocument, } from "../storybook/current-session-fixtures" import { storyDocument, storyPatchFile, storyTool } from "../storybook/current-session-scenarios" -import { timelinePresets } from "./detail" +import { timelinePresets, type TimelinePlacement } from "./detail" import { SessionTimeline } from "./session-timeline" export default { @@ -103,13 +104,16 @@ const delegationDocument = storyDocument([ { agent: "general", description: "Run the focused timeline tests", prompt: "Run the timeline tests." }, { output: "All timeline tests pass.", metadata: { sessionID: "session_child_general" } }, ), - { type: "text", text: "Each delegated task keeps its own row while the reads and searches between them stay grouped." }, + { + type: "text", + text: "Each delegated task keeps its own row while the reads and searches between them stay grouped.", + }, ]) export const DelegateBetweenTools = { args: { subagents: "separate" }, - argTypes: { subagents: { control: { type: "inline-radio" }, options: ["separate", "grouped"] } }, - render: (args: { subagents: "separate" | "grouped" }) => ( + argTypes: { subagents: { control: { type: "inline-radio" }, options: ["separate", "grouped", "hidden"] } }, + render: (args: { subagents: TimelinePlacement }) => (
- Object.entries(researchScenarios) - .find(([name]) => name === args.scenario)?.[1] - .render() ?? researchScenarios.workflow.render(), + render: (args: { scenario: keyof typeof researchScenarios }) => ( + + ), } diff --git a/packages/session-ui/src/timeline/terminal-work.stories.tsx b/packages/session-ui/src/timeline/terminal-work.stories.tsx index a67fdeb4dcd7..651ccccb836e 100644 --- a/packages/session-ui/src/timeline/terminal-work.stories.tsx +++ b/packages/session-ui/src/timeline/terminal-work.stories.tsx @@ -1,6 +1,6 @@ import type { SessionMessageAssistant, SessionMessageShell } from "@opencode/client/promise" import { Match } from "effect" -import { createMemo, createSignal } from "solid-js" +import { createEffect, createMemo, createSignal, Show } from "solid-js" import { createStore } from "solid-js/store" import { DataProvider } from "../context/data" import { SessionShellMessage } from "../tools/tool-renderer" @@ -312,16 +312,20 @@ function InteractiveCommandStory(props: { existingGroup?: boolean tool?: "shell" | "execute" | "subagent" }) { - const initialPhase: "streaming" | "input" | "running" | "completed" = props.streaming ? "streaming" : "completed" + const initialPhase = (): "streaming" | "input" | "running" | "completed" => + props.streaming ? "streaming" : "completed" const [state, setState] = createStore({ - phase: initialPhase, + phase: initialPhase(), started: !props.existingGroup, lines: 3, sibling: false, busy: false, }) + createEffect(() => setState("phase", initialPhase())) + createEffect(() => setState("started", !props.existingGroup)) + const document = createMemo(() => { const phase = state.phase @@ -413,7 +417,11 @@ export const TerminalCommands = { streaming: boolean existingGroup: boolean tool: "shell" | "execute" | "subagent" - }) => (args.scenario === "collapsed" ? CollapsedShell.render() : ), + }) => ( + }> + + + ), } export const FixedAndPassed = { diff --git a/packages/session-ui/src/timeline/timeline-row.stories.tsx b/packages/session-ui/src/timeline/timeline-row.stories.tsx index dd5c0f3791d7..0fbdfe96acaf 100644 --- a/packages/session-ui/src/timeline/timeline-row.stories.tsx +++ b/packages/session-ui/src/timeline/timeline-row.stories.tsx @@ -4,7 +4,8 @@ import type { SessionMessageInfo, SessionMessageUser, } from "@opencode/client/promise" -import { createMemo, For, onCleanup, onMount } from "solid-js" +import { createEffect, createMemo, For, onCleanup, onMount } from "solid-js" +import { Dynamic } from "solid-js/web" import { createStore } from "solid-js/store" import type { SessionDocument } from "../document" import { SessionTimeline } from "./session-timeline" @@ -49,7 +50,14 @@ export default { } export const AgentThinking = { - render: () => , + args: { mode: "compact", reasoning: "heading", tool: false, text: "" }, + argTypes: { + mode: { options: ["hidden", "compact", "full"] }, + reasoning: { options: ["none", "blank", "heading"] }, + }, + render: (args: { mode: ReasoningMode; reasoning: string; tool: boolean; text: string }) => ( + + ), } export const StreamingReasoningAndText = { @@ -125,67 +133,68 @@ export const ResponseSpeed = { } function AgentReasoningStory(props: { mode: ReasoningMode; reasoning: string; tool: boolean; text: string }) { - const content = [ - ...(props.reasoning === "none" - ? [] - : [ - { - type: "reasoning" as const, - text: - props.reasoning === "blank" - ? " " - : "## Inspecting stability\n\nI will inspect the timeline before changing its state.", - time: { created: STORY_TIME + 100, completed: props.tool || props.text ? STORY_TIME + 7100 : undefined }, - }, - ]), - ...(props.tool - ? [ + const content = createMemo( + () => + [ + ...(props.reasoning === "none" + ? [] + : [ + { + type: "reasoning" as const, + text: + props.reasoning === "blank" + ? " " + : "## Inspecting stability\n\nI will inspect the timeline before changing its state.", + time: { + created: STORY_TIME + 100, + completed: props.tool || props.text ? STORY_TIME + 7100 : undefined, + }, + }, + ]), + ...(props.tool + ? [ + { + type: "tool" as const, + id: "tool_reasoning_projection_skill", + name: "skill", + state: { status: "running" as const, input: { name: "inspect" }, metadata: {} }, + time: { created: STORY_TIME + 7200, ran: STORY_TIME + 7250 }, + }, + ] + : []), + ...(props.text ? [{ type: "text" as const, text: props.text }] : []), + ] satisfies SessionMessageAssistant["content"], + ) + + const document = createMemo( + () => + ({ + sessionID: CURRENT_SESSION_ID, + messages: [ + ...thinkingDocument.messages, { - type: "tool" as const, - id: "tool_reasoning_projection_skill", - name: "skill", - state: { status: "running" as const, input: { name: "inspect" }, metadata: {} }, - time: { created: STORY_TIME + 7200, ran: STORY_TIME + 7250 }, + id: "msg_projection_assistant", + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: content(), + time: { created: STORY_TIME }, }, - ] - : []), - ...(props.text ? [{ type: "text" as const, text: props.text }] : []), - ] satisfies SessionMessageAssistant["content"] - - const document = { - sessionID: CURRENT_SESSION_ID, - messages: [ - ...thinkingDocument.messages, - { - id: "msg_projection_assistant", - type: "assistant", - agent: "build", - model: STORY_MODEL, - content, - time: { created: STORY_TIME }, - }, - ], - status: { type: "busy" }, - diffs: [], - } satisfies SessionDocument + ], + status: { type: "busy" }, + diffs: [], + }) satisfies SessionDocument, + ) return (
- - + +
) } -const AgentReasoning = { - args: { mode: "compact", reasoning: "heading", tool: false, text: "" }, - argTypes: { reasoning: { control: "select", options: ["none", "blank", "heading"] } }, - render: (args: { mode: ReasoningMode; reasoning: string; tool: boolean; text: string }) => ( - - ), -} - function HiddenReasoningStory() { const [state, setState] = createStore({ phase: "thinking" }) @@ -929,7 +938,7 @@ const MediaAttachmentRetry = { } const conversationScenarios = { - reasoning: AgentReasoning, + reasoning: AgentThinking, hidden: WorkingWithoutReasoningDetails, retry: RetryAndRecover, notices: AgentActivityNotices, @@ -947,7 +956,9 @@ const conversationScenarios = { * the running turn. Send next adds the next prompt; Deliver next delivers the oldest steer. */ export const PromptRuns = { - render: () => { + args: { count: 1 }, + argTypes: { count: { control: { type: "range", min: 1, max: 6, step: 1 } } }, + render: (args: { count: number }) => { const start = Date.now() - 10 * 60_000 const prompt = (id: string, text: string, minute: number, variant?: string) => ({ @@ -973,11 +984,13 @@ export const PromptRuns = { const steers = ["msg_end_4", "msg_end_5"] const [state, setState] = createStore<{ count: number; delivered: string[]; removed: string[] }>({ - count: 1, + count: args.count, delivered: [], removed: [], }) + createEffect(() => setState({ count: args.count, delivered: [], removed: [] })) + const session = createMemo( (): SessionDocument => ({ sessionID: CURRENT_SESSION_ID, @@ -1027,18 +1040,23 @@ export const PromptRuns = { } export const Conversation = { - args: { scenario: "notices", mode: "compact", reasoning: "heading", tool: false, text: "" }, + args: { ...AgentThinking.args, scenario: "notices" }, argTypes: { + ...AgentThinking.argTypes, scenario: { control: "select", options: Object.keys(conversationScenarios) }, - reasoning: { control: "select", options: ["none", "blank", "heading"] }, - mode: { control: "select", options: ["hidden", "compact", "full"] }, - }, - render: (args: { scenario: string; mode: ReasoningMode; reasoning: string; tool: boolean; text: string }) => { - if (args.scenario === "reasoning") return - - // SAFETY: the scenario control only offers conversationScenarios keys, and "reasoning" returned above. - return conversationScenarios[args.scenario as Exclude].render() }, + render: (args: { + scenario: keyof typeof conversationScenarios + mode: ReasoningMode + reasoning: string + tool: boolean + text: string + }) => ( + + ), } export const InstructionsUpdatedSingle = { diff --git a/packages/session-ui/src/timeline/user-message-fold.stories.tsx b/packages/session-ui/src/timeline/user-message-fold.stories.tsx index ac862300b269..7c96a3f50169 100644 --- a/packages/session-ui/src/timeline/user-message-fold.stories.tsx +++ b/packages/session-ui/src/timeline/user-message-fold.stories.tsx @@ -1,4 +1,5 @@ import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise" +import { createMemo } from "solid-js" import type { SessionDocument } from "../document" import { SessionTimeline, type SessionUserPresentation } from "./session-timeline" import { CurrentSessionProviders } from "../storybook/current-session-story" @@ -8,16 +9,35 @@ export default { title: "OpenCode/Conversation/Long user messages", id: "user-message-fold", parameters: { layout: "fullscreen" }, - render: () => , + args: { width: 760, turn: "thread" }, + argTypes: { + width: { control: { type: "range", min: 320, max: 960, step: 10 } }, + turn: { options: ["thread", "one_liner", "three_lines", "pasted", "code", "image", "voice", "short_last"] }, + }, + render: (args: { width: number; turn: string }) => , } export const Thread = {} -function LongUserMessages() { +function LongUserMessages(props: { width: number; turn: string }) { + const document = createMemo(() => { + if (props.turn === "thread") return thread + const prompt = `msg_fold_${props.turn}` + + return { + ...thread, + messages: thread.messages.filter((message) => message.id === prompt || message.id === `${prompt}_reply`), + } + }) + return ( -
- - +
+ +
) diff --git a/packages/session-ui/src/tools/read-group.stories.tsx b/packages/session-ui/src/tools/read-group.stories.tsx index c4c6facefcce..ad68fbff2b37 100644 --- a/packages/session-ui/src/tools/read-group.stories.tsx +++ b/packages/session-ui/src/tools/read-group.stories.tsx @@ -1,5 +1,5 @@ import type { JsonValue, SessionMessageAssistant } from "@opencode/client/promise" -import { createSignal } from "solid-js" +import { createEffect, createSignal } from "solid-js" import { CurrentSessionProviders } from "../storybook/current-session-story" import { STORY_TIME } from "../storybook/current-session-fixtures" import { storyDocument, storyTool } from "../storybook/current-session-scenarios" @@ -109,7 +109,7 @@ const parts = steps.flatMap((step, index) => { return [storyTool(`read_group_shell_${index}`, "shell", "completed", { command: step.shell }, { output: "ok" })] return step.map((read, item) => { - const [path, args] = typeof read === "string" ? [read, {}] : read + const [path, args] = Array.isArray(read) ? read : [read, {}] return storyTool(`read_group_read_${index}_${item}`, "read", "completed", { path, ...args }) }) @@ -124,8 +124,10 @@ const content = parts.flatMap((part) }) export const UsedGroup = { - render: (args: { width: number }) => { - const [open, setOpen] = createSignal(true) + args: { open: true }, + render: (args: { width: number; open: boolean }) => { + const [open, setOpen] = createSignal(args.open) + createEffect(() => setOpen(args.open)) return (
@@ -138,13 +140,18 @@ export const UsedGroup = { } export const WithoutUsedGroup = { - render: (args: { width: number }) => { + args: { preset: timelinePresets[0].id }, + argTypes: { preset: { options: timelinePresets.map((preset) => preset.id) } }, + render: (args: { width: number; preset: string }) => { const document = storyDocument(content) return (
- + preset.id === args.preset)!.value} + />
) diff --git a/packages/session-ui/src/tools/subagent-row-variants.stories.tsx b/packages/session-ui/src/tools/subagent-row-variants.stories.tsx index 9584a40eedc5..9ebaca8fc439 100644 --- a/packages/session-ui/src/tools/subagent-row-variants.stories.tsx +++ b/packages/session-ui/src/tools/subagent-row-variants.stories.tsx @@ -106,13 +106,15 @@ function PlainLabel() { } export const Variants = { - render: () => ( + args: { subagents: "separate" }, + argTypes: { subagents: { options: ["separate", "grouped", "hidden"] } }, + render: (args: { subagents: "separate" | "grouped" | "hidden" }) => (
diff --git a/packages/session-ui/src/tools/tool-group.stories.tsx b/packages/session-ui/src/tools/tool-group.stories.tsx index fd580918dcbd..fa265dad0c5f 100644 --- a/packages/session-ui/src/tools/tool-group.stories.tsx +++ b/packages/session-ui/src/tools/tool-group.stories.tsx @@ -1,4 +1,4 @@ -import { createMemo, createSignal, Show } from "solid-js" +import { createEffect, createMemo, createSignal, Show } from "solid-js" import { createStore } from "solid-js/store" import { createTwoFilesPatch } from "diff" import { CurrentSessionProviders } from "../storybook/current-session-story" @@ -12,8 +12,10 @@ export default { } export const MixedTools = { - render: () => { - const [open, setOpen] = createSignal(true) + args: { open: true }, + render: (args: { open: boolean }) => { + const [open, setOpen] = createSignal(args.open) + createEffect(() => setOpen(args.open)) const tools = [ storyTool( @@ -67,10 +69,11 @@ export const NoticesOnly = { } export const MixedReasoning = { - args: { reasoningDefaultOpen: false }, - render: (args: { reasoningDefaultOpen: boolean }) => { + args: { reasoningDefaultOpen: false, appended: false }, + render: (args: { reasoningDefaultOpen: boolean; appended: boolean }) => { const [open, setOpen] = createSignal(true) - const [appended, setAppended] = createSignal(false) + const [appended, setAppended] = createSignal(args.appended) + createEffect(() => setAppended(args.appended)) const parts = createMemo(() => [ storyTool("reasoning_read", "read", "completed", { path: "src/group.ts" }), @@ -110,8 +113,12 @@ export const MixedReasoning = { } export const CountRollover = { - render: () => { - const [state, setState] = createStore({ open: false, count: 9, attached: true }) + args: { count: 9, attached: true }, + argTypes: { count: { control: { type: "range", min: 1, max: 101, step: 1 } } }, + render: (args: { count: number; attached: boolean }) => { + const [state, setState] = createStore({ open: false, count: args.count, attached: args.attached }) + createEffect(() => setState("count", args.count)) + createEffect(() => setState("attached", args.attached)) const parts = createMemo(() => Array.from({ length: state.count }, (_, index) => @@ -243,10 +250,14 @@ export const StickyHeader = { } export const PatchFollowUps = { - args: { separator: "none" }, - argTypes: { separator: { control: "select", options: ["none", "shell", "error", "reasoning"] } }, - render: (args: { separator: string }) => { - const [state, setState] = createStore({ phase: "initial", open: true, reasoning: true }) + args: { separator: "none", phase: "initial" }, + argTypes: { + separator: { control: "select", options: ["none", "shell", "error", "reasoning"] }, + phase: { options: ["initial", "running", "completed"] }, + }, + render: (args: { separator: string; phase: "initial" | "running" | "completed" }) => { + const [state, setState] = createStore({ phase: args.phase, open: true, reasoning: true }) + createEffect(() => setState("phase", args.phase)) const file = (path: string, before: number, after: number) => ({ file: path, diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index 66d56646609f..9a64de51a549 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -865,26 +865,48 @@ export function CurrentReadToolGroup(props: { open?: boolean onOpenChange?: (open: boolean) => void onSizeChange?: () => void + /** Names each file once, and up to this many while closed; past that the closed row says how many files. */ + names?: number }) { const i18n = useI18n() const [state, setState] = createStore({ truncated: false }) const disclosure = createDisclosure({ open: () => props.open, onOpenChange: (open) => props.onOpenChange?.(open) }) const open = disclosure.open - const expandable = () => open() || state.truncated const pending = createMemo(() => props.tools.some((tool) => tool.state.status === "streaming" || tool.state.status === "running"), ) - const files = createMemo(() => - props.tools.flatMap((tool) => { + const files = createMemo(() => { + const reads = props.tools.flatMap((tool) => { const input = toolInput(currentToolInput(tool)) const name = getFilename(input.path ?? "") - return name ? [{ id: tool.id, name, args: readArgs(input) }] : [] - }), + return name ? [{ id: tool.id, path: input.path ?? "", name, args: readArgs(input) }] : [] + }) + + if (props.names === undefined) return reads + + // A file read in several ranges is named once, without one range standing for the rest. + return [ + ...reads + .reduce((unique, file) => { + const seen = unique.get(file.path) + + return unique.set(file.path, seen ? { ...seen, args: [] } : file) + }, new Map()) + .values(), + ] + }) + + const summary = createMemo(() => + props.names !== undefined && !open() && files().length > props.names + ? i18n.plural("ui.timeline.activity.files", files().length) + : undefined, ) + const expandable = () => open() || state.truncated || !!summary() + let list: HTMLSpanElement | undefined const measure = () => { @@ -925,20 +947,27 @@ export function CurrentReadToolGroup(props: { - - {(file, index) => ( - <> - 0}> - - {file().name} - - {(arg) => {` ${arg}`}} - - , - - - )} - + + {(file, index) => ( + <> + 0}> + + {file().name} + + {(arg) => {` ${arg}`}} + + , + + + )} + + } + > + {(text) => text()} +
@@ -1897,7 +1926,7 @@ export function ConsoleCopy(props: { text: string; label: string }) { return (
- + } size="normal" @@ -2096,7 +2125,11 @@ function ExecuteDetailsSection(props: {
{props.label} {(meta) => {meta()}} - + } size="normal" diff --git a/packages/session-ui/src/v2/components/session-progress-indicator-v2.stories.tsx b/packages/session-ui/src/v2/components/session-progress-indicator-v2.stories.tsx index 4bbe0eb5e531..4795f3e5a798 100644 --- a/packages/session-ui/src/v2/components/session-progress-indicator-v2.stories.tsx +++ b/packages/session-ui/src/v2/components/session-progress-indicator-v2.stories.tsx @@ -1,5 +1,5 @@ import { SessionProgressIndicatorV2 } from "./session-progress-indicator-v2" -import { createSignal, onCleanup, onMount } from "solid-js" +import { Index } from "solid-js" const docs = `### Overview Animated 5×5 dot grid loader for in-progress session state. @@ -35,7 +35,9 @@ export default { } export const Basic = { - render: () => , + args: { size: 16 }, + argTypes: { size: { control: { type: "range", min: 8, max: 48, step: 1 } } }, + render: (args: { size: number }) => , } export const Sizes = { @@ -49,44 +51,36 @@ export const Sizes = { } export const StressTest = { + args: { count: 16, size: 16 }, + argTypes: { count: { control: { type: "range", min: 1, max: 256, step: 1 } } }, parameters: { layout: "fullscreen", }, - render: () => , -} - -function StressGrid() { - const measure = () => ({ - columns: Math.max(1, Math.floor((window.innerWidth + 4) / 20)), - rows: Math.max(1, Math.floor((window.innerHeight + 4) / 20)), - }) - - const [grid, setGrid] = createSignal(measure()) - const resize = () => setGrid(measure()) - onMount(() => window.addEventListener("resize", resize)) - onCleanup(() => window.removeEventListener("resize", resize)) - - return ( + render: (args: { count: number; size: number }) => (
- {Array.from({ length: grid().columns * grid().rows }, () => ( - - ))} + + {() => } +
- ) + ), } export const OnDark = { + ...Basic, globals: { theme: "dark" }, - render: () => , + render: (args: { size: number }) => ( +
+ +
+ ), } diff --git a/packages/stories/index.html b/packages/stories/index.html index eacbb457aeb4..45c1b69b655b 100644 --- a/packages/stories/index.html +++ b/packages/stories/index.html @@ -7,6 +7,6 @@
- + diff --git a/packages/stories/mocks/app/context/layout.ts b/packages/stories/mocks/app/context/layout.ts index c163783a27b9..5d54cc300213 100644 --- a/packages/stories/mocks/app/context/layout.ts +++ b/packages/stories/mocks/app/context/layout.ts @@ -2,6 +2,7 @@ import { useLocation } from "../../solid-router" import { createSignal, type ParentProps } from "solid-js" import type { ServerConnection } from "@/runtime/server/registry" import type { Project } from "@/runtime/server/types" +import { requireServerKey } from "@/shell/routes/session" export type LocalProject = Partial & { worktree: string; expanded?: boolean } @@ -30,6 +31,10 @@ export function currentRoute(pathname: string, search: string): LayoutRoute { return draftID ? { type: "draft", draftID } : { type: "home" } } + if (parts[0] === "server" && parts[2] === "session" && parts[3]) { + return { type: "session", server: requireServerKey(parts[1]), sessionId: parts[3] } + } + return { type: "home" } } diff --git a/packages/stories/mocks/gui-plugins/pairing.tsx b/packages/stories/mocks/gui-plugins/pairing.tsx index ccdb54cbf7cd..a38fde152530 100644 --- a/packages/stories/mocks/gui-plugins/pairing.tsx +++ b/packages/stories/mocks/gui-plugins/pairing.tsx @@ -4,72 +4,117 @@ import type { JSX } from "solid-js" import { usePlugin, type IpcClient } from "../../../plugin/src/gui/index" import { PluginContext } from "../../../plugin/src/gui/internal" import type { Pairing } from "../../../gui-plugins/src/pairing/contract" +import { REMOTE_READ_RETRIES } from "../../../gui-plugins/src/pairing/machine" import type { PairingServer } from "../../../gui-plugins/src/pairing/page" // The pairing page renders inside the app's settings page, which brings these styles. import "@/settings/settings.css" -/** - * A local server and pairing main entry. Remote access starts on or off; turning it on takes a moment, after which - * the server advertises its tunnel, as the background service does once OpenTunnel attaches. `fails` makes turning - * it on fail, as when the tunnel cannot be created. `screenFails` makes the page's first read of the display sleep - * setting and its three retries fail; later reads and changes work. - */ -export function pairingRemote(input: { enabled: boolean; fails?: boolean; screenFails?: boolean }) { - const state = { enabled: input.enabled, screen: false, screenFailures: input.screenFails ? 4 : 0 } +export const pairingResponses = [ + "Normal", + "Remote read fails", + "Remote change fails", + "Screen read fails", + "Screen change fails", + "Tunnel connects slowly", + "Code request fails", + "Copy fails", +] as const + +type Response = (typeof pairingResponses)[number] + +/** In-memory settings, tunnel discovery, codes and clipboard, scoped to one story instance. */ +export function pairingRemote(input: { + enabled: boolean + screenActive?: boolean + response?: Response + expiresIn?: number +}) { + const state = { + enabled: input.enabled, + screen: input.screenActive ?? false, + issued: 0, + tunnelPolls: input.response === "Tunnel connects slowly" ? 3 : 0, + // Exhaust the automatic read retries. A manual retry (or the next write, request or copy) can then succeed. + failures: + input.response === "Remote read fails" || input.response === "Screen read fails" ? REMOTE_READ_RETRIES + 1 : 1, + } + + const fail = (operation: Response) => { + if (input.response !== operation || state.failures === 0) return + + state.failures -= 1 + throw new Error(operation) + } + const server: PairingServer = { client: { server: { - info: async () => ({ - urls: [ - "http://127.0.0.1:49374", - ...(state.enabled ? ["https://cbf8424f2044b16d.vcybm3xt4hhu.opentunnel.xyz"] : []), - ], - }), - pair: async () => ({ code: pairingCode(), expires_in: 300 }), + info: async () => { + const urls = ["http://localhost.invalid"] + + if (state.enabled && state.tunnelPolls === 0) urls.push("https://pairing.invalid") + if (state.tunnelPolls > 0) state.tunnelPolls -= 1 + + return { urls } + }, + pair: async () => { + fail("Code request fails") + state.issued += 1 + // As with server codes, encode 16 bytes. A new fixture replays the same sequence of QR codes. + const code = btoa(`story:${String(state.issued).padStart(10, "0")}`).replace(/=+$/, "") + + return { code, expires_in: input.expiresIn ?? 300 } + }, }, }, } + const client: IpcClient = { - remote: async () => state.enabled, - setRemote: async (enabled) => { - await new Promise((resolve) => setTimeout(resolve, 2000)) + remote: async () => { + fail("Remote read fails") - if (input.fails) throw new Error("Timed out creating the remote access tunnel") + return state.enabled + }, + setRemote: async (enabled, options) => { + await new Promise((resolve) => setTimeout(resolve, 2000)) + options?.signal?.throwIfAborted() + fail("Remote change fails") state.enabled = enabled }, screenActive: async () => { - if (state.screenFailures > 0) { - state.screenFailures -= 1 - throw new Error("The display sleep setting could not be read") - } + fail("Screen read fails") return state.screen }, setScreenActive: async (enabled) => { + fail("Screen change fails") state.screen = enabled }, state: () => undefined, on: () => () => undefined, } - return { server, client } + return { server, client, copy: async () => fail("Copy fails") } } /** * Stands in for the HostApis the pairing page reads that plugin stories do not provide: dialogs through the app's - * dialog stack, and a clipboard that accepts every copy. + * dialog stack, and a fixture clipboard. */ -export function PairingHost(props: { children: JSX.Element }) { +export function PairingHost(props: { children: JSX.Element; copy?: () => Promise }) { const base = usePlugin() + const dialog = useDialog() + const client = new QueryClient() + // Dialogs render in the app's dialog stack, outside this subtree, so they get the context again as the host does. const scoped = (render: () => JSX.Element) => ( {render()} ) - const context = Object.create(base, { + const context: typeof base = Object.create(base, { dialogs: { value: { open: (render: () => JSX.Element) => { @@ -78,7 +123,7 @@ export function PairingHost(props: { children: JSX.Element }) { }, }, }, - system: { value: { copy: async () => undefined } }, + system: { value: { copy: props.copy ?? (async () => undefined) } }, }) return scoped(() => ( @@ -87,12 +132,3 @@ export function PairingHost(props: { children: JSX.Element }) {
)) } - -// The server's codes are 16 random bytes in base64url. -function pairingCode() { - const bytes = crypto.getRandomValues(new Uint8Array(16)) - return btoa(String.fromCharCode(...bytes)) - .replaceAll("+", "-") - .replaceAll("/", "_") - .replace(/=+$/, "") -} diff --git a/packages/stories/mocks/gui-plugins/workspace-panel.tsx b/packages/stories/mocks/gui-plugins/workspace-panel.tsx new file mode 100644 index 000000000000..46028edcac20 --- /dev/null +++ b/packages/stories/mocks/gui-plugins/workspace-panel.tsx @@ -0,0 +1,156 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/solid-query" +import { File } from "@opencode/session-ui/file" +import { FileComponentProvider } from "@opencode/ui/context/file" +import { Show, createMemo, createSignal, type Accessor } from "solid-js" +import { createStore, produce } from "solid-js/store" +import { PluginHostProvider, usePluginHost } from "@/runtime/plugin/host" +import { Contribution, PluginStyles } from "@/runtime/plugin/render" +import { persistedHandle } from "@/runtime/plugin/stores" +import { builtins } from "../../../gui-plugins/src/renderer" +import { fileTabId } from "../../../gui-plugins/src/file/path" +import { BuiltinPanel, type BuiltinLayout } from "../../../plugin/src/gui/builtin" +import { PanelContext } from "../../../plugin/src/gui/host" +import type { Layout, PanelFrame, Storage } from "../../../plugin/src/gui" +import { createStoryHostApis } from "../../src/plugin" +import { createWorkspace, type ChangesScenario } from "./workspace" + +export type { ChangesScenario } from "./workspace" + +const plugins = builtins.filter((plugin) => ["file", "review", "microsoft-office"].includes(plugin.id)) + +// Each story owns one window and one session. The host opens each declared store once; every write stays in memory. +const storage: Storage = { + store(_key, options) { + const [store, set] = createStore(structuredClone(options.initial)) + + return persistedHandle({ store, set, init: undefined }) + }, + memory(_key, options) { + const [store, set] = createStore(structuredClone(options.initial)) + + return [store, (mutate) => set(produce(mutate))] + }, + remove() {}, +} + +/** Mounts the panels contributed by the built-ins with their normal cross-plugin contracts and lazy viewers. */ +export default function WorkspacePanel(props: { + plugin: "file" | "review" + path?: string + scenario?: ChangesScenario +}) { + const workspace = createWorkspace(props.scenario ?? "Changes") + + if (props.path?.includes("/")) workspace.screen.file.tree.expand(props.path.slice(0, props.path.lastIndexOf("/"))) + + const apis = createStoryHostApis("web") + + const [tab, setTab] = createSignal( + props.plugin === "review" ? "changes" : props.path ? fileTabId(workspace.screen.file, props.path) : "open", + ) + + const [width, setWidth] = createSignal(280) + + const [opened, setOpened] = createSignal(true) + + const frame: PanelFrame = { + visible: () => true, + present: () => true, + placement: () => "side", + reserve: () => false, + animate: () => false, + sidebar: { opened, width, resize: setWidth, toggle: () => setOpened((value) => !value), transition: () => false }, + open: () => [tab()], + } + + const scroll = new Map>() + + const layout: BuiltinLayout = { + narrow: () => false, + ready: () => true, + open: (key) => setTab(key.slice(key.indexOf(":") + 1)), + state: (key) => (key === `${props.plugin}:${tab()}` ? "active" : "closed"), + stored: frame.open, + sidebar: frame.sidebar, + side: { opened: () => true, toggle() {}, menu: () => [], width: () => undefined, resize() {} }, + scroll: { get: (_session, key) => scroll.get(key), set: (_session, key, value) => scroll.set(key, value) }, + close() {}, + toggle() {}, + hide() {}, + settings() {}, + project() {}, + draft() {}, + command() {}, + } + + const query = new QueryClient() + + return ( + + plugins} + apis={{ + ...apis, + desktop: () => undefined, + layout: () => layout, + storage: () => storage, + sessions: () => ({ current: () => workspace.session, list: () => [workspace.session] }), + screen: () => ({ current: () => workspace.screen }), + system: () => ({ + copy: (text) => navigator.clipboard.writeText(text), + save: async () => false, + openExternal() {}, + }), + embeds: () => ({ View: () => null, capture: async () => undefined }), + tabs: () => ({ list: () => [], open() {}, focus() {}, move() {}, close() {} }), + }} + whenMounted={(run) => { + run() + return () => {} + }} + > + + + +
+ +
+
+
+
+
+ ) +} + +function MountedPanel(props: { plugin: string; tab: Accessor; workspace: ReturnType }) { + const host = usePluginHost() + + const panel = createMemo(() => host.items(BuiltinPanel).find((item) => item.plugin === props.plugin)?.value) + + return ( + + {(panel) => { + const tab = createMemo(() => + panel.list({ ...props.workspace, open: [props.tab()] }).find((item) => item.id === props.tab()), + ) + + return ( + + {(tab) => ( + + {() => + panel.render({ + ...props.workspace, + get tab() { + return tab() + }, + }) + } + + )} + + ) + }} + + ) +} diff --git a/packages/stories/mocks/gui-plugins/workspace.ts b/packages/stories/mocks/gui-plugins/workspace.ts new file mode 100644 index 000000000000..0901c0d64d20 --- /dev/null +++ b/packages/stories/mocks/gui-plugins/workspace.ts @@ -0,0 +1,246 @@ +import { OpenCode } from "@opencode/client/promise" +import { createData } from "@opencode/client/solid" +import { reviewDiffs } from "@opencode/session-ui/storybook" +import { createSignal } from "solid-js" +import { createStore } from "solid-js/store" +import { createFileTreeStore } from "@/workspaces/files/tree-store" +import { createPathHelpers } from "@/workspaces/files/path" +import type { + Comment, + Comments, + FileContent, + FileNode, + Files, + LineRange, + MountedSession, + SessionScreen, +} from "../../../plugin/src/gui" + +export type ChangesScenario = "Changes" | "Clean" | "Read error" | "Offline" + +const root = "/workspace/status-checks" + +const markdown = `--- +owner: Release engineering +status: In review +--- +# Status checks + +Use this workspace to review the active status label before the next release. + +## Verification + +1. Confirm the status changes to **Running checks**. +2. Review the [check results](docs/checks.csv). +3. Check the [implementation](src/status.ts) before signing off. +` + +const contents = new Map([ + ["README.md", { type: "text", content: markdown }], + [ + "src/status.ts", + { type: "text", content: 'export const activeLabel = "Running checks"\nexport const idleLabel = "Ready"\n' }, + ], + [ + "docs/checks.csv", + { + type: "text", + content: + "Check,Owner,Result\nStatus label,Interface,Passed\nLine comments,Review,Passed\nPage layout,Documents,Pending\n", + }, + ], + [ + "docs/protected.docx", + { + type: "binary", + encoding: "base64", + // Compound File signature of password-protected Office files. The viewer diagnoses it before loading an engine. + content: "0M8R4KGxGuE=", + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }, + ], +]) + +export function createWorkspace(scenario: ChangesScenario) { + const location = { directory: root } + + const paths = [...contents.keys()] + + const search = (query: string) => paths.filter((path) => path.toLowerCase().includes(query.toLowerCase())) + + let failRead = scenario === "Read error" + + const request = async (input: RequestInfo | URL) => { + const url = new URL(input instanceof Request ? input.url : input) + + if (url.pathname === "/api/fs/find") { + const data = search(url.searchParams.get("query") ?? "").map((path) => ({ path, type: "file" })) + + return Response.json({ location, data }) + } + + if (url.pathname === "/api/vcs/diff") { + if (failRead) { + failRead = false + return Response.json({ message: "Could not read the working tree" }, { status: 503 }) + } + + return Response.json({ location, data: scenario === "Clean" ? [] : reviewDiffs }) + } + + if (url.pathname === "/api/session/session-story/diff") return Response.json({ data: [] }) + + throw new Error(`Unconfigured workspace fixture: ${url.pathname}`) + } + + const client = OpenCode.make({ + baseUrl: "https://workspace.invalid", + fetch: Object.assign(request, { preconnect() {} }), + }) + + const data = createData({ api: () => client, directory: root, event: { on: () => () => {}, listen: () => () => {} } }) + + const project = { + id: "status-checks", + name: "Status checks", + worktree: root, + worktrees: [], + sandboxes: [], + vcs: "git" as const, + time: { created: 1, updated: 1, active: 1 }, + } + + const session: MountedSession = { + key: "story\nsession-story", + id: "session-story", + tab: "story", + directory: root, + location, + pending: false, + project, + listedProject: project, + local: true, + visit: {}, + background: [], + server: { + id: "story", + name: "Workspace", + url: "https://workspace.invalid", + local: true, + builtin: false, + compatible: true, + connected: scenario !== "Offline", + client, + data, + }, + } + + const pathHelpers = createPathHelpers(() => root) + + const tree = createFileTreeStore({ + normalizeDir: pathHelpers.normalizeDir, + list: async (dir) => { + const prefix = dir ? `${dir}/` : "" + + const names = new Set( + paths.filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length).split("/")[0]!), + ) + + return Array.from(names) + .sort() + .map((name): FileNode => { + const path = `${prefix}${name}` + + return { + path, + name, + type: contents.has(path) ? "file" : "directory", + absolute: `${root}/${path}`, + ignored: false, + } + }) + }, + onError: (message) => { + throw new Error(message) + }, + }) + + const [selections, setSelections] = createStore<{ [path: string]: LineRange | null | undefined }>({}) + + const file: Files = { + root, + ready: () => true, + resolve: pathHelpers.normalize, + absolute: pathHelpers.absolute, + get(path) { + const content = contents.get(path) + + return { path, name: path.split("/").pop() ?? path, loaded: !!content, notFound: !content, content } + }, + sync: async () => {}, + unwatch() {}, + missing: (path) => !contents.has(path), + exists: async (path) => contents.has(path), + search: async (query) => search(query), + selection: { get: (path) => selections[path], set: (path, range) => setSelections(path, range) }, + scroll: { get: () => ({}), set() {} }, + tree: { + list: tree.children, + state: tree.dirState, + sync: tree.listDir, + expand: tree.expandDir, + collapse: tree.collapseDir, + }, + } + + const [comments, setComments] = createStore([ + { + id: "comment-1", + time: 1, + file: reviewDiffs[0]!.file, + selection: { start: 2, end: 2, side: "additions" }, + comment: "Does this match the label in the check results?", + }, + ]) + + const [focus, setFocus] = createSignal>(null) + + let sequence = 1 + + const screen: SessionScreen = { + file, + comment: { + list: (path) => (path ? comments.filter((item) => item.file === path) : comments), + add(input) { + const time = ++sequence + + const comment = { ...input, id: `comment-${time}`, time } + + setComments(comments.length, comment) + setFocus({ file: input.file, id: comment.id }) + + return comment + }, + update: (id, text) => setComments((item) => item.id === id, "comment", text), + remove: (id) => setComments((items) => items.filter((item) => item.id !== id)), + focus: { current: focus, set: setFocus }, + active: { current: focus, set: setFocus }, + }, + composer: { + text: () => "", + setText() {}, + insert() {}, + model: () => undefined, + setModel: () => false, + setVariant: () => false, + attach() {}, + quotable: () => false, + focus() {}, + update() {}, + detach() {}, + focused: () => false, + }, + } + + return { session, screen } +} diff --git a/packages/stories/playwright/README.md b/packages/stories/playwright/README.md index d3b34c6d77cf..1b9a72f80798 100644 --- a/packages/stories/playwright/README.md +++ b/packages/stories/playwright/README.md @@ -2,6 +2,8 @@ Production Solid components are tested through their existing `*.stories.tsx` stories without booting the app, configuring a server, seeding browser storage, or navigating unrelated routes. +To browse the full components lab in a browser, run `bun run --cwd packages/stories dev` from the repo root and open (or the port Vite prints). The tree, grid, and inspector use the same story fixtures as the individual `/?id=…` pages. + Keep each spec in the package that owns its production component: - `packages/session-ui/component-tests/` owns timeline, tool, notice, reasoning, lifecycle, and review coverage. diff --git a/packages/stories/src/frame.tsx b/packages/stories/src/frame.tsx index 2c4086c8c4a4..f2cbac159b48 100644 --- a/packages/stories/src/frame.tsx +++ b/packages/stories/src/frame.tsx @@ -1,15 +1,11 @@ import "../../app/src/index.css" -import { createEffect, createResource, onCleanup, onMount, Show, type Component, type JSX } from "solid-js" +import { createResource, Show, type Component, type JSX } from "solid-js" import { Dynamic, render } from "solid-js/web" -import { MetaProvider } from "@solidjs/meta" -import { DialogProvider } from "@opencode/ui/context/dialog" -import { ThemeProvider, useTheme, type ColorScheme } from "@opencode/ui/theme" -import { Font } from "@opencode/ui/font" -import { LanguageProvider, UiI18nBridge, useLanguage } from "@/runtime/i18n/language" -import { SettingsProvider } from "@/settings/model" +import type { ColorScheme } from "@opencode/ui/theme" import { findStory } from "virtual:story-index" import { PluginStory } from "./plugin" +import { StoryProviders } from "./providers" type Args = { [key: string]: unknown } @@ -66,73 +62,22 @@ function Frame() { function Decorators(props: { scheme: ColorScheme; fullscreen: boolean; file: string; children: JSX.Element }) { return ( - - - - - - - - - - -
- {props.children} -
-
-
-
-
-
-
+ +
+ {props.children} +
+
) } -function Scheme(props: { value: ColorScheme }) { - const theme = useTheme() - - createEffect(() => theme.setColorScheme(props.value)) - createEffect(() => { - document.documentElement.classList.remove("light", "dark") - document.documentElement.classList.add(theme.mode()) - }) - - return null -} - -function Direction(props: { value?: string }) { - const language = useLanguage() - - createEffect(() => language.setDirection(props.value === "rtl" ? "rtl" : "ltr")) - - return null -} - -// The app derives this attribute from its reduce motion setting; stories follow the system preference. -function Motion() { - onMount(() => { - const motion = matchMedia("(prefers-reduced-motion: reduce)") - - const apply = () => (document.documentElement.dataset.motion = motion.matches ? "reduce" : "full") - - apply() - motion.addEventListener("change", apply) - onCleanup(() => motion.removeEventListener("change", apply)) - }) - - return null -} - function scheme(value: string): ColorScheme { if (value === "light" || value === "dark" || value === "system") return value diff --git a/packages/stories/src/index-plugin.ts b/packages/stories/src/index-plugin.ts index 8d8fd1bba01f..6681df70a2c6 100644 --- a/packages/stories/src/index-plugin.ts +++ b/packages/stories/src/index-plugin.ts @@ -12,6 +12,14 @@ export function storyIndex(roots: string[]): Plugin { return { name: "opencode:story-index", resolveId: (source) => (source === id ? `\0${id}` : undefined), + hotUpdate({ file }) { + if (!file.endsWith(".stories.tsx")) return + + // The index reads the export names itself. Recompute them for the next /?id=… visit. + const graph = this.environment.moduleGraph + const index = graph.getModuleById(`\0${id}`) + if (index) graph.invalidateModule(index) + }, load(source) { if (source !== `\0${id}`) return diff --git a/packages/stories/src/lab.tsx b/packages/stories/src/lab.tsx new file mode 100644 index 000000000000..673c9355a735 --- /dev/null +++ b/packages/stories/src/lab.tsx @@ -0,0 +1,54 @@ +import "../../app/src/index.css" + +import { createSignal, onCleanup } from "solid-js" +import { render } from "solid-js/web" +import { LabBrowser } from "../../app/src/components-lab/browser" +import { loadLabCatalog, type StoryModule } from "../../app/src/components-lab/catalog" +import { PluginStory } from "./plugin" +import { StoryProviders } from "./providers" + +// This origin uses the story mocks, so it can include the standalone dialog fixtures as well. +const modules = import.meta.glob("../../{app,ui,session-ui,gui-plugins}/src/**/*.stories.tsx") + +const sources = import.meta.glob("../../{app,ui,session-ui,gui-plugins}/src/**/*.stories.tsx", { + query: "?raw", + import: "default", +}) + +function StandaloneLab() { + const readParams = () => Object.fromEntries(new URLSearchParams(location.search)) + + const [params, setParams] = createSignal(readParams()) + + const sync = () => setParams(readParams()) + + window.addEventListener("popstate", sync) + onCleanup(() => window.removeEventListener("popstate", sync)) + + return ( + +
+ { + const url = new URL(location.href) + + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) url.searchParams.delete(key) + else url.searchParams.set(key, value) + } + if (url.href === location.href) return + + history.pushState(null, "", url) + sync() + }} + loadCatalog={() => loadLabCatalog(modules, sources)} + plugin={PluginStory} + /> +
+
+ ) +} + +document.title = "OpenCode Components Lab" +render(StandaloneLab, document.getElementById("story-root")!) diff --git a/packages/stories/src/main.ts b/packages/stories/src/main.ts new file mode 100644 index 000000000000..e27b868f764b --- /dev/null +++ b/packages/stories/src/main.ts @@ -0,0 +1,6 @@ +// Component tests navigate directly to an isolated story. Only the homepage loads the catalog and inspector. +if (new URLSearchParams(location.search).has("id")) { + void import("./frame") +} else { + void import("./lab") +} diff --git a/packages/stories/src/providers.tsx b/packages/stories/src/providers.tsx new file mode 100644 index 000000000000..f4a0a5e8507a --- /dev/null +++ b/packages/stories/src/providers.tsx @@ -0,0 +1,51 @@ +import { createEffect, onCleanup, onMount, type ParentProps } from "solid-js" +import { MetaProvider } from "@solidjs/meta" +import { DialogProvider } from "@opencode/ui/context/dialog" +import { Font } from "@opencode/ui/font" +import { ThemeProvider, useTheme, type ColorScheme } from "@opencode/ui/theme" +import { LanguageProvider, UiI18nBridge, useLanguage } from "@/runtime/i18n/language" +import { SettingsProvider } from "@/settings/model" + +export function StoryProviders(props: ParentProps<{ scheme?: ColorScheme; direction?: string; locale?: string }>) { + return ( + + + + + + + + {props.children} + + + + + + ) +} + +function Appearance(props: { scheme?: ColorScheme; direction?: string }) { + const theme = useTheme() + + const language = useLanguage() + + createEffect(() => props.scheme && theme.setColorScheme(props.scheme)) + createEffect(() => { + document.documentElement.classList.remove("light", "dark") + document.documentElement.classList.add(theme.mode()) + }) + createEffect(() => language.setDirection(props.direction === "rtl" ? "rtl" : "ltr")) + + // The app derives this attribute from its reduce motion setting; stories follow the system preference. + onMount(() => { + const motion = matchMedia("(prefers-reduced-motion: reduce)") + + const apply = () => (document.documentElement.dataset.motion = motion.matches ? "reduce" : "full") + + apply() + motion.addEventListener("change", apply) + onCleanup(() => motion.removeEventListener("change", apply)) + }) + + return null +} diff --git a/packages/stories/vite.config.ts b/packages/stories/vite.config.ts index 16529da36032..89dc10155a8a 100644 --- a/packages/stories/vite.config.ts +++ b/packages/stories/vite.config.ts @@ -6,8 +6,7 @@ import { defineConfig, searchForWorkspaceRoot } from "vite" import solid from "vite-plugin-solid" import { storyIndex } from "./src/index-plugin" -// Serves one story at a time for the component tests, the way Storybook's iframe did, without Storybook. The app's -// browsing UI for stories is the components lab in the app itself. +// The standalone components lab and the isolated story frames share the same mock runtime. const here = path.dirname(fileURLToPath(import.meta.url)) const packages = path.resolve(here, "..") const app = path.resolve(packages, "app/src") diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index 9163905125e6..fc071e870cf9 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -2046,7 +2046,6 @@ function AssistantFooter(props: { message: SessionMessageAssistant }) { const turn = () => ({ index: ctx.messageIndex(props.message.id), legacy: ctx.legacyTurns() }) const duration = createMemo(() => SessionTurn.duration(messages(), props.message, turn())) const tokensPerSecond = createMemo(() => SessionTurn.tokensPerSecond(messages(), props.message, turn())) - const timeToFirstToken = createMemo(() => SessionTurn.timeToFirstToken(messages(), props.message, turn())) const interrupted = createMemo(() => props.message.error?.message === "Step interrupted") const freeLimit = createMemo(() => props.message.error?.type === "provider.free-limit") const limitNotice = useLimitNotice(() => props.message) @@ -2081,9 +2080,6 @@ function AssistantFooter(props: { message: SessionMessageAssistant }) { {(value) => · {value().toFixed(1)} tok/s} - = 36 && timeToFirstToken()}> - {(value) => · {Locale.duration(value())} ttft} - · interrupted diff --git a/packages/tui/test/app-lifecycle.test.tsx b/packages/tui/test/app-lifecycle.test.tsx index b857987f0008..ffd54480aecb 100644 --- a/packages/tui/test/app-lifecycle.test.tsx +++ b/packages/tui/test/app-lifecycle.test.tsx @@ -795,7 +795,8 @@ test("keeps assistant footer metrics current after prepend, same-length refresh, (frame) => frame.includes("Original answer") && frame.includes("40.0 tok/s"), ) expect(initial).toContain("Current input") - expect(initial).toContain("4.0s \u00b7 40.0 tok/s \u00b7 500ms ttft") + expect(initial).toContain("4.0s \u00b7 40.0 tok/s") + expect(initial).not.toContain("ttft") expect(initial).not.toContain("Prepended input") setup.mockInput.pressKey("g", { ctrl: true }) @@ -810,7 +811,7 @@ test("keeps assistant footer metrics current after prepend, same-length refresh, ) expect(prepended).toContain("Current input") expect(prepended).toContain("Original answer") - expect(prepended).toContain("4.0s \u00b7 40.0 tok/s \u00b7 500ms ttft") + expect(prepended).toContain("4.0s \u00b7 40.0 tok/s") // Refresh the latest page: length stays four, but the retained assistant moves from index three to one. refresh = true @@ -826,7 +827,7 @@ test("keeps assistant footer metrics current after prepend, same-length refresh, ) expect(refreshed).toContain("Current input") expect(refreshed).toContain("Original answer") - expect(refreshed).toContain("4.0s \u00b7 40.0 tok/s \u00b7 500ms ttft") + expect(refreshed).toContain("4.0s \u00b7 40.0 tok/s") expect(refreshed).toContain("3.0s \u00b7 50.0 tok/s") setup.events.emit({ @@ -841,7 +842,7 @@ test("keeps assistant footer metrics current after prepend, same-length refresh, (frame) => frame.includes("Original answer") && !frame.includes("Later input") && !frame.includes("Later answer"), ) expect(reverted).toContain("Current input") - expect(reverted).toContain("4.0s \u00b7 40.0 tok/s \u00b7 500ms ttft") + expect(reverted).toContain("4.0s \u00b7 40.0 tok/s") expect(reverted).not.toContain("50.0 tok/s") }) diff --git a/packages/tui/test/component/go-upsell-art.test.tsx b/packages/tui/test/component/go-upsell-art.test.tsx index a559c7e68ce3..7100684f290d 100644 --- a/packages/tui/test/component/go-upsell-art.test.tsx +++ b/packages/tui/test/component/go-upsell-art.test.tsx @@ -1,6 +1,7 @@ import { expect, spyOn, test } from "bun:test" /** @jsxImportSource @opentui/solid */ import { OptimizedBuffer, RGBA } from "@opentui/core" +import { setRendererCapabilities } from "@opentui/core/testing" import { testRender } from "@opentui/solid" import { createSignal, Show } from "solid-js" import "../../src/component/go-upsell-art" @@ -38,6 +39,7 @@ test("the art stops every frame when hidden, closed, or still, and leaves nothin const setCell = spyOn(OptimizedBuffer.prototype, "setCell") try { + setRendererCapabilities(app.renderer, { rgb: false }) await app.renderOnce() expect(app.renderer.liveRequestCount).toBe(1) // Each frame is one direct write into the art's own buffer, never a draw call per cell. diff --git a/packages/ui/src/actions/button/button.stories.tsx b/packages/ui/src/actions/button/button.stories.tsx index c04677205fcf..cfd58675d78e 100644 --- a/packages/ui/src/actions/button/button.stories.tsx +++ b/packages/ui/src/actions/button/button.stories.tsx @@ -1,20 +1,61 @@ import { For } from "solid-js" -import { Button } from "./button" +import { iconNames } from "@opencode/ui/icons/catalog" +import { Button, type ButtonProps } from "./button" + +type Args = Pick & { + children: string + icon: string + interaction: "rest" | "hover" | "pressed" | "focus" + expanded: boolean +} + +const variants = [ + "neutral", + "danger", + "warning", + "outline", + "contrast", + "submit", + "ghost", + "ghost-muted", + "ghost-faint", + "ghost-danger", + "loading", +] satisfies ButtonProps["variant"][] + +const sizes = ["small", "normal", "large"] satisfies ButtonProps["size"][] + +const interactions = ["rest", "hover", "pressed", "focus"] as const + +const label = (value: string) => value[0].toUpperCase() + value.slice(1).replaceAll("-", " ") const docs = `### Overview Button v2 with visual variants and three sizes. ### API -- \`variant\`: "neutral" | "danger" | "warning" | "contrast" | "submit" | "ghost" | "ghost-muted" | "ghost-faint" | "ghost-danger" | "loading". -- \`submit\` shares the brighter contrast icon-button styling for Composer submission actions. -- \`size\`: "small" | "normal" | "large". +- \`variant\`: ${variants.join(", ")}. Submit shares the brighter contrast icon-button styling for Composer submission actions. +- \`size\`: small, normal or large. - \`icon\`: Optional icon name. -- Inherits Kobalte Button props and native button attributes. +- Inherits native button attributes. ### States -- default, hover, pressed, focus, disabled. -- State selectors are available via pseudo-classes and \`[data-state]\`. -` +Default, hover, pressed, focus and disabled. Try the pointer and keyboard, or pin an interaction in the panel. +Expanded styles apply to ghost, ghost-muted and ghost-faint buttons.` + +function Preview(args: Args) { + return ( + + ) +} export default { title: "UI/Button", @@ -24,164 +65,94 @@ export default { parameters: { frameHeight: "240px", frameBackground: "#fff", - docs: { - description: { - component: docs, - }, - }, + docs: { description: { component: docs } }, }, args: { children: "Button", variant: "neutral", size: "normal", - }, + icon: "none", + interaction: "rest", + disabled: false, + expanded: false, + } satisfies Args, argTypes: { - icon: { - control: "text", - }, - variant: { - control: "select", - options: [ - "neutral", - "danger", - "warning", - "contrast", - "submit", - "ghost", - "ghost-muted", - "ghost-faint", - "ghost-danger", - "loading", - ], - }, - size: { - control: "select", - options: ["normal", "large"], - }, + variant: { control: "select", options: variants }, + size: { control: "select", options: sizes }, + icon: { control: "select", options: ["none", ...iconNames().sort()] }, + interaction: { control: "select", options: interactions }, }, + render: Preview, } export const Playground = {} export const Variants = { - render: () => ( -
- - - - - - - - - - + render: (args: Args) => ( +
+ + {(variant) => ( + + {label(variant)} + + )} +
), } export const Sizes = { - render: () => ( -
- - - + render: (args: Args) => ( +
+ + {(size) => ( + + {label(size)} + + )} +
), } export const Icon = { - render: () => ( -
- - +
), } export const AllStates = { - render: () => { - const variants = [ - "neutral", - "danger", - "warning", - "contrast", - "submit", - "ghost", - "ghost-muted", - "ghost-faint", - "loading", - ] as const - - const states = ["default", "hover", "pressed", "focus", "disabled"] as const - const toTitleCase = (value: string) => value.charAt(0).toUpperCase() + value.slice(1) - - return ( -
- - {(variant) => ( -
-
- {variant} -
-
- - {(state) => ( - - )} - -
+ render: (args: Args) => ( +
+ + {(variant) => ( +
+
{variant}
+
+ + {(interaction) => ( + + {interaction === "rest" ? "Default" : label(interaction)} + + )} + + + Disabled +
- )} - -
- ) - }, +
+ )} + +
+ ), } diff --git a/packages/ui/src/actions/icon-button/icon-button.stories.tsx b/packages/ui/src/actions/icon-button/icon-button.stories.tsx index 3acbf697b457..cd9a8f3333e5 100644 --- a/packages/ui/src/actions/icon-button/icon-button.stories.tsx +++ b/packages/ui/src/actions/icon-button/icon-button.stories.tsx @@ -1,21 +1,52 @@ -import { For } from "solid-js" -import { IconButton } from "./icon-button" +import { createEffect, For } from "solid-js" import { Icon } from "@opencode/ui/icon" +import { iconNames } from "@opencode/ui/icons/catalog" +import { IconButton, type IconButtonProps } from "./icon-button" + +type Args = Pick & { + icon: string + interaction: NonNullable | "focus" + expanded: boolean +} + +const variants = ["neutral", "contrast", "submit", "ghost", "ghost-muted"] satisfies IconButtonProps["variant"][] + +const sizes = ["small", "normal", "large"] satisfies IconButtonProps["size"][] + +const interactions = ["rest", "hover", "pressed", "focus"] as const const docs = `### Overview Square icon-only button with visual variants and three sizes. ### API -- \`icon\`: Icon content. -- \`variant\`: "neutral" | "contrast" | "submit" | "ghost". -- \`submit\` shares the contrast styling with regular Composer submit buttons. -- \`size\`: "small" | "normal" | "large". -- Inherits Kobalte Button props and native button attributes. +- \`icon\`: Icon content. Choose a glyph in the panel. +- \`variant\`: ${variants.join(", ")}. Submit shares the contrast styling with Composer submit buttons. +- \`size\`: small, normal or large. +- Inherits native button attributes. ### States -- default, hover, pressed, focus, disabled. -- State selectors are available via pseudo-classes and \`[data-state]\`. -` +Default, hover, pressed, keyboard focus and disabled. The state prop pins hover or pressed styling. +Expanded styles apply to the ghost variants.` + +function Preview(args: Args) { + return ( + } + variant={args.variant} + size={args.size} + state={args.interaction === "focus" ? undefined : args.interaction} + ref={(button) => + createEffect(() => { + // CSS supports a pinned focus ring in addition to the public rest/hover/pressed prop. + if (args.interaction === "focus") button.dataset.state = "focus" + }) + } + disabled={args.disabled} + data-expanded={args.expanded ? "" : undefined} + /> + ) +} export default { title: "UI/IconButton", @@ -25,84 +56,67 @@ export default { parameters: { frameHeight: "300px", frameBackground: "#fff", - docs: { - description: { - component: docs, - }, - }, + docs: { description: { component: docs } }, }, args: { - icon: , + icon: "plus", variant: "neutral", size: "normal", - }, + interaction: "rest", + disabled: false, + expanded: false, + } satisfies Args, argTypes: { - icon: { - control: false, - }, - variant: { - control: "select", - options: ["neutral", "contrast", "submit", "ghost"], - }, - size: { - control: "select", - options: ["small", "normal", "large"], - }, + icon: { control: "select", options: iconNames().sort() }, + variant: { control: "select", options: variants }, + size: { control: "select", options: sizes }, + interaction: { control: "select", options: interactions }, }, + render: Preview, } export const Playground = {} export const Variants = { - render: () => ( -
- } variant="neutral" /> - } variant="contrast" /> - } variant="submit" /> - } variant="ghost" /> + render: (args: Args) => ( +
+ + {(variant) => ( + + )} +
), } export const Sizes = { - render: () => ( -
- } size="small" variant="neutral" /> - } size="normal" variant="neutral" /> - } size="large" variant="neutral" /> + render: (args: Args) => ( +
+ {(size) => }
), } export const AllStates = { - render: () => { - const variants = ["neutral", "contrast", "submit", "ghost"] as const - const states = ["default", "hover", "pressed", "focus", "disabled"] as const - - return ( -
- - {(variant) => ( -
-
- {variant} -
-
- - {(state) => ( - } - variant={variant} - data-state={state === "default" ? undefined : state} - disabled={state === "disabled"} - /> - )} - -
+ render: (args: Args) => ( +
+ + {(variant) => ( +
+
{variant}
+
+ + {(interaction) => } + +
- )} - -
- ) - }, +
+ )} + +
+ ), } diff --git a/packages/ui/src/actions/split-button/split-button.stories.tsx b/packages/ui/src/actions/split-button/split-button.stories.tsx index 89946da34c03..cc95b7f331f9 100644 --- a/packages/ui/src/actions/split-button/split-button.stories.tsx +++ b/packages/ui/src/actions/split-button/split-button.stories.tsx @@ -1,45 +1,59 @@ -import { Icon } from "@opencode/ui/icon" +import { createEffect, createSignal, Show } from "solid-js" import { AppIcon } from "@opencode/ui/app-icon" +import { Icon } from "@opencode/ui/icon" +import { Menu } from "@opencode/ui/menu" import { SplitButton, SplitButtonAction, SplitButtonMenuTrigger } from "./split-button" +const defaults = { label: "Open", finder: false, actionDisabled: false, menuDisabled: false, open: false } + export default { title: "UI/SplitButton", id: "ui-split-button", component: SplitButton, tags: ["autodocs"], -} + args: defaults, + render: (args: typeof defaults) => { + const [open, setOpen] = createSignal(args.open) -export const Basic = { - render: () => ( - - Open - - - - - ), -} + const [result, setResult] = createSignal("") -export const Disabled = { - render: () => ( - - Open - - - - - ), -} + createEffect(() => setOpen(args.open && !args.menuDisabled)) -export const OpenIn = { - render: () => ( - - - - - - - - - ), + return ( +
+ + setResult(args.finder ? "Opened in Finder" : "Opened")} + > + + + + + + + + + + + setResult("Opened in new window")}>Open in new window + + + + + {result()} +
+ ) + }, } + +export const Basic = {} + +export const Disabled = { args: { actionDisabled: true, menuDisabled: true } } + +export const OpenIn = { args: { finder: true } } diff --git a/packages/ui/src/components/animated-number.stories.tsx b/packages/ui/src/components/animated-number.stories.tsx new file mode 100644 index 000000000000..4a3b780a3a4c --- /dev/null +++ b/packages/ui/src/components/animated-number.stories.tsx @@ -0,0 +1,35 @@ +import { AnimatedNumber } from "./animated-number" +import { RollingNumber } from "./rolling-number" + +export default { + title: "UI/AnimatedNumber", + id: "ui-animated-number", + args: { value: 9 }, + argTypes: { value: { control: { type: "range", min: 0, max: 120, step: 1 } } }, + render: (args: { value: number }) => , +} + +export const SingleDigit = {} + +export const Carry = { args: { value: 10 } } + +export const ThreeDigits = { args: { value: 100 } } + +export const Compare = { + render: (args: { value: number }) => ( +
+
+
Animated number
+
+ +
+
+
+
Rolling number
+
+ +
+
+
+ ), +} diff --git a/packages/ui/src/components/app-icon.stories.tsx b/packages/ui/src/components/app-icon.stories.tsx index d7ca0a340d4a..7924fdcf3843 100644 --- a/packages/ui/src/components/app-icon.stories.tsx +++ b/packages/ui/src/components/app-icon.stories.tsx @@ -1,8 +1,6 @@ -// @ts-nocheck import { For } from "solid-js" -import { iconNames } from "./app-icons/types" -import * as mod from "./app-icon" -import { create } from "../storybook/scaffold" +import { iconNames, type IconName } from "./app-icons/types" +import { AppIcon } from "./app-icon" const docs = `### Overview Application icon renderer for known editor/terminal apps. @@ -27,12 +25,11 @@ Use in provider or app selection lists. ` -const story = create({ title: "UI/AppIcon", mod, args: { id: "vscode" } }) - export default { title: "UI/AppIcon", id: "components-app-icon", - component: story.meta.component, + component: AppIcon, + args: { id: "vscode" }, tags: ["autodocs"], parameters: { docs: { @@ -49,10 +46,10 @@ export default { }, } -export const Basic = story.Basic +export const Basic = {} export const AllIcons = { - render: () => ( + render: (args: { id: IconName }) => (
{(id) => ( -
- +
+
{id}
)} diff --git a/packages/ui/src/components/card.stories.tsx b/packages/ui/src/components/card.stories.tsx index 73f17dbc18e2..ee8e33af975f 100644 --- a/packages/ui/src/components/card.stories.tsx +++ b/packages/ui/src/components/card.stories.tsx @@ -1,5 +1,4 @@ -// @ts-nocheck -import { Card, CardActions, CardDescription, CardTitle } from "./card" +import { Card, CardActions, CardDescription, CardTitle, type CardProps } from "./card" import { Button } from "@opencode/ui/button" const docs = `### Overview @@ -39,18 +38,32 @@ export default { }, args: { variant: "normal", + icon: "auto", + title: "Card title", + description: "Small supporting text.", }, argTypes: { + icon: { control: "select", options: ["auto", "none", "check"] }, variant: { control: "select", options: ["normal", "error", "warning", "success", "info"], }, }, - render: (props: { variant?: "normal" | "error" | "warning" | "success" | "info" }) => { + render: (props: { + variant: CardProps["variant"] + icon: "auto" | "none" | "check" + title: string + description: string + }) => { return ( - Card title - Small supporting text. + + {props.title} + + {props.description} +
+ ) +} + +export default { title: "UI/DiagramPreview", id: "ui-diagram-preview" } + +export const Inline = { render: () => } + +export const Open = { render: () => } + +export const Wide = { render: () => } diff --git a/packages/ui/src/components/dock-surface.stories.tsx b/packages/ui/src/components/dock-surface.stories.tsx new file mode 100644 index 000000000000..e4a22ae6e1b7 --- /dev/null +++ b/packages/ui/src/components/dock-surface.stories.tsx @@ -0,0 +1,26 @@ +import { DockShell, DockTray, type DockTrayProps } from "./dock-surface" + +type Args = { attach: NonNullable; message: string } + +export default { + title: "UI/DockSurface", + id: "ui-dock-surface", + args: { attach: "top", message: "Workspace location is missing" } satisfies Args, + argTypes: { attach: { options: ["none", "top"] } }, + render: (args: Args) => ( +
+ {args.message} + + Select a directory to continue the session. + +
+ ), +} + +export const Attached = {} + +export const Detached = { args: { attach: "none" } } diff --git a/packages/ui/src/components/document-surface.stories.tsx b/packages/ui/src/components/document-surface.stories.tsx new file mode 100644 index 000000000000..614dbd8adecf --- /dev/null +++ b/packages/ui/src/components/document-surface.stories.tsx @@ -0,0 +1,42 @@ +import { Index } from "solid-js" +import { DocumentSurface } from "./document-surface" + +const defaults = { pages: 1, width: 640 } + +export default { + title: "UI/DocumentSurface", + id: "ui-document-surface", + args: defaults, + argTypes: { + pages: { control: { type: "range", min: 1, max: 5, step: 1 } }, + width: { control: { type: "range", min: 240, max: 800, step: 10 } }, + }, + render: (args: typeof defaults) => ( +
+
+
+ + {(_, i) => ( + +

Project notes

+

+ Page {i + 1} of {args.pages} +

+
+ )} +
+
+
+
+ ), +} + +export const SinglePage = {} + +export const PageStack = { args: { pages: 3 } } + +export const Narrow = { args: { pages: 2, width: 300 } } diff --git a/packages/ui/src/components/error-details.stories.tsx b/packages/ui/src/components/error-details.stories.tsx new file mode 100644 index 000000000000..140795e391ec --- /dev/null +++ b/packages/ui/src/components/error-details.stories.tsx @@ -0,0 +1,72 @@ +import { createEffect, createSignal, on, onCleanup, Show } from "solid-js" +import { Button } from "@opencode/ui/button" +import { ErrorDetails } from "./error-details" + +type Phase = "failed" | "retrying" | "connected" + +type Args = { message: string; lines: number; phase: Phase } + +function Preview(props: Args) { + const [phase, setPhase] = createSignal(props.phase) + + createEffect(on([() => props.message, () => props.lines, () => props.phase], () => setPhase(props.phase))) + createEffect(() => { + if (phase() !== "retrying") return + const timer = setTimeout(() => setPhase("connected"), 1500) + + onCleanup(() => clearTimeout(timer)) + }) + + const details = () => + [ + props.message, + ...Array.from( + { length: props.lines }, + (_, i) => `Attempt ${i + 1}: workspace index did not acknowledge the handshake.`, + ), + ].join("\n") + + return ( +
+
Workspace index
+ +

Connected to the workspace index.

+ +
+ } + > + + + + +
+ ) +} + +export default { + title: "UI/ErrorDetails", + id: "ui-error-details", + component: Preview, + args: { message: "Connection refused while opening the workspace index.", lines: 0, phase: "failed" } satisfies Args, + argTypes: { + lines: { control: { type: "range", min: 0, max: 40, step: 1 } }, + phase: { control: "select", options: ["failed", "retrying", "connected"] }, + }, +} + +export const ConnectionError = {} + +export const LongDiagnostics = { args: { lines: 24 } } + +export const Retrying = { args: { phase: "retrying" } } + +export const Recovered = { args: { phase: "connected" } } diff --git a/packages/ui/src/components/file-icon.stories.tsx b/packages/ui/src/components/file-icon.stories.tsx index e49a43be1118..1923e121c578 100644 --- a/packages/ui/src/components/file-icon.stories.tsx +++ b/packages/ui/src/components/file-icon.stories.tsx @@ -1,7 +1,7 @@ -// @ts-nocheck import { For } from "solid-js" -import * as mod from "./file-icon" -import { create } from "../storybook/scaffold" +import { FileIcon, type FileIconProps } from "./file-icon" + +type Args = FileIconProps["node"] & Pick const docs = `### Overview File and folder icon renderer based on file name and extension. @@ -26,19 +26,13 @@ Use in file trees and lists. ` -const story = create({ - title: "UI/FileIcon", - mod, - args: { - node: { path: "package.json", type: "file" }, - mono: true, - }, -}) - export default { title: "UI/FileIcon", id: "components-file-icon", - component: story.meta.component, + component: FileIcon, + args: { path: "package.json", type: "file", expanded: false, mono: true }, + argTypes: { type: { control: "select", options: ["file", "directory"] } }, + render: (args: Args) => , tags: ["autodocs"], parameters: { docs: { @@ -49,20 +43,22 @@ export default { }, } -export const Basic = story.Basic +export const Basic = {} export const Folder = { args: { - node: { path: "src", type: "directory" }, + path: "src", + type: "directory", expanded: true, mono: false, }, } export const Samples = { - render: () => { + args: { path: "README.md", mono: false }, + render: (args: Args) => { const items = [ - { path: "README.md", type: "file" }, + args, { path: "package.json", type: "file" }, { path: "tsconfig.json", type: "file" }, { path: "index.ts", type: "file" }, @@ -86,7 +82,7 @@ export const Samples = { {(node) => (
- +
{node.path}
)} diff --git a/packages/ui/src/components/hover-card.stories.tsx b/packages/ui/src/components/hover-card.stories.tsx index 5ec25d99faf8..098fa090be2a 100644 --- a/packages/ui/src/components/hover-card.stories.tsx +++ b/packages/ui/src/components/hover-card.stories.tsx @@ -1,6 +1,5 @@ -// @ts-nocheck -import { createSignal } from "solid-js" -import * as mod from "./hover-card" +import { createEffect, createSignal } from "solid-js" +import { HoverCard, type HoverCardProps } from "./hover-card" const docs = `### Overview Hover-triggered card for lightweight previews and metadata. @@ -28,7 +27,9 @@ Use for short summaries; avoid dense interactive controls. export default { title: "UI/HoverCard", id: "components-hover-card", - component: mod.HoverCard, + component: HoverCard, + args: { open: false, placement: "bottom" }, + argTypes: { placement: { control: "select", options: ["top", "right", "bottom", "left"] } }, tags: ["autodocs"], parameters: { docs: { @@ -39,32 +40,39 @@ export default { }, } -export const Basic = { - render: () => ( - Hover me}> +type CardArgs = Pick & { inline?: boolean } + +function Card(props: CardArgs) { + const [open, setOpen] = createSignal(props.open) + createEffect(() => setOpen(props.open)) + + return ( + Hover me} + >
-
Preview
-
Short supporting text.
+
{props.inline ? "Mounted inside" : "Preview"}
+
+ {props.inline ? "Uses custom mount node." : "Short supporting text."} +
-
- ), + + ) } +export const Basic = { render: Card } + export const InlineMount = { - render: () => { + render: (props: CardArgs) => { const [mount, setMount] = createSignal(undefined) return (
- Hover me} - > -
-
Mounted inside
-
Uses custom mount node.
-
-
+
) }, diff --git a/packages/ui/src/components/image-preview.stories.tsx b/packages/ui/src/components/image-preview.stories.tsx index 0729b7218b97..d8a1bafed5dc 100644 --- a/packages/ui/src/components/image-preview.stories.tsx +++ b/packages/ui/src/components/image-preview.stories.tsx @@ -1,5 +1,5 @@ // @ts-nocheck -import { onMount } from "solid-js" +import { onCleanup, onMount } from "solid-js" import * as mod from "./image-preview" import { Button } from "@opencode/ui/button" import { useDialog } from "../context/dialog" @@ -39,6 +39,8 @@ export default { component: mod.ImagePreview, tags: ["autodocs"], parameters: { + // Opening the actual preview installs its window-wide pinch and zoom handlers. + gridPreview: () => Garden open day poster, docs: { description: { component: docs, @@ -50,7 +52,7 @@ export default { export const Basic = { render: () => { const dialog = useDialog() - const src = "https://placehold.co/640x360/png" + const src = poster() const open = () => dialog.show(() => ) @@ -130,6 +132,8 @@ export const FromVideo = { canvas.height = 400 const ctx = canvas.getContext("2d") + let frame: number + const draw = (time) => { ctx.fillStyle = "#1f2a44" ctx.fillRect(0, 0, 640, 400) @@ -137,11 +141,17 @@ export const FromVideo = { ctx.beginPath() ctx.arc(320 + 200 * Math.sin(time / 700), 200, 60, 0, Math.PI * 2) ctx.fill() - requestAnimationFrame(draw) + frame = requestAnimationFrame(draw) } - requestAnimationFrame(draw) - video.srcObject = canvas.captureStream(30) + frame = requestAnimationFrame(draw) + const stream = canvas.captureStream(30) + + video.srcObject = stream + onCleanup(() => { + cancelAnimationFrame(frame) + stream.getTracks().forEach((track) => track.stop()) + }) }) const open = () => dialog.show(() => ) @@ -167,11 +177,12 @@ export const FromVideo = { } // A bright, offline poster, so the image reads clearly against the dimmed page while it moves. -function poster() { +function poster(scale = 1) { const canvas = document.createElement("canvas") - canvas.width = 1600 - canvas.height = 1000 + canvas.width = 1600 * scale + canvas.height = 1000 * scale const ctx = canvas.getContext("2d") + ctx.scale(scale, scale) const sky = ctx.createLinearGradient(0, 0, 0, 1000) sky.addColorStop(0, "#ff8a5b") sky.addColorStop(1, "#ffd27a") diff --git a/packages/ui/src/components/list.stories.tsx b/packages/ui/src/components/list.stories.tsx index b36901be81da..2eb628793f37 100644 --- a/packages/ui/src/components/list.stories.tsx +++ b/packages/ui/src/components/list.stories.tsx @@ -1,6 +1,5 @@ -// @ts-nocheck -import * as mod from "./list" -import { create } from "../storybook/scaffold" +import { createSignal } from "solid-js" +import { List } from "./list" const docs = `### Overview Filterable list with keyboard navigation and optional search input. @@ -27,21 +26,13 @@ Use within panels or popovers where keyboard navigation is expected. ` -const story = create({ - title: "UI/List", - mod, - args: { - items: ["One", "Two", "Three", "Four"], - key: (x: string) => x, - children: (x: string) => x, - search: true, - }, -}) +type ListArgs = { search: boolean } export default { title: "UI/List", id: "components-list", - component: story.meta.component, + component: List, + args: { search: true }, tags: ["autodocs"], parameters: { docs: { @@ -52,10 +43,51 @@ export default { }, } -export const Basic = story.Basic +function NumberList(props: ListArgs & { current?: string; query?: string }) { + const [selected, setSelected] = createSignal(props.current) + + const [filter, setFilter] = createSignal(props.query ?? "") + + return ( + item} + search={props.search} + current={selected()} + onSelect={setSelected} + filter={filter()} + onFilter={setFilter} + > + {(item) => item} + + ) +} + +export const Basic = { render: NumberList } + +export const Selected = { render: (props: ListArgs) => } + +export const NoMatches = { render: (props: ListArgs) => } + +export const Loading = { + render: (props: ListArgs) => { + const load = Promise.withResolvers() + + return ( +
+ load.promise} key={(item) => item} search={props.search}> + {(item) => item} + + +
+ ) + }, +} export const Grouped = { - render: () => { + render: (props: ListArgs) => { const items = [ { id: "a1", title: "Alpha", group: "Group A" }, { id: "a2", title: "Bravo", group: "Group A" }, @@ -63,35 +95,35 @@ export const Grouped = { ] return ( - item.id} groupBy={(item) => item.group} search={true}> + item.id} groupBy={(item) => item.group} search={props.search}> {(item) => item.title} - + ) }, } export const Empty = { - render: () => ( - item} search={true}> + render: (props: ListArgs) => ( + item} search={props.search}> {(item) => item} - + ), } export const LoadFailed = { - render: () => ( - Promise.reject(new Error("offline"))} key={(item: string) => item} search={true}> + render: (props: ListArgs) => ( + Promise.reject(new Error("offline"))} key={(item: string) => item} search={props.search}> {(item: string) => item} - + ), } export const WithAdd = { - render: () => ( - ( + item} - search={true} + search={props.search} add={{ render: () => ( , - }} + search={ + props.search && { + placeholder: "Filter...", + hideIcon: true, + action: , + } + } > {(item) => item} - + ), } export const ItemWrapper = { - render: () => ( - ( + item} - itemWrapper={(item, node) => ( + search={props.search} + itemWrapper={(_item, node) => (
{node}
)} > {(item) => item} -
+ ), } export const GroupHeader = { - render: () => { + args: { search: false }, + render: (props: ListArgs) => { const items = [ { id: "a1", title: "Alpha", group: "Group A" }, { id: "b1", title: "Beta", group: "Group B" }, ] return ( - item.id} groupBy={(item) => item.group} groupHeader={(group) => {group.category}} + search={props.search} > {(item) => item.title} - + ) }, } diff --git a/packages/ui/src/components/logo.stories.tsx b/packages/ui/src/components/logo.stories.tsx index 3f5dd9cef738..37156e35e15f 100644 --- a/packages/ui/src/components/logo.stories.tsx +++ b/packages/ui/src/components/logo.stories.tsx @@ -1,5 +1,4 @@ -// @ts-nocheck -import * as mod from "./logo" +import { Logo, Mark, Splash } from "./logo" const docs = `### Overview OpenCode logo assets: mark, splash, and wordmark. @@ -7,7 +6,7 @@ OpenCode logo assets: mark, splash, and wordmark. Use Mark for compact spaces, Logo for headers, Splash for hero sections. ### API -- \`Mark\`, \`Splash\`, and \`Logo\` components accept standard SVG props. +- \`Mark\`, \`Splash\`, and \`Logo\` accept a CSS class for sizing. \`Splash\` also accepts a ref. ### Variants and states - Multiple logo variants for different contexts. @@ -26,7 +25,7 @@ Use Mark for compact spaces, Logo for headers, Splash for hero sections. export default { title: "UI/Logo", id: "components-logo", - component: mod.Logo, + component: Logo, tags: ["autodocs"], parameters: { docs: { @@ -42,16 +41,22 @@ export const Basic = {
Mark
- +
Splash
- +
Logo
- +
), } + +export const CompactMark = { render: () => } + +export const SplashMark = { render: () => } + +export const Wordmark = { render: () => } diff --git a/packages/ui/src/components/menu-scroll.stories.tsx b/packages/ui/src/components/menu-scroll.stories.tsx new file mode 100644 index 000000000000..c7d3ed08689f --- /dev/null +++ b/packages/ui/src/components/menu-scroll.stories.tsx @@ -0,0 +1,73 @@ +import { createSignal, For } from "solid-js" +import { Button } from "@opencode/ui/button" +import { MenuScroll } from "./menu-scroll" + +const branches = [ + "main", + "dev", + "release", + "docs", + "file-search", + "settings", + "theme-picker", + "history", + "keyboard", + "mobile", + "accessibility", + "preview", +] + +const args = { rows: branches.length, height: 144, rtl: false } + +function Preview(props: typeof args) { + const [branch, setBranch] = createSignal("main") + + return ( +
+
Switch branch
+
+ + + {(name) => ( + + )} + + +
+ + Current branch: {branch()} + +

Tab through branches or swipe the list on a touch device.

+
+ ) +} + +export default { + title: "UI/MenuScroll", + id: "ui-menu-scroll", + component: Preview, + args, + argTypes: { + rows: { control: { type: "range", min: 1, max: branches.length, step: 1 } }, + height: { control: { type: "range", min: 80, max: 320, step: 8 } }, + }, +} + +export const Overflow = {} + +export const Fits = { args: { rows: 3 } } + +export const RightToLeft = { args: { rtl: true } } diff --git a/packages/ui/src/components/popover.stories.tsx b/packages/ui/src/components/popover.stories.tsx index ceffe7800198..361d6d82aada 100644 --- a/packages/ui/src/components/popover.stories.tsx +++ b/packages/ui/src/components/popover.stories.tsx @@ -1,7 +1,5 @@ -// @ts-nocheck -import { createSignal } from "solid-js" -import * as mod from "./popover" -import { create } from "../storybook/scaffold" +import { createEffect, createSignal } from "solid-js" +import { Popover, type PopoverProps } from "./popover" const docs = `### Overview Composable popover with optional title, description, and close button. @@ -26,24 +24,31 @@ Use for small contextual details; avoid long forms. ` -const story = create({ +export default { title: "UI/Popover", - mod, + id: "components-popover", + component: Popover, args: { trigger: "Open popover", title: "Popover", description: "Optional description", defaultOpen: true, + portal: true, children: "Popover content", }, -}) + render: (props: PopoverProps) => { + const [open, setOpen] = createSignal(props.defaultOpen) + createEffect(() => setOpen(props.defaultOpen)) -export default { - title: "UI/Popover", - id: "components-popover", - component: story.meta.component, + return + }, tags: ["autodocs"], parameters: { + gridPreview: () => ( + + Popover content + + ), docs: { description: { component: docs, @@ -52,12 +57,12 @@ export default { }, } -export const Basic = story.Basic +export const Basic = {} export const NoHeader = { args: { - title: undefined, - description: undefined, + title: "", + description: "", children: "Popover body only", }, } @@ -70,19 +75,10 @@ export const Inline = { } export const Controlled = { - render: () => { - const [open, setOpen] = createSignal(true) - - return ( - - Controlled content - - ) + args: { + trigger: "Toggle popover", + title: "Controlled", + description: "Open state is controlled", + children: "Controlled content", }, } diff --git a/packages/ui/src/components/preview-controls.stories.tsx b/packages/ui/src/components/preview-controls.stories.tsx new file mode 100644 index 000000000000..6cf5097aeacd --- /dev/null +++ b/packages/ui/src/components/preview-controls.stories.tsx @@ -0,0 +1,40 @@ +import { createEffect, createSignal } from "solid-js" +import { PreviewControls } from "./preview-controls" + +const defaults = { zoom: 100, disabled: false } + +export default { + title: "UI/PreviewControls", + id: "ui-preview-controls", + args: defaults, + argTypes: { zoom: { control: { type: "range", min: 50, max: 200, step: 25 } } }, + render: (args: typeof defaults) => { + const [zoom, setZoom] = createSignal(args.zoom) + + createEffect(() => setZoom(args.zoom)) + + return ( +
+ + {zoom()}% + + = 200} + onZoomOut={() => setZoom((n) => Math.max(50, n - 25))} + onZoomIn={() => setZoom((n) => Math.min(200, n + 25))} + onFit={() => setZoom(100)} + /> +
+ ) + }, +} + +export const Fit = {} + +export const Minimum = { args: { zoom: 50 } } + +export const Maximum = { args: { zoom: 200 } } + +export const Disabled = { args: { disabled: true } } diff --git a/packages/ui/src/components/progress.stories.tsx b/packages/ui/src/components/progress.stories.tsx index 2ee322343496..ec1d785c1714 100644 --- a/packages/ui/src/components/progress.stories.tsx +++ b/packages/ui/src/components/progress.stories.tsx @@ -1,6 +1,4 @@ -// @ts-nocheck -import * as mod from "./progress" -import { create } from "../storybook/scaffold" +import { Progress, type ProgressProps } from "./progress" const docs = `### Overview Linear progress indicator with optional label and value display. @@ -26,21 +24,27 @@ Use in forms, uploads, or background tasks. ` -const story = create({ +export default { title: "UI/Progress", - mod, + id: "components-progress", + component: Progress, + render: (args: ProgressProps) => ( + + ), args: { value: 60, + minValue: 0, maxValue: 100, children: "Progress", + indeterminate: false, + hideLabel: false, showValueLabel: true, }, -}) - -export default { - title: "UI/Progress", - id: "components-progress", - component: story.meta.component, + argTypes: { + value: { control: { type: "range", min: 0, max: 100, step: 1 } }, + minValue: { control: { type: "range", min: -100, max: 0, step: 1 } }, + maxValue: { control: { type: "range", min: 1, max: 100, step: 1 } }, + }, tags: ["autodocs"], parameters: { docs: { @@ -51,7 +55,7 @@ export default { }, } -export const Basic = story.Basic +export const Basic = {} export const NoLabel = { args: { @@ -62,6 +66,4 @@ export const NoLabel = { }, } -export const Indeterminate = { - render: () => Loading, -} +export const Indeterminate = { args: { children: "Loading", indeterminate: true, showValueLabel: false } } diff --git a/packages/ui/src/components/provider-icon.stories.tsx b/packages/ui/src/components/provider-icon.stories.tsx index a3938f4827b3..ac070d47a8a4 100644 --- a/packages/ui/src/components/provider-icon.stories.tsx +++ b/packages/ui/src/components/provider-icon.stories.tsx @@ -1,8 +1,6 @@ -// @ts-nocheck import { For } from "solid-js" import { iconNames } from "./provider-icons/types" -import * as mod from "./provider-icon" -import { create } from "../storybook/scaffold" +import { ProviderIcon } from "./provider-icon" const docs = `### Overview Provider icon sprite renderer for model/provider badges. @@ -27,12 +25,11 @@ Use in model pickers or provider lists. ` -const story = create({ title: "UI/ProviderIcon", mod, args: { id: "openai" } }) - export default { title: "UI/ProviderIcon", id: "components-provider-icon", - component: story.meta.component, + component: ProviderIcon, + args: { id: "openai" }, tags: ["autodocs"], parameters: { docs: { @@ -44,15 +41,15 @@ export default { argTypes: { id: { control: "select", - options: iconNames, + options: [...iconNames, "unknown-provider"], }, }, } -export const Basic = story.Basic +export const Basic = {} export const AllIcons = { - render: () => ( + render: (args: { id: string }) => (
- + {(id) => ( -
- +
+
{id}
)} @@ -71,3 +71,5 @@ export const AllIcons = {
), } + +export const Fallback = { args: { id: "unknown-provider" } } diff --git a/packages/ui/src/components/resize-handle.stories.tsx b/packages/ui/src/components/resize-handle.stories.tsx index d26688d266ac..ed4d084b7b9d 100644 --- a/packages/ui/src/components/resize-handle.stories.tsx +++ b/packages/ui/src/components/resize-handle.stories.tsx @@ -1,166 +1,81 @@ -// @ts-nocheck -import { createSignal } from "solid-js" -import { createStore } from "solid-js/store" -import * as mod from "./resize-handle" +import { createEffect, createSignal, on } from "solid-js" +import { ResizeHandle, type ResizeHandleProps } from "./resize-handle" -const docs = `### Overview -Drag handle for resizing panels or split views. - -Use alongside resizable panels and split layouts. - -### API -- Required: \`direction\`, \`size\`, \`min\`, \`max\`, \`onResize\`. -- Optional: \`edge\`, \`onCollapse\`, \`collapseThreshold\`. - -### Variants and states -- Horizontal and vertical directions. - -### Behavior -- Drag updates size and calls \`onResize\` with clamped values. - -### Accessibility -- TODO: provide keyboard resizing guidance if needed. - -### Theming/tokens -- Uses \`data-component="resize-handle"\` with direction/edge data attributes. - -` +type Args = Required> export default { title: "UI/ResizeHandle", id: "components-resize-handle", - component: mod.ResizeHandle, + component: ResizeHandle, tags: ["autodocs"], parameters: { docs: { description: { - component: docs, + component: + "Drag the handle to resize the panel. A positive collapse threshold lets a drag below that size collapse it on release.", }, }, }, -} - -export const Basic = { - render: () => { - const [size, setSize] = createSignal(240) - - return ( -
-
Size: {size()}px
-
- -
- ) + args: { direction: "horizontal", edge: "end", size: 240, min: 120, max: 480, collapseThreshold: 0 }, + argTypes: { + direction: { control: "select", options: ["horizontal", "vertical"] }, + edge: { control: "select", options: ["start", "end"] }, + size: { control: { type: "range", min: 120, max: 320, step: 1 } }, + min: { control: { type: "range", min: 40, max: 120, step: 1 } }, + max: { control: { type: "range", min: 320, max: 600, step: 1 } }, + collapseThreshold: { control: { type: "range", min: 0, max: 200, step: 1 } }, }, -} + render: (args: Args) => { + const [size, setSize] = createSignal(args.size) + + createEffect( + on( + () => [args.direction, args.edge, args.min, args.max, args.collapseThreshold, args.size], + () => setSize(args.size), + ), + ) -export const Vertical = { - render: () => { - const [size, setSize] = createSignal(180) + const horizontal = () => args.direction === "horizontal" return ( -
-
Size: {size()}px
+
+
{size() === 0 ? "Collapsed" : `Size: ${size()}px`}
- + > +
+ setSize(0)} + style="border:1px dashed color-mix(in oklab, var(--text-base) 20%, transparent)" + /> +
+
) }, } -export const Collapse = { - render: () => { - const [state, setState] = createStore({ - size: 200, - collapsed: false, - }) +export const Basic = {} - const size = () => state.size - const collapsed = () => state.collapsed +export const Vertical = { args: { direction: "vertical", edge: "start", size: 180, max: 320 } } - return ( -
-
- {collapsed() ? "Collapsed" : `Size: ${size()}px`} -
-
- { - setState("collapsed", false) - setState("size", next) - }} - onCollapse={() => setState("collapsed", true)} - style="height:24px;border:1px dashed color-mix(in oklab, var(--text-base) 20%, transparent)" - /> -
- ) - }, -} +export const Collapse = { args: { size: 200, min: 80, max: 360, collapseThreshold: 100 } } -export const EdgeStart = { - render: () => { - const [size, setSize] = createSignal(240) - - return ( -
-
Size: {size()}px
-
- -
- ) - }, -} +export const EdgeStart = { args: { edge: "start" } } diff --git a/packages/ui/src/components/rolling-number.stories.tsx b/packages/ui/src/components/rolling-number.stories.tsx new file mode 100644 index 000000000000..0dc882526669 --- /dev/null +++ b/packages/ui/src/components/rolling-number.stories.tsx @@ -0,0 +1,23 @@ +import { RollingNumber } from "./rolling-number" + +const defaults = { value: 9, duration: 0.375, bounce: 0 } + +export default { + title: "UI/RollingNumber", + id: "ui-rolling-number", + args: defaults, + argTypes: { + value: { control: { type: "range", min: 0, max: 120, step: 1 } }, + duration: { control: { type: "range", min: 0.1, max: 1, step: 0.025 } }, + bounce: { control: { type: "range", min: 0, max: 0.5, step: 0.05 } }, + }, + render: (args: typeof defaults) => ( + + ), +} + +export const SingleDigit = {} + +export const Carry = { args: { value: 10 } } + +export const CountDown = { args: { value: 8 } } diff --git a/packages/ui/src/components/scroll-view.stories.tsx b/packages/ui/src/components/scroll-view.stories.tsx new file mode 100644 index 000000000000..6fcb241a6088 --- /dev/null +++ b/packages/ui/src/components/scroll-view.stories.tsx @@ -0,0 +1,68 @@ +import { For, Show } from "solid-js" +import { ScrollView, type ScrollViewProps } from "./scroll-view" + +type Args = Required> & { rows: number; rtl: boolean } + +function Preview(props: Args) { + return ( +
+
Build history
+ {/* Start at the new inline edge when the inspector switches direction. */} + + {(direction) => ( + +
    + i + 1)}> + {(build) => ( +
  1. + Build {build} + + Release checks + + Passed +
  2. + )} +
    +
+
+ )} +
+

Focus the list to scroll with the keyboard, or drag a thumb.

+
+ ) +} + +export default { + title: "UI/ScrollView", + id: "ui-scroll-view", + component: Preview, + args: { orientation: "vertical", thumbVisibility: "hover", rows: 20, rtl: false } satisfies Args, + argTypes: { + orientation: { control: "select", options: ["vertical", "horizontal", "both"] }, + thumbVisibility: { control: "select", options: ["hover", "scroll"] }, + rows: { control: { type: "range", min: 1, max: 60, step: 1 } }, + }, +} + +export const Vertical = {} + +export const Horizontal = { args: { orientation: "horizontal", rows: 12 } } + +export const BothAxes = { args: { orientation: "both" } } + +export const Fits = { args: { rows: 3 } } + +export const ScrollOnly = { args: { thumbVisibility: "scroll" } } + +export const RightToLeft = { args: { orientation: "both", rtl: true } } diff --git a/packages/ui/src/components/sticky-accordion-header.stories.tsx b/packages/ui/src/components/sticky-accordion-header.stories.tsx index cb3385cf9de2..b586323bb8c6 100644 --- a/packages/ui/src/components/sticky-accordion-header.stories.tsx +++ b/packages/ui/src/components/sticky-accordion-header.stories.tsx @@ -1,6 +1,6 @@ -// @ts-nocheck +import { createEffect, createSignal } from "solid-js" import { Accordion } from "@opencode/ui/accordion" -import * as mod from "./sticky-accordion-header" +import { StickyAccordionHeader } from "./sticky-accordion-header" const docs = `### Overview Sticky accordion header wrapper for persistent section labels. @@ -27,7 +27,7 @@ Use only inside \`Accordion.Item\` with \`Accordion.Trigger\`. export default { title: "UI/StickyAccordionHeader", id: "components-sticky-accordion-header", - component: mod.StickyAccordionHeader, + component: StickyAccordionHeader, tags: ["autodocs"], parameters: { docs: { @@ -39,16 +39,26 @@ export default { } export const Basic = { - render: () => ( - - - - Sticky header - - -
Accordion content.
-
-
-
- ), + args: { expanded: false, disabled: false }, + render: (props: { expanded: boolean; disabled: boolean }) => { + const [expanded, setExpanded] = createSignal(props.expanded) + createEffect(() => setExpanded(props.expanded)) + + return ( + setExpanded(items.includes("first"))} + > + + + Sticky header + + +
Accordion content.
+
+
+
+ ) + }, } diff --git a/packages/ui/src/components/text-field.stories.tsx b/packages/ui/src/components/text-field.stories.tsx index 73f9006607b9..edfd26b633aa 100644 --- a/packages/ui/src/components/text-field.stories.tsx +++ b/packages/ui/src/components/text-field.stories.tsx @@ -1,6 +1,5 @@ -// @ts-nocheck -import * as mod from "./text-field" -import { create } from "../storybook/scaffold" +import { createEffect, createSignal } from "solid-js" +import { TextField, type TextFieldProps } from "./text-field" const docs = `### Overview Text input with label, description, and optional copy-to-clipboard action. @@ -26,20 +25,40 @@ Pair with \`Tooltip\` and \`IconButton\` for copy affordance (built in). ` -const story = create({ - title: "UI/TextField", - mod, - args: { - label: "Label", - placeholder: "Type here...", - defaultValue: "Hello", - }, -}) +function Sample(props: TextFieldProps) { + const [value, setValue] = createSignal("") + + createEffect(() => setValue(props.defaultValue ?? "")) + + return +} export default { title: "UI/TextField", id: "components-text-field", - component: story.meta.component, + component: TextField, + render: Sample, + args: { + label: "Label", + description: "", + error: "", + placeholder: "", + defaultValue: "", + variant: "normal", + hideLabel: false, + multiline: false, + copyable: false, + copyKind: "clipboard", + validationState: "valid", + required: false, + disabled: false, + readOnly: false, + } satisfies TextFieldProps, + argTypes: { + variant: { options: ["normal", "ghost"] }, + copyKind: { options: ["clipboard", "link"] }, + validationState: { options: ["valid", "invalid"] }, + }, tags: ["autodocs"], parameters: { docs: { @@ -50,13 +69,14 @@ export default { }, } -export const Basic = story.Basic +export const Basic = { args: { placeholder: "Type here...", defaultValue: "Hello" } } export const Variants = { - render: () => ( + args: { label: "Normal", placeholder: "Type here...", defaultValue: "Value" }, + render: (args: TextFieldProps) => (
- - + +
), } @@ -83,6 +103,7 @@ export const Error = { label: "Email", defaultValue: "invalid@", error: "Enter a valid email address", + validationState: "invalid", }, } diff --git a/packages/ui/src/components/text-reveal.stories.tsx b/packages/ui/src/components/text-reveal.stories.tsx index f7ab49c3b667..92a532d8244c 100644 --- a/packages/ui/src/components/text-reveal.stories.tsx +++ b/packages/ui/src/components/text-reveal.stories.tsx @@ -1,12 +1,35 @@ -// @ts-nocheck -import { For, onCleanup } from "solid-js" +import { createEffect, For, onCleanup } from "solid-js" import { createStore } from "solid-js/store" import { TextReveal } from "./text-reveal" +const defaults = { + text: "Refactor ToolStatusTitle DOM measurement", + growOnly: true, + truncate: false, + duration: 600, + bounce: 1, + bounceSoft: 1, + hybridTravel: 25, + hybridEdge: 17, + edge: 17, + revealTravel: 0, +} + export default { title: "UI/TextReveal", id: "components-text-reveal", tags: ["autodocs"], + component: TextReveal, + args: defaults, + argTypes: { + duration: { control: { type: "range", min: 100, max: 1400, step: 10 } }, + bounce: { control: { type: "range", min: 1, max: 2, step: 0.01 } }, + bounceSoft: { control: { type: "range", min: 1, max: 1.5, step: 0.01 } }, + hybridTravel: { control: { type: "range", min: 0, max: 40, step: 1 } }, + hybridEdge: { control: { type: "range", min: 0, max: 40, step: 1 } }, + edge: { control: { type: "range", min: 0, max: 40, step: 1 } }, + revealTravel: { control: { type: "range", min: 0, max: 16, step: 1 } }, + }, parameters: { docs: { description: { @@ -22,7 +45,7 @@ Playground for the TextReveal text transition component. } const TEXTS = [ - "Refactor ToolStatusTitle DOM measurement", + defaults.text, "Remove inline measure nodes", "Run typechecks and report changes", "Verify reduced-motion behavior", @@ -87,18 +110,29 @@ const headingSlot = { } as const export const Playground = { - render: () => { + render: (args: typeof defaults) => { const [state, setState] = createStore({ + ...defaults, index: 0, cycling: false, - growOnly: true, - duration: 600, - bounce: 1.0, - bounceSoft: 1.0, - hybridTravel: 25, - hybridEdge: 17, - edge: 17, - revealTravel: 0, + }) + + for (const key of [ + "duration", + "bounce", + "bounceSoft", + "hybridTravel", + "hybridEdge", + "edge", + "revealTravel", + ] as const) { + createEffect(() => setState(key, args[key])) + } + + createEffect(() => setState("growOnly", args.growOnly)) + createEffect(() => { + setState("text", args.text) + setState("index", 0) }) const index = () => state.index @@ -113,7 +147,7 @@ export const Playground = { const revealTravel = () => state.revealTravel let timer: number | undefined - const text = () => TEXTS[index()] + const text = () => (index() === 0 ? state.text || undefined : TEXTS[index()]) const next = () => setState("index", (value) => (value + 1) % TEXTS.length) const prev = () => setState("index", (value) => (value - 1 + TEXTS.length) % TEXTS.length) @@ -150,7 +184,7 @@ export const Playground = { text-reveal (mask wipe + slide)
Thinking - +
@@ -169,7 +204,7 @@ export const Playground = { text-reveal (mask wipe only)
Thinking - +
@@ -189,7 +225,7 @@ export const Playground = { {(t, i) => ( )} diff --git a/packages/ui/src/components/text-strikethrough.stories.tsx b/packages/ui/src/components/text-strikethrough.stories.tsx index 773bc5108f2b..250f79d5123f 100644 --- a/packages/ui/src/components/text-strikethrough.stories.tsx +++ b/packages/ui/src/components/text-strikethrough.stories.tsx @@ -1,5 +1,4 @@ -// @ts-nocheck -import { createSignal, onMount } from "solid-js" +import { createEffect, createSignal, onMount } from "solid-js" import { createResizeObserver } from "@solid-primitives/resize-observer" import { createStore } from "solid-js/store" import { useSpring } from "./motion-spring" @@ -198,6 +197,9 @@ export default { title: "UI/Text Strikethrough", id: "components-text-strikethrough", tags: ["autodocs"], + component: TextStrikethrough, + args: { active: false, text: TEXT_SHORT, visualDuration: 0.35 }, + argTypes: { visualDuration: { control: { type: "range", min: 0.05, max: 1.5, step: 0.05 } } }, parameters: { docs: { description: { @@ -213,8 +215,9 @@ export default { } export const Playground = { - render: () => { - const [active, setActive] = createSignal(false) + render: (args: { active: boolean; text: string; visualDuration: number }) => { + const [active, setActive] = createSignal(args.active) + createEffect(() => setActive(args.active)) const toggle = () => setActive((v) => !v) return ( @@ -227,7 +230,8 @@ export const Playground = {
F — grid stacking + clip mapped to text width (THE COMPONENT)
F (inline) — same but just inline variants
- +
@@ -264,7 +270,7 @@ export const Playground = {
E — grid stacking + clip-path (container %)
- +
@@ -273,14 +279,14 @@ export const Playground = {
A — scaleX line at 50%
- +
D — background-image line
- +
diff --git a/packages/ui/src/components/thinking-heading.stories.tsx b/packages/ui/src/components/thinking-heading.stories.tsx index be609f7a4326..f953868583b5 100644 --- a/packages/ui/src/components/thinking-heading.stories.tsx +++ b/packages/ui/src/components/thinking-heading.stories.tsx @@ -8,6 +8,19 @@ export default { title: "UI/ThinkingHeading", id: "components-thinking-heading", tags: ["autodocs"], + args: { + heading: "Planning key generation details", + active: true, + duration: 550, + travel: 25, + bounce: 1.35, + compare: false, + }, + argTypes: { + duration: { control: { type: "range", min: 200, max: 1400, step: 50 } }, + travel: { control: { type: "range", min: 0, max: 120, step: 1 } }, + bounce: { control: { type: "range", min: 1, max: 2.2, step: 0.05 } }, + }, parameters: { docs: { description: { @@ -559,14 +572,21 @@ const cardStyle = { // Variants // --------------------------------------------------------------------------- -const VARIANTS: { key: string; label: string }[] = [] +const VARIANTS = ["spring-up", "spring-down", "spring-pop", "spring-blur", "odometer"] // --------------------------------------------------------------------------- // Story // --------------------------------------------------------------------------- export const Playground = { - render: () => { + render: (args: { + heading: string + active: boolean + duration: number + travel: number + bounce: number + compare: boolean + }) => { const [state, setState] = createStore({ heading: HEADINGS[0], headingIndex: 0, @@ -574,7 +594,7 @@ export const Playground = { cycling: false, duration: 550, blur: 2, - travel: 4, + travel: 25, bounce: 1.35, maskSize: 12, maskPad: 9, @@ -583,6 +603,15 @@ export const Playground = { odoBlur: false, }) + for (const key of ["duration", "travel", "bounce", "active"] as const) { + createEffect(() => setState(key, args[key])) + } + + createEffect(() => { + setState("heading", args.heading || undefined) + setState("headingIndex", Math.max(0, HEADINGS.indexOf(args.heading || undefined))) + }) + const heading = () => state.heading const headingIndex = () => state.headingIndex const active = () => state.active @@ -671,7 +700,7 @@ export const Playground = {
- + {(v) => (
- {v.label} + {v} diff --git a/packages/ui/src/components/truncated-text.stories.tsx b/packages/ui/src/components/truncated-text.stories.tsx new file mode 100644 index 000000000000..243d2ec728df --- /dev/null +++ b/packages/ui/src/components/truncated-text.stories.tsx @@ -0,0 +1,37 @@ +import { TruncatedText } from "./truncated-text" + +const args = { text: "Workspace tools for shared development environments", width: 216, rtl: false } + +function Preview(props: typeof args) { + return ( +
+
Extension name
+

+ Hover or focus a clipped name to read it. On touch screens the name wraps. +

+
+ +
+
+ ) +} + +export default { + title: "UI/TruncatedText", + id: "ui-truncated-text", + component: Preview, + args, + argTypes: { width: { control: { type: "range", min: 96, max: 384, step: 8 } } }, +} + +export const Truncated = {} + +export const Fits = { args: { text: "Workspace tools" } } + +export const Unbroken = { args: { text: "workspace-development-environment-configuration-tools", width: 136 } } + +export const MixedDirection = { args: { rtl: true, text: "أدوات المشروع — Workspace tools v2", width: 160 } } diff --git a/packages/ui/src/components/typewriter.stories.tsx b/packages/ui/src/components/typewriter.stories.tsx index 880ca7489434..22c3c3372846 100644 --- a/packages/ui/src/components/typewriter.stories.tsx +++ b/packages/ui/src/components/typewriter.stories.tsx @@ -1,6 +1,4 @@ -// @ts-nocheck -import * as mod from "./typewriter" -import { create } from "../storybook/scaffold" +import { Typewriter } from "./typewriter" const docs = `### Overview Animated typewriter text effect for short inline messages. @@ -25,12 +23,12 @@ Use for short status lines; avoid long paragraphs. ` -const story = create({ title: "UI/Typewriter", mod, args: { text: "Typewriter text" } }) - export default { title: "UI/Typewriter", id: "components-typewriter", - component: story.meta.component, + component: Typewriter, + args: { text: "Typewriter text", as: "p" }, + argTypes: { as: { control: "select", options: ["p", "span"] } }, tags: ["autodocs"], parameters: { docs: { @@ -41,7 +39,7 @@ export default { }, } -export const Basic = story.Basic +export const Basic = {} export const Inline = { args: { @@ -49,3 +47,5 @@ export const Inline = { as: "span", }, } + +export const Empty = { args: { text: "" } } diff --git a/packages/ui/src/data-display/accordion/accordion.stories.tsx b/packages/ui/src/data-display/accordion/accordion.stories.tsx index 9c53af7a6a2f..f7ef2b022cb8 100644 --- a/packages/ui/src/data-display/accordion/accordion.stories.tsx +++ b/packages/ui/src/data-display/accordion/accordion.stories.tsx @@ -1,29 +1,24 @@ -// @ts-nocheck -import { createEffect, createSignal } from "solid-js" +import { createEffect, createSignal, Show } from "solid-js" import { Accordion } from "./accordion" -const docs = `### Overview -Accordion for collapsible content sections with optional multi-open behavior. - -Use one trigger per item; keep content concise. - -### API -- Root supports Kobalte Accordion props: \`value\`, \`multiple\`, \`collapsible\`, \`onChange\`. -- Compose with \`Accordion.Item\`, \`Header\`, \`Trigger\`, \`Content\`. - -### Variants and states -- Single or multiple open items. -- Collapsible or fixed-open behavior. +const defaults = { + value: "first", + multiple: false, + collapsible: true, + secondItem: true, + disableSecond: false, + shouldFocusWrap: true, +} -### Behavior -- Controlled via \`value\`/\`onChange\` when provided. +const docs = `### Overview +Accordion for collapsible content sections with optional multi-open behavior. Use one trigger per item. -### Accessibility -- Uses Kobalte Accordion keyboard and ARIA behavior. +### API and behavior +Compose Accordion.Item, Header, Trigger and Content. The root supports Kobalte's multiple and collapsible modes. +Control expanded items with a string array and onChange; in this preview the value control sets the starting selection. -### Theming/tokens -- Uses \`data-component="accordion"\` and slot data attributes. -` +### Accessibility and theming +Kobalte supplies keyboard navigation and ARIA behavior. Use data-component="accordion" and its slot attributes for theming.` export default { title: "UI/Accordion", @@ -31,28 +26,25 @@ export default { component: Accordion, tags: ["autodocs"], parameters: { docs: { description: { component: docs } } }, -} - -export const Basic = { - args: { collapsible: true, multiple: false, value: "first" }, - argTypes: { - collapsible: { control: "boolean" }, - multiple: { control: "boolean" }, - value: { control: "select", options: ["first", "second", "none"], mapping: { none: undefined } }, - }, - render: (props) => { - const [value, setValue] = createSignal(props.value) - createEffect(() => setValue(props.value)) + args: defaults, + argTypes: { value: { control: "select", options: ["none", "first", "second", "both"] } }, + render: (args: typeof defaults) => { + const [value, setValue] = createSignal([]) - const current = () => { - if (props.multiple) return Array.isArray(value()) ? value() : value() ? [value()] : [] - - return Array.isArray(value()) ? value()[0] : value() - } + createEffect(() => { + if (args.value === "both") return setValue(args.multiple ? ["first", "second"] : ["first"]) + setValue(args.value === "none" ? [] : [args.value]) + }) return ( -
- +
+ First @@ -61,48 +53,24 @@ export const Basic = {
Accordion content.
- - - Second - - -
More content.
-
-
+ + + + Second + + +
More content.
+
+
+
) }, } -export const Multiple = { - render: () => ( - - - - First - - Accordion content. - - - - Second - - More content. - - - ), -} +export const Basic = {} -export const NonCollapsible = { - render: () => ( - - - - First - - Accordion content. - - - ), -} +export const Multiple = { args: { multiple: true, collapsible: false, value: "both" } } + +export const NonCollapsible = { args: { collapsible: false, secondItem: false } } diff --git a/packages/ui/src/data-display/avatar/avatar.stories.tsx b/packages/ui/src/data-display/avatar/avatar.stories.tsx index 11f214cd4e66..19f2da8f1f6b 100644 --- a/packages/ui/src/data-display/avatar/avatar.stories.tsx +++ b/packages/ui/src/data-display/avatar/avatar.stories.tsx @@ -1,85 +1,48 @@ -// @ts-nocheck -import { Avatar } from "./avatar" +import { For } from "solid-js" +import image from "../../assets/favicon/apple-touch-icon.png" +import { Avatar, type AvatarProps } from "./avatar" -const docs = `### Overview -Avatar matching OpenCode DS variants from Figma. - -Use in user lists and headers. - -### API -- Required: \`fallback\` string. -- Optional: \`src\`, \`background\`, \`foreground\`, \`size\`, \`kind\`. - -### Variants and states -- Sizes: small (16), normal (20), large (28). -- Kind: user (circle), org (rounded-square). -- Image vs initials content state. +const sizes = ["small", "normal", "large"] satisfies AvatarProps["size"][] -### Behavior -- Uses grapheme-aware fallback rendering. +const docs = `### Overview +Avatar matching OpenCode DS variants from Figma, for user lists and headers. -### Accessibility -- TODO: provide alt text when using images; currently image is decorative. +### API and states +Provide a fallback string. The avatar displays its first grapheme or the image at src. Background and foreground override the fallback colors. +Sizes are small (16px), normal (20px) and large (28px); user avatars are circular and org avatars have rounded corners. -### Theming/tokens -- Uses \`data-component="avatar"\` with size and image state attributes. +### Accessibility and theming +Provide accessible context alongside image avatars. The root uses data-component="avatar-v2" and size, kind and image-state attributes.` -` +// Avatar captures its image source on mount; replace it when the source control changes. +function Preview(args: AvatarProps) { + return {(src) => } +} export default { title: "UI/Avatar", id: "ui-avatar", component: Avatar, tags: ["autodocs"], - parameters: { - docs: { - description: { - component: docs, - }, - }, - }, + parameters: { docs: { description: { component: docs } } }, + args: { fallback: "WW", size: "large", kind: "user", src: "", background: "", foreground: "" } satisfies AvatarProps, argTypes: { - size: { - control: "select", - options: ["small", "normal", "large"], - }, - kind: { - control: "select", - options: ["user", "org"], - }, - }, - args: { - fallback: "WW", - size: "large", - kind: "user", + size: { control: "select", options: sizes }, + kind: { control: "select", options: ["user", "org"] satisfies AvatarProps["kind"][] }, }, + render: Preview, } export const Basic = {} -export const WithImage = { - args: { - src: "https://placehold.co/80x80/png", - fallback: "WW", - }, -} +export const WithImage = { args: { src: image } } export const Sizes = { - render: () => ( -
- - - + render: (args: AvatarProps) => ( +
+ {(size) => }
), } -export const OrgVariant = { - render: () => ( -
- - - -
- ), -} +export const OrgVariant = { args: { kind: "org" }, render: Sizes.render } diff --git a/packages/ui/src/data-display/badge/badge.stories.tsx b/packages/ui/src/data-display/badge/badge.stories.tsx index 13b9343913ef..e410a14cdd8b 100644 --- a/packages/ui/src/data-display/badge/badge.stories.tsx +++ b/packages/ui/src/data-display/badge/badge.stories.tsx @@ -1,78 +1,75 @@ -// @ts-nocheck -import { Badge } from "./badge" +import { Badge, type BadgeProps } from "./badge" -const docs = `### Overview -Small label tag for metadata and status chips. - -Use alongside headings or lists for quick metadata. - -### API -- Accepts standard span props. -- Optional: \`appearance\` is \`compact\` (default) or \`standard\`. -- Optional: \`variant\` is \`neutral\` (default), \`accent\`, or \`subtle\` (borderless, for counts). -- Optional: \`data-high-contrast\` attribute for stronger border contrast. - -### Variants and states -- Compact and standard appearances; neutral and accent variants. -- Optional high-contrast border style. +type Args = Pick & { children: string; highContrast: boolean } -### Behavior -- Inline element with fixed 16px height and tabular numeric text. +const docs = `### Overview +Small inline label for metadata and status chips alongside headings or lists. Give it meaningful text as well as a color. -### Accessibility -- Ensure text conveys meaning; avoid color-only distinction. +### API and states +Badge accepts native span props. Compact (16px) uses tabular numeric text; standard (18px) is roomier. +Choose neutral, accent, subtle (borderless, for counts), or danger. The data-high-contrast attribute strengthens the compact neutral border. -### Theming/tokens -- Uses \`data-component="tag"\`. +### Theming +Uses data-component="tag".` -` +function Preview(args: Args) { + return ( + + {args.children} + + ) +} export default { title: "UI/Badge", id: "ui-badge", component: Badge, tags: ["autodocs"], - parameters: { - docs: { - description: { - component: docs, - }, + parameters: { docs: { description: { component: docs } } }, + args: { children: "Label", appearance: "compact", variant: "neutral", highContrast: false } satisfies Args, + argTypes: { + appearance: { control: "select", options: ["compact", "standard"] satisfies BadgeProps["appearance"][] }, + variant: { + control: "select", + options: ["neutral", "accent", "subtle", "danger"] satisfies BadgeProps["variant"][], }, }, - args: { - children: "Label", - }, + render: Preview, } export const Basic = {} export const Appearances = { - render: () => ( -
- Standard - Compact + render: (args: Args) => ( +
+ + Standard + + + Compact +
), } export const Subtle = { - render: () => ( -
- 1 - 12 + args: { variant: "subtle", children: "12" }, + render: (args: Args) => ( +
+ 1 +
), } export const HighContrast = { - render: () => ( -
- Label - Label + args: { highContrast: true }, + render: (args: Args) => ( +
+ +
), } -export const Accent = { - render: () => New, -} +export const Accent = { args: { variant: "accent", children: "New" } } diff --git a/packages/ui/src/data-display/diff-changes/diff-changes.stories.tsx b/packages/ui/src/data-display/diff-changes/diff-changes.stories.tsx index e15f952bc3b5..6f002e702883 100644 --- a/packages/ui/src/data-display/diff-changes/diff-changes.stories.tsx +++ b/packages/ui/src/data-display/diff-changes/diff-changes.stories.tsx @@ -1,70 +1,63 @@ +import type { ComponentProps } from "solid-js" import { DiffChanges } from "./diff-changes" -const docs = `### Overview -Summarize additions/deletions as compact text. - -Pair with \`Diff\`/\`DiffSSR\` to contextualize a change set. - -### API -- Required: \`changes\` as { additions, deletions } or an array of those objects. -- Optional: \`appearance\` is \`compact\` (default) or \`standard\`. +type Args = Pick, "appearance" | "markEmpty"> & { + additions: number + deletions: number + multipleFiles: boolean +} -### Variants and states -- Handles zero-change state (renders nothing). +const count = { control: { type: "range", min: 0, max: 100, step: 1 } } -### Behavior -- Aggregates arrays into total additions/deletions. +const docs = `### Overview +Summarize additions/deletions as compact text. Pair with Diff or DiffSSR to contextualize a change set. -### Accessibility -- Ensure surrounding context conveys meaning of the counts/bars. +### API and behavior +Changes accepts one { additions, deletions } object or an array. Adjust the first file’s counts; Multiple files adds two more changes (+8/−3 and +2/−0). +The component aggregates totals and renders nothing for zero changes. Marking empty sides lets the caller hide them. -### Theming/tokens -- Uses \`data-component="diff-changes"\` and diff color tokens. +### Appearance and accessibility +Choose compact or standard. Provide surrounding context for the counts. The component uses data-component="diff-changes" and diff color tokens.` -` +function Preview(args: Args) { + const file = () => ({ additions: args.additions, deletions: args.deletions }) -const changes = { additions: 12, deletions: 5 } + return ( + + ) +} export default { title: "UI/DiffChanges", id: "ui-diff-changes", component: DiffChanges, tags: ["autodocs"], - parameters: { - docs: { - description: { - component: docs, - }, - }, - }, - args: { - changes, + parameters: { docs: { description: { component: docs } } }, + args: { additions: 12, deletions: 5, appearance: "compact", markEmpty: false, multipleFiles: false } satisfies Args, + argTypes: { + additions: count, + deletions: count, + appearance: { control: "select", options: ["compact", "standard"] }, }, + render: Preview, } export const Default = {} export const Appearances = { - render: () => ( -
- - + render: (args: Args) => ( +
+ +
), } -export const MultipleFiles = { - args: { - changes: [ - { additions: 4, deletions: 1 }, - { additions: 8, deletions: 3 }, - { additions: 2, deletions: 0 }, - ], - }, -} +export const MultipleFiles = { args: { multipleFiles: true, additions: 4, deletions: 1 } } -export const Zero = { - args: { - changes: { additions: 0, deletions: 0 }, - }, -} +export const Zero = { args: { additions: 0, deletions: 0 } } diff --git a/packages/ui/src/data-display/keybind/keybind.stories.tsx b/packages/ui/src/data-display/keybind/keybind.stories.tsx index e609ddc3bae1..97f30ca9f0af 100644 --- a/packages/ui/src/data-display/keybind/keybind.stories.tsx +++ b/packages/ui/src/data-display/keybind/keybind.stories.tsx @@ -1,18 +1,25 @@ -import { Keybind } from "./keybind" +import { For } from "solid-js" +import { Keybind, type KeybindProps } from "./keybind" + +const variants = ["neutral", "ghost", "outline"] satisfies KeybindProps["variant"][] + +type Args = { keys: string; variant: KeybindProps["variant"] } + +function Preview(args: Args) { + return +} const docs = `### Overview Inline keybind indicator that renders one or more keyboard keys in a compact row. ### API -- \`keys\`: Array of key labels to display (e.g. \`["⌘", "K"]\`). -- \`variant\`: "neutral" (gray background) | "ghost" (no background) | "outline" (border, no background). +- \`keys\`: Array of key labels to display. Separate labels with spaces in the preview. - Inherits native div attributes. ### Variants -- **Neutral** — each key sits on a \`#D4D4D4\` pill with darker text. -- **Ghost** — keys render without a background, lighter text color. -- **Outline** — each key has an inset border and no background, with the same dimensions as Neutral. -` +- Neutral — each key sits on a gray pill with darker text. +- Ghost — keys render without a background, with lighter text. +- Outline — each key has an inset border and no background, with the dimensions of Neutral.` export default { title: "UI/Keybind", @@ -22,45 +29,30 @@ export default { parameters: { frameHeight: "200px", frameBackground: "#fff", - docs: { - description: { - component: docs, - }, - }, - }, - args: { - keys: ["⌘"], - variant: "neutral", + docs: { description: { component: docs } }, }, + args: { keys: "⌘", variant: "neutral" }, argTypes: { - keys: { - control: "object", - }, - variant: { - control: "select", - options: ["neutral", "ghost", "outline"], - }, + variant: { control: "select", options: variants }, }, + render: Preview, } export const Playground = {} export const Variants = { - render: () => ( -
- - - + render: (args: Args) => ( +
+ {(variant) => }
), } export const MultipleKeys = { - render: () => ( -
- - - + args: { keys: "⌘ K" }, + render: (args: Args) => ( +
+ {(variant) => }
@@ -68,29 +60,18 @@ export const MultipleKeys = { } export const AllExamples = { - render: () => ( -
-
- Neutral - - - - -
-
- Ghost - - - - -
-
- Outline - - - - -
+ render: (args: Args) => ( +
+ + {(variant) => ( +
+ {variant} + + {(keys) => } + +
+ )} +
), } diff --git a/packages/ui/src/data-display/line-comment/line-comment.stories.tsx b/packages/ui/src/data-display/line-comment/line-comment.stories.tsx index 60d05757f508..29c7aad83d12 100644 --- a/packages/ui/src/data-display/line-comment/line-comment.stories.tsx +++ b/packages/ui/src/data-display/line-comment/line-comment.stories.tsx @@ -1,6 +1,5 @@ -// @ts-nocheck -import { createSignal } from "solid-js" -import { LineCommentEditor, LineComment, LineCommentOverflowIcon } from "./line-comment" +import { createEffect, createSignal, Show } from "solid-js" +import { LineCommentEditor, LineComment, LineCommentOverflowIcon, type LineCommentEditorProps } from "./line-comment" import { Menu } from "../../navigation/menu/menu" import { Popover } from "../../components/popover" @@ -32,69 +31,116 @@ export default { } export const Display = { - render: () => ( -
- - - - - - - Edit - Delete - - - - } - /> -
- ), + args: { comment: "Consider guarding against empty arrays.", selection: "", actions: true, clickable: false }, + render: (args: { comment: string; selection: string; actions: boolean; clickable: boolean }) => { + const [result, setResult] = createSignal("") + + return ( +
+ setResult("Opened") : undefined} + tabIndex={args.clickable ? 0 : undefined} + onKeyDown={(event) => { + if (args.clickable && event.target === event.currentTarget && event.key === "Enter") setResult("Opened") + }} + actions={ + args.actions && ( + + + + + + + setResult("Editing")}>Edit + setResult("Deleted")}>Delete + + + + ) + } + /> + {result()} +
+ ) + }, } export const DisplayWithoutActions = { - render: () => ( -
- -
- ), + args: { ...Display.args, actions: false }, + render: Display.render, } export const DisplayMultiline = { - render: () => ( -
- -
- ), + args: { + ...DisplayWithoutActions.args, + comment: `${Display.args.comment}\n\nAn early return keeps the happy path flat.`, + }, + render: Display.render, +} + +const editor = { + variant: "default", + value: "", + selection: "", + allowEmpty: false, + alternateSubmit: false, + alternateDisabled: false, + submitting: false, + autofocus: true, + placeholder: "", + label: "", + cancelLabel: "", + submitLabel: "", + rows: 0, + mentions: false, + popover: false, } export const Editor = { - args: { variant: "default", allowEmpty: false, alternateSubmit: false }, + args: editor, argTypes: { variant: { control: "select", options: ["default", "compact"] }, - allowEmpty: { control: "boolean" }, - alternateSubmit: { control: "boolean" }, + rows: { control: { type: "range", min: 0, max: 10, step: 1 } }, }, - render: (args) => { - const [value, setValue] = createSignal("") + render: (args: Omit & Pick) => { + const [value, setValue] = createSignal(args.value) const [result, setResult] = createSignal("") - return ( -
+ const pending: (() => void)[] = [] + + const files = ["src/app.ts", "src/api.ts", "src/server.ts"] + + createEffect(() => setValue(args.value)) + + const content = () => ( +
{ - setValue("") + if (!args.popover) setValue("") setResult("Cancelled") }} onSubmit={(comment) => { - setValue("") + if (!args.popover) setValue("") setResult(`Submitted: ${comment}`) }} alternateSubmit={ @@ -102,6 +148,7 @@ export const Editor = { ? { label: "Send", keys: ["Ctrl", "Enter"], + disabled: args.alternateDisabled, onSubmit: (comment) => { setValue("") setResult(`Sent: ${comment}`) @@ -109,86 +156,51 @@ export const Editor = { } : undefined } + mention={ + args.mentions + ? { + items: (query) => + new Promise((resolve) => + pending.push(() => resolve(files.filter((file) => file.includes(query)))), + ), + } + : undefined + } /> - {result()} + + +
) - }, -} - -export const EditorFilled = { - render: () => { - const [value, setValue] = createSignal("Use a sentinel or early return when the list is empty.") return ( -
- setValue("")} - onSubmit={() => {}} - autofocus={false} - /> +
+ + + {content()} + + + {result()}
) }, } +export const EditorFilled = { + args: { ...editor, autofocus: false, value: "Use a sentinel or early return when the list is empty." }, + render: Editor.render, +} + /** File search answers only when "Finish search" is pressed, so the loading state can be explored. */ export const EditorWithMentions = { - render: () => { - const [value, setValue] = createSignal("") - const [result, setResult] = createSignal("") - const pending: (() => void)[] = [] - const files = ["src/app.ts", "src/api.ts", "src/server.ts"] - - return ( -
- { - setValue("") - setResult("Cancelled") - }} - onSubmit={(comment) => { - setValue("") - setResult(`Submitted: ${comment}`) - }} - mention={{ - items: (query) => - new Promise((resolve) => pending.push(() => resolve(files.filter((file) => file.includes(query))))), - }} - /> - - {result()} -
- ) - }, + args: { ...editor, mentions: true }, + render: Editor.render, } /** An editor inside a popover: Escape in the field cancels the comment, and Escape on its buttons closes the popover. */ export const EditorInPopover = { - render: () => { - const [value, setValue] = createSignal("") - const [result, setResult] = createSignal("") - - return ( -
- -
- setResult("Cancelled")} - onSubmit={(comment) => setResult(`Submitted: ${comment}`)} - /> -
-
- {result()} -
- ) - }, + args: { ...editor, popover: true }, + render: Editor.render, } diff --git a/packages/ui/src/data-display/project-avatar/project-avatar.stories.tsx b/packages/ui/src/data-display/project-avatar/project-avatar.stories.tsx index f53026460819..d7698e9bef2f 100644 --- a/packages/ui/src/data-display/project-avatar/project-avatar.stories.tsx +++ b/packages/ui/src/data-display/project-avatar/project-avatar.stories.tsx @@ -1,19 +1,20 @@ -// @ts-nocheck import { For } from "solid-js" -import { ProjectAvatar, PROJECT_AVATAR_VARIANTS } from "./project-avatar" +import image from "../../assets/favicon/apple-touch-icon.png" +import { ProjectAvatar, PROJECT_AVATAR_VARIANTS, type ProjectAvatarProps } from "./project-avatar" const docs = `### Overview Saturated 16px project avatar with color variants and optional unread dot. ### API - Required: \`fallback\` string. -- Optional: \`src\`, \`variant\`, \`unread\`. +- Optional: \`src\`, \`variant\`, \`unread\`, \`label\` and \`generated\` (a project seed). ### Variants - Color: orange, yellow, cyan, green, red, pink, blue, purple, gray. - Outline: neutral, muted style for de-emphasized projects (e.g. recently closed). - Image vs initial content state. - Unread dot with corner mask when \`unread\` is set. +- Switch the Avatars style to Generated in the panel to use the seed. An image or outline takes precedence. ### Theming - Uses \`--v2-avatar-bg-*\` and \`--v2-avatar-border-*\` tokens with inset box-shadow borders. @@ -25,6 +26,7 @@ export default { component: ProjectAvatar, tags: ["autodocs"], parameters: { + motion: ["projectAvatar.style"], docs: { description: { component: docs, @@ -40,24 +42,40 @@ export default { args: { fallback: "O", variant: "orange", - }, + src: "", + generated: "opencode", + label: "", + unread: false, + } satisfies ProjectAvatarProps, + render: Preview, +} + +function Preview(args: ProjectAvatarProps) { + return ( + + ) } export const Basic = {} export const WithImage = { args: { - src: "https://placehold.co/32x32/png", + src: image, fallback: "O", variant: "blue", }, } export const AllVariants = { - render: () => ( + render: (args: ProjectAvatarProps) => (
- {(variant) => } + {(variant) => }
), @@ -79,11 +97,6 @@ export const Unread = { } export const AllVariantsUnread = { - render: () => ( -
- - {(variant) => } - -
- ), + args: { unread: true }, + render: AllVariants.render, } diff --git a/packages/ui/src/data-display/project-avatar/project-icon-styles.stories.tsx b/packages/ui/src/data-display/project-avatar/project-icon-styles.stories.tsx index 488715d81a60..a7243a2fe553 100644 --- a/packages/ui/src/data-display/project-avatar/project-icon-styles.stories.tsx +++ b/packages/ui/src/data-display/project-avatar/project-icon-styles.stories.tsx @@ -78,6 +78,7 @@ const SURFACES = { // The default theme's tokens for each scheme, so the in-context mocks show both at once whatever the lab shows. const THEMES = (() => { + // SAFETY: this is the bundled desktop theme; JSON imports widen its hex palette values to strings. const theme = resolveThemeV2(oc2 as DesktopTheme) return { dark: themeV2ToCss(theme.dark), light: themeV2ToCss(theme.light) } @@ -89,7 +90,7 @@ type Args = { starred: boolean name: string size: number - surface: string + surface: keyof typeof SURFACES animate: boolean } @@ -98,6 +99,13 @@ export default { id: "ui-project-icon-styles", parameters: { layout: "fullscreen", + gridPreview: () => ( +
+ + {(style) => } + +
+ ), docs: { description: { component: docs, @@ -129,7 +137,7 @@ export default { size: 88, surface: "dark", animate: true, - }, + } satisfies Args, } export const Gallery = { @@ -140,22 +148,36 @@ export const ContactSheet = { render: (args: Args) => , } +function filteredStyles(args: Args, starred: readonly string[]) { + return PROJECT_ICON_STYLES.filter( + (style) => + (args.style === "all" || style.id === args.style) && + (args.family === "all" || style.family === args.family) && + (!args.starred || starred.includes(style.id)), + ) +} + function GalleryView(props: { args: Args }) { const surface = () => (props.args.surface === "light" ? SURFACES.light : SURFACES.dark) const names = () => (props.args.name ? [props.args.name, ...NAMES.slice(1)] : NAMES) - const [state, setState] = createStore({ style: "mesh", name: NAMES[0], hover: "", starred: readStars() }) - createEffect(on(() => state.starred.length, () => writeStars(state.starred), { defer: true })) + const [state, setState] = createStore({ + style: props.args.style === "all" ? "mesh" : props.args.style, + name: props.args.name || NAMES[0], + hover: "", + starred: readStars(), + }) - const styles = createMemo(() => - PROJECT_ICON_STYLES.filter( - (style) => - (props.args.style === "all" || style.id === props.args.style) && - (props.args.family === "all" || style.family === props.args.family) && - (!props.args.starred || state.starred.includes(style.id)), + createEffect( + on( + () => state.starred.length, + () => writeStars(state.starred), + { defer: true }, ), ) + const styles = createMemo(() => filteredStyles(props.args, state.starred)) + const families = createMemo(() => PROJECT_ICON_FAMILIES.map((family) => ({ family, @@ -168,7 +190,9 @@ function GalleryView(props: { args: Args }) { const starred = (style: ProjectIconStyle) => state.starred.includes(style.id) const toggleStar = (style: ProjectIconStyle) => - setState("starred", (list) => (list.includes(style.id) ? list.filter((id) => id !== style.id) : [...list, style.id])) + setState("starred", (list) => + list.includes(style.id) ? list.filter((id) => id !== style.id) : [...list, style.id], + ) createEffect( on( @@ -343,10 +367,7 @@ function InContext(props: { style: ProjectIconStyle; scheme: "dark" | "light"; a }) return ( -
+
-
+
{(label, i) => (
@@ -400,7 +423,9 @@ function InContext(props: { style: ProjectIconStyle; scheme: "dark" | "light"; a {(name, i) => ( {avatar(name)} - + {name} @@ -542,7 +567,9 @@ function readStars(): string[] { try { const value: unknown = JSON.parse(localStorage.getItem(STARS_KEY) ?? "[]") - return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [] + return Array.isArray(value) + ? PROJECT_ICON_STYLES.filter((style) => value.includes(style.id)).map((style) => style.id) + : [] } catch { return [] } @@ -557,9 +584,18 @@ function writeStars(ids: readonly string[]) { // Every style × six names at 32, 20 and 16 px, in three columns: the proof still for review. function ContactSheetView(props: { args: Args }) { const surface = () => (props.args.surface === "light" ? SURFACES.light : SURFACES.dark) - const names = NAMES.slice(0, 6) - const third = Math.ceil(PROJECT_ICON_STYLES.length / 3) - const columns = [0, 1, 2].map((i) => PROJECT_ICON_STYLES.slice(i * third, (i + 1) * third)) + const names = () => [props.args.name || NAMES[0], ...NAMES.slice(1, 6)] + const starred = readStars() + + const columns = createMemo(() => { + const styles = filteredStyles(props.args, starred) + + const third = Math.ceil(styles.length / 3) + + return Array.from({ length: third ? Math.ceil(styles.length / third) : 0 }, (_, i) => + styles.slice(i * third, (i + 1) * third), + ) + }) return (
- + {(column) => (
@@ -584,7 +620,7 @@ function ContactSheetView(props: { args: Args }) { {(size) => (
- + {(name) => }
diff --git a/packages/ui/src/feedback/activity-ring/activity-ring.stories.tsx b/packages/ui/src/feedback/activity-ring/activity-ring.stories.tsx new file mode 100644 index 000000000000..05fbda27e7bf --- /dev/null +++ b/packages/ui/src/feedback/activity-ring/activity-ring.stories.tsx @@ -0,0 +1,20 @@ +import { ActivityRing } from "./activity-ring" + +export default { + title: "UI/ActivityRing", + id: "ui-activity-ring", + args: { size: 14 }, + argTypes: { size: { control: { type: "range", min: 10, max: 32, step: 1 } } }, + render: (args: { size: number }) => ( + + + Session running + + ), +} + +export const Inline = {} + +export const Compact = { args: { size: 12 } } + +export const Large = { args: { size: 24 } } diff --git a/packages/ui/src/feedback/loader/loader.stories.tsx b/packages/ui/src/feedback/loader/loader.stories.tsx index e5baaa296e6c..4ff72667c619 100644 --- a/packages/ui/src/feedback/loader/loader.stories.tsx +++ b/packages/ui/src/feedback/loader/loader.stories.tsx @@ -17,6 +17,8 @@ export default { title: "UI/Loader", id: "ui-loader", component: Loader, + args: { size: 16 }, + argTypes: { size: { control: { type: "range", min: 8, max: 32, step: 1 } } }, tags: ["autodocs"], parameters: { docs: { @@ -28,14 +30,14 @@ export default { } export const Basic = { - render: () => , + render: (props: { size: number }) => , } export const Sizes = { - render: () => ( + render: (props: { size: number }) => (
- +
), diff --git a/packages/ui/src/feedback/progress-circle/progress-circle.stories.tsx b/packages/ui/src/feedback/progress-circle/progress-circle.stories.tsx index 9ae87f9fa949..95e48bcc1494 100644 --- a/packages/ui/src/feedback/progress-circle/progress-circle.stories.tsx +++ b/packages/ui/src/feedback/progress-circle/progress-circle.stories.tsx @@ -1,5 +1,5 @@ import { For } from "solid-js" -import { ProgressCircle } from "./progress-circle" +import { ProgressCircle, type ProgressCircleProps } from "./progress-circle" export default { title: "UI/ProgressCircle", @@ -8,6 +8,7 @@ export default { tags: ["autodocs"], args: { percentage: 60, + appearance: "compact", }, argTypes: { percentage: { control: { type: "range", min: 0, max: 100, step: 1 } }, @@ -18,28 +19,31 @@ export default { export const Playground = {} export const Progress = { - render: () => ( + args: { percentage: 50 }, + render: (props: ProgressCircleProps) => (
- {(percentage) => } + + {(percentage) => } +
), } export const Sizes = { - render: () => ( + render: (props: ProgressCircleProps) => (
- - - + + +
), } export const Indicator = { - render: () => ( + args: { appearance: "indicator" }, + render: (props: ProgressCircleProps) => ( ( + render: (props: ToastRegionProps) => (
- + + ) +} + +export const Stacked = { + render: (props: ToastRegionProps) => ( + <> + + + + ), +} diff --git a/packages/ui/src/forms/checkbox/checkbox.stories.tsx b/packages/ui/src/forms/checkbox/checkbox.stories.tsx index af619c08f8d6..1883fa55367b 100644 --- a/packages/ui/src/forms/checkbox/checkbox.stories.tsx +++ b/packages/ui/src/forms/checkbox/checkbox.stories.tsx @@ -1,6 +1,6 @@ -// @ts-nocheck +import { createEffect, createSignal } from "solid-js" import { Icon } from "@opencode/ui/icon" -import { Checkbox } from "./checkbox" +import { Checkbox, type CheckboxProps } from "./checkbox" const docs = `### Overview Checkbox control for multi-select or agreement inputs. @@ -17,20 +17,48 @@ Checkbox control for multi-select or agreement inputs. - Compact uses \`data-slot="checkbox-v2"\` with \`--v2-background-bg-accent\`, \`--v2-border-border-strong\` and \`--v2-state-fg-danger\`. ` +function Sample(props: CheckboxProps) { + const [checked, setChecked] = createSignal(false) + + createEffect(() => setChecked(!!props.defaultChecked)) + + return +} + export default { title: "UI/Checkbox", id: "ui-checkbox", component: Checkbox, + render: Sample, + args: { + appearance: "standard", + surface: "base", + defaultChecked: true, + indeterminate: false, + disabled: false, + readOnly: false, + required: false, + validationState: "valid", + hideLabel: false, + children: "Checkbox", + description: "", + } satisfies CheckboxProps, + argTypes: { + appearance: { options: ["standard", "compact"] }, + surface: { options: ["base", "layer-1"] }, + validationState: { options: ["valid", "invalid"] }, + }, tags: ["autodocs"], parameters: { docs: { description: { component: docs } } }, } -export const Basic = { render: () => Checkbox } +export const Basic = {} export const States = { - render: () => ( + args: { children: "Checked" }, + render: (args: CheckboxProps) => (
- Checked + Unchecked Disabled With description @@ -39,21 +67,17 @@ export const States = { } export const CustomIcon = { - render: () => ( - } defaultChecked> - Custom icon - - ), + args: { children: "Custom icon" }, + render: (args: CheckboxProps) => } />, } -export const HiddenLabel = { render: () => Hidden label } +export const HiddenLabel = { args: { children: "Hidden label", defaultChecked: false, hideLabel: true } } export const Compact = { - render: () => ( + args: { appearance: "compact", children: "Default", description: "Suffix", defaultChecked: false }, + render: (args: CheckboxProps) => (
- - Default - + Checked diff --git a/packages/ui/src/forms/field/field.stories.tsx b/packages/ui/src/forms/field/field.stories.tsx index 7cdf51656759..dea5d7235f13 100644 --- a/packages/ui/src/forms/field/field.stories.tsx +++ b/packages/ui/src/forms/field/field.stories.tsx @@ -1,5 +1,4 @@ -// @ts-nocheck -import { createSignal } from "solid-js" +import { createSignal, Show, type ParentProps } from "solid-js" import { Field } from "./field" import { InlineInput } from "@opencode/ui/inline-input" import { TextInput } from "@opencode/ui/text-input" @@ -29,9 +28,29 @@ Omit \`Field.Control\` and place the input directly inside \`Field\` — a11y pr - \`Field.Control\`: optional wrapper (marker only). ` +const args = { invalid: false, label: "Label", tooltip: "", prefix: "Prefix", suffix: "Suffix" } + +function Example(props: ParentProps) { + return ( +
+ + {props.label} + + {props.prefix} + + {props.children} + + {props.suffix} + + +
+ ) +} + export default { title: "UI/Field", id: "ui-field", + args, subcomponents: { Label: Field.Label, Prefix: Field.Prefix, @@ -51,86 +70,60 @@ export default { } export const TextInputExample = { - render: () => ( -
- - Label - Prefix - - - - Suffix - -
+ args: { tooltip: "Additional context" }, + render: (props: typeof args) => ( + + + + + ), } export const TextInputDirectChild = { - render: () => ( -
- - Label - Prefix - - Suffix - -
+ render: (props: typeof args) => ( + + + ), } export const TextareaExample = { - render: () => ( -
- - Label - Prefix -