mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-05 01:43:27 -04:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e15324d82 | |||
| d99fceef8e | |||
| beb04de9a9 | |||
| 995a32aa08 | |||
| 2f17fc9613 | |||
| b8ea3ea091 | |||
| 82a5796159 | |||
| 9f38562237 | |||
| 5b4fb1f770 | |||
| cb88db6ce3 | |||
| 66fdd51f0d | |||
| 1b0e4e4610 | |||
| 842f1dcfdb | |||
| 067dfa341f | |||
| 98dd65cd60 | |||
| f826f7fc9b | |||
| f0afb6750e | |||
| 703d09f306 | |||
| 27ecc46dc7 | |||
| 8c7c69c749 | |||
| 9b16d0b069 | |||
| ccc11dc92d | |||
| a47dabff22 | |||
| 1277ceb426 | |||
| 7b7335b7e9 | |||
| 7192fa8b7a | |||
| 4062b30409 | |||
| f77f5a343e | |||
| 985ee1e2ec | |||
| 83bee1e776 | |||
| 124714ca3a |
@@ -0,0 +1,63 @@
|
||||
---
|
||||
name: rtl-aware-development
|
||||
description: OpenCode Desktop should be RTL-aware. Use when implementing or reviewing RTL/LTR behavior in the web app, desktop app, CSS, menus, scrolling, resizing, icons, mixed-direction text, or Electron title bars.
|
||||
---
|
||||
|
||||
# RTL-Aware Development
|
||||
|
||||
Treat direction as independent from language. Test English in both directions as well as real RTL and mixed-script content.
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Set `lang` and `dir` on the document, and propagate direction through component providers used by portaled menus and popovers. Do not change the selected locale merely to force RTL.
|
||||
- Keep DOM and focus order semantic. Flexbox and Grid already follow `dir`; do not add `row-reverse`, CSS `order`, or reversed markup just to mirror a layout.
|
||||
- Prefer logical CSS for semantic layout. Reserve physical coordinates for pointer positions, canvas geometry, native window controls, and other genuinely physical placement.
|
||||
|
||||
```css
|
||||
/* Avoid */
|
||||
padding-left: 12px;
|
||||
right: 0;
|
||||
border-right: 1px solid;
|
||||
text-align: left;
|
||||
|
||||
/* Prefer */
|
||||
padding-inline-start: 12px;
|
||||
inset-inline-end: 0;
|
||||
border-inline-end: 1px solid;
|
||||
text-align: start;
|
||||
```
|
||||
|
||||
- Isolate mixed-direction text. Use `dir="auto"` or `<bdi>` for unknown text; keep code, URLs, IDs, and filesystem paths LTR without forcing the surrounding component LTR.
|
||||
|
||||
```html
|
||||
<span class="file-row"><bdi dir="auto">README.md</bdi></span> <bdi dir="ltr"><code>C:\src\app.ts</code></bdi>
|
||||
```
|
||||
|
||||
- Mirror directional meaning, not every image. Back/forward, previous/next, disclosure, indentation, and directional progress may need mirroring. Do not mirror brands, clocks, media controls, charts, or text. Reverse physical gradients, `translateX`, SVG transforms, and animation deltas explicitly.
|
||||
- Map interactions through direction. `clientX` remains physical; resizing a logical edge needs an RTL-aware delta. Logical previous/next keyboard controls may swap ArrowLeft/ArrowRight. Follow the relevant WAI-ARIA widget pattern.
|
||||
- Do not assume LTR scrolling. RTL `scrollLeft` can start at `0` and become negative. Prefer `scrollIntoView({ inline: "nearest" })` or a tested direction-normalizing helper.
|
||||
- For Electron title bars, prefer native caption controls and use `titleBarOverlay` plus `env(titlebar-area-*)` for the safe content rectangle. Keep Windows/macOS native-control avoidance and `trafficLightPosition` physical; keep app navigation inside that rectangle logical. Mark interactive titlebar children `app-region: no-drag`.
|
||||
- Verify behavior, not screenshots alone. Check computed styles, pseudo-element geometry, hit zones, focus order, keyboard behavior, submenu direction, zoom/scaling, and both LTR and RTL scroll endpoints.
|
||||
|
||||
## Test Matrix
|
||||
|
||||
- English + LTR
|
||||
- English + forced RTL
|
||||
- A real RTL locale + RTL
|
||||
- Mixed RTL/LTR content, long labels, numbers, code, and paths
|
||||
- Keyboard, pointer resize, scrolling, menus/submenus, and Electron titlebar controls in both directions
|
||||
|
||||
## References
|
||||
|
||||
- [RTL Styling 101, Ahmad Shadeed](https://rtlstyling.com/posts/rtl-styling/)
|
||||
- [CSS-Tricks: RTL Styling 101](https://css-tricks.com/rtl-styling-101/)
|
||||
- [CSS-Tricks: CSS Logical Properties and Values](https://css-tricks.com/css-logical-properties-and-values/)
|
||||
- [W3C: Structural markup and right-to-left text](https://www.w3.org/International/questions/qa-html-dir)
|
||||
- [W3C: Inline bidirectional markup](https://www.w3.org/International/articles/inline-bidi-markup/)
|
||||
- [MDN: CSS logical properties and values](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Logical_properties_and_values)
|
||||
- [MDN: `dir`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/dir)
|
||||
- [MDN: `scrollLeft`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft)
|
||||
- [web.dev: Logical properties](https://web.dev/learn/css/logical-properties/)
|
||||
- [Electron: Custom title bar](https://www.electronjs.org/docs/latest/tutorial/custom-title-bar)
|
||||
- [WAI-ARIA: Window splitter pattern](https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/)
|
||||
- [Kobalte: I18n Provider](https://kobalte.dev/docs/core/components/i18n-provider/)
|
||||
@@ -0,0 +1,16 @@
|
||||
## Required Reading
|
||||
|
||||
- Before writing, changing, or reviewing E2E tests, ALWAYS read and follow Playwright's official [Best Practices](https://playwright.dev/docs/best-practices), [Auto-waiting](https://playwright.dev/docs/actionability), and [Assertions](https://playwright.dev/docs/test-assertions) guides.
|
||||
- Use the official [Locators](https://playwright.dev/docs/locators), [Network](https://playwright.dev/docs/network), and [Test Isolation](https://playwright.dev/docs/browser-contexts) guides when those concerns apply.
|
||||
|
||||
## Test Hygiene
|
||||
|
||||
- Test user-visible behavior with isolated, deterministic data and scoped, unique locators.
|
||||
- Prefer role, label, text, and explicit test-contract locators. Do not use `.first()` or `.last()` merely to silence strictness errors.
|
||||
- Use locator actions, Playwright auto-waiting, and web-first assertions for observable readiness and outcomes.
|
||||
- NEVER use `waitForTimeout`, `setTimeout`, sleeps, animation-frame counts, or other wall-clock delays to synchronize a test. Wait for the specific UI state, request, response, event, or application outcome instead.
|
||||
- Do not treat navigation, a network response, DOM attachment, or visibility alone as proof that asynchronously rendered UI is ready. Assert the state the next action actually requires.
|
||||
- Register event and network waits before the action that triggers them.
|
||||
- Do not retry state-changing actions. Retry idempotent readiness checks, then perform the action once and assert its outcome.
|
||||
- Keep action and assertion timeouts adaptive. Do not use short timeouts as readiness probes or rely on retries to hide flakes.
|
||||
- Assert exact outcomes and identities so stale state, duplicate rendering, and interactions with the wrong element cannot pass.
|
||||
@@ -56,6 +56,32 @@ Benchmarks do not assert machine-dependent performance budgets. Streaming proces
|
||||
|
||||
Committed smoke and regression tests continue to own correctness coverage for pagination, tab paint, context resize, collapse state, and composer spacing.
|
||||
|
||||
## Desktop profiler
|
||||
|
||||
The desktop profiler launches the existing production build directly, creates isolated desktop state, chooses an available CDP port, and writes reports under the OS temporary directory by default.
|
||||
|
||||
```sh
|
||||
bun run profile:desktop --help
|
||||
```
|
||||
|
||||
Create a private partial snapshot from the default local database and run Home once:
|
||||
|
||||
```sh
|
||||
bun run profile:desktop --partial-snapshot-out /tmp/opencode-perf.db \
|
||||
--window-end 2026-08-04T06:14:26.878Z \
|
||||
--scenarios home,calibration --skip-build
|
||||
```
|
||||
|
||||
Repeat against the immutable partial snapshot:
|
||||
|
||||
```sh
|
||||
bun run profile:desktop --mode partial-snapshot --db /tmp/opencode-perf.db \
|
||||
--window-end 2026-08-04T06:14:26.878Z \
|
||||
--scenarios home,calibration --runs 3 --skip-build
|
||||
```
|
||||
|
||||
Partial snapshots contain private application data and must not be committed or shared. The profiler copies each partial snapshot to a per-run working database and remaps selected project paths to temporary workspaces, leaving the source snapshot unchanged. `PROFILE_SUMMARY` is the compact comparison output; `PROFILE_REPORT` points to the complete JSON report with the database hash, invocation parameters, raw runs, and attribution data.
|
||||
|
||||
## Chrome traces
|
||||
|
||||
Set `OPENCODE_PERFORMANCE_TRACE_DIR` to emit a standard Chrome DevTools trace for every benchmark page automatically:
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { Database } from "bun:sqlite"
|
||||
import { mkdir, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { progress } from "./progress"
|
||||
import type { Options, Target } from "./types"
|
||||
|
||||
export async function createPartialSnapshot(source: string, destination: string, options: Options, targets: Target[]) {
|
||||
await mkdir(path.dirname(destination), { recursive: true })
|
||||
await rm(destination, { force: true })
|
||||
const input = new Database(source, { readonly: true })
|
||||
const schema = input
|
||||
.query(
|
||||
`SELECT type, name, sql FROM sqlite_schema
|
||||
WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'
|
||||
ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'index' THEN 1 ELSE 2 END, name`,
|
||||
)
|
||||
.all() as { type: string; name: string; sql: string }[]
|
||||
input.close()
|
||||
|
||||
const output = new Database(destination, { create: true })
|
||||
output.run("PRAGMA foreign_keys = OFF")
|
||||
schema.filter((item) => item.type === "table").forEach((item) => output.run(item.sql))
|
||||
output.run("ATTACH DATABASE ? AS source", source)
|
||||
const selected = [...new Set(targets.map((target) => target.id))]
|
||||
const placeholders = selected.map(() => "?").join(",")
|
||||
|
||||
for (const table of schema.filter((item) => item.type === "table").map((item) => item.name)) {
|
||||
progress("copying partial snapshot table", { table })
|
||||
if (table === "event") continue
|
||||
if (table === "message") {
|
||||
output.run(
|
||||
`INSERT INTO main.message SELECT * FROM source.message
|
||||
WHERE (time_created >= ? AND time_created < ? AND session_id IN (
|
||||
SELECT id FROM source.session WHERE parent_id IS NULL
|
||||
)) OR session_id IN (${placeholders})`,
|
||||
options.windowStart,
|
||||
options.windowEnd,
|
||||
...selected,
|
||||
)
|
||||
continue
|
||||
}
|
||||
if (table === "part") {
|
||||
output.run("INSERT INTO main.part SELECT * FROM source.part WHERE message_id IN (SELECT id FROM main.message)")
|
||||
continue
|
||||
}
|
||||
if (["session_context_epoch", "session_input", "session_message", "session_share", "todo"].includes(table)) {
|
||||
output.run(
|
||||
`INSERT INTO main."${table}" SELECT * FROM source."${table}" WHERE session_id IN (${placeholders})`,
|
||||
...selected,
|
||||
)
|
||||
continue
|
||||
}
|
||||
output.run(`INSERT INTO main."${table}" SELECT * FROM source."${table}"`)
|
||||
}
|
||||
output.run("DETACH DATABASE source")
|
||||
schema.filter((item) => item.type !== "table").forEach((item) => output.run(item.sql))
|
||||
output.close()
|
||||
}
|
||||
|
||||
export async function fingerprint(file: string) {
|
||||
const input = Bun.file(file)
|
||||
const hasher = new Bun.CryptoHasher("sha256")
|
||||
for await (const chunk of input.stream()) hasher.update(chunk)
|
||||
return { bytes: input.size, sha256: hasher.digest("hex") }
|
||||
}
|
||||
|
||||
export function loadCorpus(options: Options) {
|
||||
const database = new Database(options.database, { readonly: true })
|
||||
database.run("PRAGMA query_only = ON")
|
||||
const sessions = database
|
||||
.query(
|
||||
`SELECT id, project_id AS projectID, directory, title
|
||||
FROM session AS candidate
|
||||
WHERE parent_id IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM message
|
||||
WHERE session_id = candidate.id AND time_created >= ? AND time_created < ?
|
||||
)`,
|
||||
)
|
||||
.all(options.windowStart, options.windowEnd) as { id: string; projectID: string; directory: string; title: string }[]
|
||||
const messageRows = database.query(
|
||||
`SELECT id, data FROM message
|
||||
WHERE session_id = ? AND time_created >= ? AND time_created < ?
|
||||
ORDER BY time_created, id`,
|
||||
)
|
||||
const partRows = database.query(`SELECT data FROM part WHERE message_id = ? ORDER BY id`)
|
||||
const ranked = sessions
|
||||
.map((session) => {
|
||||
const messages = messageRows.all(session.id, options.windowStart, options.windowEnd) as {
|
||||
id: string
|
||||
data: string
|
||||
}[]
|
||||
const parts = messages.flatMap((message) => partRows.all(message.id) as { data: string }[])
|
||||
return {
|
||||
...session,
|
||||
bytes:
|
||||
messages.reduce((sum, message) => sum + Buffer.byteLength(message.data), 0) +
|
||||
parts.reduce((sum, part) => sum + Buffer.byteLength(part.data), 0),
|
||||
messages: messages.length,
|
||||
parts: parts.length,
|
||||
userTurns: messages.filter((message) => JSON.parse(message.data).role === "user").length,
|
||||
}
|
||||
})
|
||||
.filter((session) => session.messages > 0)
|
||||
.sort((a, b) => a.bytes - b.bytes || a.id.localeCompare(b.id))
|
||||
if (ranked.length === 0) throw new Error("No sessions found in the profile window")
|
||||
const select = (label: Target["label"], percentile: number) => ({
|
||||
label,
|
||||
...ranked[Math.max(0, Math.ceil(ranked.length * percentile) - 1)]!,
|
||||
})
|
||||
const targets = [select("p50", 0.5), select("p95", 0.95), select("max", 1)] satisfies Target[]
|
||||
const typingText = loadTypingText(database, partRows, messageRows, targets[2]!, options)
|
||||
const projectIDs = [...new Set(ranked.map((session) => session.projectID))]
|
||||
database.close()
|
||||
return { targets, typingText, projectIDs }
|
||||
}
|
||||
|
||||
function loadTypingText(
|
||||
database: Database,
|
||||
partRows: ReturnType<Database["query"]>,
|
||||
messageRows: ReturnType<Database["query"]>,
|
||||
target: Target,
|
||||
options: Options,
|
||||
) {
|
||||
const messages = messageRows.all(target.id, options.windowStart, options.windowEnd) as { id: string; data: string }[]
|
||||
const text = messages
|
||||
.filter((message) => JSON.parse(message.data).role === "user")
|
||||
.flatMap((message) =>
|
||||
(partRows.all(message.id) as { data: string }[]).flatMap((part) => {
|
||||
const data = JSON.parse(part.data)
|
||||
return data.type === "text" && typeof data.text === "string" ? [data.text] : []
|
||||
}),
|
||||
)
|
||||
.sort((a, b) => b.length - a.length)[0]
|
||||
if (!text) throw new Error("No real user prompt found for composer profiling")
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Database } from "bun:sqlite"
|
||||
import { mkdir } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import type { Options } from "./types"
|
||||
|
||||
export async function prepareDesktopState(
|
||||
options: Options,
|
||||
databasePath: string,
|
||||
userData: string,
|
||||
run: number,
|
||||
projectIDs: string[],
|
||||
) {
|
||||
const database = new Database(databasePath)
|
||||
const projects = database.query("SELECT id, worktree, sandboxes FROM project ORDER BY id").all() as {
|
||||
id: string
|
||||
worktree: string
|
||||
sandboxes: string
|
||||
}[]
|
||||
const selected = new Set(projectIDs)
|
||||
const profileProjects = projects.filter((project) => selected.has(project.id))
|
||||
const worktrees =
|
||||
options.mode === "partial-snapshot"
|
||||
? await remapDirectories(database, profileProjects, path.join(options.output, "workspaces", String(run)))
|
||||
: profileProjects.map((project) => project.worktree)
|
||||
database.close()
|
||||
|
||||
await Bun.write(
|
||||
path.join(userData, "opencode.settings"),
|
||||
JSON.stringify({ firstLaunchOnboardingComplete: true, oldLayoutEligible: true, tauriMigrated: true }),
|
||||
)
|
||||
await Bun.write(
|
||||
path.join(userData, "opencode.global.dat"),
|
||||
JSON.stringify({
|
||||
server: JSON.stringify({
|
||||
list: [],
|
||||
projects: { local: worktrees.map((worktree) => ({ worktree, expanded: true })) },
|
||||
lastProject: worktrees[0] ? { local: worktrees[0] } : {},
|
||||
recentlyClosed: {},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async function remapDirectories(
|
||||
database: Database,
|
||||
projects: { id: string; worktree: string; sandboxes: string }[],
|
||||
root: string,
|
||||
) {
|
||||
await mkdir(root, { recursive: true })
|
||||
const mappings = new Map<string, string>()
|
||||
const worktrees = await Promise.all(
|
||||
projects.map(async (project, index) => {
|
||||
const worktree = path.join(root, `project-${String(index + 1).padStart(3, "0")}`)
|
||||
await mkdir(worktree, { recursive: true })
|
||||
mappings.set(project.worktree, worktree)
|
||||
const sandboxes = JSON.parse(project.sandboxes) as string[]
|
||||
const nextSandboxes = await Promise.all(
|
||||
sandboxes.map(async (sandbox, sandboxIndex) => {
|
||||
const next = path.join(worktree, `sandbox-${sandboxIndex + 1}`)
|
||||
await mkdir(next, { recursive: true })
|
||||
mappings.set(sandbox, next)
|
||||
return next
|
||||
}),
|
||||
)
|
||||
database.run("UPDATE project SET worktree = ?, sandboxes = ? WHERE id = ?", worktree, JSON.stringify(nextSandboxes), project.id)
|
||||
return worktree
|
||||
}),
|
||||
)
|
||||
const byProject = new Map(projects.map((project, index) => [project.id, worktrees[index]!]))
|
||||
const sessions = database.query("SELECT id, project_id, directory FROM session").all() as {
|
||||
id: string
|
||||
project_id: string
|
||||
directory: string
|
||||
}[]
|
||||
const directories = database.query("SELECT * FROM project_directory").all() as {
|
||||
project_id: string
|
||||
directory: string
|
||||
type: string | null
|
||||
strategy: string | null
|
||||
time_created: number
|
||||
}[]
|
||||
const selected = new Set(projects.map((project) => project.id))
|
||||
const nextDirectories = await Promise.all(
|
||||
directories.filter((item) => selected.has(item.project_id)).map(async (item, index) => {
|
||||
const directory =
|
||||
mappings.get(item.directory) ?? path.join(byProject.get(item.project_id) ?? root, `directory-${index + 1}`)
|
||||
await mkdir(directory, { recursive: true })
|
||||
return { ...item, directory }
|
||||
}),
|
||||
)
|
||||
database.transaction(() => {
|
||||
sessions.filter((session) => selected.has(session.project_id)).forEach((session) =>
|
||||
database.run(
|
||||
"UPDATE session SET directory = ? WHERE id = ?",
|
||||
mappings.get(session.directory) ?? byProject.get(session.project_id) ?? worktrees[0]!,
|
||||
session.id,
|
||||
),
|
||||
)
|
||||
database.run(
|
||||
`DELETE FROM project_directory WHERE project_id IN (${projects.map(() => "?").join(",")})`,
|
||||
...projects.map((project) => project.id),
|
||||
)
|
||||
nextDirectories.forEach((item) =>
|
||||
database.run(
|
||||
`INSERT INTO project_directory (project_id, directory, type, strategy, time_created)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
item.project_id,
|
||||
item.directory,
|
||||
item.type,
|
||||
item.strategy,
|
||||
item.time_created,
|
||||
),
|
||||
)
|
||||
})()
|
||||
return worktrees
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Database } from "bun:sqlite"
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import { mkdir, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { createPartialSnapshot, fingerprint } from "./corpus"
|
||||
import { parseOptions } from "./options"
|
||||
|
||||
const directory = path.join(import.meta.dir, `.tmp-${process.pid}`)
|
||||
const source = path.join(directory, "source.db")
|
||||
const partialSnapshot = path.join(directory, "partial-snapshot.db")
|
||||
await mkdir(directory, { recursive: true })
|
||||
const database = new Database(source, { create: true })
|
||||
database.run("CREATE TABLE sample (value TEXT NOT NULL)")
|
||||
database.run("INSERT INTO sample VALUES ('repeatable')")
|
||||
database.close()
|
||||
|
||||
afterAll(() => rm(directory, { recursive: true, force: true }))
|
||||
|
||||
test("parses a portable fixed-window partial snapshot invocation", () => {
|
||||
const options = parseOptions([
|
||||
"--mode",
|
||||
"partial-snapshot",
|
||||
"--db",
|
||||
source,
|
||||
"--window-end",
|
||||
"2026-08-04T06:14:26.878Z",
|
||||
"--window-hours",
|
||||
"24",
|
||||
"--scenarios",
|
||||
"home,calibration",
|
||||
"--runs",
|
||||
"3",
|
||||
"--skip-build",
|
||||
])!
|
||||
|
||||
expect(options.database).toBe(source)
|
||||
expect(options.windowEnd).toBe(1_785_824_066_878)
|
||||
expect(options.windowStart).toBe(1_785_737_666_878)
|
||||
expect(options.scenarios).toEqual(["home", "calibration"])
|
||||
expect(options.runs).toBe(3)
|
||||
expect(options.build).toBe(false)
|
||||
})
|
||||
|
||||
test("creates a consistent private partial database snapshot", async () => {
|
||||
const options = parseOptions(["--db", source, "--window-end", "2026-08-04T06:14:26.878Z"])!
|
||||
await createPartialSnapshot(source, partialSnapshot, options, [])
|
||||
const copy = new Database(partialSnapshot, { readonly: true })
|
||||
expect(copy.query("SELECT value FROM sample").get()).toEqual({ value: "repeatable" })
|
||||
copy.close()
|
||||
expect(await fingerprint(partialSnapshot)).toEqual({
|
||||
bytes: expect.any(Number),
|
||||
sha256: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Global } from "@opencode-ai/core/global"
|
||||
import { existsSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { scenarios, type Options, type Scenario } from "./types"
|
||||
|
||||
const help = `Desktop renderer profiler
|
||||
|
||||
Usage:
|
||||
bun run profile:desktop [options]
|
||||
|
||||
Options:
|
||||
--mode local|partial-snapshot
|
||||
Local corpus or fixed partial snapshot (default: local)
|
||||
--db <path> SQLite database (default: opencode data directory)
|
||||
--partial-snapshot-out <path>
|
||||
Copy the benchmark corpus to a private partial snapshot
|
||||
--output <directory> Report directory (default: OS temp directory)
|
||||
--window-end <ISO|epoch> End of corpus window (default: now; required for partial snapshot)
|
||||
--window-hours <hours> Corpus window size (default: 24)
|
||||
--scenarios <names> Comma list: ${scenarios.join(",")} (default: all)
|
||||
--runs <count> Restart Electron and repeat (default: 1)
|
||||
--skip-build Use the existing desktop production build
|
||||
--diagnostics Capture Chrome traces
|
||||
--cpu Capture sampled CPU summaries
|
||||
--response-urls Attribute Response.text durations by URL
|
||||
--help Show this message
|
||||
|
||||
Partial snapshots contain private application data. Do not commit or share them.
|
||||
`
|
||||
|
||||
export function parseOptions(args: string[], now = Date.now()): Options | undefined {
|
||||
if (args.includes("--help")) {
|
||||
console.log(help)
|
||||
return
|
||||
}
|
||||
|
||||
const value = (name: string) => {
|
||||
const index = args.indexOf(name)
|
||||
if (index === -1) return
|
||||
const result = args[index + 1]
|
||||
if (!result || result.startsWith("--")) throw new Error(`${name} requires a value`)
|
||||
return result
|
||||
}
|
||||
const mode = value("--mode") ?? "local"
|
||||
if (mode !== "local" && mode !== "partial-snapshot") throw new Error(`Unsupported mode: ${mode}`)
|
||||
const endValue = value("--window-end")
|
||||
if (mode === "partial-snapshot" && !endValue)
|
||||
throw new Error("--window-end is required in partial-snapshot mode")
|
||||
const windowEnd = endValue ? parseTime(endValue) : now
|
||||
const windowHours = number(value("--window-hours") ?? "24", "--window-hours")
|
||||
const selected = (value("--scenarios")?.split(",") ?? [...scenarios]).map((item) => item.trim())
|
||||
if (selected.some((item) => !scenarios.includes(item as Scenario)))
|
||||
throw new Error(`--scenarios must contain only: ${scenarios.join(", ")}`)
|
||||
const database = path.resolve(value("--db") ?? path.join(Global.Path.data, "opencode.db"))
|
||||
if (!existsSync(database)) throw new Error(`Database does not exist: ${database}`)
|
||||
|
||||
return {
|
||||
mode,
|
||||
database,
|
||||
output: path.resolve(
|
||||
value("--output") ?? path.join(tmpdir(), "opencode-performance", new Date(windowEnd).toISOString().replace(/[:.]/g, "-")),
|
||||
),
|
||||
windowStart: windowEnd - windowHours * 60 * 60 * 1_000,
|
||||
windowEnd,
|
||||
scenarios: selected as Scenario[],
|
||||
runs: number(value("--runs") ?? "1", "--runs"),
|
||||
build: !args.includes("--skip-build"),
|
||||
diagnostics: args.includes("--diagnostics"),
|
||||
cpu: args.includes("--cpu"),
|
||||
responseURLs: args.includes("--response-urls"),
|
||||
partialSnapshotOut: value("--partial-snapshot-out")
|
||||
? path.resolve(value("--partial-snapshot-out")!)
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function parseTime(value: string) {
|
||||
const result = /^\d+$/.test(value) ? Number(value) : Date.parse(value)
|
||||
if (!Number.isFinite(result)) throw new Error(`Invalid --window-end: ${value}`)
|
||||
return result
|
||||
}
|
||||
|
||||
function number(value: string, option: string) {
|
||||
const result = Number(value)
|
||||
if (!Number.isFinite(result) || result <= 0) throw new Error(`${option} must be greater than zero`)
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { Page } from "@playwright/test"
|
||||
import type { Options, ProbeResult } from "./types"
|
||||
|
||||
export async function installProbe(page: Page, options: Options) {
|
||||
await page.addInitScript((attributeResponses) => {
|
||||
const state = {
|
||||
longTasks: [] as number[],
|
||||
animationFrames: [] as ProbeResult["animationFrames"],
|
||||
frameGaps: [] as number[],
|
||||
responseText: [] as ProbeResult["responseText"],
|
||||
}
|
||||
;(window as Window & { __opencodeRendererProfile?: typeof state }).__opencodeRendererProfile = state
|
||||
if (PerformanceObserver.supportedEntryTypes.includes("longtask")) {
|
||||
new PerformanceObserver((list) =>
|
||||
state.longTasks.push(...list.getEntries().map((entry) => entry.duration)),
|
||||
).observe({ type: "longtask" })
|
||||
}
|
||||
if (PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")) {
|
||||
new PerformanceObserver((list) =>
|
||||
state.animationFrames.push(
|
||||
...list.getEntries().map((entry) => {
|
||||
const frame = entry as PerformanceEntry & {
|
||||
blockingDuration: number
|
||||
scripts?: {
|
||||
duration: number
|
||||
forcedStyleAndLayoutDuration?: number
|
||||
sourceFunctionName?: string
|
||||
sourceURL?: string
|
||||
sourceCharPosition?: number
|
||||
invoker?: string
|
||||
invokerType?: string
|
||||
}[]
|
||||
}
|
||||
return {
|
||||
duration: frame.duration,
|
||||
blockingDuration: frame.blockingDuration,
|
||||
forcedStyleAndLayoutDuration:
|
||||
frame.scripts?.reduce((sum, script) => sum + (script.forcedStyleAndLayoutDuration ?? 0), 0) ?? 0,
|
||||
scripts:
|
||||
frame.scripts?.map((script) => ({
|
||||
function: script.sourceFunctionName || "(anonymous)",
|
||||
source: script.sourceURL?.split("/").at(-1) || "(document)",
|
||||
position: script.sourceCharPosition ?? -1,
|
||||
invoker: script.invoker ?? "(unknown)",
|
||||
invokerType: script.invokerType ?? "(unknown)",
|
||||
duration: script.duration,
|
||||
forcedStyleAndLayoutDuration: script.forcedStyleAndLayoutDuration ?? 0,
|
||||
})) ?? [],
|
||||
}
|
||||
}),
|
||||
),
|
||||
).observe({ type: "long-animation-frame" })
|
||||
}
|
||||
let previous = performance.now()
|
||||
const frame = (now: number) => {
|
||||
const gap = now - previous
|
||||
if (gap > 20) state.frameGaps.push(gap)
|
||||
previous = now
|
||||
requestAnimationFrame(frame)
|
||||
}
|
||||
requestAnimationFrame(frame)
|
||||
if (!attributeResponses) return
|
||||
const responseText = Response.prototype.text
|
||||
Response.prototype.text = function () {
|
||||
const started = performance.now()
|
||||
const url = this.url
|
||||
return responseText.call(this).then((text) => {
|
||||
state.responseText.push({ url, duration: performance.now() - started })
|
||||
return text
|
||||
})
|
||||
}
|
||||
}, options.responseURLs)
|
||||
}
|
||||
|
||||
export async function resetProbe(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
const state = (window as Window & { __opencodeRendererProfile?: ProbeResult }).__opencodeRendererProfile
|
||||
if (!state) return
|
||||
state.longTasks.length = 0
|
||||
state.animationFrames.length = 0
|
||||
state.frameGaps.length = 0
|
||||
state.responseText.length = 0
|
||||
})
|
||||
}
|
||||
|
||||
export async function collectProbe(page: Page) {
|
||||
return page.evaluate(
|
||||
() => (window as Window & { __opencodeRendererProfile?: ProbeResult }).__opencodeRendererProfile!,
|
||||
)
|
||||
}
|
||||
|
||||
export function summarizeProbe(probe: ProbeResult) {
|
||||
const scripts = new Map<
|
||||
string,
|
||||
{
|
||||
function: string
|
||||
source: string
|
||||
position: number
|
||||
invoker: string
|
||||
invokerType: string
|
||||
durationMs: number
|
||||
forcedStyleAndLayoutMs: number
|
||||
}
|
||||
>()
|
||||
probe.animationFrames
|
||||
.flatMap((frame) => frame.scripts)
|
||||
.forEach((script) => {
|
||||
const key = `${script.source}:${script.position}:${script.invoker}`
|
||||
const current = scripts.get(key) ?? {
|
||||
function: script.function,
|
||||
source: script.source,
|
||||
position: script.position,
|
||||
invoker: script.invoker,
|
||||
invokerType: script.invokerType,
|
||||
durationMs: 0,
|
||||
forcedStyleAndLayoutMs: 0,
|
||||
}
|
||||
current.durationMs += script.duration
|
||||
current.forcedStyleAndLayoutMs += script.forcedStyleAndLayoutDuration
|
||||
scripts.set(key, current)
|
||||
})
|
||||
return {
|
||||
longTasks: {
|
||||
count: probe.longTasks.length,
|
||||
totalMs: sum(probe.longTasks),
|
||||
maxMs: Math.max(0, ...probe.longTasks),
|
||||
},
|
||||
longAnimationFrames: {
|
||||
count: probe.animationFrames.length,
|
||||
totalBlockingMs: sum(probe.animationFrames.map((frame) => frame.blockingDuration)),
|
||||
maxDurationMs: Math.max(0, ...probe.animationFrames.map((frame) => frame.duration)),
|
||||
forcedStyleAndLayoutMs: sum(probe.animationFrames.map((frame) => frame.forcedStyleAndLayoutDuration)),
|
||||
scripts: [...scripts.values()].sort((a, b) => b.durationMs - a.durationMs).slice(0, 15),
|
||||
},
|
||||
frameGaps: {
|
||||
count: probe.frameGaps.length,
|
||||
maxMs: Math.max(0, ...probe.frameGaps),
|
||||
},
|
||||
responseText: probe.responseText
|
||||
.map((item) => ({ path: responsePath(item.url), durationMs: item.duration }))
|
||||
.sort((a, b) => b.durationMs - a.durationMs),
|
||||
}
|
||||
}
|
||||
|
||||
export async function startCPUProfile(page: Page, enabled: boolean) {
|
||||
if (!enabled) return { stop: async () => [] }
|
||||
const session = await page.context().newCDPSession(page)
|
||||
await session.send("Profiler.enable")
|
||||
await session.send("Profiler.setSamplingInterval", { interval: 1_000 })
|
||||
await session.send("Profiler.start")
|
||||
return {
|
||||
async stop() {
|
||||
const result = await session.send("Profiler.stop")
|
||||
await session.detach()
|
||||
const self = new Map<number, number>()
|
||||
result.profile.samples?.forEach((id, index) => {
|
||||
self.set(id, (self.get(id) ?? 0) + (result.profile.timeDeltas?.[index] ?? 0) / 1_000)
|
||||
})
|
||||
return result.profile.nodes
|
||||
.map((node) => ({
|
||||
function: node.callFrame.functionName || "(anonymous)",
|
||||
source: sourceName(node.callFrame.url),
|
||||
line: node.callFrame.lineNumber + 1,
|
||||
selfMs: self.get(node.id) ?? 0,
|
||||
}))
|
||||
.filter((node) => node.selfMs >= 1)
|
||||
.sort((a, b) => b.selfMs - a.selfMs)
|
||||
.slice(0, 40)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function responsePath(value: string) {
|
||||
try {
|
||||
return new URL(value).pathname
|
||||
} catch {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
function sourceName(value: string) {
|
||||
if (!value) return "(native)"
|
||||
try {
|
||||
return new URL(value).pathname.split("/").at(-1) || "(document)"
|
||||
} catch {
|
||||
return value.split(/[\\/]/).at(-1) || value
|
||||
}
|
||||
}
|
||||
|
||||
function sum(values: number[]) {
|
||||
return values.reduce((total, value) => total + value, 0)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const started = performance.now()
|
||||
|
||||
export function progress(message: string, details?: Record<string, unknown>) {
|
||||
const elapsed = ((performance.now() - started) / 1_000).toFixed(1)
|
||||
const suffix = details ? ` ${JSON.stringify(details)}` : ""
|
||||
console.error(`[desktop-profile +${elapsed}s] ${message}${suffix}`)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { chromium, type Page } from "@playwright/test"
|
||||
import { copyFile, mkdir, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { prepareDesktopState } from "./desktop-state"
|
||||
import { progress } from "./progress"
|
||||
import type { Options } from "./types"
|
||||
|
||||
export async function withDesktop<T>(
|
||||
options: Options,
|
||||
desktop: string,
|
||||
run: number,
|
||||
projectIDs: string[],
|
||||
use: (page: Page) => Promise<T>,
|
||||
) {
|
||||
const port = availablePort()
|
||||
const endpoint = `http://127.0.0.1:${port}`
|
||||
const userData = path.join(options.output, `user-data-${run}`)
|
||||
const database =
|
||||
options.mode === "partial-snapshot" ? path.join(options.output, `working-database-${run}.db`) : options.database
|
||||
await rm(userData, { recursive: true, force: true })
|
||||
await mkdir(userData, { recursive: true })
|
||||
if (database !== options.database) await copyFile(options.database, database)
|
||||
await prepareDesktopState(options, database, userData, run, projectIDs)
|
||||
const electron = path.join(
|
||||
desktop,
|
||||
"node_modules",
|
||||
"electron",
|
||||
"dist",
|
||||
(await Bun.file(path.join(desktop, "node_modules", "electron", "path.txt")).text()).trim(),
|
||||
)
|
||||
progress("launching Electron", { run, port })
|
||||
const child = Bun.spawn([electron, "."], {
|
||||
cwd: desktop,
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_DB: database,
|
||||
OPENCODE_CHANNEL: "dev",
|
||||
OPENCODE_PROFILE_LOAF: "1",
|
||||
OPENCODE_PROFILE_CDP_PORT: String(port),
|
||||
OPENCODE_PROFILE_USER_DATA: userData,
|
||||
OPENCODE_PERFORMANCE_TRACE_DIR: options.diagnostics ? path.join(options.output, "traces", String(run)) : "",
|
||||
OPENCODE_PERFORMANCE_RUN_ID: `desktop-${run}`,
|
||||
},
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
})
|
||||
const stdout = drain(child.stdout, "stdout")
|
||||
const stderr = drain(child.stderr, "stderr")
|
||||
let browser: Awaited<ReturnType<typeof chromium.connectOverCDP>> | undefined
|
||||
|
||||
try {
|
||||
progress("waiting for CDP", { run })
|
||||
await waitForCDP(endpoint, child, stdout, stderr)
|
||||
progress("connecting Playwright", { run })
|
||||
browser = await chromium.connectOverCDP(endpoint)
|
||||
progress("waiting for renderer", { run })
|
||||
const page = await waitForRenderer(browser)
|
||||
progress("waiting for desktop API", { run })
|
||||
await page.waitForFunction(() => typeof window.api === "object", undefined, { timeout: 60_000 })
|
||||
progress("desktop ready", { run })
|
||||
return await use(page)
|
||||
} finally {
|
||||
progress("stopping Electron", { run })
|
||||
await browser?.close().catch(() => {})
|
||||
await killTree(child.pid)
|
||||
await Promise.allSettled([stdout, stderr])
|
||||
if (database !== options.database) {
|
||||
await Bun.sleep(500)
|
||||
await rm(database, { force: true }).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function run(command: string[], cwd: string, database: string) {
|
||||
const child = Bun.spawn(command, {
|
||||
cwd,
|
||||
env: { ...process.env, OPENCODE_DB: database, OPENCODE_CHANNEL: "dev" },
|
||||
stdout: "inherit",
|
||||
stderr: "inherit",
|
||||
})
|
||||
const code = await child.exited
|
||||
if (code !== 0) throw new Error(`${command.join(" ")} exited with ${code}`)
|
||||
}
|
||||
|
||||
function availablePort() {
|
||||
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response() })
|
||||
const port = server.port
|
||||
server.stop(true)
|
||||
return port
|
||||
}
|
||||
|
||||
async function waitForCDP(
|
||||
endpoint: string,
|
||||
child: ReturnType<typeof Bun.spawn>,
|
||||
stdout: Promise<string>,
|
||||
stderr: Promise<string>,
|
||||
) {
|
||||
const timeout = Date.now() + 5 * 60_000
|
||||
let heartbeat = Date.now() + 10_000
|
||||
while (Date.now() < timeout) {
|
||||
const ready = await fetch(`${endpoint}/json/version`)
|
||||
.then((response) => response.ok)
|
||||
.catch(() => false)
|
||||
if (ready) return
|
||||
if (child.exitCode !== null)
|
||||
throw new Error(`Desktop exited before CDP was ready (${child.exitCode})\n${await stdout}\n${await stderr}`)
|
||||
if (Date.now() >= heartbeat) {
|
||||
progress("still waiting for CDP")
|
||||
heartbeat = Date.now() + 10_000
|
||||
}
|
||||
await Bun.sleep(250)
|
||||
}
|
||||
throw new Error("Timed out waiting for desktop CDP")
|
||||
}
|
||||
|
||||
async function waitForRenderer(browser: Awaited<ReturnType<typeof chromium.connectOverCDP>>) {
|
||||
const timeout = Date.now() + 60_000
|
||||
let heartbeat = Date.now() + 10_000
|
||||
while (Date.now() < timeout) {
|
||||
const page = browser
|
||||
.contexts()
|
||||
.flatMap((context) => context.pages())
|
||||
.find((candidate) => candidate.url().startsWith("oc://renderer"))
|
||||
if (page) return page
|
||||
if (Date.now() >= heartbeat) {
|
||||
progress("still waiting for renderer")
|
||||
heartbeat = Date.now() + 10_000
|
||||
}
|
||||
await Bun.sleep(100)
|
||||
}
|
||||
throw new Error("Desktop renderer target was not found")
|
||||
}
|
||||
|
||||
async function drain(stream: ReadableStream<Uint8Array>, label: string) {
|
||||
const decoder = new TextDecoder()
|
||||
let output = ""
|
||||
let pending = ""
|
||||
for await (const chunk of stream) {
|
||||
const text = decoder.decode(chunk, { stream: true })
|
||||
output = (output + text).slice(-50_000)
|
||||
const lines = (pending + text).split(/\r?\n/)
|
||||
pending = lines.pop() ?? ""
|
||||
lines.filter(Boolean).forEach((line) => progress(`Electron ${label}`, { line: line.slice(0, 500) }))
|
||||
}
|
||||
if (pending) progress(`Electron ${label}`, { line: pending.slice(0, 500) })
|
||||
return output + decoder.decode()
|
||||
}
|
||||
|
||||
async function killTree(pid: number) {
|
||||
if (process.platform !== "win32") {
|
||||
process.kill(pid, "SIGTERM")
|
||||
return
|
||||
}
|
||||
const child = Bun.spawn(["taskkill", "/pid", String(pid), "/T", "/F"], { stdout: "ignore", stderr: "ignore" })
|
||||
await child.exited
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { Page } from "@playwright/test"
|
||||
import { progress } from "./progress"
|
||||
|
||||
export async function setDesktopRoute(page: Page, route: string) {
|
||||
await page.evaluate(async (value) => {
|
||||
const api = window.api as typeof window.api & { getWindowID?: () => Promise<string> }
|
||||
const id = (await api.getWindowID?.()) ?? "browser"
|
||||
localStorage.setItem(`opencode.desktop.window.${id}.last-active-url`, value)
|
||||
}, route)
|
||||
}
|
||||
|
||||
export async function waitForQuietDOM(page: Page) {
|
||||
progress("waiting for DOM to settle")
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
let settled = false
|
||||
let timer = setTimeout(done, 750)
|
||||
const deadline = setTimeout(done, 30_000)
|
||||
const observer = new MutationObserver(() => {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(done, 750)
|
||||
})
|
||||
observer.observe(document.body, { childList: true, subtree: true, characterData: true })
|
||||
function done() {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(deadline)
|
||||
observer.disconnect()
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
|
||||
}
|
||||
}),
|
||||
)
|
||||
progress("DOM settled")
|
||||
}
|
||||
|
||||
export async function waitForSelector(page: Page, selector: string, label: string) {
|
||||
progress("waiting for UI", { label })
|
||||
try {
|
||||
await page.waitForSelector(selector, { timeout: 30_000 })
|
||||
} catch (error) {
|
||||
progress("UI wait failed", {
|
||||
label,
|
||||
url: page.url(),
|
||||
body: (await page.locator("body").innerText().catch(() => "")).replace(/\s+/g, " ").slice(0, 500),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
progress("UI ready", { label })
|
||||
}
|
||||
|
||||
export async function domCounts(page: Page, review = false) {
|
||||
return page.evaluate((review) => ({
|
||||
elements: document.getElementsByTagName("*").length,
|
||||
...(review
|
||||
? {
|
||||
diffViewers: document.querySelectorAll('[data-component="file"][data-mode="diff"]').length,
|
||||
diffLines: document.querySelectorAll("[data-line]").length,
|
||||
}
|
||||
: {
|
||||
timelineRows: document.querySelectorAll("[data-timeline-row]").length,
|
||||
messageRows: document.querySelectorAll("[data-message-id]").length,
|
||||
markdownRoots: document.querySelectorAll('[data-component="markdown"]').length,
|
||||
diffViewers: document.querySelectorAll('[data-component="file"][data-mode="diff"]').length,
|
||||
}),
|
||||
}), review)
|
||||
}
|
||||
|
||||
export function sum(values: number[]) {
|
||||
return values.reduce((total, value) => total + value, 0)
|
||||
}
|
||||
|
||||
export function percentile(values: number[], quantile: number) {
|
||||
return values.toSorted((a, b) => a - b)[Math.max(0, Math.ceil(values.length * quantile) - 1)] ?? 0
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { Page } from "@playwright/test"
|
||||
import { base64Encode } from "@opencode-ai/core/util/encode"
|
||||
import { startChromeTrace } from "../chrome-trace"
|
||||
import { collectProbe, resetProbe, startCPUProfile, summarizeProbe } from "./probe"
|
||||
import { progress } from "./progress"
|
||||
import { domCounts, percentile, setDesktopRoute, sum, waitForQuietDOM, waitForSelector } from "./scenario-utils"
|
||||
import type { Options, Target } from "./types"
|
||||
|
||||
export async function runScenarios(page: Page, options: Options, targets: Target[], typingText: string) {
|
||||
const results: unknown[] = []
|
||||
if (options.scenarios.includes("home")) results.push(await profileHome(page, options))
|
||||
if (options.scenarios.includes("calibration")) results.push(await profileCalibration(page))
|
||||
if (options.scenarios.includes("session")) {
|
||||
for (const target of targets) results.push(await profileSession(page, options, target))
|
||||
}
|
||||
if (options.scenarios.some((scenario) => ["composer", "history", "review"].includes(scenario))) {
|
||||
await openSession(page, targets[2]!)
|
||||
}
|
||||
if (options.scenarios.includes("composer")) results.push(await profileComposer(page, options, typingText))
|
||||
if (options.scenarios.includes("history")) results.push(await profileHistory(page, options, targets[2]!))
|
||||
if (options.scenarios.includes("review")) {
|
||||
const review = await profileReview(page, options)
|
||||
if (review) results.push(review)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
async function profileHome(page: Page, options: Options) {
|
||||
const measured = await measure(page, options, "home", async () => {
|
||||
await setDesktopRoute(page, "/")
|
||||
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 })
|
||||
await waitForSelector(page, '[data-component="home-session-row"]', "Home session rows")
|
||||
await waitForQuietDOM(page)
|
||||
})
|
||||
return { ...measured, dom: await domCounts(page) }
|
||||
}
|
||||
|
||||
async function profileCalibration(page: Page) {
|
||||
await resetProbe(page)
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
setTimeout(function opencodeProfileCalibration() {
|
||||
const end = performance.now() + 80
|
||||
while (performance.now() < end) {
|
||||
// Deliberate benchmark-only main-thread block.
|
||||
}
|
||||
requestAnimationFrame(() => setTimeout(resolve, 100))
|
||||
})
|
||||
}),
|
||||
)
|
||||
return { name: "attribution-calibration", ...summarizeProbe(await collectProbe(page)) }
|
||||
}
|
||||
|
||||
async function profileSession(page: Page, options: Options, target: Target) {
|
||||
await prepareHome(page)
|
||||
const measured = await measure(page, options, `session-${target.label}`, async () => {
|
||||
await navigateSession(page, target)
|
||||
await waitForSelector(page, '[data-component="prompt-input"]', "session composer")
|
||||
await waitForQuietDOM(page)
|
||||
})
|
||||
return { ...measured, context: targetContext(target), dom: await domCounts(page) }
|
||||
}
|
||||
|
||||
async function profileComposer(page: Page, options: Options, typingText: string) {
|
||||
const editor = page.locator('[data-component="prompt-input"][contenteditable="true"]').first()
|
||||
await editor.click()
|
||||
await page.keyboard.press("Control+A")
|
||||
await page.keyboard.press("Backspace")
|
||||
const printable = [...typingText].filter((character) => !["\r", "\n", "\t"].includes(character))
|
||||
const measuredText = printable.slice(-120).join("")
|
||||
const prefix = printable.slice(0, -measuredText.length).join("")
|
||||
if (prefix) await page.keyboard.insertText(prefix)
|
||||
await waitForQuietDOM(page)
|
||||
const durations: number[] = []
|
||||
const measured = await measure(page, options, "composer-typing", async () => {
|
||||
for (const character of measuredText) {
|
||||
const started = performance.now()
|
||||
await page.keyboard.type(character)
|
||||
durations.push(performance.now() - started)
|
||||
}
|
||||
await waitForQuietDOM(page)
|
||||
})
|
||||
await page.keyboard.press("Control+A")
|
||||
await page.keyboard.press("Backspace")
|
||||
return {
|
||||
...measured,
|
||||
context: { promptCharacters: printable.length, measuredCharacters: measuredText.length },
|
||||
typing: {
|
||||
totalMs: sum(durations),
|
||||
meanMs: sum(durations) / durations.length,
|
||||
p50Ms: percentile(durations, 0.5),
|
||||
p95Ms: percentile(durations, 0.95),
|
||||
maxMs: Math.max(...durations),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function profileHistory(page: Page, options: Options, target: Target) {
|
||||
await waitForSelector(page, '[data-component="prompt-input"]', "history session composer")
|
||||
await waitForQuietDOM(page)
|
||||
let requests = 0
|
||||
const onResponse = (response: { url(): string }) => {
|
||||
if (/\/session\/[^/]+\/message(?:\?|$)/.test(response.url())) requests++
|
||||
}
|
||||
page.on("response", onResponse)
|
||||
const measured = await measure(page, options, "session-max-history-boundary", async () => {
|
||||
const scroller = page.locator(".scroll-view__viewport", { has: page.locator("[data-timeline-row]") }).first()
|
||||
await scroller.evaluate((element) => {
|
||||
element.scrollTop = 0
|
||||
element.dispatchEvent(new WheelEvent("wheel", { deltaY: -10_000, bubbles: true }))
|
||||
element.dispatchEvent(new Event("scroll", { bubbles: true }))
|
||||
})
|
||||
const timeout = Date.now() + 60_000
|
||||
while (requests === 0 && Date.now() < timeout) await page.waitForTimeout(50)
|
||||
if (requests === 0) throw new Error("History boundary did not request a page")
|
||||
await waitForQuietDOM(page)
|
||||
})
|
||||
page.off("response", onResponse)
|
||||
return { ...measured, context: targetContext(target), messageRequests: requests }
|
||||
}
|
||||
|
||||
async function profileReview(page: Page, options: Options) {
|
||||
const button = page.getByRole("button", { name: "Toggle review" })
|
||||
if (!(await button.isVisible().catch(() => false))) return
|
||||
const panel = page.locator("#review-panel")
|
||||
if (await panel.isVisible().catch(() => false)) {
|
||||
await button.click()
|
||||
await panel.waitFor({ state: "hidden", timeout: 60_000 })
|
||||
await waitForQuietDOM(page)
|
||||
}
|
||||
const measured = await measure(page, options, "review-open", async () => {
|
||||
await button.click()
|
||||
await panel.waitFor({ state: "visible", timeout: 60_000 })
|
||||
await waitForQuietDOM(page)
|
||||
})
|
||||
return { ...measured, dom: await domCounts(page, true) }
|
||||
}
|
||||
|
||||
async function measure(page: Page, options: Options, name: string, action: () => Promise<void>) {
|
||||
progress("scenario started", { name })
|
||||
await resetProbe(page)
|
||||
const stopTrace = options.diagnostics ? await startChromeTrace(page, name) : undefined
|
||||
const cpu = await startCPUProfile(page, options.cpu)
|
||||
const started = performance.now()
|
||||
await action()
|
||||
const result = {
|
||||
name,
|
||||
elapsedMs: performance.now() - started,
|
||||
...summarizeProbe(await collectProbe(page)),
|
||||
cpu: await cpu.stop(),
|
||||
trace: await stopTrace?.(),
|
||||
}
|
||||
progress("scenario completed", { name, elapsedMs: Math.round(result.elapsedMs), longTasks: result.longTasks.count })
|
||||
return result
|
||||
}
|
||||
|
||||
async function openSession(page: Page, target: Target) {
|
||||
await navigateSession(page, target)
|
||||
await waitForSelector(page, '[data-component="prompt-input"]', "session composer")
|
||||
await waitForQuietDOM(page)
|
||||
}
|
||||
|
||||
async function prepareHome(page: Page) {
|
||||
await setDesktopRoute(page, "/")
|
||||
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 })
|
||||
await waitForSelector(page, '[data-component="home-session-row"]', "Home session rows")
|
||||
await waitForQuietDOM(page)
|
||||
}
|
||||
|
||||
async function navigateSession(page: Page, target: Target) {
|
||||
await setDesktopRoute(page, `/server/${base64Encode("sidecar")}/session/${target.id}`)
|
||||
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 })
|
||||
}
|
||||
|
||||
function targetContext(target: Target) {
|
||||
return { serializedBytes: target.bytes, messages: target.messages, parts: target.parts, userTurns: target.userTurns }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
export const scenarios = ["home", "calibration", "session", "composer", "history", "review"] as const
|
||||
|
||||
export type Scenario = (typeof scenarios)[number]
|
||||
|
||||
export type Options = {
|
||||
mode: "local" | "partial-snapshot"
|
||||
database: string
|
||||
output: string
|
||||
windowStart: number
|
||||
windowEnd: number
|
||||
scenarios: Scenario[]
|
||||
runs: number
|
||||
build: boolean
|
||||
diagnostics: boolean
|
||||
cpu: boolean
|
||||
responseURLs: boolean
|
||||
partialSnapshotOut?: string
|
||||
}
|
||||
|
||||
export type Target = {
|
||||
label: "p50" | "p95" | "max"
|
||||
id: string
|
||||
projectID: string
|
||||
directory: string
|
||||
title: string
|
||||
bytes: number
|
||||
messages: number
|
||||
parts: number
|
||||
userTurns: number
|
||||
}
|
||||
|
||||
export type ProbeResult = {
|
||||
longTasks: number[]
|
||||
animationFrames: {
|
||||
duration: number
|
||||
blockingDuration: number
|
||||
forcedStyleAndLayoutDuration: number
|
||||
scripts: {
|
||||
function: string
|
||||
source: string
|
||||
position: number
|
||||
invoker: string
|
||||
invokerType: string
|
||||
duration: number
|
||||
forcedStyleAndLayoutDuration: number
|
||||
}[]
|
||||
}[]
|
||||
frameGaps: number[]
|
||||
responseText: { url: string; duration: number }[]
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { mkdir } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { createPartialSnapshot, fingerprint, loadCorpus } from "./desktop-profile/corpus"
|
||||
import { parseOptions } from "./desktop-profile/options"
|
||||
import { installProbe } from "./desktop-profile/probe"
|
||||
import { progress } from "./desktop-profile/progress"
|
||||
import { withDesktop, run } from "./desktop-profile/runtime"
|
||||
import { runScenarios } from "./desktop-profile/scenarios"
|
||||
|
||||
const root = path.resolve(import.meta.dir, "../../../..")
|
||||
const desktop = path.join(root, "packages/desktop")
|
||||
const options = parseOptions(process.argv.slice(2))
|
||||
if (!options) process.exit(0)
|
||||
|
||||
await mkdir(options.output, { recursive: true })
|
||||
progress("loading corpus", { mode: options.mode })
|
||||
let corpus = loadCorpus(options)
|
||||
if (options.partialSnapshotOut) {
|
||||
progress("creating partial snapshot")
|
||||
await createPartialSnapshot(options.database, options.partialSnapshotOut, options, corpus.targets)
|
||||
options.database = options.partialSnapshotOut
|
||||
options.mode = "partial-snapshot"
|
||||
corpus = loadCorpus(options)
|
||||
}
|
||||
if (options.build) {
|
||||
progress("building desktop production bundle")
|
||||
await run(["bun", "run", "build"], desktop, options.database)
|
||||
}
|
||||
|
||||
progress("corpus ready", { targets: corpus.targets.map((target) => target.label), runs: options.runs })
|
||||
const runs = []
|
||||
for (let index = 1; index <= options.runs; index++) {
|
||||
runs.push(
|
||||
await withDesktop(options, desktop, index, corpus.projectIDs, async (page) => {
|
||||
await installProbe(page, options)
|
||||
await page.evaluate(() => {
|
||||
const settings = JSON.parse(localStorage.getItem("settings.v3") ?? "{}")
|
||||
localStorage.setItem(
|
||||
"settings.v3",
|
||||
JSON.stringify({ ...settings, general: { ...settings.general, newLayoutDesigns: true } }),
|
||||
)
|
||||
})
|
||||
return runScenarios(page, options, corpus.targets, corpus.typingText)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const report = {
|
||||
schemaVersion: 2,
|
||||
source: options.mode === "partial-snapshot" ? "partial-database-snapshot" : "local-opencode-db",
|
||||
command: process.argv.slice(2),
|
||||
diagnostics: options.diagnostics,
|
||||
profileCPU: options.cpu,
|
||||
database: await fingerprint(options.database),
|
||||
window: {
|
||||
start: new Date(options.windowStart).toISOString(),
|
||||
end: new Date(options.windowEnd).toISOString(),
|
||||
},
|
||||
revision: (await Bun.$`git rev-parse HEAD`.cwd(root).text()).trim(),
|
||||
targets: corpus.targets.map(({ id: _, projectID: __, directory: ___, title: ____, ...target }) => target),
|
||||
summary: summarize(runs),
|
||||
runs: runs.map((results, index) => ({ index: index + 1, results })),
|
||||
}
|
||||
const file = path.join(options.output, "renderer-profile.json")
|
||||
await Bun.write(file, JSON.stringify(report, null, 2))
|
||||
console.log(`PROFILE_REPORT ${file}`)
|
||||
console.log(`PROFILE_SUMMARY ${JSON.stringify(report.summary)}`)
|
||||
console.log(JSON.stringify(report, null, 2))
|
||||
|
||||
function summarize(runs: unknown[][]) {
|
||||
type Result = {
|
||||
name: string
|
||||
elapsedMs?: number
|
||||
longTasks: { count: number; totalMs: number; maxMs: number }
|
||||
longAnimationFrames: { totalBlockingMs: number }
|
||||
typing?: { p50Ms: number; p95Ms: number; maxMs: number }
|
||||
}
|
||||
return Object.fromEntries(
|
||||
[...Map.groupBy(runs.flat() as Result[], (result) => result.name)].map(([name, samples]) => [
|
||||
name,
|
||||
{
|
||||
samples: samples.length,
|
||||
elapsedMedianMs: median(samples.flatMap((sample) => sample.elapsedMs ?? [])),
|
||||
longTasks: {
|
||||
maxCount: Math.max(...samples.map((sample) => sample.longTasks.count)),
|
||||
maxTotalMs: Math.max(...samples.map((sample) => sample.longTasks.totalMs)),
|
||||
maxTaskMs: Math.max(...samples.map((sample) => sample.longTasks.maxMs)),
|
||||
},
|
||||
maxBlockingMs: Math.max(...samples.map((sample) => sample.longAnimationFrames.totalBlockingMs)),
|
||||
...(samples[0]?.typing
|
||||
? {
|
||||
typingMedianMs: {
|
||||
p50: median(samples.flatMap((sample) => sample.typing?.p50Ms ?? [])),
|
||||
p95: median(samples.flatMap((sample) => sample.typing?.p95Ms ?? [])),
|
||||
max: median(samples.flatMap((sample) => sample.typing?.maxMs ?? [])),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
function median(values: number[]) {
|
||||
if (values.length === 0) return
|
||||
return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
import "./profile-desktop"
|
||||
@@ -197,7 +197,9 @@ export async function setupTimeline(
|
||||
)
|
||||
},
|
||||
async waitForPart(partID: string) {
|
||||
await expect(page.locator(`[data-timeline-part-id="${partID}"]`).first()).toBeVisible()
|
||||
const part = page.locator(`[data-timeline-part-id="${partID}"]`)
|
||||
await expect(part).toHaveCount(1)
|
||||
await expect(part).toBeVisible()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ test("opens the comment editor when code is clicked", async ({ page }) => {
|
||||
await line.click()
|
||||
|
||||
await expect(review.getByRole("textbox")).toBeVisible()
|
||||
await expect(review.locator('[data-slot="line-comment-editor-label"]')).toHaveText("Commenting on line 2")
|
||||
})
|
||||
|
||||
test("opens the comment editor when a line number is clicked", async ({ page }) => {
|
||||
@@ -27,6 +28,7 @@ test("opens the comment editor when a line number is clicked", async ({ page })
|
||||
await lineNumber.click()
|
||||
|
||||
await expect(review.getByRole("textbox")).toBeVisible()
|
||||
await expect(review.locator('[data-slot="line-comment-editor-label"]')).toHaveText("Commenting on line 1")
|
||||
})
|
||||
|
||||
test("opens the comment editor for a line number range", async ({ page }) => {
|
||||
@@ -36,15 +38,10 @@ test("opens the comment editor for a line number range", async ({ page }) => {
|
||||
await expectAppVisible(start)
|
||||
await expectAppVisible(end)
|
||||
|
||||
const from = await start.boundingBox()
|
||||
const to = await end.boundingBox()
|
||||
if (!from || !to) throw new Error("Missing line number bounds")
|
||||
await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2)
|
||||
await page.mouse.up()
|
||||
await start.dragTo(end)
|
||||
|
||||
await expect(review.getByRole("textbox")).toBeVisible()
|
||||
await expect(review.locator('[data-slot="line-comment-editor-label"]')).toHaveText("Commenting on lines 1-3")
|
||||
})
|
||||
|
||||
test("shows a comment button when a line number is hovered", async ({ page }) => {
|
||||
@@ -54,31 +51,38 @@ test("shows a comment button when a line number is hovered", async ({ page }) =>
|
||||
|
||||
const comment = review.getByRole("button", { name: "Comment", exact: true })
|
||||
await expect(async () => {
|
||||
await page.mouse.move(0, 0)
|
||||
await lineNumber.hover()
|
||||
await expect(comment).toBeVisible({ timeout: 500 })
|
||||
await comment.click({ timeout: 500 })
|
||||
}).toPass()
|
||||
await expect(lineNumber).toHaveAttribute("data-hovered", "")
|
||||
await expect(comment).toHaveCount(1)
|
||||
await expect(comment).toHaveCSS("pointer-events", "auto")
|
||||
await comment.focus()
|
||||
await expect(comment).toBeFocused()
|
||||
}).toPass({ timeout: 10_000 })
|
||||
await comment.press("Enter")
|
||||
await expect(review.getByRole("textbox")).toBeVisible()
|
||||
await expect(review.locator('[data-slot="line-comment-editor-label"]')).toHaveText("Commenting on line 1")
|
||||
})
|
||||
|
||||
test("stages a submitted line comment in the prompt context", async ({ page }) => {
|
||||
const requests: string[] = []
|
||||
page.on("request", (request) => {
|
||||
if (request.method() !== "GET") requests.push(`${request.method()} ${new URL(request.url()).pathname}`)
|
||||
expect.soft(request.method(), `unexpected ${request.method()} ${new URL(request.url()).pathname}`).toBe("GET")
|
||||
})
|
||||
|
||||
const review = page.locator('[data-component="session-review"]')
|
||||
await review.getByText("export const value = 'after'", { exact: true }).click()
|
||||
await review.getByRole("textbox").fill("Use the existing value instead")
|
||||
await review.locator('[data-slot="line-comment-action"][data-variant="primary"]').click()
|
||||
const textbox = review.getByRole("textbox")
|
||||
await expect(textbox).toBeVisible()
|
||||
await expect(review.locator('[data-slot="line-comment-editor-label"]')).toHaveText("Commenting on line 2")
|
||||
await textbox.fill("Use the existing value instead")
|
||||
const submit = review.locator('[data-slot="line-comment-action"][data-variant="primary"]')
|
||||
await expect(submit).toBeEnabled()
|
||||
await submit.click()
|
||||
|
||||
await expect(review.getByText("Use the existing value instead", { exact: true })).toBeVisible()
|
||||
await page.getByRole("tab", { name: "Session" }).click()
|
||||
const context = page.getByText("Use the existing value instead", { exact: true }).last()
|
||||
await expect(context).toBeVisible()
|
||||
await expect(context.locator("..")).toContainText("review.ts:2")
|
||||
expect(requests).toEqual([])
|
||||
})
|
||||
|
||||
async function openReview(page: Page) {
|
||||
@@ -144,15 +148,22 @@ async function openReview(page: Page) {
|
||||
|
||||
await page.goto(`/${base64Encode(directory)}/session/${sessionID}`)
|
||||
await expectSessionTitle(page, title)
|
||||
const diffResponse = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/vcs/diff")
|
||||
await page.getByRole("tab", { name: "Changes" }).click()
|
||||
const changes = page.getByRole("tab", { name: "Changes" })
|
||||
const diffResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" && response.ok() && new URL(response.url()).pathname === "/api/vcs/diff",
|
||||
)
|
||||
await changes.click()
|
||||
expect((await (await diffResponse).json()).data).toHaveLength(1)
|
||||
await expect(page.getByRole("tab", { selected: true })).toHaveAccessibleName(/Files Changed/)
|
||||
|
||||
const review = page.locator('[data-component="session-review"]')
|
||||
await expectAppVisible(review)
|
||||
await review
|
||||
.getByRole("heading", { name: /review\.ts/ })
|
||||
.getByRole("button")
|
||||
.first()
|
||||
.click()
|
||||
const file = review.locator('[data-file="src/review.ts"]')
|
||||
await expectAppVisible(file)
|
||||
const trigger = file.getByRole("button", { expanded: false })
|
||||
await expect(trigger).toHaveCount(1)
|
||||
await trigger.click()
|
||||
await expect(file.getByRole("button", { expanded: true })).toBeVisible()
|
||||
await expect(file.getByText("export const value = 'after'", { exact: true })).toBeVisible()
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import { installSseTransport } from "../utils/sse-transport"
|
||||
import { expectSessionTitle } from "../utils/waits"
|
||||
|
||||
const initialPageSize = 20
|
||||
const historyPageSize = 200
|
||||
const historyPageSize = 50
|
||||
const assistants = Array.from({ length: initialPageSize + 1 }, (_, index) =>
|
||||
assistantMessage([textPart(`prt_history_root_${index}`, `Assistant response ${index}`)], {
|
||||
id: `msg_${String(index + 1001).padStart(4, "0")}_history_root_assistant`,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { expect, test, type Page } from "@playwright/test"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
setupTimeline,
|
||||
status,
|
||||
textPart,
|
||||
userMessage,
|
||||
} from "../performance/timeline-stability/fixture"
|
||||
@@ -17,7 +16,7 @@ test("keeps one connection open while delivering multiple events", async ({ page
|
||||
await timeline.waitForPart("prt_transport_first")
|
||||
await timeline.waitForPart("prt_transport_second")
|
||||
expect(first.connectionID).toBe(second.connectionID)
|
||||
expect(await timeline.transport.connections()).toHaveLength(1)
|
||||
await expect.poll(async () => (await timeline.transport.connections()).length).toBe(1)
|
||||
expect(await timeline.transport.acknowledgements()).toHaveLength(2)
|
||||
})
|
||||
|
||||
@@ -51,20 +50,28 @@ test("parses split JSON and a split multibyte code point", async ({ page }) => {
|
||||
})
|
||||
|
||||
test("delivers server heartbeat without mutating the timeline", async ({ page }) => {
|
||||
const sentinelID = "prt_transport_heartbeat_sentinel"
|
||||
const timeline = await setupTimeline(page, {
|
||||
messages: [userMessage(), assistantMessage([textPart("prt_transport_steady", "steady")])],
|
||||
})
|
||||
const before = await page.locator("[data-timeline-row]").allTextContents()
|
||||
await timeline.waitForPart("prt_transport_steady")
|
||||
const before = await stableTimelineRows(page)
|
||||
|
||||
await timeline.transport.heartbeat()
|
||||
await timeline.settle()
|
||||
await timeline.transport.writeRaw(": heartbeat\n\n")
|
||||
await timeline.transport.send(partUpdated(textPart(sentinelID, "heartbeat processed")))
|
||||
await timeline.waitForPart(sentinelID)
|
||||
|
||||
expect(await page.locator("[data-timeline-row]").allTextContents()).toEqual(before)
|
||||
expect(await timeline.transport.connections()).toHaveLength(1)
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const rows = await timelineRows(page)
|
||||
return rows.filter((row) => before.some((item) => item.key === row.key))
|
||||
})
|
||||
.toEqual(before)
|
||||
await expect.poll(async () => (await timeline.transport.connections()).length).toBe(1)
|
||||
})
|
||||
|
||||
test("reconnects after a clean close", async ({ page }) => {
|
||||
const timeline = await setupTimeline(page, { eventRetry: 10 })
|
||||
const timeline = await setupTimeline(page)
|
||||
const first = await timeline.transport.waitForConnection()
|
||||
|
||||
await timeline.transport.close()
|
||||
@@ -77,20 +84,21 @@ test("reconnects after a clean close", async ({ page }) => {
|
||||
})
|
||||
|
||||
test("reconnects after a stream error", async ({ page }) => {
|
||||
const timeline = await setupTimeline(page, { eventRetry: 10 })
|
||||
const timeline = await setupTimeline(page)
|
||||
const first = await timeline.transport.waitForConnection()
|
||||
|
||||
await timeline.transport.error("contract failure")
|
||||
const second = await timeline.transport.waitForConnection({ after: first.id })
|
||||
await timeline.transport.send(status("busy"))
|
||||
await timeline.transport.send(partUpdated(textPart("prt_transport_error", "after error")))
|
||||
|
||||
await timeline.waitForPart("prt_transport_error")
|
||||
await expect.poll(async () => (await timeline.transport.connections()).length).toBe(2)
|
||||
expect(second.id).toBeGreaterThan(first.id)
|
||||
expect((await timeline.transport.connections())[0]?.endedBy).toBe("error")
|
||||
})
|
||||
|
||||
test("does not request replay when reconnecting the volatile V2 event stream", async ({ page }) => {
|
||||
const timeline = await setupTimeline(page, { eventRetry: 10, protocol: "v2" })
|
||||
const timeline = await setupTimeline(page, { protocol: "v2" })
|
||||
const first = await timeline.transport.send(partUpdated(textPart("prt_transport_id", "event with id")), {
|
||||
id: "timeline-event-7",
|
||||
})
|
||||
@@ -112,5 +120,35 @@ test("passes through non-event fetches", async ({ page }) => {
|
||||
})
|
||||
|
||||
expect(health).toEqual({ healthy: true })
|
||||
expect(await timeline.transport.connections()).toHaveLength(1)
|
||||
await expect.poll(async () => (await timeline.transport.connections()).length).toBe(1)
|
||||
})
|
||||
|
||||
async function stableTimelineRows(page: Page) {
|
||||
let previous: Awaited<ReturnType<typeof timelineRows>> | undefined
|
||||
let stable = 0
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const next = await timelineRows(page)
|
||||
stable = JSON.stringify(next) === JSON.stringify(previous) ? stable + 1 : 0
|
||||
previous = next
|
||||
return stable
|
||||
},
|
||||
{ intervals: [50, 50, 100] },
|
||||
)
|
||||
.toBeGreaterThanOrEqual(2)
|
||||
return previous!
|
||||
}
|
||||
|
||||
function timelineRows(page: Page) {
|
||||
return page.locator("[data-timeline-key]").evaluateAll((elements) =>
|
||||
elements.map((element) => ({
|
||||
key: element.getAttribute("data-timeline-key"),
|
||||
row: element.querySelector("[data-timeline-row]")?.getAttribute("data-timeline-row"),
|
||||
parts: Array.from(element.querySelectorAll("[data-timeline-part-id]"), (part) =>
|
||||
part.getAttribute("data-timeline-part-id"),
|
||||
),
|
||||
text: element.textContent,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -247,18 +247,23 @@ export async function installSseTransport<T>(
|
||||
return {
|
||||
server,
|
||||
async waitForConnection(input = {}) {
|
||||
await page.waitForFunction(
|
||||
const connection = await page.waitForFunction(
|
||||
(after) => {
|
||||
const transport = (window as BrowserTransport).__testSseTransport
|
||||
const connections = transport?.command({ type: "connections" }) as SseConnectionRecord[] | undefined
|
||||
return connections?.some((connection) => connection.id > after)
|
||||
return connections?.findLast((connection) => connection.id > after && connection.endedAt === undefined)
|
||||
},
|
||||
input.after ?? 0,
|
||||
{ timeout: input.timeout },
|
||||
)
|
||||
return (await command<SseConnectionRecord[]>({ type: "connections" })).findLast(
|
||||
(connection) => connection.id > (input.after ?? 0),
|
||||
)!
|
||||
let result: SseConnectionRecord | undefined
|
||||
try {
|
||||
result = await connection.jsonValue()
|
||||
} finally {
|
||||
await connection.dispose()
|
||||
}
|
||||
if (!result) throw new Error("SSE transport connection disappeared while waiting")
|
||||
return result
|
||||
},
|
||||
send(payload, eventOptions) {
|
||||
return command({ type: "send", deliveries: [{ payload, options: eventOptions }], burst: false })
|
||||
|
||||
@@ -28,7 +28,8 @@
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"test:e2e:report": "playwright show-report e2e/playwright-report",
|
||||
"test:stability": "bun test ./e2e/performance/unit/visual-stability.test.ts && playwright test --config e2e/performance/timeline-stability/playwright.config.ts",
|
||||
"test:bench": "bun test ./e2e/performance/unit && playwright test --config e2e/performance/playwright.config.ts"
|
||||
"test:bench": "bun test ./e2e/performance/unit && playwright test --config e2e/performance/playwright.config.ts",
|
||||
"profile:desktop": "bun run e2e/performance/profile-desktop.ts"
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as Sentry from "@sentry/solid"
|
||||
import { I18nProvider } from "@opencode-ai/ui/context"
|
||||
import { DialogProvider } from "@opencode-ai/ui/context/dialog"
|
||||
import { FileComponentProvider } from "@opencode-ai/ui/context/file"
|
||||
import { File } from "@opencode-ai/session-ui/file"
|
||||
import { Font } from "@opencode-ai/ui/font"
|
||||
import { Splash } from "@opencode-ai/ui/logo"
|
||||
import { ThemeProvider } from "@opencode-ai/ui/theme/context"
|
||||
@@ -58,18 +57,24 @@ import { TabsProvider, useTabs, type DraftTab } from "@/context/tabs"
|
||||
import { SDKProvider, useSDK } from "@/context/sdk"
|
||||
import { WslServersProvider } from "@/wsl/context"
|
||||
import DirectoryLayout, { DirectoryDataProvider } from "@/pages/directory-layout"
|
||||
import LegacyLayout from "@/pages/layout"
|
||||
import NewLayout from "@/pages/layout-new"
|
||||
import { ErrorPage } from "./pages/error"
|
||||
import { useCheckServerHealth } from "./utils/server-health"
|
||||
import { legacySessionHref, legacySessionServer, requireServerKey, sessionHref } from "./utils/session-route"
|
||||
import { createSessionLineage } from "@/pages/session/session-lineage"
|
||||
|
||||
import { SessionPage, SessionRouteErrorBoundary, TargetSessionRouteContent } from "@/pages/session"
|
||||
import { NewHome } from "@/pages/home"
|
||||
import { LegacyHome } from "@/pages/home/legacy-home"
|
||||
|
||||
const NewSession = lazy(() => import("@/pages/new-session"))
|
||||
const NewLayout = lazy(() => import("@/pages/layout-new"))
|
||||
const NewHome = lazy(() => import("@/pages/home").then((module) => ({ default: module.NewHome })))
|
||||
const LegacyLayout = lazy(() => import("@/pages/layout"))
|
||||
const LegacyHome = lazy(() => import("@/pages/home/legacy-home").then((module) => ({ default: module.LegacyHome })))
|
||||
const File = lazy(() => import("@opencode-ai/session-ui/file").then((module) => ({ default: module.File })))
|
||||
const SessionPage = lazy(() => import("@/pages/session").then((module) => ({ default: module.SessionPage })))
|
||||
const SessionRouteErrorBoundary = lazy(() =>
|
||||
import("@/pages/session").then((module) => ({ default: module.SessionRouteErrorBoundary })),
|
||||
)
|
||||
const TargetSessionRouteContent = lazy(() =>
|
||||
import("@/pages/session").then((module) => ({ default: module.TargetSessionRouteContent })),
|
||||
)
|
||||
|
||||
const SessionRoute = () => {
|
||||
const settings = useSettings()
|
||||
|
||||
@@ -88,7 +88,7 @@ export const DialogSelectModelUnpaidV2: Component<{ model?: ModelState }> = (pro
|
||||
class="w-full"
|
||||
placement="right-start"
|
||||
gutter={6}
|
||||
openDelay={0}
|
||||
delay="intent"
|
||||
contentStyle={{ "font-family": "var(--v2-font-family-sans)" }}
|
||||
value={
|
||||
<ModelTooltip
|
||||
|
||||
@@ -460,7 +460,7 @@ function ModelSelectorPopoverV2View(props: {
|
||||
class="w-full"
|
||||
placement="right-start"
|
||||
gutter={6}
|
||||
openDelay={0}
|
||||
delay="intent"
|
||||
value={
|
||||
<ModelTooltip
|
||||
model={item}
|
||||
|
||||
@@ -47,7 +47,7 @@ export const PromptContextItems: Component<ContextItemsProps> = (props) => {
|
||||
</span>
|
||||
}
|
||||
placement="top"
|
||||
openDelay={800}
|
||||
{...(!props.newLayoutDesigns ? { openDelay: 800 } : {})}
|
||||
>
|
||||
<div
|
||||
classList={{
|
||||
|
||||
@@ -53,12 +53,7 @@ export const PromptImageAttachments: Component<PromptImageAttachmentsProps> = (p
|
||||
<For each={props.comments ?? []}>
|
||||
{(item) => (
|
||||
<div class="relative group shrink-0">
|
||||
<TooltipV2
|
||||
value={item.comment}
|
||||
placement="top"
|
||||
openDelay={800}
|
||||
contentClass="max-w-[300px] break-words"
|
||||
>
|
||||
<TooltipV2 value={item.comment} placement="top" contentClass="max-w-[300px] break-words">
|
||||
<CommentCardV2
|
||||
comment={item.comment ?? ""}
|
||||
path={item.path}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { TextField } from "@opencode-ai/ui/text-field"
|
||||
import { type Component, For, Show } from "solid-js"
|
||||
import { useLanguage } from "@/context/language"
|
||||
import { useModels } from "@/context/models"
|
||||
import { useServerSync } from "@/context/server-sync"
|
||||
import { popularProviders } from "@/hooks/use-providers"
|
||||
import { SettingsList } from "./settings-list"
|
||||
import { SettingsServerPicker, SettingsServerScope } from "./settings-server-picker"
|
||||
@@ -43,6 +44,7 @@ export const SettingsModels: Component = () => {
|
||||
const SettingsModelsContent: Component = () => {
|
||||
const language = useLanguage()
|
||||
const models = useModels()
|
||||
useServerSync()().loadProviders()
|
||||
|
||||
const list = useFilteredList<ModelItem>({
|
||||
items: (_filter) => models.list(),
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createStore } from "solid-js/store"
|
||||
import { useLanguage } from "@/context/language"
|
||||
import { useModels } from "@/context/models"
|
||||
import { useServerSDK } from "@/context/server-sdk"
|
||||
import { useServerSync } from "@/context/server-sync"
|
||||
import { popularProviders } from "@/hooks/use-providers"
|
||||
import { Persist, persisted } from "@/utils/persist"
|
||||
import { SettingsListV2 } from "./parts/list"
|
||||
@@ -23,6 +24,7 @@ export const SettingsModelsV2: Component = () => {
|
||||
const language = useLanguage()
|
||||
const models = useModels()
|
||||
const serverSdk = useServerSDK()
|
||||
useServerSync()().loadProviders()
|
||||
const [store, setStore] = persisted(
|
||||
Persist.serverGlobal(serverSdk().scope, "settings-v2.models.providers"),
|
||||
createStore({ collapsed: {} as Record<string, boolean> }),
|
||||
|
||||
@@ -353,6 +353,22 @@ export function Titlebar(props: { update?: TitlebarUpdate; debugTools?: { visibl
|
||||
keybind: "mod+shift+t",
|
||||
onSelect: () => tabsStoreActions.reopenClosedTab(),
|
||||
},
|
||||
{
|
||||
id: `tab.prev`,
|
||||
category: "tab",
|
||||
title: "",
|
||||
keybind: `mod+option+ArrowLeft,ctrl+shift+tab`,
|
||||
hidden: true,
|
||||
onSelect: tabs.previous,
|
||||
},
|
||||
{
|
||||
id: `tab.next`,
|
||||
category: "tab",
|
||||
title: "",
|
||||
keybind: `mod+option+ArrowRight,ctrl+tab`,
|
||||
hidden: true,
|
||||
onSelect: tabs.next,
|
||||
},
|
||||
].filter((v) => v !== undefined)
|
||||
})
|
||||
|
||||
|
||||
@@ -152,12 +152,6 @@ export async function bootstrapGlobal(input: {
|
||||
queryClient: QueryClient
|
||||
}) {
|
||||
const slow = [
|
||||
() => input.queryClient.fetchQuery(loadGlobalConfigQuery(input.scope, input.serverSDK, input.protocol)),
|
||||
() =>
|
||||
input.queryClient.fetchQuery(
|
||||
loadProvidersQuery(input.scope, null, input.serverAPI, input.serverSDK, input.protocol),
|
||||
),
|
||||
() => input.queryClient.fetchQuery(loadPathQuery(input.scope, null, input.serverSDK, input.protocol)),
|
||||
() =>
|
||||
input.queryClient
|
||||
.fetchQuery(loadProjectsQuery(input.scope, input.serverAPI.project))
|
||||
@@ -524,17 +518,6 @@ export async function bootstrapDirectory(input: {
|
||||
input.queryClient.fetchQuery(
|
||||
loadMcpResourcesQuery(input.scope, input.directory, input.api.mcp, input.sdk, input.protocol),
|
||||
)),
|
||||
() =>
|
||||
input.queryClient
|
||||
.fetchQuery(loadProvidersQuery(input.scope, input.directory, input.api, input.sdk, input.protocol))
|
||||
.catch((err) => {
|
||||
const project = getFilename(input.directory)
|
||||
showToast({
|
||||
variant: "error",
|
||||
title: input.translate("toast.project.reloadFailed.title", { project }),
|
||||
description: formatServerError(err, input.translate),
|
||||
})
|
||||
}),
|
||||
].filter(Boolean) as (() => Promise<any>)[]
|
||||
|
||||
await waitForPaint()
|
||||
|
||||
@@ -263,10 +263,13 @@ describe("createChildStoreManager", () => {
|
||||
manager.child("/project")
|
||||
expect(queries[0]?.().enabled).toBe(true)
|
||||
expect(queries[3]?.().enabled).toBe(true)
|
||||
expect(queries[4]?.().enabled).toBe(true)
|
||||
expect(queries[4]?.().enabled).toBe(false)
|
||||
expect(queries[5]?.().enabled).toBe(true)
|
||||
expect(bootstraps).toEqual(["/project"])
|
||||
|
||||
manager.enableProviders("/project")
|
||||
expect(queries[4]?.().enabled).toBe(true)
|
||||
|
||||
manager.child("/project", { bootstrap: false })
|
||||
expect(queries[0]?.().enabled).toBe(true)
|
||||
} finally {
|
||||
|
||||
@@ -47,6 +47,7 @@ export function createChildStoreManager(input: {
|
||||
const mcpToggles = new Map<string, (enabled: boolean) => void>()
|
||||
const activeDirectories = new Set<string>()
|
||||
const activationToggles = new Map<string, (enabled: boolean) => void>()
|
||||
const providerToggles = new Map<string, (enabled: boolean) => void>()
|
||||
|
||||
const markKey = (key: DirectoryKey) => {
|
||||
if (!key) return
|
||||
@@ -122,6 +123,7 @@ export function createChildStoreManager(input: {
|
||||
mcpToggles.delete(key)
|
||||
activeDirectories.delete(key)
|
||||
activationToggles.delete(key)
|
||||
providerToggles.delete(key)
|
||||
const dispose = disposers.get(key)
|
||||
if (dispose) {
|
||||
dispose()
|
||||
@@ -187,6 +189,7 @@ export function createChildStoreManager(input: {
|
||||
const initialIcon = icon[0].value
|
||||
const [mcpEnabled, setMcpEnabled] = createSignal(false)
|
||||
const [instanceQueriesEnabled, setInstanceQueriesEnabled] = createSignal(false)
|
||||
const [providerEnabled, setProviderEnabled] = createSignal(false)
|
||||
|
||||
const pathQuery = useQuery(() => ({ ...input.queryOptions.path(key), enabled: instanceQueriesEnabled() }))
|
||||
const mcpQuery = useQuery(() => ({ ...input.queryOptions.mcp(key), enabled: mcpEnabled() }))
|
||||
@@ -194,7 +197,7 @@ export function createChildStoreManager(input: {
|
||||
const lspQuery = useQuery(() => ({ ...input.queryOptions.lsp(key), enabled: instanceQueriesEnabled() }))
|
||||
const providerQuery = useQuery(() => ({
|
||||
...input.queryOptions.providers(key),
|
||||
enabled: instanceQueriesEnabled(),
|
||||
enabled: providerEnabled(),
|
||||
}))
|
||||
const referenceQuery = useQuery(() => ({
|
||||
...input.queryOptions.references(key),
|
||||
@@ -206,7 +209,7 @@ export function createChildStoreManager(input: {
|
||||
projectMeta: initialMeta,
|
||||
icon: initialIcon,
|
||||
get provider_ready() {
|
||||
return instanceQueriesEnabled() && !providerQuery.isLoading
|
||||
return providerEnabled() && !providerQuery.isLoading
|
||||
},
|
||||
get provider() {
|
||||
const EMPTY = { all: new Map(), connected: [], default: {} }
|
||||
@@ -263,6 +266,7 @@ export function createChildStoreManager(input: {
|
||||
disposers.set(key, dispose)
|
||||
mcpToggles.set(key, setMcpEnabled)
|
||||
activationToggles.set(key, setInstanceQueriesEnabled)
|
||||
providerToggles.set(key, setProviderEnabled)
|
||||
|
||||
const onPersistedInit = (init: Promise<string> | string | null, run: () => void) => {
|
||||
if (!(init instanceof Promise)) return
|
||||
@@ -329,6 +333,12 @@ export function createChildStoreManager(input: {
|
||||
if (childStore[0].status !== "loading") input.onMcp(directory, childStore[1])
|
||||
}
|
||||
|
||||
function enableProviders(directory: string) {
|
||||
const key = directoryKey(directory)
|
||||
ensureChild(directory)
|
||||
providerToggles.get(key)?.(true)
|
||||
}
|
||||
|
||||
// Passive Home/project metadata reads must not initialize the directory.
|
||||
// A real directory access enables these queries once for the store lifetime.
|
||||
// TODO(v2): After Home switches to v2.project.list and root-filtered,
|
||||
@@ -387,6 +397,7 @@ export function createChildStoreManager(input: {
|
||||
mcp: (directory: string) => mcpDirectories.has(directoryKey(directory)),
|
||||
active: (directory: string) => activeDirectories.has(directoryKey(directory)),
|
||||
disableMcp,
|
||||
enableProviders,
|
||||
disposeDirectory,
|
||||
runEviction,
|
||||
vcsCache,
|
||||
|
||||
@@ -22,6 +22,7 @@ export const homeSessionIndexKey = (server: string) => ["home", "session-index",
|
||||
export const homeSessionEventsKey = (server: string) => ["home", "session-events", server] as const
|
||||
|
||||
type HomeSessionPage = { data?: V2SessionListResponse }
|
||||
type ProjectedHomeSessionPage = { data?: { data: Session[]; cursor: { next?: string } } }
|
||||
|
||||
export async function loadHomeSessionIndex(
|
||||
list: (
|
||||
@@ -31,7 +32,30 @@ export async function loadHomeSessionIndex(
|
||||
eventSequence = 0,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const data: SessionV2Info[] = []
|
||||
return loadHomeSessionPages(list, parseHomeSessionIndex, eventSequence, signal)
|
||||
}
|
||||
|
||||
export async function loadProjectedHomeSessionIndex(
|
||||
list: (
|
||||
input: { limit: number; order: "desc"; cursor?: string },
|
||||
options: { signal?: AbortSignal },
|
||||
) => Promise<ProjectedHomeSessionPage>,
|
||||
eventSequence = 0,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
return loadHomeSessionPages(list, (sessions) => sessions, eventSequence, signal)
|
||||
}
|
||||
|
||||
async function loadHomeSessionPages<T>(
|
||||
list: (
|
||||
input: { limit: number; order: "desc"; cursor?: string },
|
||||
options: { signal?: AbortSignal },
|
||||
) => Promise<{ data?: { data: T[]; cursor: { next?: string } } }>,
|
||||
project: (sessions: T[]) => Session[],
|
||||
eventSequence: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const data: T[] = []
|
||||
let cursor: string | undefined
|
||||
|
||||
for (;;) {
|
||||
@@ -46,7 +70,7 @@ export async function loadHomeSessionIndex(
|
||||
const page = response.data!
|
||||
data.push(...page.data)
|
||||
if (page.data.length < HOME_V2_SESSION_PAGE_LIMIT || !page.cursor.next)
|
||||
return { sessions: parseHomeSessionIndex(data), eventSequence }
|
||||
return { sessions: project(data), eventSequence }
|
||||
cursor = page.cursor.next
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ import { useGlobal } from "./global"
|
||||
import { ServerScope } from "@/utils/server-scope"
|
||||
import { detectServerProtocol, type ServerProtocol } from "@/utils/server-protocol"
|
||||
import { createCompatibleApi, type CompatibleApi } from "@/utils/server-compat"
|
||||
import { decodeVcsDiff } from "@/utils/vcs-diff-decoder"
|
||||
import { decodeSessionList } from "./session-message-decoder"
|
||||
|
||||
const isAbortError = (error: unknown) =>
|
||||
error !== null && typeof error === "object" && "name" in error && error.name === "AbortError"
|
||||
@@ -346,7 +348,7 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
|
||||
throwOnError: true,
|
||||
directory,
|
||||
})
|
||||
const api = createCompatibleApi({ protocol, current: currentApi, legacy })
|
||||
const api = createCompatibleApi({ protocol, current: currentApi, legacy, decodeVcsDiff, decodeSessionList })
|
||||
|
||||
return {
|
||||
server,
|
||||
@@ -432,6 +434,8 @@ function createDirSdkContext(directory: string, serverSDK: ServerSDKBase) {
|
||||
current: serverSDK.currentApi,
|
||||
legacy: (next) => serverSDK.createClient({ directory: next ?? directory, throwOnError: true }),
|
||||
directory,
|
||||
decodeVcsDiff,
|
||||
decodeSessionList,
|
||||
}),
|
||||
event: emitter,
|
||||
get url() {
|
||||
|
||||
@@ -22,6 +22,7 @@ import { normalizeSessionMessages } from "@/utils/session-message"
|
||||
import { dropSessionCaches, pickSessionCacheEvictions, SESSION_CACHE_LIMIT } from "./global-sync/session-cache"
|
||||
import { createV2SessionReducer, type V2SessionReduction } from "./server-session-v2-reducer"
|
||||
import type { ServerApi } from "@/utils/server"
|
||||
import type { DecodedLegacyMessagePage } from "./session-message-decode"
|
||||
|
||||
type MessageApi = ServerApi["message"]
|
||||
|
||||
@@ -29,10 +30,16 @@ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
|
||||
const cmpMessage = (a: Message, b: Message) => a.time.created - b.time.created || cmp(a.id, b.id)
|
||||
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
||||
const initialMessagePageSize = 20
|
||||
const historyMessagePageSize = 200
|
||||
const historyMessagePageSize = 50
|
||||
const sessionInfoLimit = 2_048
|
||||
const emptyIDs: ReadonlySet<string> = new Set()
|
||||
|
||||
function yieldToMain() {
|
||||
const scheduler = (globalThis as { scheduler?: { yield: () => Promise<void> } }).scheduler
|
||||
if (scheduler) return scheduler.yield()
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, 0))
|
||||
}
|
||||
|
||||
function needsOlderTurnRoot(source: readonly SessionMessageInfo[]) {
|
||||
const boundary = source.find(
|
||||
(message) =>
|
||||
@@ -183,7 +190,11 @@ function reconcileFetched<T extends { id: string }>(
|
||||
return [...result.values()].sort((a, b) => cmp(a.id, b.id))
|
||||
}
|
||||
|
||||
type ServerSessionOptions = { retry?: typeof retry; protocol?: Promise<"v1" | "v2"> }
|
||||
type ServerSessionOptions = {
|
||||
retry?: typeof retry
|
||||
protocol?: Promise<"v1" | "v2">
|
||||
decodeMessages?: (buffer: ArrayBuffer) => Promise<DecodedLegacyMessagePage>
|
||||
}
|
||||
|
||||
export function createServerSession(
|
||||
client: OpencodeClient,
|
||||
@@ -552,6 +563,7 @@ export function createServerSession(
|
||||
if (!response.data.length) break
|
||||
}
|
||||
const response = pages.at(-1)!
|
||||
await yieldToMain()
|
||||
const source = pages.flatMap((page) => page.data).toReversed()
|
||||
const normalized = normalizeSessionMessages(sessionID, source)
|
||||
return {
|
||||
@@ -566,10 +578,21 @@ export function createServerSession(
|
||||
complete: response.data.length === 0,
|
||||
}
|
||||
}
|
||||
const response = await (options?.retry ?? retry)(() => {
|
||||
const response = await (options?.retry ?? retry)(async () => {
|
||||
onAttempt?.()
|
||||
return client.session.messages({ sessionID, limit, before })
|
||||
if (!options?.decodeMessages) return client.session.messages({ sessionID, limit, before })
|
||||
const response = await client.session.messages({ sessionID, limit, before }, { parseAs: "arrayBuffer" })
|
||||
if (!(response.data instanceof ArrayBuffer)) throw new Error("Session messages response is not an ArrayBuffer")
|
||||
return { response, decoded: await options.decodeMessages(response.data) }
|
||||
})
|
||||
await yieldToMain()
|
||||
if ("decoded" in response)
|
||||
return {
|
||||
...response.decoded,
|
||||
sourceMode: before ? ("older" as const) : ("latest" as const),
|
||||
cursor: response.response.response.headers.get("x-next-cursor") ?? undefined,
|
||||
complete: !response.response.response.headers.get("x-next-cursor"),
|
||||
}
|
||||
const items = (response.data ?? []).filter((item) => !!item?.info?.id)
|
||||
return {
|
||||
session: items.map((item) => cleanMessage(item.info)).sort((a, b) => cmp(a.id, b.id)),
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
} from "@opencode-ai/sdk/v2/client"
|
||||
import { showToast } from "@/utils/toast"
|
||||
import { getFilename } from "@opencode-ai/core/util/path"
|
||||
import { type Accessor, batch, createMemo, getOwner, onCleanup, onMount, untrack } from "solid-js"
|
||||
import { type Accessor, batch, createMemo, createSignal, getOwner, onCleanup, onMount, untrack } from "solid-js"
|
||||
import { createStore, produce, reconcile } from "solid-js/store"
|
||||
import { useLanguage } from "@/context/language"
|
||||
import type { InitError } from "../pages/error"
|
||||
@@ -59,6 +59,7 @@ import type {
|
||||
} from "@opencode-ai/client/promise"
|
||||
import { toggleMcp } from "./global-sync/mcp"
|
||||
import { createServerSession, type ServerSession } from "./server-session"
|
||||
import { decodeSessionMessages } from "./session-message-decoder"
|
||||
|
||||
type GlobalStore = {
|
||||
ready: boolean
|
||||
@@ -226,6 +227,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
||||
|
||||
const session = createServerSession(serverSDK.client, serverSDK.api.session, serverSDK.api.message, {
|
||||
protocol: serverSDK.protocol,
|
||||
decodeMessages: decodeSessionMessages,
|
||||
})
|
||||
const queryOptionsApi = makeQueryOptionsApi(
|
||||
serverSDK.scope,
|
||||
@@ -235,31 +237,40 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
||||
serverSDK.protocol,
|
||||
)
|
||||
|
||||
const [providersEnabled, setProvidersEnabled] = createSignal(false)
|
||||
const [backgroundEnabled, setBackgroundEnabled] = createSignal(false)
|
||||
const [configQuery, providerQuery, pathQuery] = useQueries(() => ({
|
||||
queries: [queryOptionsApi.globalConfig(), queryOptionsApi.providers(null), queryOptionsApi.path(null)],
|
||||
queries: [
|
||||
{ ...queryOptionsApi.globalConfig(), enabled: backgroundEnabled() },
|
||||
{ ...queryOptionsApi.providers(null), enabled: providersEnabled() },
|
||||
{ ...queryOptionsApi.path(null), enabled: backgroundEnabled() },
|
||||
],
|
||||
}))
|
||||
const activeSessionsQuery = useQuery(() =>
|
||||
loadActiveSessionsQuery(serverSDK.scope, {
|
||||
active: async () => {
|
||||
if ((await serverSDK.protocol) === "v1") {
|
||||
const statuses = (await serverSDK.client.session.status()).data ?? {}
|
||||
seedActiveSessionStatuses(session, statuses)
|
||||
for (const sessionID of Object.keys(statuses)) {
|
||||
({
|
||||
...loadActiveSessionsQuery(serverSDK.scope, {
|
||||
active: async () => {
|
||||
if ((await serverSDK.protocol) === "v1") {
|
||||
const statuses = (await serverSDK.client.session.status()).data ?? {}
|
||||
seedActiveSessionStatuses(session, statuses)
|
||||
for (const sessionID of Object.keys(statuses)) {
|
||||
void session.resolve(sessionID).catch(() => undefined)
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(statuses).flatMap(([sessionID, status]) =>
|
||||
status.type === "idle" ? [] : [[sessionID, { type: "running" as const }]],
|
||||
),
|
||||
)
|
||||
}
|
||||
const active = await serverSDK.api.session.active()
|
||||
seedActiveSessionStatuses(session, active)
|
||||
for (const sessionID of Object.keys(active)) {
|
||||
void session.resolve(sessionID).catch(() => undefined)
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(statuses).flatMap(([sessionID, status]) =>
|
||||
status.type === "idle" ? [] : [[sessionID, { type: "running" as const }]],
|
||||
),
|
||||
)
|
||||
}
|
||||
const active = await serverSDK.api.session.active()
|
||||
seedActiveSessionStatuses(session, active)
|
||||
for (const sessionID of Object.keys(active)) {
|
||||
void session.resolve(sessionID).catch(() => undefined)
|
||||
}
|
||||
return active
|
||||
},
|
||||
return active
|
||||
},
|
||||
}),
|
||||
enabled: backgroundEnabled(),
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -299,10 +310,36 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
||||
let bootingRoot = false
|
||||
let eventFrame: number | undefined
|
||||
let eventTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let providerFrame: number | undefined
|
||||
let providerIdle: number | undefined
|
||||
let providerTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
onMount(() => {
|
||||
providerFrame = requestAnimationFrame(() => {
|
||||
providerFrame = requestAnimationFrame(() => {
|
||||
providerFrame = undefined
|
||||
providerTimer = setTimeout(() => {
|
||||
providerTimer = undefined
|
||||
if ("requestIdleCallback" in window) {
|
||||
providerIdle = requestIdleCallback(() => {
|
||||
setProvidersEnabled(true)
|
||||
setBackgroundEnabled(true)
|
||||
}, { timeout: 5_000 })
|
||||
return
|
||||
}
|
||||
setProvidersEnabled(true)
|
||||
setBackgroundEnabled(true)
|
||||
}, 10_000)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
|
||||
if (eventTimer !== undefined) clearTimeout(eventTimer)
|
||||
if (providerFrame !== undefined) cancelAnimationFrame(providerFrame)
|
||||
if (providerIdle !== undefined) cancelIdleCallback(providerIdle)
|
||||
if (providerTimer !== undefined) clearTimeout(providerTimer)
|
||||
})
|
||||
|
||||
const setProjects = (next: Project[] | ((draft: Project[]) => Project[])) => {
|
||||
@@ -682,7 +719,9 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
||||
child: children.child,
|
||||
peek: children.peek,
|
||||
disableMcp: children.disableMcp,
|
||||
enableProviders: children.enableProviders,
|
||||
queryOptions: queryOptionsApi,
|
||||
loadProviders: () => setProvidersEnabled(true),
|
||||
refreshProviders,
|
||||
// bootstrap,
|
||||
updateConfig: updateConfigMutation.mutateAsync,
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import type { Message, Part, Session, SessionV2Info } from "@opencode-ai/sdk/v2/client"
|
||||
import { decodeHomeSessionPage, decodeLegacyMessagePage, decodeLegacySessionList } from "./session-message-decode"
|
||||
|
||||
test("decodes and projects a legacy message page", () => {
|
||||
const info = {
|
||||
id: "message",
|
||||
sessionID: "session",
|
||||
role: "user",
|
||||
time: { created: 1 },
|
||||
agent: "build",
|
||||
model: { providerID: "provider", modelID: "model" },
|
||||
} as Message
|
||||
const part = {
|
||||
id: "part",
|
||||
sessionID: "session",
|
||||
messageID: info.id,
|
||||
type: "text",
|
||||
text: "hello",
|
||||
} as Part
|
||||
const result = decodeLegacyMessagePage(new TextEncoder().encode(JSON.stringify([{ info, parts: [part] }])).buffer)
|
||||
|
||||
expect(result.session).toEqual([info])
|
||||
expect(result.part).toEqual([{ id: info.id, part: [part] }])
|
||||
expect(result.source).toEqual([{ id: info.id, type: "user", text: "hello", time: info.time }])
|
||||
})
|
||||
|
||||
test("decodes and projects a legacy session list", () => {
|
||||
const session = {
|
||||
id: "session",
|
||||
projectID: "project",
|
||||
directory: "/repo",
|
||||
title: "Session",
|
||||
version: "1",
|
||||
time: { created: 1, updated: 1 },
|
||||
} as Session
|
||||
const result = decodeLegacySessionList(new TextEncoder().encode(JSON.stringify([session])).buffer)
|
||||
|
||||
expect(result).toEqual([
|
||||
expect.objectContaining({ id: session.id, title: session.title, location: { directory: "/repo" } }),
|
||||
])
|
||||
})
|
||||
|
||||
test("bounds Home sessions by directory before returning from the decoder", () => {
|
||||
const session = (id: string, directory: string, updated: number) =>
|
||||
({
|
||||
id,
|
||||
projectID: "project",
|
||||
location: { directory },
|
||||
subpath: "",
|
||||
title: id,
|
||||
time: { created: updated, updated },
|
||||
}) as SessionV2Info
|
||||
const page = {
|
||||
data: [session("old", "/repo", 1), session("new", "/repo", 2), session("other", "/other", 3)],
|
||||
cursor: {},
|
||||
}
|
||||
const result = decodeHomeSessionPage(new TextEncoder().encode(JSON.stringify(page)).buffer, {
|
||||
directories: ["/repo"],
|
||||
limit: 1,
|
||||
})
|
||||
|
||||
expect(result.data.map((item) => item.id)).toEqual(["new"])
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { SessionInfo, SessionMessageInfo } from "@opencode-ai/client/promise"
|
||||
import type { Message, Part, Session, V2SessionListResponse } from "@opencode-ai/sdk/v2/client"
|
||||
import { message as cleanMessage } from "@/utils/diffs"
|
||||
import { pathKey } from "@/utils/path-key"
|
||||
import { parseHomeSessionIndex } from "./global-sync/home-session-index"
|
||||
import { takeRecentSessions } from "./global-sync/session-trim"
|
||||
|
||||
export type DecodedLegacyMessagePage = {
|
||||
session: Message[]
|
||||
part: { id: string; part: Part[] }[]
|
||||
source: SessionMessageInfo[]
|
||||
}
|
||||
|
||||
export function decodeLegacyMessagePage(buffer: ArrayBuffer): DecodedLegacyMessagePage {
|
||||
const text = new TextDecoder().decode(buffer)
|
||||
const items = (text ? (JSON.parse(text) as { info?: Message; parts?: Part[] }[]) : []).filter(
|
||||
(item): item is { info: Message; parts: Part[] } => !!item.info?.id && Array.isArray(item.parts),
|
||||
)
|
||||
return {
|
||||
session: items.map((item) => cleanMessage(item.info)).sort((a, b) => compare(a.id, b.id)),
|
||||
part: items.map((item) => ({
|
||||
id: item.info.id,
|
||||
part: item.parts.filter((part) => !!part?.id).sort((a, b) => compare(a.id, b.id)),
|
||||
})),
|
||||
source: items
|
||||
.slice()
|
||||
.sort((a, b) => compare(a.info.id, b.info.id))
|
||||
.map((item) =>
|
||||
item.info.role === "user"
|
||||
? {
|
||||
id: item.info.id,
|
||||
type: "user" as const,
|
||||
text: item.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"),
|
||||
time: item.info.time,
|
||||
}
|
||||
: {
|
||||
id: item.info.id,
|
||||
type: "assistant" as const,
|
||||
agent: item.info.agent ?? item.info.mode,
|
||||
model: { id: item.info.modelID, providerID: item.info.providerID, variant: item.info.variant },
|
||||
content: [],
|
||||
time: item.info.time,
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeLegacySessionList(buffer: ArrayBuffer) {
|
||||
const text = new TextDecoder().decode(buffer)
|
||||
return (text ? (JSON.parse(text) as Session[]) : []).map(legacySessionInfo)
|
||||
}
|
||||
|
||||
export function decodeHomeSessionPage(buffer: ArrayBuffer, options?: { directories: string[]; limit: number }) {
|
||||
const text = new TextDecoder().decode(buffer)
|
||||
const page = (text ? JSON.parse(text) : { data: [], cursor: {} }) as V2SessionListResponse
|
||||
const sessions = parseHomeSessionIndex(page.data)
|
||||
if (!options) return { data: sessions, cursor: page.cursor }
|
||||
const directories = new Set(options.directories.map(pathKey))
|
||||
return {
|
||||
data: [...Map.groupBy(sessions, (session) => pathKey(session.directory))]
|
||||
.filter(([directory]) => directories.has(directory))
|
||||
.flatMap(([, items]) => takeRecentSessions(items, options.limit, Number.NEGATIVE_INFINITY)),
|
||||
cursor: page.cursor,
|
||||
}
|
||||
}
|
||||
|
||||
export function legacySessionInfo(session: Session): SessionInfo {
|
||||
return {
|
||||
id: session.id,
|
||||
parentID: session.parentID,
|
||||
projectID: session.projectID,
|
||||
agent: session.agent,
|
||||
model: session.model && {
|
||||
id: session.model.id,
|
||||
providerID: session.model.providerID,
|
||||
variant: session.model.variant,
|
||||
},
|
||||
cost: session.cost ?? 0,
|
||||
tokens: session.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: session.time,
|
||||
title: session.title,
|
||||
location: { directory: session.directory, workspaceID: session.workspaceID },
|
||||
subpath: session.path,
|
||||
revert: session.revert && {
|
||||
messageID: session.revert.messageID,
|
||||
partID: session.revert.partID,
|
||||
snapshot: session.revert.snapshot,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function compare(a: string, b: string) {
|
||||
return a < b ? -1 : a > b ? 1 : 0
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { DecodedLegacyMessagePage } from "./session-message-decode"
|
||||
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||
import type { Session } from "@opencode-ai/sdk/v2/client"
|
||||
|
||||
type Response = { id: number; data?: unknown; error?: string }
|
||||
|
||||
let worker: Worker | undefined
|
||||
let nextID = 0
|
||||
const pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>()
|
||||
|
||||
export function decodeSessionMessages(buffer: ArrayBuffer) {
|
||||
return decode<DecodedLegacyMessagePage>("messages", buffer)
|
||||
}
|
||||
|
||||
export function decodeSessionList(buffer: ArrayBuffer) {
|
||||
return decode<SessionInfo[]>("sessions", buffer)
|
||||
}
|
||||
|
||||
export function decodeHomeSessionPage(buffer: ArrayBuffer, options: { directories: string[]; limit: number }) {
|
||||
return decode<{ data: Session[]; cursor: { next?: string } }>("homeSessions", buffer, options)
|
||||
}
|
||||
|
||||
function decode<T>(
|
||||
type: "messages" | "sessions" | "homeSessions",
|
||||
buffer: ArrayBuffer,
|
||||
options?: { directories: string[]; limit: number },
|
||||
) {
|
||||
const id = ++nextID
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
pending.set(id, { resolve: (value) => resolve(value as T), reject })
|
||||
getWorker().postMessage({ id, type, buffer, options }, [buffer])
|
||||
})
|
||||
}
|
||||
|
||||
function getWorker() {
|
||||
if (worker) return worker
|
||||
worker = new Worker(new URL("./session-message-decoder.worker.ts", import.meta.url), { type: "module" })
|
||||
worker.onmessage = (event: MessageEvent<Response>) => {
|
||||
const request = pending.get(event.data.id)
|
||||
if (!request) return
|
||||
pending.delete(event.data.id)
|
||||
if (event.data.error) {
|
||||
request.reject(new Error(event.data.error))
|
||||
return
|
||||
}
|
||||
request.resolve(event.data.data)
|
||||
}
|
||||
worker.onerror = (event) => {
|
||||
const error = new Error(event.message)
|
||||
pending.forEach((request) => request.reject(error))
|
||||
pending.clear()
|
||||
worker?.terminate()
|
||||
worker = undefined
|
||||
}
|
||||
return worker
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { decodeHomeSessionPage, decodeLegacyMessagePage, decodeLegacySessionList } from "./session-message-decode"
|
||||
|
||||
type DecoderRequest = {
|
||||
id: number
|
||||
type: "messages" | "sessions" | "homeSessions"
|
||||
buffer: ArrayBuffer
|
||||
options?: { directories: string[]; limit: number }
|
||||
}
|
||||
|
||||
self.onmessage = (event: MessageEvent<DecoderRequest>) => {
|
||||
try {
|
||||
self.postMessage({
|
||||
id: event.data.id,
|
||||
data: (() => {
|
||||
if (event.data.type === "messages") return decodeLegacyMessagePage(event.data.buffer)
|
||||
if (event.data.type === "sessions") return decodeLegacySessionList(event.data.buffer)
|
||||
return decodeHomeSessionPage(event.data.buffer, event.data.options)
|
||||
})(),
|
||||
})
|
||||
} catch (error) {
|
||||
self.postMessage({ id: event.data.id, error: error instanceof Error ? error.message : String(error) })
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { nextTab, previousTab, rememberTab, type TabHistory } from "./tab-history"
|
||||
|
||||
function history(): TabHistory {
|
||||
return { stack: [], index: -1 }
|
||||
}
|
||||
|
||||
describe("tab history", () => {
|
||||
test("moves backward and forward through selected tabs", () => {
|
||||
const selected = ["a", "b", "c"].reduce(rememberTab, history())
|
||||
const available = new Set(selected.stack)
|
||||
|
||||
const previous = previousTab(selected, available)
|
||||
expect(previous?.key).toBe("b")
|
||||
|
||||
const first = previousTab(previous!.state, available)
|
||||
expect(first?.key).toBe("a")
|
||||
|
||||
const next = nextTab(first!.state, available)
|
||||
expect(next?.key).toBe("b")
|
||||
})
|
||||
|
||||
test("replaces forward history after a new selection", () => {
|
||||
const selected = ["a", "b", "c"].reduce(rememberTab, history())
|
||||
const previous = previousTab(selected, new Set(selected.stack))
|
||||
const next = rememberTab(previous!.state, "d")
|
||||
|
||||
expect(next).toEqual({ stack: ["a", "b", "d"], index: 2 })
|
||||
expect(nextTab(next, new Set(next.stack))).toBeUndefined()
|
||||
})
|
||||
|
||||
test("skips tabs that are no longer open", () => {
|
||||
const selected = ["a", "b", "c"].reduce(rememberTab, history())
|
||||
|
||||
expect(previousTab(selected, new Set(["a", "c"]))?.key).toBe("a")
|
||||
})
|
||||
|
||||
test("skips a repeated current tab after closing the previous selection", () => {
|
||||
const selected = ["a", "b", "c", "b"].reduce(rememberTab, history())
|
||||
|
||||
expect(previousTab(selected, new Set(["a", "b"]))?.key).toBe("a")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
const MAX_TAB_HISTORY = 100
|
||||
|
||||
export type TabHistory = {
|
||||
stack: string[]
|
||||
index: number
|
||||
}
|
||||
|
||||
export function rememberTab(state: TabHistory, key: string): TabHistory {
|
||||
if (state.stack[state.index] === key) return state
|
||||
const stack = state.stack.slice(0, state.index + 1).concat(key).slice(-MAX_TAB_HISTORY)
|
||||
return { stack, index: stack.length - 1 }
|
||||
}
|
||||
|
||||
export function previousTab(state: TabHistory, available: Set<string>) {
|
||||
return move(state, -1, available)
|
||||
}
|
||||
|
||||
export function nextTab(state: TabHistory, available: Set<string>) {
|
||||
return move(state, 1, available)
|
||||
}
|
||||
|
||||
function move(state: TabHistory, offset: -1 | 1, available: Set<string>) {
|
||||
const current = state.stack[state.index]
|
||||
for (let index = state.index + offset; index >= 0 && index < state.stack.length; index += offset) {
|
||||
const key = state.stack[index]
|
||||
if (key && key !== current && available.has(key)) return { state: { ...state, index }, key }
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { createTabMemory } from "./tab-memory"
|
||||
import { nextTabAfterClose, pushClosedTab, removeClosedTabs, takeClosedTab, type ClosedTab } from "./closed-tabs"
|
||||
import { createDraftPromptSession, type PromptModel } from "./prompt-state"
|
||||
import { migrateTabs } from "./tab-migration"
|
||||
import { nextTab, previousTab, rememberTab, type TabHistory } from "./tab-history"
|
||||
|
||||
export type SessionTab = {
|
||||
type: "session"
|
||||
@@ -74,6 +75,7 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
|
||||
const memory = createTabMemory(getOwner())
|
||||
|
||||
const closing = new Set<string>()
|
||||
let history: TabHistory = { stack: [], index: -1 }
|
||||
let recentWrite = 0
|
||||
let recentValue: string | undefined
|
||||
|
||||
@@ -148,10 +150,21 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
|
||||
|
||||
const navigateTab = (tab: Tab) => {
|
||||
const href = tabHref(tab)
|
||||
history = rememberTab(history, tabKey(tab))
|
||||
setRecentKey(tabKey(tab))
|
||||
navigate(href)
|
||||
}
|
||||
|
||||
const moveHistory = (direction: "previous" | "next") => {
|
||||
const available = new Set(store.map(tabKey))
|
||||
const result = direction === "previous" ? previousTab(history, available) : nextTab(history, available)
|
||||
if (!result) return
|
||||
const tab = store.find((item) => tabKey(item) === result.key)
|
||||
if (!tab) return
|
||||
history = result.state
|
||||
navigateTab(tab)
|
||||
}
|
||||
|
||||
const removeTab = (index: number) => {
|
||||
const tab = store[index]
|
||||
if (!tab) return
|
||||
@@ -357,8 +370,11 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
|
||||
select: navigateTab,
|
||||
remember(tab: Tab) {
|
||||
const key = tabKey(tab)
|
||||
history = rememberTab(history, key)
|
||||
if (recentKey() !== key) setRecentKey(key)
|
||||
},
|
||||
previous: () => moveHistory("previous"),
|
||||
next: () => moveHistory("next"),
|
||||
toggleHome(input: { home: boolean; current?: Tab }) {
|
||||
if (input.home) {
|
||||
const tab = store.find((tab) => tabKey(tab) === recentKey())
|
||||
|
||||
@@ -2,6 +2,29 @@ import { describe, expect, test } from "bun:test"
|
||||
import { DESKTOP_MENU } from "./desktop-menu"
|
||||
|
||||
describe("desktop menu", () => {
|
||||
test("navigates between tabs", () => {
|
||||
const items = DESKTOP_MENU.flatMap((menu) => menu.items ?? []).filter(
|
||||
(item) =>
|
||||
item.type === "item" &&
|
||||
(item.labelKey === "desktop.menu.previousTab" || item.labelKey === "desktop.menu.nextTab"),
|
||||
)
|
||||
|
||||
expect(items).toEqual([
|
||||
{
|
||||
type: "item",
|
||||
labelKey: "desktop.menu.previousTab",
|
||||
command: "tab.prev",
|
||||
accelerator: { macos: "Option+Up" },
|
||||
},
|
||||
{
|
||||
type: "item",
|
||||
labelKey: "desktop.menu.nextTab",
|
||||
command: "tab.next",
|
||||
accelerator: { macos: "Option+Down" },
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
test("exports logs through the desktop command registry", () => {
|
||||
const items = DESKTOP_MENU.flatMap((menu) => menu.items ?? []).filter(
|
||||
(item) => item.type === "item" && item.labelKey === "desktop.menu.exportLogs",
|
||||
|
||||
@@ -237,6 +237,19 @@ export const DESKTOP_MENU: DesktopMenu[] = [
|
||||
{ type: "item", labelKey: "desktop.menu.back", command: "common.goBack", accelerator: { macos: "Cmd+[" } },
|
||||
{ type: "item", labelKey: "desktop.menu.forward", command: "common.goForward", accelerator: { macos: "Cmd+]" } },
|
||||
{ type: "separator" },
|
||||
{
|
||||
type: "item",
|
||||
labelKey: "desktop.menu.previousTab",
|
||||
command: "tab.prev",
|
||||
accelerator: { macos: "Option+Up" },
|
||||
},
|
||||
{
|
||||
type: "item",
|
||||
labelKey: "desktop.menu.nextTab",
|
||||
command: "tab.next",
|
||||
accelerator: { macos: "Option+Down" },
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
type: "item",
|
||||
labelKey: "desktop.menu.previousSession",
|
||||
|
||||
@@ -21,6 +21,12 @@ export function useProviders(directory: Accessor<string | undefined>) {
|
||||
const serverSync = useServerSync()
|
||||
const params = useParams()
|
||||
const dir = () => (directory ? directory() : decode64(params.dir))
|
||||
createEffect(() => {
|
||||
const value = dir()
|
||||
if (value) {
|
||||
serverSync().enableProviders(value)
|
||||
}
|
||||
})
|
||||
const providers = () => {
|
||||
const value = dir()
|
||||
const projectStore = value ? serverSync().child(value)[0] : undefined
|
||||
|
||||
@@ -66,6 +66,8 @@ export const DESKTOP_NATIVE_ENGLISH = {
|
||||
"desktop.menu.toggleFullScreen": "Toggle Full Screen",
|
||||
"desktop.menu.back": "Back",
|
||||
"desktop.menu.forward": "Forward",
|
||||
"desktop.menu.previousTab": "Previous Tab",
|
||||
"desktop.menu.nextTab": "Next Tab",
|
||||
"desktop.menu.previousSession": "Previous Session",
|
||||
"desktop.menu.nextSession": "Next Session",
|
||||
"desktop.menu.previousProject": "Previous Project",
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import type { Session } from "@opencode-ai/sdk/v2/client"
|
||||
import { preloadMarkdown } from "@opencode-ai/session-ui/markdown-cache"
|
||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||
import { useQuery } from "@tanstack/solid-query"
|
||||
import { DateTime } from "luxon"
|
||||
import { type Accessor, createEffect, createMemo, createRoot, type JSX, startTransition } from "solid-js"
|
||||
import { type Accessor, createEffect, createMemo, createSignal, onCleanup, type JSX, startTransition } from "solid-js"
|
||||
import { produce } from "solid-js/store"
|
||||
import { useCommand } from "@/context/command"
|
||||
import {
|
||||
loadHomeSessionIndex,
|
||||
retainHomeSessions,
|
||||
loadProjectedHomeSessionIndex,
|
||||
type HomeSessionEvents,
|
||||
} from "@/context/global-sync/home-session-index"
|
||||
import { takeRecentSessions } from "@/context/global-sync/session-trim"
|
||||
import { decodeHomeSessionPage } from "@/context/session-message-decoder"
|
||||
import type { LocalProject } from "@/context/layout"
|
||||
import { useLanguage } from "@/context/language"
|
||||
import { ServerConnection } from "@/context/server"
|
||||
@@ -24,6 +24,7 @@ import { archiveHomeSession } from "../home-session-archive"
|
||||
import type { HomeController } from "./home-controller"
|
||||
|
||||
const HOME_SESSION_LIMIT = 64
|
||||
const HOME_SESSION_RENDER_BATCH = 4
|
||||
export type HomeSessionRecord = {
|
||||
session: Session
|
||||
project: LocalProject
|
||||
@@ -66,8 +67,17 @@ export function createHomeSessionsController(home: HomeController) {
|
||||
if (!ctx) return { sessions: [], eventSequence: 0 }
|
||||
const cache = homeSessions()
|
||||
const eventSequence = cache.eventSequence()
|
||||
const index = await loadHomeSessionIndex(
|
||||
(input, options) => ctx.sdk.client.v2.session.list(input, options),
|
||||
const index = await loadProjectedHomeSessionIndex(
|
||||
async (input, options) => {
|
||||
const response = await ctx.sdk.client.v2.session.list(input, { ...options, parseAs: "arrayBuffer" })
|
||||
if (!(response.data instanceof ArrayBuffer)) throw new Error("Home session response is not an ArrayBuffer")
|
||||
return {
|
||||
data: await decodeHomeSessionPage(response.data, {
|
||||
directories: projectDirectories(),
|
||||
limit: HOME_SESSION_LIMIT,
|
||||
}),
|
||||
}
|
||||
},
|
||||
eventSequence,
|
||||
signal,
|
||||
)
|
||||
@@ -79,13 +89,16 @@ export function createHomeSessionsController(home: HomeController) {
|
||||
refetchOnMount: true,
|
||||
refetchOnReconnect: true,
|
||||
}))
|
||||
const indexedSessions = createMemo(() =>
|
||||
retainHomeSessions(
|
||||
homeSessions().sessions(sessionLoad.data, sessionEventLoad.data),
|
||||
const indexedSessions = createMemo(() => {
|
||||
const directories = new Set(projectDirectories().map(pathKey))
|
||||
return takeRecentSessions(
|
||||
homeSessions()
|
||||
.sessions(sessionLoad.data, sessionEventLoad.data)
|
||||
.filter((session) => directories.has(pathKey(session.directory))),
|
||||
HOME_SESSION_LIMIT,
|
||||
Date.now(),
|
||||
),
|
||||
)
|
||||
Number.NEGATIVE_INFINITY,
|
||||
)
|
||||
})
|
||||
const allRecords = createMemo(() =>
|
||||
buildHomeSessionRecords({
|
||||
sessions: indexedSessions,
|
||||
@@ -94,43 +107,21 @@ export function createHomeSessionsController(home: HomeController) {
|
||||
projectByID,
|
||||
}),
|
||||
)
|
||||
const records = createMemo(() => allRecords().slice(0, HOME_SESSION_LIMIT))
|
||||
const groups = createMemo(() => groupSessions(records(), language))
|
||||
const prefetched = new Set<string>()
|
||||
|
||||
const [visible, setVisible] = createSignal(HOME_SESSION_RENDER_BATCH)
|
||||
let revealFrame: number | undefined
|
||||
createEffect(() => {
|
||||
const ctx = home.server.focusedContext()
|
||||
const conn = home.server.focused()
|
||||
if (!ctx || !conn) return
|
||||
records()
|
||||
.slice(0, 2)
|
||||
.forEach((record) => {
|
||||
const key = `${ServerConnection.key(conn)}\0${record.session.id}`
|
||||
if (prefetched.has(key)) return
|
||||
prefetched.add(key)
|
||||
createRoot((dispose) => {
|
||||
try {
|
||||
void ctx.sync.session
|
||||
.sync(record.session.id)
|
||||
.then(() =>
|
||||
Promise.all(
|
||||
(ctx.sync.session.data.message[record.session.id] ?? []).flatMap((message) =>
|
||||
(ctx.sync.session.data.part[message.id] ?? []).flatMap((part) => {
|
||||
if (part.type !== "text" || !part.text) return []
|
||||
return preloadMarkdown(part.text, part.id)
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.catch(() => {})
|
||||
.finally(dispose)
|
||||
} catch {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
const count = Math.min(allRecords().length, HOME_SESSION_LIMIT)
|
||||
if (visible() >= count || revealFrame !== undefined) return
|
||||
revealFrame = requestAnimationFrame(() => {
|
||||
revealFrame = undefined
|
||||
setVisible((current) => Math.min(current + HOME_SESSION_RENDER_BATCH, count))
|
||||
})
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
if (revealFrame !== undefined) cancelAnimationFrame(revealFrame)
|
||||
})
|
||||
const records = createMemo(() => allRecords().slice(0, visible()))
|
||||
const groups = createMemo(() => groupSessions(records(), language))
|
||||
command.register("home.palette", () => [
|
||||
{
|
||||
id: "command.palette",
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { createEffect, Suspense, type ParentProps } from "solid-js"
|
||||
import { createEffect, lazy, Suspense, type ParentProps } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { DebugBar } from "@/components/debug-bar"
|
||||
import { TabsInfoPopup } from "@/components/help-button"
|
||||
import { Titlebar, type TitlebarUpdate } from "@/components/titlebar"
|
||||
import type { TitlebarUpdate } from "@/components/titlebar"
|
||||
import { usePlatform } from "@/context/platform"
|
||||
import { setV2Toast, ToastRegion } from "@/utils/toast"
|
||||
|
||||
const Titlebar = lazy(() => import("@/components/titlebar").then((module) => ({ default: module.Titlebar })))
|
||||
const TabsInfoPopup = lazy(() =>
|
||||
import("@/components/help-button").then((module) => ({ default: module.TabsInfoPopup })),
|
||||
)
|
||||
|
||||
export default function NewLayout(props: ParentProps) {
|
||||
const platform = usePlatform()
|
||||
const [state, setState] = createStore({ debugTools: true })
|
||||
@@ -30,19 +34,23 @@ export default function NewLayout(props: ParentProps) {
|
||||
"padding-bottom": "env(safe-area-inset-bottom, 0px)",
|
||||
}}
|
||||
>
|
||||
<Titlebar
|
||||
update={update}
|
||||
debugTools={
|
||||
import.meta.env.DEV
|
||||
? { visible: state.debugTools, toggle: () => setState("debugTools", (value) => !value) }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<Suspense fallback={<div class="h-10 shrink-0" />}>
|
||||
<Titlebar
|
||||
update={update}
|
||||
debugTools={
|
||||
import.meta.env.DEV
|
||||
? { visible: state.debugTools, toggle: () => setState("debugTools", (value) => !value) }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</Suspense>
|
||||
<main class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-strict">
|
||||
<Suspense>{props.children}</Suspense>
|
||||
</main>
|
||||
{import.meta.env.DEV && state.debugTools && <DebugBar inline />}
|
||||
<TabsInfoPopup />
|
||||
<Suspense>
|
||||
<TabsInfoPopup />
|
||||
</Suspense>
|
||||
<ToastRegion v2 />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -634,7 +634,7 @@ export default function LegacyLayout(props: ParentProps) {
|
||||
running: number
|
||||
}
|
||||
|
||||
const prefetchChunk = 200
|
||||
const prefetchChunk = 50
|
||||
const prefetchConcurrency = 2
|
||||
const prefetchPendingLimit = 10
|
||||
const span = 4
|
||||
@@ -777,18 +777,11 @@ export default function LegacyLayout(props: ParentProps) {
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (params.id) return
|
||||
const sessions = currentSessions()
|
||||
if (sessions.length === 0) return
|
||||
|
||||
const index = params.id ? sessions.findIndex((s) => s.id === params.id) : 0
|
||||
if (index === -1) return
|
||||
|
||||
if (!params.id) {
|
||||
const first = sessions[index]
|
||||
if (first) prefetchSession(first, "high")
|
||||
}
|
||||
|
||||
warm(sessions, index)
|
||||
const first = sessions[0]
|
||||
if (first) prefetchSession(first, "high")
|
||||
})
|
||||
|
||||
function navigateSessionByOffset(offset: number) {
|
||||
|
||||
@@ -143,7 +143,7 @@ function ProviderTip() {
|
||||
<TooltipV2
|
||||
class="hover-reveal absolute left-full top-0 flex h-6 w-7 items-center justify-end delay-0 duration-0 group-hover/provider-tip:delay-[250ms] group-hover/provider-tip:duration-150 group-hover/provider-tip:opacity-100 focus-within:delay-0 focus-within:duration-0 focus-within:opacity-100"
|
||||
placement="top"
|
||||
openDelay={1000}
|
||||
delay="intent"
|
||||
value={language.t("common.dismiss")}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -690,8 +690,12 @@ export default function Page() {
|
||||
queryFn: mode
|
||||
? () =>
|
||||
sdk()
|
||||
.api.vcs.diff({ location: { directory: sdk().directory }, mode: mode === "git" ? "working" : mode })
|
||||
.then((result) => result.data)
|
||||
.api.vcs.diff({
|
||||
location: { directory: sdk().directory },
|
||||
mode: mode === "git" ? "working" : mode,
|
||||
context: 0,
|
||||
})
|
||||
.then((result) => result.data.map((diff) => ({ ...diff, patch: "" })))
|
||||
.catch((error) => {
|
||||
console.debug("[session-review] failed to load vcs diff", { mode, error })
|
||||
return []
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { createApiForServer, createSdkForServer } from "./server"
|
||||
import { createCompatibleApi } from "./server-compat"
|
||||
import { decodeVcsDiffData } from "./vcs-diff-data"
|
||||
import { decodeLegacySessionList } from "@/context/session-message-decode"
|
||||
|
||||
function setup(
|
||||
protocol: "v1" | "v2" | Promise<"v1" | "v2">,
|
||||
@@ -48,6 +50,8 @@ function setup(
|
||||
current: createApiForServer({ server, fetch: fetcher }),
|
||||
legacy: (directory) => createSdkForServer({ server, fetch: fetcher, directory, throwOnError: true }),
|
||||
directory: "/repo",
|
||||
decodeVcsDiff: async (buffer) => decodeVcsDiffData(buffer),
|
||||
decodeSessionList: async (buffer) => decodeLegacySessionList(buffer),
|
||||
})
|
||||
return { api, requests }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { ServerApi } from "./server"
|
||||
import type { ServerProtocol } from "./server-protocol"
|
||||
import type { AgentPartInput, FilePartInput, OpencodeClient, Session, TextPartInput } from "@opencode-ai/sdk/v2/client"
|
||||
import type { AgentPartInput, FilePartInput, OpencodeClient, TextPartInput } from "@opencode-ai/sdk/v2/client"
|
||||
import type {
|
||||
FileDiffInfo,
|
||||
Project,
|
||||
ProjectCurrent,
|
||||
SessionApi,
|
||||
@@ -15,6 +16,7 @@ import type {
|
||||
SessionShellInput,
|
||||
SessionShellOutput,
|
||||
} from "@opencode-ai/client/promise"
|
||||
import { legacySessionInfo } from "@/context/session-message-decode"
|
||||
|
||||
type LegacyClient = OpencodeClient
|
||||
type LegacyFor = (directory?: string) => LegacyClient
|
||||
@@ -51,6 +53,8 @@ type CompatibleInput = {
|
||||
current: ServerApi
|
||||
legacy: LegacyFor
|
||||
directory?: string
|
||||
decodeVcsDiff: (buffer: ArrayBuffer) => Promise<FileDiffInfo[]>
|
||||
decodeSessionList: (buffer: ArrayBuffer) => Promise<SessionInfo[]>
|
||||
}
|
||||
|
||||
function mime(uri: string) {
|
||||
@@ -58,31 +62,6 @@ function mime(uri: string) {
|
||||
return match?.[1] ?? "application/octet-stream"
|
||||
}
|
||||
|
||||
function sessionInfo(session: Session): SessionInfo {
|
||||
return {
|
||||
id: session.id,
|
||||
parentID: session.parentID,
|
||||
projectID: session.projectID,
|
||||
agent: session.agent,
|
||||
model: session.model && {
|
||||
id: session.model.id,
|
||||
providerID: session.model.providerID,
|
||||
variant: session.model.variant,
|
||||
},
|
||||
cost: session.cost ?? 0,
|
||||
tokens: session.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: session.time,
|
||||
title: session.title,
|
||||
location: { directory: session.directory, workspaceID: session.workspaceID },
|
||||
subpath: session.path,
|
||||
revert: session.revert && {
|
||||
messageID: session.revert.messageID,
|
||||
partID: session.revert.partID,
|
||||
snapshot: session.revert.snapshot,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function createCompatibleApi(input: CompatibleInput): CompatibleApi {
|
||||
const v1 = createV1Api(input)
|
||||
return lazyApi(
|
||||
@@ -148,29 +127,34 @@ function createV1Api(input: CompatibleInput): CompatibleApi {
|
||||
search: value.search,
|
||||
limit: value.limit,
|
||||
},
|
||||
options,
|
||||
{ ...options, parseAs: "arrayBuffer" },
|
||||
)
|
||||
return { data: (result.data ?? []).map(sessionInfo), cursor: {} }
|
||||
if (!(result.data instanceof ArrayBuffer)) throw new Error("Session list response is not an ArrayBuffer")
|
||||
return { data: await input.decodeSessionList(result.data), cursor: {} }
|
||||
}
|
||||
const result = await legacy({ directory: value?.directory }).session.list({
|
||||
directory: value?.directory,
|
||||
roots: value?.parentID === null ? true : undefined,
|
||||
search: value?.search,
|
||||
limit: value?.limit,
|
||||
})
|
||||
return { data: (result.data ?? []).map(sessionInfo), cursor: {} }
|
||||
const result = await legacy({ directory: value?.directory }).session.list(
|
||||
{
|
||||
directory: value?.directory,
|
||||
roots: value?.parentID === null ? true : undefined,
|
||||
search: value?.search,
|
||||
limit: value?.limit,
|
||||
},
|
||||
{ parseAs: "arrayBuffer" },
|
||||
)
|
||||
if (!(result.data instanceof ArrayBuffer)) throw new Error("Session list response is not an ArrayBuffer")
|
||||
return { data: await input.decodeSessionList(result.data), cursor: {} }
|
||||
},
|
||||
async create(value?: Parameters<ServerApi["session"]["create"]>[0]) {
|
||||
const result = await legacy(value?.location ?? undefined).session.create({
|
||||
directory: directory(value?.location ?? undefined),
|
||||
})
|
||||
if (!result.data) throw new Error("Failed to create session")
|
||||
return sessionInfo(result.data)
|
||||
return legacySessionInfo(result.data)
|
||||
},
|
||||
async get(value: Parameters<ServerApi["session"]["get"]>[0]) {
|
||||
const result = await legacy().session.get(value)
|
||||
if (!result.data) throw new Error(`Session not found: ${value.sessionID}`)
|
||||
return sessionInfo(result.data)
|
||||
return legacySessionInfo(result.data)
|
||||
},
|
||||
async active() {
|
||||
const result = await legacy().session.status()
|
||||
@@ -192,7 +176,7 @@ function createV1Api(input: CompatibleInput): CompatibleApi {
|
||||
async fork(value: Parameters<ServerApi["session"]["fork"]>[0]) {
|
||||
const result = await legacy().session.fork(value)
|
||||
if (!result.data) throw new Error("Failed to fork session")
|
||||
return sessionInfo(result.data)
|
||||
return legacySessionInfo(result.data)
|
||||
},
|
||||
async interrupt(value: Parameters<ServerApi["session"]["interrupt"]>[0]) {
|
||||
await legacy().session.abort(value)
|
||||
@@ -341,20 +325,15 @@ function createV1Api(input: CompatibleInput): CompatibleApi {
|
||||
return located(result.data ?? [], value?.location)
|
||||
},
|
||||
async diff(value: Parameters<ServerApi["vcs"]["diff"]>[0]) {
|
||||
const result = await legacy(value.location).vcs.diff({
|
||||
mode: value.mode === "working" ? "git" : value.mode,
|
||||
context: value.context,
|
||||
})
|
||||
return located(
|
||||
(result.data ?? []).map((file) => ({
|
||||
file: file.file,
|
||||
patch: file.patch ?? "",
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
status: file.status ?? "modified",
|
||||
})),
|
||||
value.location,
|
||||
const result = await legacy(value.location).vcs.diff(
|
||||
{
|
||||
mode: value.mode === "working" ? "git" : value.mode,
|
||||
context: value.context,
|
||||
},
|
||||
{ parseAs: "arrayBuffer" },
|
||||
)
|
||||
if (!(result.data instanceof ArrayBuffer)) throw new Error("VCS diff response is not an ArrayBuffer")
|
||||
return located(await input.decodeVcsDiff(result.data), value.location)
|
||||
},
|
||||
},
|
||||
file: {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
||||
|
||||
export function decodeVcsDiffData(buffer: ArrayBuffer): FileDiffInfo[] {
|
||||
const text = new TextDecoder().decode(buffer)
|
||||
return (text ? JSON.parse(text) : []).map(
|
||||
(file: {
|
||||
file: string
|
||||
patch?: string
|
||||
additions: number
|
||||
deletions: number
|
||||
status?: "added" | "deleted" | "modified"
|
||||
}) => ({
|
||||
file: file.file,
|
||||
patch: file.patch ?? "",
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
status: file.status ?? "modified",
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
||||
|
||||
type Response = { id: number; data?: FileDiffInfo[]; error?: string }
|
||||
|
||||
let worker: Worker | undefined
|
||||
let nextID = 0
|
||||
const pending = new Map<number, { resolve: (value: FileDiffInfo[]) => void; reject: (error: Error) => void }>()
|
||||
let lastInput = 0
|
||||
document.addEventListener(
|
||||
"beforeinput",
|
||||
() => {
|
||||
lastInput = performance.now()
|
||||
},
|
||||
{ capture: true },
|
||||
)
|
||||
|
||||
export function decodeVcsDiff(buffer: ArrayBuffer) {
|
||||
const id = ++nextID
|
||||
return new Promise<FileDiffInfo[]>((resolve, reject) => {
|
||||
pending.set(id, { resolve, reject })
|
||||
getWorker().postMessage({ id, buffer }, [buffer])
|
||||
})
|
||||
}
|
||||
|
||||
function getWorker() {
|
||||
if (worker) return worker
|
||||
worker = new Worker(new URL("./vcs-diff-decoder.worker.ts", import.meta.url), { type: "module" })
|
||||
worker.onmessage = (event: MessageEvent<Response>) => {
|
||||
const request = pending.get(event.data.id)
|
||||
if (!request) return
|
||||
pending.delete(event.data.id)
|
||||
if (event.data.error) {
|
||||
request.reject(new Error(event.data.error))
|
||||
return
|
||||
}
|
||||
resolveWhenInputIdle(request.resolve, event.data.data ?? [])
|
||||
}
|
||||
worker.onerror = (event) => {
|
||||
const error = new Error(event.message)
|
||||
pending.forEach((request) => request.reject(error))
|
||||
pending.clear()
|
||||
worker?.terminate()
|
||||
worker = undefined
|
||||
}
|
||||
return worker
|
||||
}
|
||||
|
||||
function resolveWhenInputIdle(resolve: (value: FileDiffInfo[]) => void, value: FileDiffInfo[], initial = true) {
|
||||
const active = document.activeElement
|
||||
const editing =
|
||||
active instanceof HTMLInputElement ||
|
||||
active instanceof HTMLTextAreaElement ||
|
||||
(active instanceof HTMLElement && active.isContentEditable)
|
||||
const delay = Math.max(lastInput + 100 - performance.now(), initial && editing ? 100 : 0)
|
||||
if (delay <= 0) {
|
||||
resolve(value)
|
||||
return
|
||||
}
|
||||
setTimeout(() => resolveWhenInputIdle(resolve, value, false), delay)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { decodeVcsDiffData } from "./vcs-diff-data"
|
||||
|
||||
type Request = { id: number; buffer: ArrayBuffer }
|
||||
|
||||
self.onmessage = (event: MessageEvent<Request>) => {
|
||||
try {
|
||||
self.postMessage({ id: event.data.id, data: decodeVcsDiffData(event.data.buffer) })
|
||||
} catch (error) {
|
||||
self.postMessage({ id: event.data.id, error: error instanceof Error ? error.message : String(error) })
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
@@ -142,8 +142,11 @@ const main = Effect.gen(function* () {
|
||||
app.setAppUserModelId(appId)
|
||||
app.setPath(
|
||||
"userData",
|
||||
onboardingTestRoot ? join(onboardingTestRoot, "desktop") : join(app.getPath("appData"), appId),
|
||||
process.env.OPENCODE_PROFILE_USER_DATA ??
|
||||
(onboardingTestRoot ? join(onboardingTestRoot, "desktop") : join(app.getPath("appData"), appId)),
|
||||
)
|
||||
if (process.env.OPENCODE_PROFILE_USER_DATA)
|
||||
app.setPath("sessionData", join(process.env.OPENCODE_PROFILE_USER_DATA, "session"))
|
||||
if (onboardingTestRoot) app.setPath("sessionData", join(onboardingTestRoot, "session"))
|
||||
initializeOldLayoutEligibility(app.getPath("userData"))
|
||||
logger = initLogging()
|
||||
@@ -191,9 +194,16 @@ const main = Effect.gen(function* () {
|
||||
ensureLoopbackNoProxy()
|
||||
useEnvProxy()
|
||||
app.commandLine.appendSwitch("proxy-bypass-list", "<-loopback>")
|
||||
const features = app.commandLine.getSwitchValue("enable-features")
|
||||
app.commandLine.appendSwitch("enable-features", features ? `${jsCallStackFeature},${features}` : jsCallStackFeature)
|
||||
if (!app.isPackaged) app.commandLine.appendSwitch("remote-debugging-port", "9222")
|
||||
const features = [
|
||||
jsCallStackFeature,
|
||||
process.env.OPENCODE_PROFILE_LOAF === "1" ? "AlwaysLogLOAFURL" : "",
|
||||
app.commandLine.getSwitchValue("enable-features"),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(",")
|
||||
app.commandLine.appendSwitch("enable-features", features)
|
||||
if (!app.isPackaged)
|
||||
app.commandLine.appendSwitch("remote-debugging-port", process.env.OPENCODE_PROFILE_CDP_PORT ?? "9222")
|
||||
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
|
||||
@@ -1,62 +1,7 @@
|
||||
import * as i18n from "@solid-primitives/i18n"
|
||||
|
||||
import { dict as desktopEn } from "./en"
|
||||
import { dict as desktopZh } from "./zh"
|
||||
import { dict as desktopZht } from "./zht"
|
||||
import { dict as desktopKo } from "./ko"
|
||||
import { dict as desktopDe } from "./de"
|
||||
import { dict as desktopEs } from "./es"
|
||||
import { dict as desktopFr } from "./fr"
|
||||
import { dict as desktopDa } from "./da"
|
||||
import { dict as desktopJa } from "./ja"
|
||||
import { dict as desktopPl } from "./pl"
|
||||
import { dict as desktopRu } from "./ru"
|
||||
import { dict as desktopUk } from "./uk"
|
||||
import { dict as desktopAr } from "./ar"
|
||||
import { dict as desktopNo } from "./no"
|
||||
import { dict as desktopBr } from "./br"
|
||||
import { dict as desktopBs } from "./bs"
|
||||
import { dict as desktopTr } from "./tr"
|
||||
import { dict as desktopHi } from "./hi"
|
||||
import { dict as desktopNl } from "./nl"
|
||||
import { dict as desktopId } from "./id"
|
||||
import { dict as desktopVi } from "./vi"
|
||||
import { dict as desktopIt } from "./it"
|
||||
import { dict as desktopUr } from "./ur"
|
||||
import { dict as desktopPa } from "./pa"
|
||||
import { dict as desktopAz } from "./az"
|
||||
import { dict as desktopFi } from "./fi"
|
||||
import { dict as desktopSv } from "./sv"
|
||||
import { dict as desktopTh } from "./th"
|
||||
|
||||
import { dict as appEn } from "../../../../app/src/i18n/en"
|
||||
import { dict as appZh } from "../../../../app/src/i18n/zh"
|
||||
import { dict as appZht } from "../../../../app/src/i18n/zht"
|
||||
import { dict as appKo } from "../../../../app/src/i18n/ko"
|
||||
import { dict as appDe } from "../../../../app/src/i18n/de"
|
||||
import { dict as appEs } from "../../../../app/src/i18n/es"
|
||||
import { dict as appFr } from "../../../../app/src/i18n/fr"
|
||||
import { dict as appDa } from "../../../../app/src/i18n/da"
|
||||
import { dict as appJa } from "../../../../app/src/i18n/ja"
|
||||
import { dict as appPl } from "../../../../app/src/i18n/pl"
|
||||
import { dict as appRu } from "../../../../app/src/i18n/ru"
|
||||
import { dict as appUk } from "../../../../app/src/i18n/uk"
|
||||
import { dict as appAr } from "../../../../app/src/i18n/ar"
|
||||
import { dict as appNo } from "../../../../app/src/i18n/no"
|
||||
import { dict as appBr } from "../../../../app/src/i18n/br"
|
||||
import { dict as appBs } from "../../../../app/src/i18n/bs"
|
||||
import { dict as appTr } from "../../../../app/src/i18n/tr"
|
||||
import { dict as appHi } from "../../../../app/src/i18n/hi"
|
||||
import { dict as appNl } from "../../../../app/src/i18n/nl"
|
||||
import { dict as appId } from "../../../../app/src/i18n/id"
|
||||
import { dict as appVi } from "../../../../app/src/i18n/vi"
|
||||
import { dict as appIt } from "../../../../app/src/i18n/it"
|
||||
import { dict as appUr } from "../../../../app/src/i18n/ur"
|
||||
import { dict as appPa } from "../../../../app/src/i18n/pa"
|
||||
import { dict as appAz } from "../../../../app/src/i18n/az"
|
||||
import { dict as appFi } from "../../../../app/src/i18n/fi"
|
||||
import { dict as appSv } from "../../../../app/src/i18n/sv"
|
||||
import { dict as appTh } from "../../../../app/src/i18n/th"
|
||||
|
||||
export type Locale =
|
||||
| "en"
|
||||
@@ -217,35 +162,40 @@ function pickLocale(value: unknown): Locale | null {
|
||||
|
||||
const base = i18n.flatten({ ...appEn, ...desktopEn })
|
||||
|
||||
function build(locale: Locale): Dictionary {
|
||||
const loaders = {
|
||||
zh: () => Promise.all([import("../../../../app/src/i18n/zh"), import("./zh")]),
|
||||
zht: () => Promise.all([import("../../../../app/src/i18n/zht"), import("./zht")]),
|
||||
ko: () => Promise.all([import("../../../../app/src/i18n/ko"), import("./ko")]),
|
||||
de: () => Promise.all([import("../../../../app/src/i18n/de"), import("./de")]),
|
||||
es: () => Promise.all([import("../../../../app/src/i18n/es"), import("./es")]),
|
||||
fr: () => Promise.all([import("../../../../app/src/i18n/fr"), import("./fr")]),
|
||||
da: () => Promise.all([import("../../../../app/src/i18n/da"), import("./da")]),
|
||||
ja: () => Promise.all([import("../../../../app/src/i18n/ja"), import("./ja")]),
|
||||
pl: () => Promise.all([import("../../../../app/src/i18n/pl"), import("./pl")]),
|
||||
ru: () => Promise.all([import("../../../../app/src/i18n/ru"), import("./ru")]),
|
||||
uk: () => Promise.all([import("../../../../app/src/i18n/uk"), import("./uk")]),
|
||||
ar: () => Promise.all([import("../../../../app/src/i18n/ar"), import("./ar")]),
|
||||
no: () => Promise.all([import("../../../../app/src/i18n/no"), import("./no")]),
|
||||
br: () => Promise.all([import("../../../../app/src/i18n/br"), import("./br")]),
|
||||
bs: () => Promise.all([import("../../../../app/src/i18n/bs"), import("./bs")]),
|
||||
tr: () => Promise.all([import("../../../../app/src/i18n/tr"), import("./tr")]),
|
||||
hi: () => Promise.all([import("../../../../app/src/i18n/hi"), import("./hi")]),
|
||||
nl: () => Promise.all([import("../../../../app/src/i18n/nl"), import("./nl")]),
|
||||
id: () => Promise.all([import("../../../../app/src/i18n/id"), import("./id")]),
|
||||
vi: () => Promise.all([import("../../../../app/src/i18n/vi"), import("./vi")]),
|
||||
it: () => Promise.all([import("../../../../app/src/i18n/it"), import("./it")]),
|
||||
ur: () => Promise.all([import("../../../../app/src/i18n/ur"), import("./ur")]),
|
||||
pa: () => Promise.all([import("../../../../app/src/i18n/pa"), import("./pa")]),
|
||||
az: () => Promise.all([import("../../../../app/src/i18n/az"), import("./az")]),
|
||||
fi: () => Promise.all([import("../../../../app/src/i18n/fi"), import("./fi")]),
|
||||
sv: () => Promise.all([import("../../../../app/src/i18n/sv"), import("./sv")]),
|
||||
th: () => Promise.all([import("../../../../app/src/i18n/th"), import("./th")]),
|
||||
}
|
||||
|
||||
async function build(locale: Locale): Promise<Dictionary> {
|
||||
if (locale === "en") return base
|
||||
if (locale === "zh") return { ...base, ...i18n.flatten(appZh), ...i18n.flatten(desktopZh) }
|
||||
if (locale === "zht") return { ...base, ...i18n.flatten(appZht), ...i18n.flatten(desktopZht) }
|
||||
if (locale === "de") return { ...base, ...i18n.flatten(appDe), ...i18n.flatten(desktopDe) }
|
||||
if (locale === "es") return { ...base, ...i18n.flatten(appEs), ...i18n.flatten(desktopEs) }
|
||||
if (locale === "fr") return { ...base, ...i18n.flatten(appFr), ...i18n.flatten(desktopFr) }
|
||||
if (locale === "da") return { ...base, ...i18n.flatten(appDa), ...i18n.flatten(desktopDa) }
|
||||
if (locale === "ja") return { ...base, ...i18n.flatten(appJa), ...i18n.flatten(desktopJa) }
|
||||
if (locale === "pl") return { ...base, ...i18n.flatten(appPl), ...i18n.flatten(desktopPl) }
|
||||
if (locale === "ru") return { ...base, ...i18n.flatten(appRu), ...i18n.flatten(desktopRu) }
|
||||
if (locale === "uk") return { ...base, ...i18n.flatten(appUk), ...i18n.flatten(desktopUk) }
|
||||
if (locale === "ar") return { ...base, ...i18n.flatten(appAr), ...i18n.flatten(desktopAr) }
|
||||
if (locale === "no") return { ...base, ...i18n.flatten(appNo), ...i18n.flatten(desktopNo) }
|
||||
if (locale === "br") return { ...base, ...i18n.flatten(appBr), ...i18n.flatten(desktopBr) }
|
||||
if (locale === "bs") return { ...base, ...i18n.flatten(appBs), ...i18n.flatten(desktopBs) }
|
||||
if (locale === "tr") return { ...base, ...i18n.flatten(appTr), ...i18n.flatten(desktopTr) }
|
||||
if (locale === "hi") return { ...base, ...i18n.flatten(appHi), ...i18n.flatten(desktopHi) }
|
||||
if (locale === "nl") return { ...base, ...i18n.flatten(appNl), ...i18n.flatten(desktopNl) }
|
||||
if (locale === "id") return { ...base, ...i18n.flatten(appId), ...i18n.flatten(desktopId) }
|
||||
if (locale === "vi") return { ...base, ...i18n.flatten(appVi), ...i18n.flatten(desktopVi) }
|
||||
if (locale === "it") return { ...base, ...i18n.flatten(appIt), ...i18n.flatten(desktopIt) }
|
||||
if (locale === "ur") return { ...base, ...i18n.flatten(appUr), ...i18n.flatten(desktopUr) }
|
||||
if (locale === "pa") return { ...base, ...i18n.flatten(appPa), ...i18n.flatten(desktopPa) }
|
||||
if (locale === "az") return { ...base, ...i18n.flatten(appAz), ...i18n.flatten(desktopAz) }
|
||||
if (locale === "fi") return { ...base, ...i18n.flatten(appFi), ...i18n.flatten(desktopFi) }
|
||||
if (locale === "sv") return { ...base, ...i18n.flatten(appSv), ...i18n.flatten(desktopSv) }
|
||||
if (locale === "th") return { ...base, ...i18n.flatten(appTh), ...i18n.flatten(desktopTh) }
|
||||
return { ...base, ...i18n.flatten(appKo), ...i18n.flatten(desktopKo) }
|
||||
const dictionaries = await loaders[locale]()
|
||||
return { ...base, ...i18n.flatten(dictionaries[0].dict), ...i18n.flatten(dictionaries[1].dict) }
|
||||
}
|
||||
|
||||
const state = {
|
||||
@@ -254,8 +204,6 @@ const state = {
|
||||
init: undefined as Promise<Locale> | undefined,
|
||||
}
|
||||
|
||||
state.dict = build(state.locale)
|
||||
|
||||
const translate = i18n.translator(() => state.dict, i18n.resolveTemplate)
|
||||
|
||||
export function t(key: keyof Dictionary, params?: Record<string, string | number>) {
|
||||
@@ -272,7 +220,7 @@ export function initI18n(): Promise<Locale> {
|
||||
const next = pickLocale(value) ?? state.locale
|
||||
|
||||
state.locale = next
|
||||
state.dict = build(next)
|
||||
state.dict = await build(next)
|
||||
return next
|
||||
})().catch(() => state.locale)
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ import { createMemoryHistory, MemoryRouter, type BaseRouterProps } from "@solidj
|
||||
import { createEffect, createMemo, createResource, createSignal, onCleanup, Show } from "solid-js"
|
||||
import { render } from "solid-js/web"
|
||||
import pkg from "../../package.json"
|
||||
import { t } from "./i18n"
|
||||
import { initI18n, t } from "./i18n"
|
||||
import { initializationData } from "./initialization"
|
||||
import { DesktopFirstLaunchOnboarding } from "./onboarding"
|
||||
import { resetZoom, setPinchZoomEnabled, webviewZoom, zoomIn, zoomOut } from "./webview-zoom"
|
||||
@@ -60,6 +60,8 @@ if (import.meta.env.VITE_SENTRY_DSN) {
|
||||
})
|
||||
}
|
||||
|
||||
void initI18n()
|
||||
|
||||
const [updaterState, setUpdaterState] = createSignal<UpdaterState>({ status: "disabled" })
|
||||
void window.api.updater.subscribe(setUpdaterState)
|
||||
|
||||
|
||||
@@ -656,7 +656,7 @@ function makeUsageService(sdk: OpencodeClient) {
|
||||
sessionId: params.sessionID,
|
||||
update: {
|
||||
sessionUpdate: "usage_update",
|
||||
used: message.tokens.input + message.tokens.cache.read,
|
||||
used: UsageService.contextTokens(message),
|
||||
size,
|
||||
cost: { amount: UsageService.totalSessionCost(messages), currency: "USD" },
|
||||
},
|
||||
|
||||
@@ -83,6 +83,10 @@ export function messageLoaderFromSDK(sdk: SDK): MessageLoaderInterface {
|
||||
|
||||
export const messageLoaderLayer = (sdk: SDK) => Layer.succeed(MessageLoader, messageLoaderFromSDK(sdk))
|
||||
|
||||
export function contextTokens(message: AssistantTokenCost): number {
|
||||
return message.tokens.input + message.tokens.cache.read + message.tokens.cache.write
|
||||
}
|
||||
|
||||
export function buildUsage(message: AssistantTokenCost): Usage {
|
||||
const cachedReadTokens = message.tokens.cache.read
|
||||
const cachedWriteTokens = message.tokens.cache.write
|
||||
@@ -207,7 +211,7 @@ const layer = Layer.effect(
|
||||
sessionId: input.sessionID,
|
||||
update: {
|
||||
sessionUpdate: "usage_update",
|
||||
used: message.tokens.input + message.tokens.cache.read,
|
||||
used: contextTokens(message),
|
||||
size,
|
||||
cost: { amount: totalSessionCost(messages), currency: "USD" },
|
||||
},
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
|
||||
import { OAUTH_DUMMY_KEY } from "../auth"
|
||||
import { createServer } from "http"
|
||||
import { InstallationVersion } from "@opencode-ai/core/installation/version"
|
||||
import { OauthCallbackPage } from "@opencode-ai/core/oauth/page"
|
||||
|
||||
// Public Grok-CLI OAuth client. xAI's auth server rejects loopback OAuth from
|
||||
// non-allowlisted clients, so we reuse the Grok-CLI client_id that xAI ships
|
||||
// for desktop OAuth flows. Source of truth: hermes-agent PR #26534.
|
||||
// Public Grok-CLI OAuth client.
|
||||
const CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
|
||||
const AUTHORIZE_URL = "https://auth.x.ai/oauth2/authorize"
|
||||
const TOKEN_URL = "https://auth.x.ai/oauth2/token"
|
||||
// RFC 8628 device authorization grant. Confirmed exposed by xAI's
|
||||
// /.well-known/openid-configuration as `device_authorization_endpoint`
|
||||
@@ -30,51 +25,15 @@ const DEVICE_CODE_SLOW_DOWN_INCREMENT_MS = 5_000
|
||||
const DEVICE_CODE_DEFAULT_EXPIRES_MS = 5 * 60 * 1000
|
||||
const OAUTH_POLLING_SAFETY_MARGIN_MS = 3_000
|
||||
|
||||
// xAI rejects redirect_uris that don't match what was registered for the
|
||||
// Grok-CLI client. The host:port pair is part of the registration, so we have
|
||||
// to bind the loopback server to this exact port.
|
||||
const OAUTH_HOST = "127.0.0.1"
|
||||
const OAUTH_PORT = 56121
|
||||
const OAUTH_REDIRECT_PATH = "/callback"
|
||||
const REDIRECT_URI = `http://${OAUTH_HOST}:${OAUTH_PORT}${OAUTH_REDIRECT_PATH}`
|
||||
|
||||
// Refresh the access token a little before it actually expires so a single
|
||||
// long-running tool call doesn't have to recover from a mid-flight 401.
|
||||
const ACCESS_TOKEN_REFRESH_SKEW_MS = 120_000
|
||||
|
||||
interface XaiAuthPluginOptions {
|
||||
authorizeUrl?: string
|
||||
tokenUrl?: string
|
||||
deviceAuthorizationUrl?: string
|
||||
}
|
||||
|
||||
interface PkceCodes {
|
||||
verifier: string
|
||||
challenge: string
|
||||
}
|
||||
|
||||
async function generatePKCE(): Promise<PkceCodes> {
|
||||
const verifier = generateRandomString(64)
|
||||
const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
|
||||
return { verifier, challenge: base64UrlEncode(hash) }
|
||||
}
|
||||
|
||||
function generateRandomString(length: number): string {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
|
||||
return Array.from(crypto.getRandomValues(new Uint8Array(length)))
|
||||
.map((b) => chars[b % chars.length])
|
||||
.join("")
|
||||
}
|
||||
|
||||
function base64UrlEncode(buffer: ArrayBuffer): string {
|
||||
const binary = String.fromCharCode(...new Uint8Array(buffer))
|
||||
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
|
||||
}
|
||||
|
||||
function generateState(): string {
|
||||
return base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
|
||||
}
|
||||
|
||||
interface TokenResponse {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
@@ -115,55 +74,6 @@ export function accessTokenIsExpiring(
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAuthorizeUrl(
|
||||
pkce: PkceCodes,
|
||||
state: string,
|
||||
nonce: string,
|
||||
options: XaiAuthPluginOptions = {},
|
||||
): string {
|
||||
// `plan=generic` opts the consent screen into xAI's generic OAuth plan tier;
|
||||
// without it, accounts.x.ai rejects loopback OAuth from non-allowlisted
|
||||
// clients. `referrer=opencode` lets xAI attribute opencode-originated
|
||||
// logins in their OAuth server logs (best-effort attribution while we
|
||||
// continue to reuse the Grok-CLI client_id).
|
||||
const params = new URLSearchParams({
|
||||
response_type: "code",
|
||||
client_id: CLIENT_ID,
|
||||
redirect_uri: REDIRECT_URI,
|
||||
scope: SCOPE,
|
||||
code_challenge: pkce.challenge,
|
||||
code_challenge_method: "S256",
|
||||
state,
|
||||
nonce,
|
||||
plan: "generic",
|
||||
referrer: "opencode",
|
||||
})
|
||||
return `${options.authorizeUrl ?? AUTHORIZE_URL}?${params.toString()}`
|
||||
}
|
||||
|
||||
async function exchangeCodeForTokens(
|
||||
code: string,
|
||||
pkce: PkceCodes,
|
||||
options: XaiAuthPluginOptions = {},
|
||||
): Promise<TokenResponse> {
|
||||
const response = await fetch(options.tokenUrl ?? TOKEN_URL, {
|
||||
method: "POST",
|
||||
headers: authHeaders(),
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: REDIRECT_URI,
|
||||
client_id: CLIENT_ID,
|
||||
code_verifier: pkce.verifier,
|
||||
}).toString(),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const detail = await response.text().catch(() => "")
|
||||
throw new Error(`xAI token exchange failed (${response.status})${detail ? `: ${detail}` : ""}`)
|
||||
}
|
||||
return response.json() as Promise<TokenResponse>
|
||||
}
|
||||
|
||||
async function refreshAccessToken(refreshToken: string, options: XaiAuthPluginOptions = {}): Promise<TokenResponse> {
|
||||
const response = await fetch(options.tokenUrl ?? TOKEN_URL, {
|
||||
method: "POST",
|
||||
@@ -202,6 +112,7 @@ export async function requestDeviceCode(options: XaiAuthPluginOptions = {}): Pro
|
||||
body: new URLSearchParams({
|
||||
client_id: CLIENT_ID,
|
||||
scope: SCOPE,
|
||||
referrer: "opencode",
|
||||
}).toString(),
|
||||
})
|
||||
if (!response.ok) {
|
||||
@@ -285,170 +196,6 @@ export async function pollDeviceCodeToken(
|
||||
throw new Error("xAI device authorization timed out")
|
||||
}
|
||||
|
||||
// CORS allowlist for the loopback callback. The redirect_uri itself is
|
||||
// already bound to 127.0.0.1 and gated by PKCE+state, so we only accept
|
||||
// xAI's own auth origins for additional defense-in-depth on the OPTIONS
|
||||
// preflight.
|
||||
const CORS_ALLOWED_ORIGINS = new Set(["https://accounts.x.ai", "https://auth.x.ai"])
|
||||
|
||||
interface PendingOAuth {
|
||||
pkce: PkceCodes
|
||||
state: string
|
||||
resolve: (tokens: TokenResponse) => void
|
||||
reject: (error: Error) => void
|
||||
}
|
||||
|
||||
let oauthServer: ReturnType<typeof createServer> | undefined
|
||||
let pendingOAuth: PendingOAuth | undefined
|
||||
|
||||
async function startOAuthServer(): Promise<{ port: number; redirectUri: string }> {
|
||||
if (oauthServer) return { port: OAUTH_PORT, redirectUri: REDIRECT_URI }
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const reqUrl = req.url || "/"
|
||||
const url = new URL(reqUrl, `http://${OAUTH_HOST}:${OAUTH_PORT}`)
|
||||
|
||||
const origin = req.headers["origin"]
|
||||
const allowOrigin = typeof origin === "string" && CORS_ALLOWED_ORIGINS.has(origin) ? origin : ""
|
||||
if (allowOrigin) {
|
||||
res.setHeader("Access-Control-Allow-Origin", allowOrigin)
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type")
|
||||
res.setHeader("Access-Control-Allow-Private-Network", "true")
|
||||
res.setHeader("Vary", "Origin")
|
||||
}
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
res.writeHead(204)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname === OAUTH_REDIRECT_PATH) {
|
||||
const code = url.searchParams.get("code")
|
||||
const state = url.searchParams.get("state")
|
||||
const error = url.searchParams.get("error")
|
||||
const errorDescription = url.searchParams.get("error_description")
|
||||
|
||||
if (error) {
|
||||
const errorMsg = errorDescription || error
|
||||
pendingOAuth?.reject(new Error(errorMsg))
|
||||
pendingOAuth = undefined
|
||||
res.writeHead(200, { "Content-Type": "text/html" })
|
||||
res.end(OauthCallbackPage.error(errorMsg, { provider: "xAI" }))
|
||||
return
|
||||
}
|
||||
|
||||
if (!code) {
|
||||
const errorMsg = "Missing authorization code"
|
||||
pendingOAuth?.reject(new Error(errorMsg))
|
||||
pendingOAuth = undefined
|
||||
res.writeHead(400, { "Content-Type": "text/html" })
|
||||
res.end(OauthCallbackPage.error(errorMsg, { provider: "xAI" }))
|
||||
return
|
||||
}
|
||||
|
||||
if (!pendingOAuth || state !== pendingOAuth.state) {
|
||||
const errorMsg = "Invalid state - potential CSRF attack"
|
||||
pendingOAuth?.reject(new Error(errorMsg))
|
||||
pendingOAuth = undefined
|
||||
res.writeHead(400, { "Content-Type": "text/html" })
|
||||
res.end(OauthCallbackPage.error(errorMsg, { provider: "xAI" }))
|
||||
return
|
||||
}
|
||||
|
||||
const current = pendingOAuth
|
||||
pendingOAuth = undefined
|
||||
|
||||
exchangeCodeForTokens(code, current.pkce)
|
||||
.then((tokens) => current.resolve(tokens))
|
||||
.catch((err) => current.reject(err))
|
||||
|
||||
res.writeHead(200, { "Content-Type": "text/html" })
|
||||
res.end(OauthCallbackPage.success({ provider: "xAI" }))
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname === "/cancel") {
|
||||
pendingOAuth?.reject(new Error("Login cancelled"))
|
||||
pendingOAuth = undefined
|
||||
res.writeHead(200)
|
||||
res.end("Login cancelled")
|
||||
return
|
||||
}
|
||||
|
||||
res.writeHead(404)
|
||||
res.end("Not found")
|
||||
})
|
||||
|
||||
// listen() failures (e.g. EADDRINUSE because Grok-CLI is bound to the same
|
||||
// pinned port) must clear `oauthServer` and remove our error listener,
|
||||
// otherwise the next startOAuthServer() short-circuits on the truthy check
|
||||
// and returns a redirect_uri pointing at nothing.
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (err: Error) => {
|
||||
oauthServer = undefined
|
||||
reject(err)
|
||||
}
|
||||
server.once("error", onError)
|
||||
server.listen(OAUTH_PORT, OAUTH_HOST, () => {
|
||||
server.removeListener("error", onError)
|
||||
// After listen() succeeds, install a permanent log-only listener so
|
||||
// that subsequent server errors (e.g. accept() failures, socket-level
|
||||
// errors) don't trip Node's default "unhandled error event = throw"
|
||||
// behavior and crash the entire opencode process. Matches the silent-
|
||||
// swallow behavior the Codex plugin gets from its permanent
|
||||
// `oauthServer!.on("error", reject)`.
|
||||
resolve()
|
||||
})
|
||||
oauthServer = server
|
||||
})
|
||||
|
||||
return { port: OAUTH_PORT, redirectUri: REDIRECT_URI }
|
||||
}
|
||||
|
||||
function stopOAuthServer() {
|
||||
if (oauthServer) {
|
||||
oauthServer.close()
|
||||
oauthServer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise<TokenResponse> {
|
||||
// A previous in-flight authorize() that the user abandoned (or that is
|
||||
// being superseded by a fresh attempt) still owns `pendingOAuth`. Reject
|
||||
// it eagerly so its caller stops waiting on a state value that can never
|
||||
// match the next callback.
|
||||
if (pendingOAuth) {
|
||||
pendingOAuth.reject(new Error("Superseded by a newer xAI authorize request"))
|
||||
pendingOAuth = undefined
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(
|
||||
() => {
|
||||
if (pendingOAuth) {
|
||||
pendingOAuth = undefined
|
||||
reject(new Error("OAuth callback timeout - authorization took too long"))
|
||||
}
|
||||
},
|
||||
5 * 60 * 1000,
|
||||
)
|
||||
|
||||
pendingOAuth = {
|
||||
pkce,
|
||||
state,
|
||||
resolve: (tokens) => {
|
||||
clearTimeout(timeout)
|
||||
resolve(tokens)
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout)
|
||||
reject(error)
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
interface RefreshResult {
|
||||
access: string
|
||||
refresh: string
|
||||
@@ -548,40 +295,6 @@ export async function XaiAuthPlugin(input: PluginInput, options: XaiAuthPluginOp
|
||||
}
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
label: "xAI Grok OAuth (SuperGrok Subscription)",
|
||||
type: "oauth",
|
||||
authorize: async () => {
|
||||
await startOAuthServer()
|
||||
const pkce = await generatePKCE()
|
||||
const state = generateState()
|
||||
const nonce = generateState()
|
||||
const authUrl = buildAuthorizeUrl(pkce, state, nonce, options)
|
||||
|
||||
const callbackPromise = waitForOAuthCallback(pkce, state)
|
||||
|
||||
return {
|
||||
url: authUrl,
|
||||
instructions: "Complete authorization in your browser. This window will close automatically.",
|
||||
method: "auto" as const,
|
||||
callback: async () => {
|
||||
try {
|
||||
const tokens = await callbackPromise
|
||||
return {
|
||||
type: "success" as const,
|
||||
refresh: tokens.refresh_token,
|
||||
access: tokens.access_token,
|
||||
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
|
||||
}
|
||||
} catch (err) {
|
||||
return { type: "failed" as const }
|
||||
} finally {
|
||||
stopOAuthServer()
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
// RFC 8628 device-code flow. The CLI prints a verification URL
|
||||
// and a short user_code that the user enters in a browser on
|
||||
@@ -591,7 +304,7 @@ export async function XaiAuthPlugin(input: PluginInput, options: XaiAuthPluginOp
|
||||
// user's browser. Defends the only attack surface (the polling
|
||||
// loop) with the standard authorization_pending / slow_down
|
||||
// backoff and a hard deadline from xAI's `expires_in`.
|
||||
label: "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
label: "SuperGrok Subscription",
|
||||
type: "oauth",
|
||||
authorize: async () => {
|
||||
const device = await requestDeviceCode(options)
|
||||
|
||||
@@ -97,6 +97,29 @@ export function http(
|
||||
headers.delete("content-encoding")
|
||||
headers.delete("content-length")
|
||||
|
||||
// An upstream 5xx from a remote workspace sandbox arrives here as an opaque
|
||||
// status — its real cause (and log line) live only inside the sandbox. Buffer
|
||||
// the small error body, log it locally so it shows up in the host's log, and
|
||||
// forward it unchanged (preserving content-type so the client can still parse
|
||||
// the structured error, e.g. its `ref`).
|
||||
if (response.status >= 500) {
|
||||
const body = yield* response.text.pipe(Effect.catch(() => Effect.succeed("")))
|
||||
const contentType = response.headers["content-type"] ?? "application/json"
|
||||
headers.delete("content-type")
|
||||
yield* Effect.logError("workspace proxy upstream error", {
|
||||
url: url.toString(),
|
||||
method: request.method,
|
||||
status: response.status,
|
||||
body: body.slice(0, 2000),
|
||||
})
|
||||
return HttpServerResponse.text(body, {
|
||||
status: response.status,
|
||||
statusText: statusText(response),
|
||||
headers,
|
||||
contentType,
|
||||
})
|
||||
}
|
||||
|
||||
return HttpServerResponse.stream(response.stream.pipe(Stream.catchCause(() => Stream.empty)), {
|
||||
status: response.status,
|
||||
statusText: statusText(response),
|
||||
|
||||
@@ -34,5 +34,12 @@ export function workspaceProxyURL(target: string | URL, requestURL: URL) {
|
||||
proxyURL.search = requestURL.search
|
||||
proxyURL.hash = requestURL.hash
|
||||
proxyURL.searchParams.delete("workspace")
|
||||
// The `directory` param is the *host's* working directory (e.g. a Windows
|
||||
// path like `F:\proj`). It is meaningless — and dangerous — on the remote:
|
||||
// the sandbox would `path.resolve` it against its own cwd, producing a bogus
|
||||
// path like `/home/daytona/workspace/repo/F:\proj` that does not exist and
|
||||
// crashes prompt handling. Drop it so the remote falls back to its own
|
||||
// project root. This mirrors ProxyUtil.headers stripping `x-opencode-directory`.
|
||||
proxyURL.searchParams.delete("directory")
|
||||
return proxyURL
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ describe("acp usage", () => {
|
||||
)
|
||||
})
|
||||
|
||||
it.effect("sends ACP usage_update with context size and cumulative assistant cost", () => {
|
||||
it.effect("includes cache reads and writes in ACP context usage", () => {
|
||||
const updates: SessionNotification[] = []
|
||||
return Effect.gen(function* () {
|
||||
const usage = yield* UsageService.Service
|
||||
@@ -222,7 +222,7 @@ describe("acp usage", () => {
|
||||
sessionId: "ses_1",
|
||||
update: {
|
||||
sessionUpdate: "usage_update",
|
||||
used: 15,
|
||||
used: 22,
|
||||
size: 128_000,
|
||||
cost: { amount: 3, currency: "USD" },
|
||||
},
|
||||
@@ -239,7 +239,7 @@ describe("acp usage", () => {
|
||||
input: 10,
|
||||
output: 20,
|
||||
reasoning: 0,
|
||||
cache: { read: 5, write: 0 },
|
||||
cache: { read: 5, write: 7 },
|
||||
},
|
||||
}),
|
||||
]),
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
accessTokenIsExpiring,
|
||||
buildAuthorizeUrl,
|
||||
pollDeviceCodeToken,
|
||||
requestDeviceCode,
|
||||
XaiAuthPlugin,
|
||||
} from "../../src/plugin/xai"
|
||||
import { accessTokenIsExpiring, pollDeviceCodeToken, requestDeviceCode, XaiAuthPlugin } from "../../src/plugin/xai"
|
||||
import { OAUTH_DUMMY_KEY } from "../../src/auth"
|
||||
|
||||
function makeJwt(payload: object): string {
|
||||
@@ -76,32 +70,6 @@ describe("plugin.xai", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildAuthorizeUrl", () => {
|
||||
const pkce = { verifier: "ver", challenge: "chal" }
|
||||
|
||||
test("includes required OAuth + PKCE + OIDC params", () => {
|
||||
const url = new URL(buildAuthorizeUrl(pkce, "state-abc", "nonce-xyz"))
|
||||
const params = url.searchParams
|
||||
|
||||
expect(url.origin + url.pathname).toBe("https://auth.x.ai/oauth2/authorize")
|
||||
expect(params.get("response_type")).toBe("code")
|
||||
expect(params.get("client_id")).toBe("b1a00492-073a-47ea-816f-4c329264a828")
|
||||
expect(params.get("redirect_uri")).toBe("http://127.0.0.1:56121/callback")
|
||||
expect(params.get("scope")).toBe("openid profile email offline_access grok-cli:access api:access")
|
||||
expect(params.get("code_challenge")).toBe("chal")
|
||||
expect(params.get("code_challenge_method")).toBe("S256")
|
||||
expect(params.get("state")).toBe("state-abc")
|
||||
expect(params.get("nonce")).toBe("nonce-xyz")
|
||||
expect(params.get("plan")).toBe("generic")
|
||||
expect(params.get("referrer")).toBe("opencode")
|
||||
})
|
||||
|
||||
test("supports endpoint override for local integration tests", () => {
|
||||
const url = new URL(buildAuthorizeUrl(pkce, "s", "n", { authorizeUrl: "http://127.0.0.1/oauth2/authorize" }))
|
||||
expect(url.origin + url.pathname).toBe("http://127.0.0.1/oauth2/authorize")
|
||||
})
|
||||
})
|
||||
|
||||
describe("loader", () => {
|
||||
test("returns no options unless stored auth is OAuth and exposes methods in order", async () => {
|
||||
const hooks = await XaiAuthPlugin({} as any)
|
||||
@@ -110,8 +78,7 @@ describe("plugin.xai", () => {
|
||||
await hooks.auth!.loader!(async () => ({ type: "wellknown", key: "k", token: "t" }) as any, {} as any),
|
||||
).toEqual({})
|
||||
expect(hooks.auth!.methods.map((m) => [m.type, m.label])).toEqual([
|
||||
["oauth", "xAI Grok OAuth (SuperGrok Subscription)"],
|
||||
["oauth", "xAI Grok OAuth (Headless / Remote / VPS)"],
|
||||
["oauth", "SuperGrok Subscription"],
|
||||
["api", "Manually enter API Key"],
|
||||
])
|
||||
})
|
||||
@@ -425,8 +392,7 @@ describe("plugin.xai", () => {
|
||||
})
|
||||
const hooks = await XaiAuthPlugin({} as any, serverOptions(server))
|
||||
const headless = hooks.auth!.methods.find(
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> =>
|
||||
m.type === "oauth" && m.label === "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> => m.type === "oauth" && m.label === "SuperGrok Subscription",
|
||||
)!
|
||||
const result = await headless.authorize!()
|
||||
|
||||
@@ -449,8 +415,7 @@ describe("plugin.xai", () => {
|
||||
return new Response("unexpected request", { status: 500 })
|
||||
})
|
||||
const headless = (await XaiAuthPlugin({} as any, serverOptions(server))).auth!.methods.find(
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> =>
|
||||
m.type === "oauth" && m.label === "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> => m.type === "oauth" && m.label === "SuperGrok Subscription",
|
||||
)!
|
||||
expect((await headless.authorize!()).url).toBe("https://x.ai/device")
|
||||
})
|
||||
@@ -474,6 +439,7 @@ describe("plugin.xai", () => {
|
||||
expect(parsed.get("scope")).toContain("offline_access")
|
||||
expect(parsed.get("scope")).toContain("grok-cli:access")
|
||||
expect(parsed.get("scope")).toContain("api:access")
|
||||
expect(parsed.get("referrer")).toBe("opencode")
|
||||
await expect(
|
||||
requestDeviceCode({ deviceAuthorizationUrl: new URL("/error", server.url).toString() }),
|
||||
).rejects.toThrow(/429.*rate limited/)
|
||||
@@ -611,8 +577,7 @@ describe("plugin.xai", () => {
|
||||
return Response.json({ error: "access_denied" }, { status: 400 })
|
||||
})
|
||||
const headless = (await XaiAuthPlugin({} as any, serverOptions(server))).auth!.methods.find(
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> =>
|
||||
m.type === "oauth" && m.label === "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> => m.type === "oauth" && m.label === "SuperGrok Subscription",
|
||||
)!
|
||||
expect(await ((await headless.authorize!()) as any).callback()).toEqual({ type: "failed" })
|
||||
})
|
||||
|
||||
@@ -80,6 +80,13 @@ describe("workspaceProxyURL", () => {
|
||||
expect(result.searchParams.get("keep")).toBe("yes")
|
||||
})
|
||||
|
||||
test("strips the host directory param so the remote resolves its own root", () => {
|
||||
const url = new URL("http://localhost/session/abc?directory=F%3A%5Cproj&keep=yes")
|
||||
const result = workspaceProxyURL("http://remote:8080/base", url)
|
||||
expect(result.searchParams.get("directory")).toBeNull()
|
||||
expect(result.searchParams.get("keep")).toBe("yes")
|
||||
})
|
||||
|
||||
test("preserves hash from request", () => {
|
||||
const url = new URL("http://localhost/page#section")
|
||||
const result = workspaceProxyURL("http://remote:8080", url)
|
||||
|
||||
@@ -158,6 +158,12 @@ describe("markdown stream", () => {
|
||||
expect(final.blocks[2]).toEqual({ raw: "- final item", src: "- final item", mode: "full" })
|
||||
})
|
||||
|
||||
test("splits completed markdown into bounded top-level blocks", () => {
|
||||
const result = project(undefined, "# Plan\n\nFirst paragraph.\n\nSecond paragraph.", false)
|
||||
|
||||
expect(result.blocks.map((block) => block.raw)).toEqual(["# Plan", "First paragraph.", "Second paragraph."])
|
||||
})
|
||||
|
||||
test("catches up paced text before finalizing", () => {
|
||||
const live = project(undefined, "# Plan\n\nFinished paragraph.\n\n- final", true)
|
||||
const final = project(live, `${live.text} item`, false)
|
||||
|
||||
@@ -51,7 +51,7 @@ function heal(text: string) {
|
||||
}
|
||||
|
||||
export function stream(text: string, live: boolean): Block[] {
|
||||
if (!live) return completedProjection(text).blocks
|
||||
if (!live) return completedBlocks(text)
|
||||
if (refs(text)) return [{ raw: text, src: heal(text), mode: "live" }] satisfies Block[]
|
||||
const tokens = marked.lexer(text)
|
||||
const tail = tokens.findLastIndex((token) => token.type !== "space")
|
||||
@@ -85,6 +85,17 @@ export function stream(text: string, live: boolean): Block[] {
|
||||
return [...result, { raw, src: openCode(code.raw), mode: "code", language: language(code.lang) }]
|
||||
}
|
||||
|
||||
function completedBlocks(text: string) {
|
||||
if (refs(text)) return completedProjection(text).blocks
|
||||
const tokens = marked.lexer(text)
|
||||
return tokens.flatMap((token): Block[] => {
|
||||
if (token.type === "space") return []
|
||||
if (token.type !== "code") return [{ raw: token.raw, src: token.raw, mode: "full" }]
|
||||
const code = token as Tokens.Code
|
||||
return [{ raw: code.raw, src: code.text, mode: "code", language: language(code.lang), complete: true }]
|
||||
})
|
||||
}
|
||||
|
||||
export function project(previous: Projection | undefined, text: string, live: boolean): Projection {
|
||||
if (!live) {
|
||||
const current =
|
||||
@@ -93,7 +104,7 @@ export function project(previous: Projection | undefined, text: string, live: bo
|
||||
: previous && text.startsWith(previous.text)
|
||||
? project(previous, text, true)
|
||||
: undefined
|
||||
if (!current) return completedProjection(text)
|
||||
if (!current) return { text, blocks: completedBlocks(text) }
|
||||
return {
|
||||
text,
|
||||
blocks: current.blocks.map((block) => {
|
||||
|
||||
@@ -491,6 +491,8 @@ export function Markdown(
|
||||
)
|
||||
|
||||
let copyCleanup: (() => void) | undefined
|
||||
let renderFrame: number | undefined
|
||||
let renderGeneration = 0
|
||||
|
||||
createEffect(() => {
|
||||
const container = root()
|
||||
@@ -499,6 +501,9 @@ export function Markdown(
|
||||
const content = local.text ? pendingBlocks(result, projected, local.cacheKey, owner) : []
|
||||
if (!container) return
|
||||
if (isServer) return
|
||||
const generation = ++renderGeneration
|
||||
if (renderFrame !== undefined) cancelAnimationFrame(renderFrame)
|
||||
renderFrame = undefined
|
||||
if (content.length === 0) {
|
||||
disposeCopyButtons(container)
|
||||
container.innerHTML = ""
|
||||
@@ -515,24 +520,40 @@ export function Markdown(
|
||||
})
|
||||
activeCodeKeys.clear()
|
||||
nextCodeKeys.forEach((key) => activeCodeKeys.add(key))
|
||||
content.forEach((block, index) => updateBlock(container, index, block, labels))
|
||||
while (container.children.length > content.length) {
|
||||
const child = container.lastElementChild
|
||||
if (!child) break
|
||||
disposeCopyButtons(child)
|
||||
child.remove()
|
||||
let index = 0
|
||||
const update = () => {
|
||||
renderFrame = undefined
|
||||
if (generation !== renderGeneration) return
|
||||
const deadline = performance.now() + 8
|
||||
while (index < content.length && performance.now() < deadline) {
|
||||
updateBlock(container, index, content[index]!, labels)
|
||||
index += 1
|
||||
}
|
||||
if (index < content.length) {
|
||||
renderFrame = requestAnimationFrame(update)
|
||||
return
|
||||
}
|
||||
while (container.children.length > content.length) {
|
||||
const child = container.lastElementChild
|
||||
if (!child) break
|
||||
disposeCopyButtons(child)
|
||||
child.remove()
|
||||
}
|
||||
container
|
||||
.querySelectorAll<HTMLElement>('[data-slot="markdown-copy-button"]')
|
||||
.forEach((button) => setCopyState(button, labels, button.dataset.copied === "true"))
|
||||
if (!copyCleanup)
|
||||
copyCleanup = setupCodeCopy(container, () => ({
|
||||
copy: i18n.t("ui.message.copy"),
|
||||
copied: i18n.t("ui.message.copied"),
|
||||
}))
|
||||
}
|
||||
container
|
||||
.querySelectorAll<HTMLElement>('[data-slot="markdown-copy-button"]')
|
||||
.forEach((button) => setCopyState(button, labels, button.dataset.copied === "true"))
|
||||
if (!copyCleanup)
|
||||
copyCleanup = setupCodeCopy(container, () => ({
|
||||
copy: i18n.t("ui.message.copy"),
|
||||
copied: i18n.t("ui.message.copied"),
|
||||
}))
|
||||
update()
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
renderGeneration += 1
|
||||
if (renderFrame !== undefined) cancelAnimationFrame(renderFrame)
|
||||
if (copyCleanup) copyCleanup()
|
||||
disposeMarkdownProjection(owner)
|
||||
activeCodeKeys.forEach(disposeCode)
|
||||
|
||||
@@ -61,6 +61,7 @@ import { TextShimmer } from "@opencode-ai/ui/text-shimmer"
|
||||
import { AnimatedCountList } from "./tool-count-summary"
|
||||
import { ToolStatusTitle } from "./tool-status-title"
|
||||
import { patchFiles } from "./apply-patch-file"
|
||||
import { partDefaultOpen } from "./part-default-open"
|
||||
import { animate } from "motion"
|
||||
import { attached, inline, kind, typeLabel } from "./message-file"
|
||||
import { readPartText } from "./message-part-text"
|
||||
@@ -718,15 +719,7 @@ export function renderable(part: PartType, showReasoningSummaries = true) {
|
||||
return !!PART_MAPPING[part.type]
|
||||
}
|
||||
|
||||
function toolDefaultOpen(tool: string, shell = false, edit = false) {
|
||||
if (tool === "bash" || tool === "shell") return shell
|
||||
if (tool === "edit" || tool === "write" || tool === "patch" || tool === "apply_patch") return edit
|
||||
}
|
||||
|
||||
export function partDefaultOpen(part: PartType, shell = false, edit = false) {
|
||||
if (part.type !== "tool") return
|
||||
return toolDefaultOpen(part.tool, shell, edit)
|
||||
}
|
||||
export { partDefaultOpen } from "./part-default-open"
|
||||
|
||||
export function AssistantParts(props: {
|
||||
messages: AssistantMessage[]
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { Part as PartType } from "@opencode-ai/sdk/v2"
|
||||
import { partDefaultOpen } from "./part-default-open"
|
||||
|
||||
describe("partDefaultOpen", () => {
|
||||
test("keeps edited files expanded when enabled", () => {
|
||||
expect(partDefaultOpen(tool("edit", { filediff: { additions: 1, deletions: 1 } }), false, true)).toBe(true)
|
||||
})
|
||||
|
||||
test("collapses deletion-only edits when enabled", () => {
|
||||
expect(partDefaultOpen(tool("edit", { filediff: { additions: 0, deletions: 1_200 } }), false, true)).toBe(false)
|
||||
})
|
||||
|
||||
test("collapses patches containing only deleted files when enabled", () => {
|
||||
expect(
|
||||
partDefaultOpen(
|
||||
tool("apply_patch", {
|
||||
files: [
|
||||
{ filePath: "one.ts", type: "delete" },
|
||||
{ filePath: "two.ts", type: "delete" },
|
||||
],
|
||||
}),
|
||||
false,
|
||||
true,
|
||||
),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
test("keeps mixed patches expanded when enabled", () => {
|
||||
expect(
|
||||
partDefaultOpen(
|
||||
tool("apply_patch", {
|
||||
files: [
|
||||
{ filePath: "one.ts", type: "delete" },
|
||||
{ filePath: "two.ts", type: "update" },
|
||||
],
|
||||
}),
|
||||
false,
|
||||
true,
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
test("preserves shell defaults", () => {
|
||||
expect(partDefaultOpen(tool("shell", {}), true, false)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
function tool(name: string, metadata: Record<string, unknown>): PartType {
|
||||
return {
|
||||
id: `part_${name}`,
|
||||
sessionID: "session",
|
||||
messageID: "message",
|
||||
type: "tool",
|
||||
callID: `call_${name}`,
|
||||
tool: name,
|
||||
state: {
|
||||
status: "completed",
|
||||
input: {},
|
||||
output: "",
|
||||
title: name,
|
||||
metadata,
|
||||
time: { start: 0, end: 1 },
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Part as PartType, ToolPart } from "@opencode-ai/sdk/v2"
|
||||
|
||||
function deletionOnly(part: ToolPart) {
|
||||
if (!("metadata" in part.state)) return false
|
||||
const metadata = part.state.metadata
|
||||
if (!metadata) return false
|
||||
|
||||
const files = metadata.files
|
||||
if (Array.isArray(files) && files.length > 0) {
|
||||
return files.every((file) => !!file && typeof file === "object" && "type" in file && file.type === "delete")
|
||||
}
|
||||
|
||||
const filediff = metadata.filediff
|
||||
if (!filediff || typeof filediff !== "object") return false
|
||||
if (!("additions" in filediff) || !("deletions" in filediff)) return false
|
||||
return filediff.additions === 0 && typeof filediff.deletions === "number" && filediff.deletions > 0
|
||||
}
|
||||
|
||||
export function partDefaultOpen(part: PartType, shell = false, edit = false) {
|
||||
if (part.type !== "tool") return
|
||||
if (part.tool === "bash" || part.tool === "shell") return shell
|
||||
if (part.tool === "edit" || part.tool === "write" || part.tool === "patch" || part.tool === "apply_patch") {
|
||||
if (!edit) return false
|
||||
return !deletionOnly(part)
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ function createPool(lineDiffType: "none" | "word-alt") {
|
||||
{
|
||||
theme: "OpenCode",
|
||||
lineDiffType,
|
||||
preferredHighlighter: "shiki-wasm",
|
||||
preferredHighlighter: "shiki-js",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ export function CommentCardV2(props: {
|
||||
return (
|
||||
<TooltipV2
|
||||
placement="top"
|
||||
openDelay={1000}
|
||||
value={props.title ?? props.comment}
|
||||
disabled={!props.tooltip || !truncated()}
|
||||
class={props.wide ? "w-full" : undefined}
|
||||
|
||||
@@ -52,9 +52,11 @@ export function PromptInputV2(props: PromptInputV2Props) {
|
||||
const view = props.controller.view
|
||||
let editor: HTMLDivElement | undefined
|
||||
let localInput = false
|
||||
const updateCursor = () => {
|
||||
const updateCursor = (event: KeyboardEvent | PointerEvent) => {
|
||||
if (!editor || !window.getSelection()?.isCollapsed) return
|
||||
props.controller.onCursor(promptInputV2Cursor(editor))
|
||||
if (event instanceof KeyboardEvent && !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key))
|
||||
return
|
||||
props.controller.onCursor(parsePromptInputV2Editor(editor).cursor)
|
||||
}
|
||||
const mode = createMemo(() => state.mode)
|
||||
const buttons = createMemo(() => ({
|
||||
@@ -163,8 +165,7 @@ export function PromptInputV2(props: PromptInputV2Props) {
|
||||
class="relative z-10 block min-h-[60px] max-h-[180px] w-full overflow-y-auto whitespace-pre-wrap bg-transparent px-4 pt-4 pb-2 text-[13px] font-[440] leading-5 text-v2-text-text-base focus:outline-none empty:before:content-['\200B'] [&_[data-mention=file]]:text-syntax-property [&_[data-mention=agent]]:text-syntax-type [&_[data-mention=reference]]:text-syntax-keyword"
|
||||
classList={{ "font-mono!": state.mode === "shell", "opacity-50": props.disabled }}
|
||||
onInput={(event) => {
|
||||
const cursor = promptInputV2Cursor(event.currentTarget)
|
||||
const prompt = parsePromptInputV2Editor(event.currentTarget)
|
||||
const { prompt, cursor } = parsePromptInputV2Editor(event.currentTarget)
|
||||
const images = props.controller.parts().filter((part) => part.type === "image")
|
||||
localInput = true
|
||||
props.controller.onInput(prompt.map((part) => part.content).join(""), [...prompt, ...images], cursor)
|
||||
@@ -300,8 +301,13 @@ function renderPromptInputV2Editor(editor: HTMLDivElement, prompt: PromptInputV2
|
||||
|
||||
function parsePromptInputV2Editor(editor: HTMLDivElement) {
|
||||
const parts: Exclude<PromptInputV2Prompt[number], PromptInputV2Attachment>[] = []
|
||||
const selection = window.getSelection()
|
||||
const anchorNode = selection && editor.contains(selection.anchorNode) ? selection.anchorNode : undefined
|
||||
const anchorOffset = anchorNode ? selection!.anchorOffset : 0
|
||||
let buffer = ""
|
||||
let position = 0
|
||||
let cursor: number | undefined
|
||||
const offset = () => position + buffer.length
|
||||
|
||||
const flush = () => {
|
||||
if (!buffer) return
|
||||
@@ -336,43 +342,42 @@ function parsePromptInputV2Editor(editor: HTMLDivElement) {
|
||||
}
|
||||
const visit = (node: Node) => {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
if (node === anchorNode) cursor = offset() + Math.min(anchorOffset, node.textContent?.length ?? 0)
|
||||
buffer += node.textContent ?? ""
|
||||
return
|
||||
}
|
||||
if (!(node instanceof HTMLElement)) return
|
||||
if (node.dataset.mention) {
|
||||
if (node === anchorNode) cursor = offset() + (anchorOffset > 0 ? (node.textContent?.length ?? 0) : 0)
|
||||
mention(node)
|
||||
return
|
||||
}
|
||||
if (node.tagName === "BR") {
|
||||
if (node === anchorNode) cursor = offset() + (anchorOffset > 0 ? 1 : 0)
|
||||
buffer += "\n"
|
||||
return
|
||||
}
|
||||
Array.from(node.childNodes).forEach(visit)
|
||||
Array.from(node.childNodes).forEach((child, index) => {
|
||||
if (node === anchorNode && anchorOffset === index) cursor = offset()
|
||||
visit(child)
|
||||
})
|
||||
if (node === anchorNode && anchorOffset >= node.childNodes.length) cursor = offset()
|
||||
}
|
||||
|
||||
Array.from(editor.childNodes).forEach((node, index, nodes) => {
|
||||
if (editor === anchorNode && anchorOffset === index) cursor = offset()
|
||||
visit(node)
|
||||
if (node instanceof HTMLElement && ["DIV", "P"].includes(node.tagName) && index < nodes.length - 1) buffer += "\n"
|
||||
})
|
||||
if (editor === anchorNode && anchorOffset >= editor.childNodes.length) cursor = offset()
|
||||
flush()
|
||||
if (
|
||||
parts.every((part) => part.type === "text") &&
|
||||
parts.every((part) => part.content.replace(/[\n\u200B]/g, "") === "")
|
||||
) {
|
||||
return [{ type: "text" as const, content: "", start: 0, end: 0 }]
|
||||
}
|
||||
if (parts.length > 0) return parts
|
||||
return [{ type: "text" as const, content: "", start: 0, end: 0 }]
|
||||
}
|
||||
|
||||
function promptInputV2Cursor(editor: HTMLDivElement) {
|
||||
const selection = window.getSelection()
|
||||
if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return editor.textContent?.length ?? 0
|
||||
const range = selection.getRangeAt(0).cloneRange()
|
||||
range.selectNodeContents(editor)
|
||||
range.setEnd(selection.anchorNode!, selection.anchorOffset)
|
||||
return range.toString().length
|
||||
const result =
|
||||
parts.length === 0 ||
|
||||
(parts.every((part) => part.type === "text") &&
|
||||
parts.every((part) => part.content.replace(/[\n\u200B]/g, "") === ""))
|
||||
? [{ type: "text" as const, content: "", start: 0, end: 0 }]
|
||||
: parts
|
||||
return { prompt: result, cursor: cursor ?? offset() }
|
||||
}
|
||||
|
||||
export function PromptInputV2Attachments(props: {
|
||||
@@ -396,12 +401,7 @@ export function PromptInputV2Attachments(props: {
|
||||
<For each={props.comments ?? []}>
|
||||
{(comment) => (
|
||||
<div class="relative group shrink-0">
|
||||
<TooltipV2
|
||||
value={comment.comment}
|
||||
placement="top"
|
||||
openDelay={800}
|
||||
contentClass="max-w-[300px] break-words"
|
||||
>
|
||||
<TooltipV2 value={comment.comment} placement="top" contentClass="max-w-[300px] break-words">
|
||||
<CommentCardV2
|
||||
comment={comment.comment ?? ""}
|
||||
path={comment.path}
|
||||
|
||||
@@ -220,7 +220,6 @@ export function SessionReviewV2(props: SessionReviewV2Props) {
|
||||
</Show>
|
||||
<div class="flex items-center">
|
||||
<TooltipV2
|
||||
openDelay={2000}
|
||||
inactive={!prev()}
|
||||
value={
|
||||
<>
|
||||
@@ -240,7 +239,6 @@ export function SessionReviewV2(props: SessionReviewV2Props) {
|
||||
/>
|
||||
</TooltipV2>
|
||||
<TooltipV2
|
||||
openDelay={2000}
|
||||
inactive={!next()}
|
||||
value={
|
||||
<>
|
||||
@@ -274,12 +272,12 @@ export function SessionReviewV2(props: SessionReviewV2Props) {
|
||||
class="session-review-v2-segmented-control session-review-v2-segmented-control--icon"
|
||||
aria-label={i18n.t("ui.sessionReviewV2.expandMode")}
|
||||
>
|
||||
<TooltipV2 openDelay={2000} value={i18n.t("ui.sessionReviewV2.showAllLines")}>
|
||||
<TooltipV2 value={i18n.t("ui.sessionReviewV2.showAllLines")}>
|
||||
<SegmentedControlItemV2 value="expand" aria-label={i18n.t("ui.sessionReviewV2.showAllLines")}>
|
||||
<Icon name="expand" />
|
||||
</SegmentedControlItemV2>
|
||||
</TooltipV2>
|
||||
<TooltipV2 openDelay={2000} value={i18n.t("ui.sessionReviewV2.hideNonDiffLines")}>
|
||||
<TooltipV2 value={i18n.t("ui.sessionReviewV2.hideNonDiffLines")}>
|
||||
<SegmentedControlItemV2 value="collapse" aria-label={i18n.t("ui.sessionReviewV2.hideNonDiffLines")}>
|
||||
<Icon name="collapse" />
|
||||
</SegmentedControlItemV2>
|
||||
@@ -295,12 +293,12 @@ export function SessionReviewV2(props: SessionReviewV2Props) {
|
||||
class="session-review-v2-segmented-control session-review-v2-segmented-control--icon"
|
||||
aria-label={i18n.t("ui.sessionReviewV2.diffView")}
|
||||
>
|
||||
<TooltipV2 openDelay={2000} value={i18n.t("ui.sessionReviewV2.unifiedDiff")}>
|
||||
<TooltipV2 value={i18n.t("ui.sessionReviewV2.unifiedDiff")}>
|
||||
<SegmentedControlItemV2 value="unified" aria-label={i18n.t("ui.sessionReviewV2.unifiedDiff")}>
|
||||
<Icon name="unified" />
|
||||
</SegmentedControlItemV2>
|
||||
</TooltipV2>
|
||||
<TooltipV2 openDelay={2000} value={i18n.t("ui.sessionReviewV2.splitDiff")}>
|
||||
<TooltipV2 value={i18n.t("ui.sessionReviewV2.splitDiff")}>
|
||||
<SegmentedControlItemV2 value="split" aria-label={i18n.t("ui.sessionReviewV2.splitDiff")}>
|
||||
<Icon name="split" />
|
||||
</SegmentedControlItemV2>
|
||||
|
||||
@@ -104,7 +104,6 @@ const appGlobalBindingCommands = [
|
||||
] as const
|
||||
|
||||
const appBindingCommands = [
|
||||
"command.palette.show",
|
||||
"model.list",
|
||||
"model.cycle_recent",
|
||||
"model.cycle_recent_reverse",
|
||||
@@ -963,6 +962,11 @@ function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPlugi
|
||||
commands: appCommands(),
|
||||
}))
|
||||
|
||||
useBindings(() => ({
|
||||
enabled: () => dialog.stack.length === 0,
|
||||
bindings: tuiConfig.keybinds.get(COMMAND_PALETTE_COMMAND),
|
||||
}))
|
||||
|
||||
useBindings(() => ({
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
bindings: tuiConfig.keybinds.gather("app", appBindingCommands),
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { RGBA, TextAttributes } from "@opentui/core"
|
||||
import { For, type JSX } from "solid-js"
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
import { tint, useTheme } from "../context/theme"
|
||||
import { go, logo } from "../logo"
|
||||
import { logo } from "../logo"
|
||||
|
||||
export function Logo() {
|
||||
const { theme } = useTheme()
|
||||
const dimensions = useTerminalDimensions()
|
||||
const variant = () => logoVariant(dimensions().width, dimensions().height)
|
||||
|
||||
const renderLine = (line: string, fg: RGBA, bold: boolean): JSX.Element[] => {
|
||||
const shadow = tint(theme.background, fg, 0.25)
|
||||
@@ -51,36 +48,14 @@ export function Logo() {
|
||||
|
||||
return (
|
||||
<box>
|
||||
{variant() === "hidden" ? null : variant() === "compact" ? (
|
||||
<For each={go.right.slice(1)}>
|
||||
{(line) => <box flexDirection="row">{renderLine(line, theme.text, true)}</box>}
|
||||
</For>
|
||||
) : variant() === "stacked" ? (
|
||||
<>
|
||||
<For each={logo.left.slice(1)}>
|
||||
{(line) => <box flexDirection="row">{renderLine(line, theme.textMuted, false)}</box>}
|
||||
</For>
|
||||
<For each={logo.right}>
|
||||
{(line) => <box flexDirection="row">{renderLine(line, theme.text, true)}</box>}
|
||||
</For>
|
||||
</>
|
||||
) : (
|
||||
<For each={logo.left}>
|
||||
{(line, index) => (
|
||||
<box flexDirection="row" gap={1}>
|
||||
<box flexDirection="row">{renderLine(line, theme.textMuted, false)}</box>
|
||||
<box flexDirection="row">{renderLine(logo.right[index()], theme.text, true)}</box>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
)}
|
||||
<For each={logo.left}>
|
||||
{(line, index) => (
|
||||
<box flexDirection="row" gap={1}>
|
||||
<box flexDirection="row">{renderLine(line, theme.textMuted, false)}</box>
|
||||
<box flexDirection="row">{renderLine(logo.right[index()], theme.text, true)}</box>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
export function logoVariant(width: number, height: number) {
|
||||
if (height < 12) return "hidden"
|
||||
if (width < 22) return "compact"
|
||||
if (width < 44) return "stacked"
|
||||
return "full"
|
||||
}
|
||||
|
||||
@@ -5,7 +5,13 @@ import { testRender, useRenderer } from "@opentui/solid"
|
||||
import { expect, test } from "bun:test"
|
||||
import { onCleanup } from "solid-js"
|
||||
import { TuiKeybind } from "../src/config/keybind"
|
||||
import { getOpencodeModeStack, OPENCODE_BASE_MODE, OpencodeKeymapProvider, registerOpencodeKeymap } from "../src/keymap"
|
||||
import {
|
||||
COMMAND_PALETTE_COMMAND,
|
||||
getOpencodeModeStack,
|
||||
OPENCODE_BASE_MODE,
|
||||
OpencodeKeymapProvider,
|
||||
registerOpencodeKeymap,
|
||||
} from "../src/keymap"
|
||||
|
||||
function createResolvedKeymapConfig(input: TuiKeybind.KeybindOverrides = {}) {
|
||||
const keybinds = TuiKeybind.parse(input)
|
||||
@@ -73,12 +79,14 @@ test("mode-less bindings stay active when opencode mode changes", async () => {
|
||||
const offKeymap = registerOpencodeKeymap(keymap, renderer, config)
|
||||
const offGlobal = keymap.registerLayer({
|
||||
commands: [
|
||||
{ name: COMMAND_PALETTE_COMMAND, run() {} },
|
||||
{ name: "session.list", run() {} },
|
||||
{ name: "session.new", run() {} },
|
||||
{ name: "session.page.up", run() {} },
|
||||
{ name: "session.first", run() {} },
|
||||
],
|
||||
bindings: config.keybinds.gather("test.global", [
|
||||
COMMAND_PALETTE_COMMAND,
|
||||
"session.list",
|
||||
"session.new",
|
||||
"session.page.up",
|
||||
@@ -95,7 +103,14 @@ test("mode-less bindings stay active when opencode mode changes", async () => {
|
||||
Array.from(
|
||||
keymap.getCommandBindings({
|
||||
visibility: "active",
|
||||
commands: ["session.list", "session.new", "session.page.up", "session.first", "model.list"],
|
||||
commands: [
|
||||
COMMAND_PALETTE_COMMAND,
|
||||
"session.list",
|
||||
"session.new",
|
||||
"session.page.up",
|
||||
"session.first",
|
||||
"model.list",
|
||||
],
|
||||
}),
|
||||
([command, bindings]) => [command, bindings.length],
|
||||
),
|
||||
@@ -125,9 +140,24 @@ test("mode-less bindings stay active when opencode mode changes", async () => {
|
||||
const app = await testRender(() => <Harness />)
|
||||
try {
|
||||
expect(counts).toEqual({
|
||||
base: { "session.list": 1, "session.new": 1, "session.page.up": 2, "session.first": 2, "model.list": 1 },
|
||||
question: { "session.list": 1, "session.new": 1, "session.page.up": 2, "session.first": 2, "model.list": 0 },
|
||||
base: {
|
||||
[COMMAND_PALETTE_COMMAND]: 1,
|
||||
"session.list": 1,
|
||||
"session.new": 1,
|
||||
"session.page.up": 2,
|
||||
"session.first": 2,
|
||||
"model.list": 1,
|
||||
},
|
||||
question: {
|
||||
[COMMAND_PALETTE_COMMAND]: 1,
|
||||
"session.list": 1,
|
||||
"session.new": 1,
|
||||
"session.page.up": 2,
|
||||
"session.first": 2,
|
||||
"model.list": 0,
|
||||
},
|
||||
autocomplete: {
|
||||
[COMMAND_PALETTE_COMMAND]: 1,
|
||||
"session.list": 1,
|
||||
"session.new": 1,
|
||||
"session.page.up": 2,
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { logoVariant } from "../src/component/logo"
|
||||
|
||||
test("adapts the logo to constrained terminals", () => {
|
||||
expect(logoVariant(19, 24)).toBe("compact")
|
||||
expect(logoVariant(21, 24)).toBe("compact")
|
||||
expect(logoVariant(22, 24)).toBe("stacked")
|
||||
expect(logoVariant(43, 24)).toBe("stacked")
|
||||
expect(logoVariant(44, 24)).toBe("full")
|
||||
expect(logoVariant(80, 11)).toBe("hidden")
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
const OPEN_DELAY = 1_000
|
||||
|
||||
// Kobalte warms every tooltip globally. Keep intent previews isolated so opening
|
||||
// a model picker never inherits warm state from an unrelated tooltip.
|
||||
let warm = false
|
||||
let reset: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
export function openTooltipIntent(open: () => void) {
|
||||
clearTimeout(reset)
|
||||
reset = undefined
|
||||
if (warm) {
|
||||
open()
|
||||
return
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
warm = true
|
||||
open()
|
||||
}, OPEN_DELAY)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
|
||||
export function closeTooltipIntent() {
|
||||
clearTimeout(reset)
|
||||
// Adjacent triggers enter before the next task; leaving the group does not.
|
||||
reset = setTimeout(() => {
|
||||
warm = false
|
||||
reset = undefined
|
||||
})
|
||||
}
|
||||
|
||||
export function resetTooltipIntent() {
|
||||
clearTimeout(reset)
|
||||
reset = undefined
|
||||
warm = false
|
||||
}
|
||||
@@ -2,19 +2,22 @@ import { Tooltip as KobalteTooltip } from "@kobalte/core/tooltip"
|
||||
import { createEffect, Match, onCleanup, splitProps, Switch, type JSX } from "solid-js"
|
||||
import type { ComponentProps } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { closeTooltipIntent, openTooltipIntent, resetTooltipIntent } from "./tooltip-intent"
|
||||
import "./tooltip-v2.css"
|
||||
|
||||
export interface TooltipV2Props extends ComponentProps<typeof KobalteTooltip> {
|
||||
export interface TooltipV2Props extends Omit<ComponentProps<typeof KobalteTooltip>, "openDelay"> {
|
||||
value: JSX.Element
|
||||
class?: string
|
||||
contentClass?: string
|
||||
contentStyle?: JSX.CSSProperties
|
||||
inactive?: boolean
|
||||
delay?: "standard" | "intent"
|
||||
forceOpen?: boolean
|
||||
}
|
||||
|
||||
export function TooltipV2(props: TooltipV2Props) {
|
||||
let ref: HTMLDivElement | undefined
|
||||
let cancelIntent: (() => void) | undefined
|
||||
const [state, setState] = createStore({
|
||||
open: false,
|
||||
block: false,
|
||||
@@ -26,19 +29,37 @@ export function TooltipV2(props: TooltipV2Props) {
|
||||
"contentClass",
|
||||
"contentStyle",
|
||||
"inactive",
|
||||
"delay",
|
||||
"forceOpen",
|
||||
"ignoreSafeArea",
|
||||
"value",
|
||||
])
|
||||
|
||||
const close = () => setState("open", false)
|
||||
|
||||
const inside = () => {
|
||||
const active = document.activeElement
|
||||
if (!ref || !active) return false
|
||||
return ref.contains(active)
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
cancelIntent?.()
|
||||
cancelIntent = undefined
|
||||
if (local.delay === "intent") closeTooltipIntent()
|
||||
setState("open", false)
|
||||
}
|
||||
|
||||
const show = () => {
|
||||
if (local.delay !== "intent" || inside()) {
|
||||
setState("open", true)
|
||||
return
|
||||
}
|
||||
if (cancelIntent) return
|
||||
cancelIntent = openTooltipIntent(() => {
|
||||
cancelIntent = undefined
|
||||
setState("open", true)
|
||||
})
|
||||
}
|
||||
|
||||
const drop = (expand = state.expand) => {
|
||||
if (expand) return
|
||||
if (ref?.matches(":hover")) return
|
||||
@@ -80,6 +101,11 @@ export function TooltipV2(props: TooltipV2Props) {
|
||||
onCleanup(() => obs.disconnect())
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
cancelIntent?.()
|
||||
if (local.delay === "intent") resetTooltipIntent()
|
||||
})
|
||||
|
||||
let justClickedTrigger = false
|
||||
|
||||
return (
|
||||
@@ -88,8 +114,8 @@ export function TooltipV2(props: TooltipV2Props) {
|
||||
<Match when={true}>
|
||||
<KobalteTooltip
|
||||
gutter={4}
|
||||
openDelay={400}
|
||||
skipDelayDuration={300}
|
||||
openDelay={local.delay === "intent" ? 0 : 400}
|
||||
skipDelayDuration={local.delay === "intent" ? 0 : 300}
|
||||
{...others}
|
||||
closeDelay={0}
|
||||
ignoreSafeArea={local.ignoreSafeArea ?? true}
|
||||
@@ -101,7 +127,11 @@ export function TooltipV2(props: TooltipV2Props) {
|
||||
justClickedTrigger = false
|
||||
return
|
||||
}
|
||||
setState("open", open)
|
||||
if (open) {
|
||||
show()
|
||||
return
|
||||
}
|
||||
close()
|
||||
}}
|
||||
>
|
||||
<KobalteTooltip.Trigger
|
||||
|
||||
@@ -112,6 +112,7 @@ OpenCode Zen هي بوابة AI تتيح لك الوصول إلى هذه الن
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -141,6 +142,7 @@ https://opencode.ai/zen/v1/models
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -217,6 +219,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
- Laguna S 2.1 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
- Ling-3.0-flash Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
- LongCat-2.0 Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
- North Mini Code Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
- Nemotron 3 Ultra Free متاح على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
- Big Pickle نموذج خفي ومتاح مجانا على OpenCode لفترة محدودة. يستخدم الفريق هذه الفترة لجمع الملاحظات وتحسين النموذج.
|
||||
@@ -275,6 +278,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free: خلال فترته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج.
|
||||
- Laguna S 2.1 Free: خلال فترته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج.
|
||||
- Ling-3.0-flash Free: خلال فترته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج.
|
||||
- LongCat-2.0 Free: خلال فترته المجانية، قد تُستخدم البيانات المجمعة لتحسين النموذج.
|
||||
- North Mini Code Free: خلال فترته المجانية، قد يُحتفَظ بالبيانات المُجمَّعة وتُستخدم لتحسين النموذج. لا تُرسل بيانات شخصية أو سرية. راجع [شروط الاستخدام](https://cohere.com/terms-of-use) و[سياسة الخصوصية](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (نقاط نهاية NVIDIA المجانية): للاستخدام التجريبي فقط — لا ترسل بيانات شخصية أو سرية. يُسجَّل استخدامك لأغراض أمنية ولتحسين منتجات وخدمات NVIDIA. بيانات الجلسة المُسجَّلة لأغراض التحسين غير مرتبطة بهويتك أو بأي مُعرِّف دائم. لمزيد من المعلومات حول ممارسات معالجة البيانات لدينا، راجع [سياسة الخصوصية](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). بتفاعلك مع نقطة النهاية هذه، فإنك توافق على جمعنا لهذه المعلومات وتسجيلها واستخدامها وعلى [شروط خدمة النسخة التجريبية من واجهة NVIDIA API](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: يتم الاحتفاظ بالطلبات لمدة 30 يوما وفقا لـ [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -117,6 +117,7 @@ Našim modelima možete pristupiti i preko sljedećih API endpointa.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ Podržavamo pay-as-you-go model. Ispod su cijene **po 1M tokena**.
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ Besplatni modeli:
|
||||
- MiMo-V2.5 Free je dostupan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
- Laguna S 2.1 Free je dostupan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
- Ling-3.0-flash Free je dostupan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
- LongCat-2.0 Free je dostupan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
- North Mini Code Free je dostupan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
- Nemotron 3 Ultra Free je dostupan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
- Big Pickle je stealth model koji je besplatan na OpenCode ograničeno vrijeme. Tim koristi ovo vrijeme da prikupi povratne informacije i poboljša model.
|
||||
@@ -287,6 +290,7 @@ i ne koriste vaše podatke za treniranje modela, uz sljedeće izuzetke:
|
||||
- MiMo-V2.5 Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljšanje modela.
|
||||
- Laguna S 2.1 Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljšanje modela.
|
||||
- Ling-3.0-flash Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljšanje modela.
|
||||
- LongCat-2.0 Free: Tokom besplatnog perioda, prikupljeni podaci mogu se koristiti za poboljšanje modela.
|
||||
- North Mini Code Free: Tokom besplatnog perioda, prikupljeni podaci mogu biti zadržani i korišteni za poboljšanje modela. Nemojte slati lične ili povjerljive podatke. Pogledajte naše [Uslove korištenja](https://cohere.com/terms-of-use) i [Politiku privatnosti](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (besplatni NVIDIA endpointi): Samo za probnu upotrebu — nemojte slati lične ili povjerljive podatke. Vaše korištenje se bilježi radi sigurnosti i poboljšanja NVIDIA proizvoda i usluga. Zabilježeni podaci sesije koji se koriste u svrhu poboljšanja nisu povezani s vašim identitetom niti bilo kojim trajnim identifikatorom. Za više informacija o našim praksama obrade podataka pogledajte našu [Politiku privatnosti](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Interakcijom s ovim endpointom pristajete na naše prikupljanje, bilježenje i korištenje takvih informacija te na [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: Requests are retained for 30 days in accordance with [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -117,6 +117,7 @@ Du kan også få adgang til vores modeller gennem følgende API-endpoints.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ Vi understøtter en pay-as-you-go-model. Nedenfor er priserne **pr. 1M tokens**.
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ De gratis modeller:
|
||||
- MiMo-V2.5 Free er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
- Laguna S 2.1 Free er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
- Ling-3.0-flash Free er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
- LongCat-2.0 Free er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
- North Mini Code Free er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
- Nemotron 3 Ultra Free er tilgængelig på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
- Big Pickle er en stealth-model, som er gratis på OpenCode i en begrænset periode. Teamet bruger denne tid til at indsamle feedback og forbedre modellen.
|
||||
@@ -285,6 +288,7 @@ Alle vores modeller hostes i US. Vores udbydere følger en nul-opbevaringspoliti
|
||||
- MiMo-V2.5 Free: I den gratis periode kan indsamlede data blive brugt til at forbedre modellen.
|
||||
- Laguna S 2.1 Free: I den gratis periode kan indsamlede data blive brugt til at forbedre modellen.
|
||||
- Ling-3.0-flash Free: I den gratis periode kan indsamlede data blive brugt til at forbedre modellen.
|
||||
- LongCat-2.0 Free: I den gratis periode kan indsamlede data blive brugt til at forbedre modellen.
|
||||
- North Mini Code Free: I gratisperioden kan indsamlede data blive opbevaret og brugt til at forbedre modellen. Indsend ikke personlige eller fortrolige oplysninger. Se vores [Brugsvilkår](https://cohere.com/terms-of-use) og [Privatlivspolitik](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (gratis NVIDIA-endpoints): Kun til prøvebrug — indsend ikke personlige eller fortrolige data. Din brug logges af sikkerhedshensyn og for at forbedre NVIDIAs produkter og tjenester. De loggede sessionsdata, der bruges til forbedringsformål, er ikke knyttet til din identitet eller nogen vedvarende identifikator. For mere information om vores databehandlingspraksis, se vores [privatlivspolitik](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Ved at interagere med dette endpoint giver du samtykke til vores indsamling, registrering og brug af sådanne oplysninger samt [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: Anmodninger opbevares i 30 dage i overensstemmelse med [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -108,6 +108,7 @@ Du kannst auch über die folgenden API-Endpunkte auf unsere Modelle zugreifen.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -137,6 +138,7 @@ Wir unterstützen ein Pay-as-you-go-Modell. Unten findest du die Preise **pro 1M
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -213,6 +215,7 @@ Die kostenlosen Modelle:
|
||||
- MiMo-V2.5 Free ist für begrenzte Zeit auf OpenCode verfügbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
- Laguna S 2.1 Free ist für begrenzte Zeit auf OpenCode verfügbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
- Ling-3.0-flash Free ist für begrenzte Zeit auf OpenCode verfügbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
- LongCat-2.0 Free ist für begrenzte Zeit auf OpenCode verfügbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
- North Mini Code Free ist für begrenzte Zeit auf OpenCode verfügbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
- Nemotron 3 Ultra Free ist für begrenzte Zeit auf OpenCode verfügbar. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
- Big Pickle ist ein Stealth-Modell, das für begrenzte Zeit kostenlos auf OpenCode verfügbar ist. Das Team nutzt diese Zeit, um Feedback zu sammeln und das Modell zu verbessern.
|
||||
@@ -271,6 +274,7 @@ Alle unsere Modelle werden in den USA gehostet. Unsere Provider folgen einer Zer
|
||||
- MiMo-V2.5 Free: Während des kostenlosen Zeitraums können gesammelte Daten zur Verbesserung des Modells verwendet werden.
|
||||
- Laguna S 2.1 Free: Während des kostenlosen Zeitraums können gesammelte Daten zur Verbesserung des Modells verwendet werden.
|
||||
- Ling-3.0-flash Free: Während des kostenlosen Zeitraums können gesammelte Daten zur Verbesserung des Modells verwendet werden.
|
||||
- LongCat-2.0 Free: Während des kostenlosen Zeitraums können gesammelte Daten zur Verbesserung des Modells verwendet werden.
|
||||
- North Mini Code Free: Während des kostenlosen Zeitraums können erhobene Daten gespeichert und zur Verbesserung des Modells verwendet werden. Übermitteln Sie keine personenbezogenen oder vertraulichen Daten. Weitere Informationen finden Sie in unseren [Nutzungsbedingungen](https://cohere.com/terms-of-use) und unserer [Datenschutzerklärung](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (kostenlose NVIDIA-Endpunkte): Nur für Testzwecke — übermitteln Sie keine personenbezogenen oder vertraulichen Daten. Ihre Nutzung wird zu Sicherheitszwecken und zur Verbesserung der Produkte und Dienste von NVIDIA protokolliert. Die zu Verbesserungszwecken protokollierten Sitzungsdaten sind nicht mit Ihrer Identität oder einem dauerhaften Identifikator verknüpft. Weitere Informationen zu unseren Datenverarbeitungspraktiken finden Sie in unserer [Datenschutzrichtlinie](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Durch die Interaktion mit diesem Endpunkt stimmen Sie unserer Erhebung, Aufzeichnung und Nutzung solcher Informationen sowie den [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf) zu.
|
||||
- OpenAI APIs: Anfragen werden in Übereinstimmung mit [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data) 30 Tage lang gespeichert.
|
||||
|
||||
@@ -117,6 +117,7 @@ También puedes acceder a nuestros modelos a través de los siguientes endpoints
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ Admitimos un modelo de pago por uso. A continuación se muestran los precios **p
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ Los modelos gratuitos:
|
||||
- MiMo-V2.5 Free está disponible en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
- Laguna S 2.1 Free está disponible en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
- Ling-3.0-flash Free está disponible en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
- LongCat-2.0 Free está disponible en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
- North Mini Code Free está disponible en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
- Nemotron 3 Ultra Free está disponible en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
- Big Pickle es un modelo stealth que es gratuito en OpenCode por tiempo limitado. El equipo está usando este tiempo para recopilar comentarios y mejorar el modelo.
|
||||
@@ -285,6 +288,7 @@ Todos nuestros modelos están alojados en US. Nuestros proveedores siguen una po
|
||||
- MiMo-V2.5 Free: Durante su período gratuito, los datos recopilados pueden usarse para mejorar el modelo.
|
||||
- Laguna S 2.1 Free: Durante su período gratuito, los datos recopilados pueden usarse para mejorar el modelo.
|
||||
- Ling-3.0-flash Free: Durante su período gratuito, los datos recopilados pueden usarse para mejorar el modelo.
|
||||
- LongCat-2.0 Free: Durante su período gratuito, los datos recopilados pueden usarse para mejorar el modelo.
|
||||
- North Mini Code Free: Durante el período gratuito, los datos recopilados podrán conservarse y utilizarse para mejorar el modelo. No envíes datos personales ni confidenciales. Consulta nuestros [Términos de uso](https://cohere.com/terms-of-use) y nuestra [Política de privacidad](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (endpoints gratuitos de NVIDIA): Solo para uso de prueba — no envíes datos personales ni confidenciales. Tu uso se registra con fines de seguridad y para mejorar los productos y servicios de NVIDIA. Los datos de sesión registrados con fines de mejora no están vinculados a tu identidad ni a ningún identificador persistente. Para obtener más información sobre nuestras prácticas de procesamiento de datos, consulta nuestra [Política de privacidad](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Al interactuar con este endpoint, aceptas que recopilemos, registremos y usemos dicha información, así como los [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: Las solicitudes se conservan durante 30 días de acuerdo con [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -108,6 +108,7 @@ Vous pouvez également accéder à nos modèles via les points de terminaison AP
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -137,6 +138,7 @@ Nous prenons en charge un modèle de paiement à l'utilisation. Vous trouverez c
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -213,6 +215,7 @@ Les modèles gratuits :
|
||||
- MiMo-V2.5 Free est disponible sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
- Laguna S 2.1 Free est disponible sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
- Ling-3.0-flash Free est disponible sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
- LongCat-2.0 Free est disponible sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
- North Mini Code Free est disponible sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
- Nemotron 3 Ultra Free est disponible sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
- Big Pickle est un modèle stealth gratuit sur OpenCode pour une durée limitée. L'équipe utilise cette période pour recueillir des retours et améliorer le modèle.
|
||||
@@ -271,6 +274,7 @@ Tous nos modèles sont hébergés aux US. Nos fournisseurs suivent une politique
|
||||
- MiMo-V2.5 Free : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle.
|
||||
- Laguna S 2.1 Free : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle.
|
||||
- Ling-3.0-flash Free : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle.
|
||||
- LongCat-2.0 Free : Pendant sa période gratuite, les données collectées peuvent être utilisées pour améliorer le modèle.
|
||||
- North Mini Code Free : Pendant la période de gratuité, les données collectées peuvent être conservées et utilisées pour améliorer le modèle. Ne transmettez aucune donnée personnelle ou confidentielle. Consultez nos [Conditions d’utilisation](https://cohere.com/terms-of-use) et notre [Politique de confidentialité](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (endpoints NVIDIA gratuits) : Réservé à un usage d'essai — n'envoyez pas de données personnelles ou confidentielles. Votre utilisation est journalisée à des fins de sécurité et pour améliorer les produits et services de NVIDIA. Les données de session journalisées à des fins d'amélioration ne sont pas liées à votre identité ni à un quelconque identifiant persistant. Pour plus d'informations sur nos pratiques de traitement des données, consultez notre [Politique de confidentialité](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). En interagissant avec cet endpoint, vous consentez à notre collecte, à notre enregistrement et à notre utilisation de ces informations ainsi qu'aux [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs : Les requêtes sont conservées pendant 30 jours conformément à [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -117,6 +117,7 @@ Puoi anche accedere ai nostri modelli tramite i seguenti endpoint API.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ Supportiamo un modello pay-as-you-go. Qui sotto trovi i prezzi **per 1M token**.
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ I modelli gratuiti:
|
||||
- MiMo-V2.5 Free è disponibile su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
- Laguna S 2.1 Free è disponibile su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
- Ling-3.0-flash Free è disponibile su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
- LongCat-2.0 Free è disponibile su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
- North Mini Code Free è disponibile su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
- Nemotron 3 Ultra Free è disponibile su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
- Big Pickle è un modello stealth che è gratuito su OpenCode per un periodo limitato. Il team usa questo periodo per raccogliere feedback e migliorare il modello.
|
||||
@@ -285,6 +288,7 @@ Tutti i nostri modelli sono ospitati negli US. I nostri provider seguono una pol
|
||||
- MiMo-V2.5 Free: durante il periodo gratuito, i dati raccolti possono essere usati per migliorare il modello.
|
||||
- Laguna S 2.1 Free: durante il periodo gratuito, i dati raccolti possono essere usati per migliorare il modello.
|
||||
- Ling-3.0-flash Free: durante il periodo gratuito, i dati raccolti possono essere usati per migliorare il modello.
|
||||
- LongCat-2.0 Free: durante il periodo gratuito, i dati raccolti possono essere usati per migliorare il modello.
|
||||
- North Mini Code Free: Durante il periodo gratuito, i dati raccolti possono essere conservati e utilizzati per migliorare il modello. Non inviare dati personali o riservati. Consulta i nostri [Termini di utilizzo](https://cohere.com/terms-of-use) e la nostra [Informativa sulla privacy](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (endpoint NVIDIA gratuiti): solo per uso di prova — non inviare dati personali o riservati. Il tuo utilizzo viene registrato per finalità di sicurezza e per migliorare i prodotti e i servizi di NVIDIA. I dati di sessione registrati a fini di miglioramento non sono collegati alla tua identità né ad alcun identificatore persistente. Per maggiori informazioni sulle nostre pratiche di trattamento dei dati, consulta la nostra [Informativa sulla privacy](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Interagendo con questo endpoint, acconsenti alla nostra raccolta, registrazione e utilizzo di tali informazioni e ai [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: le richieste vengono conservate per 30 giorni in conformità con [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -108,6 +108,7 @@ OpenCode Zen は、OpenCode のほかのプロバイダーと同じように動
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -137,6 +138,7 @@ https://opencode.ai/zen/v1/models
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -213,6 +215,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free は期間限定で OpenCode で利用できます。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
- Laguna S 2.1 Free は期間限定で OpenCode で利用できます。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
- Ling-3.0-flash Free は期間限定で OpenCode で利用できます。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
- LongCat-2.0 Free は期間限定で OpenCode で利用できます。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
- North Mini Code Free は期間限定で OpenCode で利用できます。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
- Nemotron 3 Ultra Free は期間限定で OpenCode で利用できます。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
- Big Pickle はステルスモデルで、期間限定で OpenCode で無料提供されています。チームはこの期間中にフィードバックを集め、モデルを改善しています。
|
||||
@@ -271,6 +274,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free: 無料提供期間中、収集されたデータがモデル改善に使われる場合があります。
|
||||
- Laguna S 2.1 Free: 無料提供期間中、収集されたデータがモデル改善に使われる場合があります。
|
||||
- Ling-3.0-flash Free: 無料提供期間中、収集されたデータがモデル改善に使われる場合があります。
|
||||
- LongCat-2.0 Free: 無料提供期間中、収集されたデータがモデル改善に使われる場合があります。
|
||||
- North Mini Code Free: 無料提供期間中、収集されたデータは保持され、モデルの改善に使用される場合があります。個人情報や機密情報を送信しないでください。詳しくは、[利用規約](https://cohere.com/terms-of-use)および[プライバシーポリシー](https://cohere.com/privacy)をご覧ください。
|
||||
- Nemotron 3 Ultra Free(NVIDIA の無料エンドポイント): 試用専用です — 個人情報や機密データは送信しないでください。お客様の利用は、セキュリティ目的および NVIDIA の製品とサービスの改善のために記録されます。改善目的で記録されたセッションデータは、お客様の身元や永続的な識別子とは関連付けられません。当社のデータ処理慣行の詳細については、[プライバシーポリシー](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf)をご覧ください。このエンドポイントを利用することで、お客様はそのような情報の当社による収集、記録、利用、および [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf) に同意したものとみなされます。
|
||||
- OpenAI APIs: リクエストは [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data) に従って 30 日間保持されます。
|
||||
|
||||
@@ -108,6 +108,7 @@ OpenCode Zen은 OpenCode의 다른 provider와 똑같이 작동합니다.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -137,6 +138,7 @@ https://opencode.ai/zen/v1/models
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -213,6 +215,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
- Laguna S 2.1 Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
- Ling-3.0-flash Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
- LongCat-2.0 Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
- North Mini Code Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
- Nemotron 3 Ultra Free는 한정된 기간 동안 OpenCode에서 제공됩니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
- Big Pickle은 한정된 기간 동안 OpenCode에서 무료로 제공되는 stealth model입니다. 팀은 이 기간에 피드백을 수집하고 모델을 개선합니다.
|
||||
@@ -271,6 +274,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free: 무료 제공 기간에는 수집된 데이터가 모델 개선에 사용될 수 있습니다.
|
||||
- Laguna S 2.1 Free: 무료 제공 기간에는 수집된 데이터가 모델 개선에 사용될 수 있습니다.
|
||||
- Ling-3.0-flash Free: 무료 제공 기간에는 수집된 데이터가 모델 개선에 사용될 수 있습니다.
|
||||
- LongCat-2.0 Free: 무료 제공 기간에는 수집된 데이터가 모델 개선에 사용될 수 있습니다.
|
||||
- North Mini Code Free: 무료 제공 기간 동안 수집된 데이터는 보관되며 모델 개선에 사용될 수 있습니다. 개인 정보나 기밀 정보를 제출하지 마세요. 자세한 내용은 [이용 약관](https://cohere.com/terms-of-use) 및 [개인정보 처리방침](https://cohere.com/privacy)을 참조하세요.
|
||||
- Nemotron 3 Ultra Free(NVIDIA 무료 엔드포인트): 평가판 전용이며 — 개인 정보나 기밀 데이터는 제출하지 마세요. 사용 내역은 보안 목적과 NVIDIA 제품 및 서비스 개선을 위해 기록됩니다. 개선 목적으로 기록된 세션 데이터는 사용자의 신원이나 영구 식별자와 연결되지 않습니다. 당사의 데이터 처리 관행에 대한 자세한 내용은 [개인정보처리방침](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf)을 참조하세요. 이 엔드포인트와 상호 작용함으로써 사용자는 당사가 이러한 정보를 수집, 기록, 사용하는 것과 [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf)에 동의하게 됩니다.
|
||||
- OpenAI APIs: 요청은 [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data)에 따라 30일 동안 보관됩니다.
|
||||
|
||||
@@ -117,6 +117,7 @@ Du kan også få tilgang til modellene våre gjennom følgende API-endepunkter.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ Vi støtter en pay-as-you-go-modell. Nedenfor er prisene **per 1M tokens**.
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ Gratis-modellene:
|
||||
- MiMo-V2.5 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
- Laguna S 2.1 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
- Ling-3.0-flash Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
- LongCat-2.0 Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
- North Mini Code Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
- Nemotron 3 Ultra Free er tilgjengelig på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
- Big Pickle er en stealth-modell som er gratis på OpenCode i en begrenset periode. Teamet bruker denne tiden til å samle inn tilbakemeldinger og forbedre modellen.
|
||||
@@ -285,6 +288,7 @@ Alle modellene våre hostes i US. Leverandørene våre følger en policy for zer
|
||||
- MiMo-V2.5 Free: I gratisperioden kan innsamlede data brukes til å forbedre modellen.
|
||||
- Laguna S 2.1 Free: I gratisperioden kan innsamlede data brukes til å forbedre modellen.
|
||||
- Ling-3.0-flash Free: I gratisperioden kan innsamlede data brukes til å forbedre modellen.
|
||||
- LongCat-2.0 Free: I gratisperioden kan innsamlede data brukes til å forbedre modellen.
|
||||
- North Mini Code Free: I gratisperioden kan innsamlede data bli oppbevart og brukt til å forbedre modellen. Ikke send inn personopplysninger eller konfidensielle opplysninger. Se våre [Vilkår for bruk](https://cohere.com/terms-of-use) og vår [Personvernerklæring](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (gratis NVIDIA-endepunkter): Kun for prøvebruk — ikke send inn personopplysninger eller konfidensielle data. Bruken din logges av sikkerhetshensyn og for å forbedre NVIDIAs produkter og tjenester. Sesjonsdataene som logges for forbedringsformål, er ikke knyttet til identiteten din eller noen vedvarende identifikator. For mer informasjon om vår databehandlingspraksis, se vår [personvernerklæring](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Ved å samhandle med dette endepunktet samtykker du til at vi samler inn, registrerer og bruker slik informasjon, samt til [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: Forespørsler lagres i 30 dager i samsvar med [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -117,6 +117,7 @@ Możesz też uzyskać dostęp do naszych modeli przez poniższe endpointy API.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ Obsługujemy model pay-as-you-go. Poniżej znajdują się ceny **za 1M tokenów*
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ Darmowe modele:
|
||||
- MiMo-V2.5 Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
- Laguna S 2.1 Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
- Ling-3.0-flash Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
- LongCat-2.0 Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
- North Mini Code Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
- Nemotron 3 Ultra Free jest dostępny w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
- Big Pickle to stealth model, który jest darmowy w OpenCode przez ograniczony czas. Zespół wykorzystuje ten czas do zbierania opinii i ulepszania modelu.
|
||||
@@ -285,6 +288,7 @@ Wszystkie nasze modele są hostowane w US. Nasi dostawcy stosują politykę zero
|
||||
- MiMo-V2.5 Free: W czasie darmowego okresu zebrane dane mogą być wykorzystywane do ulepszania modelu.
|
||||
- Laguna S 2.1 Free: W czasie darmowego okresu zebrane dane mogą być wykorzystywane do ulepszania modelu.
|
||||
- Ling-3.0-flash Free: W czasie darmowego okresu zebrane dane mogą być wykorzystywane do ulepszania modelu.
|
||||
- LongCat-2.0 Free: W czasie darmowego okresu zebrane dane mogą być wykorzystywane do ulepszania modelu.
|
||||
- North Mini Code Free: W okresie bezpłatnego dostępu zebrane dane mogą być przechowywane i wykorzystywane do ulepszania modelu. Nie przesyłaj danych osobowych ani poufnych. Zapoznaj się z naszym [Regulaminem korzystania](https://cohere.com/terms-of-use) i [Polityką prywatności](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (darmowe endpointy NVIDIA): Tylko do użytku próbnego — nie przesyłaj danych osobowych ani poufnych. Twoje korzystanie jest rejestrowane w celach bezpieczeństwa oraz w celu ulepszania produktów i usług NVIDIA. Rejestrowane dane sesji wykorzystywane do celów ulepszania nie są powiązane z Twoją tożsamością ani żadnym trwałym identyfikatorem. Aby uzyskać więcej informacji o naszych praktykach przetwarzania danych, zapoznaj się z naszą [Polityką prywatności](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Korzystając z tego endpointu, wyrażasz zgodę na gromadzenie, rejestrowanie i wykorzystywanie przez nas takich informacji oraz na [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: Żądania są przechowywane przez 30 dni zgodnie z [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -2308,9 +2308,9 @@ Some useful routing options:
|
||||
|
||||
### xAI
|
||||
|
||||
Three ways to authenticate: a SuperGrok subscription via browser OAuth, the same SuperGrok subscription via a headless device-code flow (for VPS / SSH / Docker), or a pay-as-you-go API key from the xAI console.
|
||||
Two ways to authenticate: a SuperGrok subscription via device-code OAuth or a pay-as-you-go API key from the xAI console.
|
||||
|
||||
#### Option A — SuperGrok OAuth (browser login)
|
||||
#### Option A — SuperGrok subscription
|
||||
|
||||
1. Run the `/connect` command and search for **xAI**.
|
||||
|
||||
@@ -2318,9 +2318,11 @@ Three ways to authenticate: a SuperGrok subscription via browser OAuth, the same
|
||||
/connect
|
||||
```
|
||||
|
||||
2. Select **xAI Grok OAuth (SuperGrok Subscription)**. OpenCode opens xAI's consent screen in your browser and waits for the callback on `http://127.0.0.1:56121/callback`.
|
||||
2. Select **SuperGrok Subscription**. OpenCode opens xAI's verification link with the user code pre-populated when supported.
|
||||
|
||||
3. Run the `/models` command to select a Grok model.
|
||||
3. Approve the consent screen. If xAI asks for a code, enter the user code displayed by OpenCode. OpenCode polls xAI's token endpoint and stores the resulting OAuth tokens once you approve.
|
||||
|
||||
4. Run the `/models` command to select a Grok model.
|
||||
|
||||
```txt
|
||||
/models
|
||||
@@ -2328,25 +2330,7 @@ Three ways to authenticate: a SuperGrok subscription via browser OAuth, the same
|
||||
|
||||
OpenCode refreshes the OAuth access token automatically. Any Grok or X Premium plan that includes Grok API access works; you do not need a separate `XAI_API_KEY`.
|
||||
|
||||
#### Option B — SuperGrok device-code (headless / remote server / VPS)
|
||||
|
||||
Use this when OpenCode is running somewhere a browser can't reach the loopback redirect: a VPS, a remote dev box over SSH, inside Docker, in CI, etc. No callback port is opened on the host running OpenCode — instead xAI hands the CLI a short code that you type into a browser on any other device (laptop, phone, …).
|
||||
|
||||
1. Run the `/connect` command on the remote host and search for **xAI**.
|
||||
|
||||
```txt
|
||||
/connect
|
||||
```
|
||||
|
||||
2. Select **xAI Grok OAuth (Headless / Remote / VPS)**. OpenCode prints a verification URL and a short user code.
|
||||
|
||||
```txt
|
||||
Open https://x.ai/device on any device and enter code: ABCD-1234
|
||||
```
|
||||
|
||||
3. Open the URL on a device that has a browser (your laptop or phone), enter the code, and approve the consent screen. OpenCode polls xAI's token endpoint and stores the resulting OAuth tokens once you approve. Token refresh works the same as Option A.
|
||||
|
||||
#### Option C — API key
|
||||
#### Option B — API key
|
||||
|
||||
1. Head over to the [xAI console](https://console.x.ai/), create an account, and generate an API key.
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ Você também pode acessar nossos modelos pelos seguintes endpoints de API.
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -137,6 +138,7 @@ Oferecemos um modelo pay-as-you-go. Abaixo estão os preços **por 1M tokens**.
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -213,6 +215,7 @@ Os modelos gratuitos:
|
||||
- MiMo-V2.5 Free está disponível no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
- Laguna S 2.1 Free está disponível no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
- Ling-3.0-flash Free está disponível no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
- LongCat-2.0 Free está disponível no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
- North Mini Code Free está disponível no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
- Nemotron 3 Ultra Free está disponível no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
- Big Pickle é um modelo stealth que está gratuito no OpenCode por tempo limitado. A equipe está usando esse período para coletar feedback e melhorar o modelo.
|
||||
@@ -271,6 +274,7 @@ Todos os nossos modelos são hospedados nos US. Nossos provedores seguem uma pol
|
||||
- MiMo-V2.5 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo.
|
||||
- Laguna S 2.1 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo.
|
||||
- Ling-3.0-flash Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo.
|
||||
- LongCat-2.0 Free: Durante seu período gratuito, os dados coletados podem ser usados para melhorar o modelo.
|
||||
- North Mini Code Free: Durante o período gratuito, os dados coletados poderão ser retidos e usados para aprimorar o modelo. Não envie dados pessoais ou confidenciais. Consulte nossos [Termos de Uso](https://cohere.com/terms-of-use) e nossa [Política de Privacidade](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (endpoints gratuitos da NVIDIA): Apenas para uso de avaliação — não envie dados pessoais ou confidenciais. Seu uso é registrado para fins de segurança e para melhorar os produtos e serviços da NVIDIA. Os dados de sessão registrados para fins de melhoria não estão vinculados à sua identidade nem a qualquer identificador persistente. Para mais informações sobre nossas práticas de processamento de dados, consulte nossa [Política de Privacidade](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Ao interagir com este endpoint, você consente com a nossa coleta, registro e uso dessas informações e com os [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: As solicitações são retidas por 30 dias de acordo com [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -117,6 +117,7 @@ OpenCode Zen работает как любой другой провайдер
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -148,6 +149,7 @@ https://opencode.ai/zen/v1/models
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -224,6 +226,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free доступна в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
- Laguna S 2.1 Free доступна в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
- Ling-3.0-flash Free доступна в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
- LongCat-2.0 Free доступна в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
- North Mini Code Free доступна в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
- Nemotron 3 Ultra Free доступна в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
- Big Pickle — это скрытая модель, которая доступна бесплатно в OpenCode ограниченное время. Команда использует это время, чтобы собирать отзывы и улучшать модель.
|
||||
@@ -285,6 +288,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free: во время бесплатного периода собранные данные могут использоваться для улучшения модели.
|
||||
- Laguna S 2.1 Free: во время бесплатного периода собранные данные могут использоваться для улучшения модели.
|
||||
- Ling-3.0-flash Free: во время бесплатного периода собранные данные могут использоваться для улучшения модели.
|
||||
- LongCat-2.0 Free: во время бесплатного периода собранные данные могут использоваться для улучшения модели.
|
||||
- North Mini Code Free: В течение бесплатного периода собранные данные могут храниться и использоваться для улучшения модели. Не отправляйте персональные или конфиденциальные данные. Ознакомьтесь с нашими [Условиями использования](https://cohere.com/terms-of-use) и [Политикой конфиденциальности](https://cohere.com/privacy).
|
||||
- Nemotron 3 Ultra Free (бесплатные эндпоинты NVIDIA): только для пробного использования — не отправляйте персональные или конфиденциальные данные. Использование логируется в целях безопасности и для улучшения продуктов и сервисов NVIDIA. Логируемые данные сессии, используемые в целях улучшения, не связаны с вашей личностью или каким-либо постоянным идентификатором. Подробнее о наших практиках обработки данных см. в нашей [Политике конфиденциальности](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Взаимодействуя с этим эндпоинтом, вы соглашаетесь на сбор, запись и использование нами такой информации, а также с [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf).
|
||||
- OpenAI APIs: запросы хранятся 30 дней в соответствии с [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -110,6 +110,7 @@ OpenCode Zen ทำงานเหมือน provider อื่น ๆ ใน
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -139,6 +140,7 @@ https://opencode.ai/zen/v1/models
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -215,6 +217,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free เปิดให้ใช้บน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
- Laguna S 2.1 Free เปิดให้ใช้บน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
- Ling-3.0-flash Free เปิดให้ใช้บน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
- LongCat-2.0 Free เปิดให้ใช้บน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
- North Mini Code Free เปิดให้ใช้บน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
- Nemotron 3 Ultra Free เปิดให้ใช้บน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
- Big Pickle เป็น stealth model ที่ใช้งานฟรีบน OpenCode ในช่วงเวลาจำกัด ทีมกำลังใช้ช่วงเวลานี้เพื่อเก็บ feedback และปรับปรุงโมเดล
|
||||
@@ -273,6 +276,7 @@ https://opencode.ai/zen/v1/models
|
||||
- MiMo-V2.5 Free: ระหว่างช่วงที่เปิดให้ใช้ฟรี ข้อมูลที่เก็บรวบรวมอาจถูกนำไปใช้เพื่อปรับปรุงโมเดล
|
||||
- Laguna S 2.1 Free: ระหว่างช่วงที่เปิดให้ใช้ฟรี ข้อมูลที่เก็บรวบรวมอาจถูกนำไปใช้เพื่อปรับปรุงโมเดล
|
||||
- Ling-3.0-flash Free: ระหว่างช่วงที่เปิดให้ใช้ฟรี ข้อมูลที่เก็บรวบรวมอาจถูกนำไปใช้เพื่อปรับปรุงโมเดล
|
||||
- LongCat-2.0 Free: ระหว่างช่วงที่เปิดให้ใช้ฟรี ข้อมูลที่เก็บรวบรวมอาจถูกนำไปใช้เพื่อปรับปรุงโมเดล
|
||||
- North Mini Code Free: ในช่วงที่เปิดให้ใช้ฟรี ข้อมูลที่เก็บรวบรวมอาจถูกเก็บรักษาและนำไปใช้เพื่อปรับปรุงโมเดล โปรดอย่าส่งข้อมูลส่วนบุคคลหรือข้อมูลที่เป็นความลับ ดู[ข้อกำหนดการใช้งาน](https://cohere.com/terms-of-use)และ[นโยบายความเป็นส่วนตัว](https://cohere.com/privacy)ของเรา
|
||||
- Nemotron 3 Ultra Free (endpoint ฟรีของ NVIDIA): ใช้สำหรับการทดลองเท่านั้น — โปรดอย่าส่งข้อมูลส่วนบุคคลหรือข้อมูลลับ การใช้งานของคุณจะถูกบันทึกเพื่อวัตถุประสงค์ด้านความปลอดภัยและเพื่อปรับปรุงผลิตภัณฑ์และบริการของ NVIDIA ข้อมูลเซสชันที่บันทึกไว้เพื่อวัตถุประสงค์ในการปรับปรุงจะไม่เชื่อมโยงกับตัวตนของคุณหรือตัวระบุถาวรใด ๆ สำหรับข้อมูลเพิ่มเติมเกี่ยวกับแนวปฏิบัติในการประมวลผลข้อมูลของเรา โปรดดู [นโยบายความเป็นส่วนตัว](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf) ของเรา การโต้ตอบกับ endpoint นี้ถือว่าคุณยินยอมให้เราเก็บรวบรวม บันทึก และใช้ข้อมูลดังกล่าว รวมถึง [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf)
|
||||
- OpenAI APIs: คำขอจะถูกเก็บไว้เป็นเวลา 30 วันตาม [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data).
|
||||
|
||||
@@ -108,6 +108,7 @@ Modellerimize aşağıdaki API uç noktaları aracılığıyla da erişebilirsin
|
||||
| MiMo-V2.5 Free | mimo-v2.5-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Laguna S 2.1 Free | laguna-s-2.1-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Ling-3.0-flash Free | ling-3.0-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| LongCat-2.0 Free | longcat-2.0-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| North Mini Code Free | north-mini-code-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| Nemotron 3 Ultra Free | nemotron-3-ultra-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
| DeepSeek V4 Flash Free | deepseek-v4-flash-free | `https://opencode.ai/zen/v1/chat/completions` | `@ai-sdk/openai-compatible` |
|
||||
@@ -137,6 +138,7 @@ Kullandıkça öde modelini destekliyoruz. Aşağıda **1M token başına** fiya
|
||||
| MiMo-V2.5 Free | Free | Free | Free | - |
|
||||
| Laguna S 2.1 Free | Free | Free | Free | - |
|
||||
| Ling-3.0-flash Free | Free | Free | Free | - |
|
||||
| LongCat-2.0 Free | Free | Free | Free | - |
|
||||
| North Mini Code Free | Free | Free | Free | - |
|
||||
| Nemotron 3 Ultra Free | Free | Free | Free | - |
|
||||
| MiniMax M3 | $0.30 | $1.20 | $0.06 | - |
|
||||
@@ -213,6 +215,7 @@ Kredi kartı ücretleri maliyet üzerinden yansıtılır (%4.4 + işlem başına
|
||||
- MiMo-V2.5 Free, sınırlı bir süre için OpenCode'da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
- Laguna S 2.1 Free, sınırlı bir süre için OpenCode'da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
- Ling-3.0-flash Free, sınırlı bir süre için OpenCode'da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
- LongCat-2.0 Free, sınırlı bir süre için OpenCode'da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
- North Mini Code Free, sınırlı bir süre için OpenCode'da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
- Nemotron 3 Ultra Free, sınırlı bir süre için OpenCode'da ücretsizdir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
- Big Pickle, sınırlı bir süre için OpenCode'da ücretsiz olan gizli bir modeldir. Ekip bu süreyi geri bildirim toplamak ve modeli iyileştirmek için kullanıyor.
|
||||
@@ -271,6 +274,7 @@ Tüm modellerimiz US'de barındırılıyor. Sağlayıcılarımız zero-retention
|
||||
- MiMo-V2.5 Free: Ücretsiz döneminde toplanan veriler modeli iyileştirmek için kullanılabilir.
|
||||
- Laguna S 2.1 Free: Ücretsiz döneminde toplanan veriler modeli iyileştirmek için kullanılabilir.
|
||||
- Ling-3.0-flash Free: Ücretsiz döneminde toplanan veriler modeli iyileştirmek için kullanılabilir.
|
||||
- LongCat-2.0 Free: Ücretsiz döneminde toplanan veriler modeli iyileştirmek için kullanılabilir.
|
||||
- North Mini Code Free: Ücretsiz kullanım süresi boyunca toplanan veriler saklanabilir ve modeli geliştirmek için kullanılabilir. Kişisel veya gizli veriler göndermeyin. [Kullanım Koşullarımıza](https://cohere.com/terms-of-use) ve [Gizlilik Politikamıza](https://cohere.com/privacy) bakın.
|
||||
- Nemotron 3 Ultra Free (ücretsiz NVIDIA uç noktaları): Yalnızca deneme amaçlıdır — kişisel veya gizli veri göndermeyin. Kullanımınız güvenlik amacıyla ve NVIDIA ürünlerini ve hizmetlerini geliştirmek için kaydedilir. Geliştirme amacıyla kaydedilen oturum verileri kimliğinizle veya herhangi bir kalıcı tanımlayıcıyla ilişkilendirilmez. Veri işleme uygulamalarımız hakkında daha fazla bilgi için [Gizlilik Politikamıza](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf) bakın. Bu uç noktayla etkileşime geçerek, bu tür bilgileri toplamamıza, kaydetmemize ve kullanmamıza ve [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf) koşullarına onay vermiş olursunuz.
|
||||
- OpenAI APIs: İstekler [OpenAI's Data Policies](https://platform.openai.com/docs/guides/your-data) uyarınca 30 gün boyunca saklanır.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user