Compare commits

..

2 Commits

Author SHA1 Message Date
Kit Langton 5acc917591 refactor(test/cli): simplify pass on tier-A + prebuild
Applies findings from the third simplify pass:

1. \`cliArgv\` is a module-level const, not a function — prebuiltCli is
   read once at module init and never mutated, so the per-spawn function
   allocation was pure overhead.

2. Help-snapshot failures surface via \`Effect.fail\` instead of \`throw\`,
   symmetric with the \`Effect.fail\` already inside the partition above.
   Keeps the failure typed in the Effect channel rather than as a defect.

3. \`prebuild-test-cli.ts\` skips the build when the binary is already
   newer than every file in src/ — saves the 2.8s rebuild cost on every
   subsequent invocation. Pass --force to bypass.

4. \`prebuild-test-cli.ts\` verifies the built binary is executable before
   symlinking — catches a silently-failed build leaving stale output
   instead of letting tests fail with confusing exec errors later.

Verified: 331/331 CLI tests pass; typecheck clean; skip-if-fresh + --force
behave as documented.
2026-05-19 11:36:15 -04:00
Kit Langton 5bc6a7f6d0 test(cli): opt-in pre-built binary for ~3x faster subprocess spawns
\`bun run --conditions=browser src/index.ts\` pays ~15s of JIT + plugin
init + DB migration per subprocess spawn in isolation mode. A pre-built
binary cuts that to ~5s — most of which is now the SQLite \`:memory:\`
migration that runs regardless of execution mode.

Adds \`script/prebuild-test-cli.ts\` which wraps the existing build.ts
with \`--single --skip-embed-web-ui --skip-install\`, then symlinks the
platform-specific output to \`dist/test-cli/bin/opencode\` so the
harness has a stable path.

The harness (test/lib/cli-process.ts) reads OPENCODE_TEST_CLI_PATH and
spawns the binary directly when set; falls back to dev mode otherwise.
Strictly opt-in — default behavior, CI, and local iteration are
unchanged. Anyone who wants the speedup runs:

  bun script/prebuild-test-cli.ts
  export OPENCODE_TEST_CLI_PATH="\$PWD/dist/test-cli/bin/opencode"
  bun test test/cli/

Measured locally:
  Dev mode (default):  29.9s  (331 tests)
  Binary mode:         22.1s  (-26%, after one-time 2.8s build)

The win compounds as more subprocess tests are added — every new test
that hits DB migration saves ~10s vs dev mode.
2026-05-19 11:36:15 -04:00
195 changed files with 1524 additions and 34111 deletions
+2 -2
View File
@@ -4,8 +4,8 @@ import { tool } from "@opencode-ai/plugin"
const TEAM = {
tui: ["kommander", "simonklee"],
desktop_web: ["Hona", "Brendonovich"],
core: ["jlongster", "rekram1-node", "nexxeln", "kitlangton", "starptech"],
inference: ["fwang", "MrMushrooooom", "starptech"],
core: ["jlongster", "rekram1-node", "nexxeln", "kitlangton"],
inference: ["fwang", "MrMushrooooom"],
windows: ["Hona"],
} as const
-1
View File
@@ -5,7 +5,6 @@
"type": "module",
"exports": {
".": "./src/index.ts",
"./desktop-menu": "./src/desktop-menu.ts",
"./vite": "./vite.js",
"./index.css": "./src/index.css"
},
+148 -372
View File
@@ -1,23 +1,18 @@
import { createEffect, createMemo, For, mapArray, Match, Show, startTransition, Switch, untrack } from "solid-js"
import { createStore, produce } from "solid-js/store"
import { useLocation, useMatch, useNavigate, useParams } from "@solidjs/router"
import { createEffect, createMemo, Show, untrack } from "solid-js"
import { createStore } from "solid-js/store"
import { useLocation, useNavigate, useParams } from "@solidjs/router"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { Icon } from "@opencode-ai/ui/icon"
import { Button } from "@opencode-ai/ui/button"
import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
import { useTheme } from "@opencode-ai/ui/theme/context"
import { IconButtonV2 } from "@opencode-ai/ui/v2/components/icon-button-v2.jsx"
import { useLayout } from "@/context/layout"
import { usePlatform } from "@/context/platform"
import { useCommand } from "@/context/command"
import { useLanguage } from "@/context/language"
import { useSettings } from "@/context/settings"
import { WindowsAppMenu } from "./windows-app-menu"
import { applyPath, backPath, forwardPath } from "./titlebar-history"
import { useGlobalSync } from "@/context/global-sync"
import { decodeDirectory } from "@/pages/directory-layout"
import { iife } from "@opencode-ai/core/util/iife"
type TauriDesktopWindow = {
startDragging?: () => Promise<void>
@@ -44,8 +39,6 @@ const titlebarHeight = 40
const minTitlebarZoom = 0.25
const windowsControlsBaseWidth = 138 // 3 native Windows caption buttons at 46px each.
const makeSessionHref = (b64Dir: string, sessionId: string) => `/${b64Dir}/session/${sessionId}`
export function Titlebar() {
const layout = useLayout()
const platform = usePlatform()
@@ -59,7 +52,6 @@ export function Titlebar() {
const mac = createMemo(() => platform.platform === "desktop" && platform.os === "macos")
const windows = createMemo(() => platform.platform === "desktop" && platform.os === "windows")
const linux = createMemo(() => platform.platform === "desktop" && platform.os === "linux")
const web = createMemo(() => platform.platform === "web")
const zoom = () => platform.webviewZoom?.() ?? 1
const titlebarZoom = () => (windows() ? Math.max(zoom(), minTitlebarZoom) : zoom())
@@ -183,378 +175,162 @@ export function Titlebar() {
return (
<header
class="h-10 shrink-0 bg-background-base relative overflow-hidden flex flex-row"
style={{ "min-height": minHeight(), "padding-left": mac() ? `${84 / zoom()}px` : 0 }}
class="h-10 shrink-0 bg-background-base relative overflow-hidden"
style={{ "min-height": minHeight() }}
data-tauri-drag-region
onMouseDown={drag}
onDblClick={maximize}
>
<Switch>
<Match when={import.meta.env.VITE_OPENCODE_CHANNEL !== "prod"}>
{(_) => {
const globalSync = useGlobalSync()
const navigate = useNavigate()
type Tab = { dir: string; sessionId: string; params: any; href: string }
const [tabsStore, tabsStoreActions] = iife(() => {
const [store, setStore] = createStore<Tab[]>(
iife(() => {
if (!params.dir || !params.id) return []
return [
{
dir: decodeDirectory(params.dir) ?? "",
sessionId: params.id,
params: { id: params.id, dir: params.dir },
href: makeSessionHref(params.dir, params.id),
},
]
}),
)
const actions = {
addTab: (tab: Tab) => {
setStore(
produce((tabs) => {
if (tabs.some((t) => t.href === tab.href)) return
tabs.push(tab)
}),
)
},
removeTab: (href: string) => {
startTransition(() => {
setStore(
produce((tabs) => {
const index = tabs.findIndex((t) => t.href === href)
if (index === -1) return
tabs.splice(index, 1)
const nextTab = tabs[index] ?? tabs[tabs.length - 1]
if (nextTab) navigate(nextTab.href)
else navigate("/")
}),
)
})
},
}
return [store, actions]
})
createEffect(() => {
const params = useParams()
if (!(params.dir && params.id)) return
tabsStoreActions.addTab({
dir: decodeDirectory(params.dir) ?? "",
sessionId: params.id,
params: { id: params.id, dir: params.dir },
href: makeSessionHref(params.dir, params.id),
})
})
const tabsEnriched = iife(() => {
const base = mapArray(
() => tabsStore,
(tab) => {
const sync = globalSync.createDirSyncContext(tab.dir)
const session = sync.session.get(tab.sessionId)
return session ? { ...tab, info: session } : null
},
)
return () => base().flatMap((s) => (s ? [s] : []))
})
return (
<div class="h-full flex-1 flex flex-row items-center gap-1.5 pr-3">
<ChannelIndicator />
<Show when={windows() || linux()}>
<WindowsAppMenu command={command} platform={platform} />
</Show>
<IconButtonV2
as="a"
href="/"
variant="ghost-muted"
size="large"
class="!w-8"
state={!!useMatch(() => "/")() ? "pressed" : undefined}
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
<path
d="M13.9948 11.668H9.32812M11.6641 9.33203V13.9987M6.66667 9.33203V13.9987H2V9.33203H6.66667ZM6.66667 2V6.66667H2V2H6.66667ZM13.9948 2V6.66667H9.32812V2H13.9948Z"
stroke="currentColor"
stroke-miterlimit="10"
stroke-linecap="square"
/>
</svg>
</IconButtonV2>
<div class="flex flex-row items-center gap-2">
<For each={tabsEnriched()}>
{(tab, i) => (
<>
{i() !== 0 && <div class="w-[1.5px] h-3 rounded-full bg-[var(--v2-background-bg-layer-02)]" />}
<TabNavItem
href={tab.href}
title={tab.info.title}
onClose={() => tabsStoreActions.removeTab(tab.href)}
hideClose={tabsEnriched().length < 2}
/>
</>
)}
</For>
</div>
<button>
<div class="p-1.5">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
class="size-4"
>
<path
d="M7.99978 2.88867V13.1109M2.88867 7.99978H13.1109"
stroke="#808080"
stroke-linejoin="round"
/>
</svg>
</div>
</button>
<div class="flex-1" />
{/*<button class="px-2.5 py-1.5 bg-[rgba(0,0,0,0.08)] rounded-[6px]">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
class="size-4"
>
<path
d="M10.4443 2.44436V13.5555M1.55546 13.5554H14.4443V2.44434H1.55542L1.55546 13.5554Z"
stroke="#3A3A3A"
/>
</svg>
</button>*/}
</div>
)
<div
class="grid h-full min-h-full w-full grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center"
style={{ zoom: counterZoom() }}
>
<div
classList={{
"flex items-center min-w-0": true,
"pl-2": !mac(),
}}
</Match>
<Match when>
<div
class="grid h-full min-h-full w-full grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center"
style={{ zoom: counterZoom() }}
>
<div
classList={{
"flex items-center min-w-0": true,
"pl-2": !mac(),
}}
>
<Show when={windows() || linux()}>
<WindowsAppMenu command={command} platform={platform} />
</Show>
<Show when={mac()}>
<div class="h-full shrink-0" style={{ width: `${72 / zoom()}px` }} />
<div class="xl:hidden w-10 shrink-0 flex items-center justify-center">
<IconButton
icon="menu"
variant="ghost"
class="titlebar-icon rounded-md"
onClick={layout.mobileSidebar.toggle}
aria-label={language.t("sidebar.menu.toggle")}
aria-expanded={layout.mobileSidebar.opened()}
/>
</div>
</Show>
<Show when={!mac()}>
<div class="xl:hidden w-[48px] shrink-0 flex items-center justify-center">
<IconButton
icon="menu"
variant="ghost"
class="titlebar-icon rounded-md"
onClick={layout.mobileSidebar.toggle}
aria-label={language.t("sidebar.menu.toggle")}
aria-expanded={layout.mobileSidebar.opened()}
/>
</div>
</Show>
<div class="flex items-center gap-1 shrink-0">
<TooltipKeybind
class={web() ? "hidden xl:flex shrink-0 ml-14" : "hidden xl:flex shrink-0 ml-2"}
placement="bottom"
title={language.t("command.sidebar.toggle")}
keybind={command.keybind("sidebar.toggle")}
>
<Button
variant="ghost"
class="group/sidebar-toggle titlebar-icon w-8 h-6 p-0 box-border"
onClick={layout.sidebar.toggle}
aria-label={language.t("command.sidebar.toggle")}
aria-expanded={layout.sidebar.opened()}
>
<Icon size="small" name={layout.sidebar.opened() ? "sidebar-active" : "sidebar"} />
</Button>
</TooltipKeybind>
<div class="hidden xl:flex items-center shrink-0">
<Show when={params.dir}>
<div
class="flex items-center shrink-0 w-8 mr-1"
aria-hidden={layout.sidebar.opened() ? "true" : undefined}
>
<div
class="transition-opacity"
classList={{
"opacity-100 duration-120 ease-out": !layout.sidebar.opened(),
"opacity-0 duration-120 ease-in delay-0 pointer-events-none": layout.sidebar.opened(),
}}
>
<TooltipKeybind
placement="bottom"
title={language.t("command.session.new")}
keybind={command.keybind("session.new")}
openDelay={2000}
>
<Button
variant="ghost"
icon={creating() ? "new-session-active" : "new-session"}
class="titlebar-icon w-8 h-6 p-0 box-border"
disabled={layout.sidebar.opened()}
tabIndex={layout.sidebar.opened() ? -1 : undefined}
onClick={() => {
if (!params.dir) return
navigate(`/${params.dir}/session`)
}}
aria-label={language.t("command.session.new")}
aria-current={creating() ? "page" : undefined}
/>
</TooltipKeybind>
</div>
</div>
</Show>
<div
class="flex items-center shrink-0"
classList={{
"-translate-x-[36px]": layout.sidebar.opened() && !!params.dir,
"duration-180 ease-out": !layout.sidebar.opened(),
"duration-180 ease-in": layout.sidebar.opened(),
}}
>
<Show when={hasProjects() && nav()}>
<div class="flex items-center gap-0 transition-transform">
<Tooltip placement="bottom" value={language.t("common.goBack")} openDelay={2000}>
<Button
variant="ghost"
icon="chevron-left"
class="titlebar-icon w-6 h-6 p-0 box-border"
disabled={!canBack()}
onClick={back}
aria-label={language.t("common.goBack")}
/>
</Tooltip>
<Tooltip placement="bottom" value={language.t("common.goForward")} openDelay={2000}>
<Button
variant="ghost"
icon="chevron-right"
class="titlebar-icon w-6 h-6 p-0 box-border"
disabled={!canForward()}
onClick={forward}
aria-label={language.t("common.goForward")}
/>
</Tooltip>
</div>
</Show>
<div id="opencode-titlebar-left" class="flex items-center gap-3 min-w-0 px-2" />
<ChannelIndicator />
</div>
</div>
</div>
</div>
<div class="min-w-0 flex items-center justify-center pointer-events-none">
<div
id="opencode-titlebar-center"
class="pointer-events-auto min-w-0 flex justify-center w-fit max-w-full"
>
<Show when={mac()}>
<div class="h-full shrink-0" style={{ width: `${72 / zoom()}px` }} />
<div class="xl:hidden w-10 shrink-0 flex items-center justify-center">
<IconButton
icon="menu"
variant="ghost"
class="titlebar-icon rounded-md"
onClick={layout.mobileSidebar.toggle}
aria-label={language.t("sidebar.menu.toggle")}
aria-expanded={layout.mobileSidebar.opened()}
/>
</div>
<div
classList={{
"flex items-center min-w-0 justify-end": true,
"pr-2": !windows(),
}}
data-tauri-drag-region
onMouseDown={drag}
</Show>
<Show when={!mac()}>
<div class="xl:hidden w-[48px] shrink-0 flex items-center justify-center">
<IconButton
icon="menu"
variant="ghost"
class="titlebar-icon rounded-md"
onClick={layout.mobileSidebar.toggle}
aria-label={language.t("sidebar.menu.toggle")}
aria-expanded={layout.mobileSidebar.opened()}
/>
</div>
</Show>
<div class="flex items-center gap-1 shrink-0">
<TooltipKeybind
class={web() ? "hidden xl:flex shrink-0 ml-14" : "hidden xl:flex shrink-0 ml-2"}
placement="bottom"
title={language.t("command.sidebar.toggle")}
keybind={command.keybind("sidebar.toggle")}
>
<div id="opencode-titlebar-right" class="flex items-center gap-1 shrink-0 justify-end" />
<Show when={windows()}>
{!tauriApi() && <div class="shrink-0" style={{ width: windowsControlsWidth() }} />}
<div data-tauri-decorum-tb class="flex flex-row" />
<Button
variant="ghost"
class="group/sidebar-toggle titlebar-icon w-8 h-6 p-0 box-border"
onClick={layout.sidebar.toggle}
aria-label={language.t("command.sidebar.toggle")}
aria-expanded={layout.sidebar.opened()}
>
<Icon size="small" name={layout.sidebar.opened() ? "sidebar-active" : "sidebar"} />
</Button>
</TooltipKeybind>
<div class="hidden xl:flex items-center shrink-0">
<Show when={params.dir}>
<div
class="flex items-center shrink-0 w-8 mr-1"
aria-hidden={layout.sidebar.opened() ? "true" : undefined}
>
<div
class="transition-opacity"
classList={{
"opacity-100 duration-120 ease-out": !layout.sidebar.opened(),
"opacity-0 duration-120 ease-in delay-0 pointer-events-none": layout.sidebar.opened(),
}}
>
<TooltipKeybind
placement="bottom"
title={language.t("command.session.new")}
keybind={command.keybind("session.new")}
openDelay={2000}
>
<Button
variant="ghost"
icon={creating() ? "new-session-active" : "new-session"}
class="titlebar-icon w-8 h-6 p-0 box-border"
disabled={layout.sidebar.opened()}
tabIndex={layout.sidebar.opened() ? -1 : undefined}
onClick={() => {
if (!params.dir) return
navigate(`/${params.dir}/session`)
}}
aria-label={language.t("command.session.new")}
aria-current={creating() ? "page" : undefined}
/>
</TooltipKeybind>
</div>
</div>
</Show>
<div
class="flex items-center shrink-0"
classList={{
"-translate-x-[36px]": layout.sidebar.opened() && !!params.dir,
"duration-180 ease-out": !layout.sidebar.opened(),
"duration-180 ease-in": layout.sidebar.opened(),
}}
>
<Show when={hasProjects() && nav()}>
<div class="flex items-center gap-0 transition-transform">
<Tooltip placement="bottom" value={language.t("common.goBack")} openDelay={2000}>
<Button
variant="ghost"
icon="chevron-left"
class="titlebar-icon w-6 h-6 p-0 box-border"
disabled={!canBack()}
onClick={back}
aria-label={language.t("common.goBack")}
/>
</Tooltip>
<Tooltip placement="bottom" value={language.t("common.goForward")} openDelay={2000}>
<Button
variant="ghost"
icon="chevron-right"
class="titlebar-icon w-6 h-6 p-0 box-border"
disabled={!canForward()}
onClick={forward}
aria-label={language.t("common.goForward")}
/>
</Tooltip>
</div>
</Show>
<div id="opencode-titlebar-left" class="flex items-center gap-3 min-w-0 px-2" />
{["beta", "dev"].includes(import.meta.env.VITE_OPENCODE_CHANNEL) && (
<div class="bg-icon-interactive-base text-[#FFF] font-medium px-2 rounded-sm uppercase font-mono">
{import.meta.env.VITE_OPENCODE_CHANNEL.toUpperCase()}
</div>
)}
</div>
</div>
</div>
</Match>
</Switch>
</div>
<div class="min-w-0 flex items-center justify-center pointer-events-none">
<div id="opencode-titlebar-center" class="pointer-events-auto min-w-0 flex justify-center w-fit max-w-full" />
</div>
<div
classList={{
"flex items-center min-w-0 justify-end": true,
"pr-2": !windows(),
}}
data-tauri-drag-region
onMouseDown={drag}
>
<div id="opencode-titlebar-right" class="flex items-center gap-1 shrink-0 justify-end" />
<Show when={windows()}>
{!tauriApi() && <div class="shrink-0" style={{ width: windowsControlsWidth() }} />}
<div data-tauri-decorum-tb class="flex flex-row" />
</Show>
</div>
</div>
</header>
)
}
function TabNavItem(props: { href: string; title: string; hideClose?: boolean; onClose: () => void }) {
const match = useMatch(() => props.href)
const isActive = () => !!match()
return (
<div
class="group flex flex-row items-center max-w-60 whitespace-nowrap [--tab-bg:var(--v2-background-bg-deep)] data-[active='true']:[--tab-bg:var(--v2-background-bg-layer-02)] hover:[--tab-bg:var(--v2-background-bg-layer-02)] bg-[var(--tab-bg)] h-7 rounded-[6px] relative overflow-hidden"
data-active={isActive()}
>
<a
href={props.href}
class="w-full h-full pl-1.5 flex-1 max-w-full flex flex-row items-center overflow-hidden font-medium"
>
{props.title}
</a>
<div class="absolute right-0 inset-y-0 flex flex-row items-center pr-1 py-1 w-8 pl-2">
<div
class="absolute inset-0 bg-(image:--inactive-bg) group-hover:bg-(image:--active-bg) group-data-[active=true]:bg-(image:--active-bg)"
style={{
"--inactive-bg": "linear-gradient(to right, transparent 0%, var(--tab-bg) 80%)",
"--active-bg": "linear-gradient(90deg, transparent 0%, var(--tab-bg) 25%)",
}}
/>
<IconButtonV2
size="small"
variant="ghost-muted"
class="opacity-0 group-hover:opacity-100 group-data-[active='true']:opacity-100"
onClick={props.onClose}
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
class="size-4"
>
<path d="M4.25 11.75L11.75 4.25M11.75 11.75L4.25 4.25" stroke="currentColor" />
</svg>
}
/>
</div>
</div>
)
}
function ChannelIndicator() {
return (
<>
{["beta", "dev"].includes(import.meta.env.VITE_OPENCODE_CHANNEL) && (
<div class="bg-icon-interactive-base text-[#FFF] font-medium px-2 rounded-sm uppercase font-mono">
{import.meta.env.VITE_OPENCODE_CHANNEL.toUpperCase()}
</div>
)}
</>
)
}
@@ -1,111 +0,0 @@
import { Show, type JSX } from "solid-js"
import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu"
import { Icon } from "@opencode-ai/ui/icon"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { useCommand } from "@/context/command"
import { DESKTOP_MENU, desktopMenuVisible, type DesktopMenuAction, type DesktopMenuEntry } from "@/desktop-menu"
import { usePlatform } from "@/context/platform"
export function WindowsAppMenu(props: {
command: ReturnType<typeof useCommand>
platform: ReturnType<typeof usePlatform>
}) {
let lastFocused: HTMLElement | undefined
const rememberFocus = () => {
const active = document.activeElement
lastFocused = active instanceof HTMLElement ? active : undefined
}
const commandDisabled = (id: string) => {
const option = props.command.options.find((option) => option.id === id)
if (!option) return true
return option.disabled ?? false
}
const runCommand = (id: string) => {
if (commandDisabled(id)) return
props.command.trigger(id)
}
const runAction = (action: DesktopMenuAction) => {
if (action.startsWith("edit.") && lastFocused?.isConnected) lastFocused.focus({ preventScroll: true })
void props.platform.runDesktopMenuAction?.(action)
}
const runEntry = (entry: DesktopMenuEntry) => {
if (entry.type === "separator") return
if (entry.command) {
runCommand(entry.command)
return
}
if (entry.action) {
runAction(entry.action)
return
}
if (entry.href) props.platform.openLink(entry.href)
}
return (
<DropdownMenu gutter={4} modal={false} placement="bottom-start">
<DropdownMenu.Trigger
as={IconButton}
icon="menu"
variant="ghost"
class="titlebar-icon rounded-md shrink-0"
aria-label="OpenCode menu"
onPointerDown={rememberFocus}
onKeyDown={rememberFocus}
/>
<DropdownMenu.Portal>
<DropdownMenu.Content class="desktop-app-menu">
<DropdownMenu.Group>
<DropdownMenu.GroupLabel class="desktop-app-menu-heading">OpenCode</DropdownMenu.GroupLabel>
{DESKTOP_MENU.filter((menu) => desktopMenuVisible(menu, "windows")).map((menu) => (
<DesktopMenuSubmenu label={menu.label}>
{menu.items
?.filter((entry) => desktopMenuVisible(entry, "windows"))
.map((entry) =>
entry.type === "separator" ? (
<DropdownMenu.Separator />
) : (
<DesktopMenuItem
label={entry.label ?? ""}
keybind={entry.command ? props.command.keybind(entry.command) : entry.accelerator?.windows}
disabled={entry.command ? commandDisabled(entry.command) : false}
onSelect={() => runEntry(entry)}
/>
),
)}
</DesktopMenuSubmenu>
))}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu>
)
}
function DesktopMenuSubmenu(props: { label: string; children: JSX.Element }) {
return (
<DropdownMenu.Sub>
<DropdownMenu.SubTrigger>
<span data-slot="dropdown-menu-item-label">{props.label}</span>
<span data-slot="desktop-app-menu-chevron">
<Icon name="chevron-right" size="small" />
</span>
</DropdownMenu.SubTrigger>
<DropdownMenu.Portal>
<DropdownMenu.SubContent class="desktop-app-menu">{props.children}</DropdownMenu.SubContent>
</DropdownMenu.Portal>
</DropdownMenu.Sub>
)
}
function DesktopMenuItem(props: { label: string; keybind?: string; disabled?: boolean; onSelect: () => void }) {
return (
<DropdownMenu.Item disabled={props.disabled} onSelect={props.onSelect}>
<DropdownMenu.ItemLabel>{props.label}</DropdownMenu.ItemLabel>
<Show when={props.keybind}>
<span data-slot="desktop-app-menu-keybind">{props.keybind}</span>
</Show>
</DropdownMenu.Item>
)
}
-596
View File
@@ -1,596 +0,0 @@
import { batch, createMemo } from "solid-js"
import { createStore, produce, reconcile } from "solid-js/store"
import { Binary } from "@opencode-ai/core/util/binary"
import { retry } from "@opencode-ai/core/util/retry"
import {
clearSessionPrefetch,
getSessionPrefetch,
getSessionPrefetchPromise,
setSessionPrefetch,
} from "./global-sync/session-prefetch"
import { useGlobalSync } from "./global-sync"
import type { Message, OpencodeClient, Part } from "@opencode-ai/sdk/v2/client"
import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
import { diffs as list, message as clean } from "@/utils/diffs"
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
function sortParts(parts: Part[]) {
return parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id))
}
function runInflight(map: Map<string, Promise<void>>, key: string, task: () => Promise<void>) {
const pending = map.get(key)
if (pending) return pending
const promise = task().finally(() => {
map.delete(key)
})
map.set(key, promise)
return promise
}
const keyFor = (directory: string, id: string) => `${directory}\n${id}`
const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
function merge<T extends { id: string }>(a: readonly T[], b: readonly T[]) {
const map = new Map(a.map((item) => [item.id, item] as const))
for (const item of b) map.set(item.id, item)
return [...map.values()].sort((x, y) => cmp(x.id, y.id))
}
type OptimisticStore = {
message: Record<string, Message[] | undefined>
part: Record<string, Part[] | undefined>
}
type OptimisticAddInput = {
sessionID: string
message: Message
parts: Part[]
}
type OptimisticRemoveInput = {
sessionID: string
messageID: string
}
type OptimisticItem = {
message: Message
parts: Part[]
}
type MessagePage = {
session: Message[]
part: { id: string; part: Part[] }[]
cursor?: string
complete: boolean
}
const hasParts = (parts: Part[] | undefined, want: Part[]) => {
if (!parts) return want.length === 0
return want.every((part) => Binary.search(parts, part.id, (item) => item.id).found)
}
const mergeParts = (parts: Part[] | undefined, want: Part[]) => {
if (!parts) return sortParts(want)
const next = [...parts]
let changed = false
for (const part of want) {
const result = Binary.search(next, part.id, (item) => item.id)
if (result.found) continue
next.splice(result.index, 0, part)
changed = true
}
if (!changed) return parts
return next
}
export function mergeOptimisticPage(page: MessagePage, items: OptimisticItem[]) {
if (items.length === 0) return { ...page, confirmed: [] as string[] }
const session = [...page.session]
const part = new Map(page.part.map((item) => [item.id, sortParts(item.part)]))
const confirmed: string[] = []
for (const item of items) {
const result = Binary.search(session, item.message.id, (message) => message.id)
const found = result.found
if (!found) session.splice(result.index, 0, item.message)
const current = part.get(item.message.id)
if (found && hasParts(current, item.parts)) {
confirmed.push(item.message.id)
continue
}
part.set(item.message.id, mergeParts(current, item.parts))
}
return {
cursor: page.cursor,
complete: page.complete,
session,
part: [...part.entries()].sort((a, b) => cmp(a[0], b[0])).map(([id, part]) => ({ id, part })),
confirmed,
}
}
export function applyOptimisticAdd(draft: OptimisticStore, input: OptimisticAddInput) {
const messages = draft.message[input.sessionID]
if (messages) {
const result = Binary.search(messages, input.message.id, (m) => m.id)
messages.splice(result.index, 0, input.message)
} else {
draft.message[input.sessionID] = [input.message]
}
draft.part[input.message.id] = sortParts(input.parts)
}
export function applyOptimisticRemove(draft: OptimisticStore, input: OptimisticRemoveInput) {
const messages = draft.message[input.sessionID]
if (messages) {
const result = Binary.search(messages, input.messageID, (m) => m.id)
if (result.found) messages.splice(result.index, 1)
}
delete draft.part[input.messageID]
}
function setOptimisticAdd(setStore: (...args: unknown[]) => void, input: OptimisticAddInput) {
setStore("message", input.sessionID, (messages: Message[] | undefined) => {
if (!messages) return [input.message]
const result = Binary.search(messages, input.message.id, (m) => m.id)
const next = [...messages]
next.splice(result.index, 0, input.message)
return next
})
setStore("part", input.message.id, sortParts(input.parts))
}
function setOptimisticRemove(setStore: (...args: unknown[]) => void, input: OptimisticRemoveInput) {
setStore("message", input.sessionID, (messages: Message[] | undefined) => {
if (!messages) return messages
const result = Binary.search(messages, input.messageID, (m) => m.id)
if (!result.found) return messages
const next = [...messages]
next.splice(result.index, 1)
return next
})
setStore("part", (part: Record<string, Part[] | undefined>) => {
if (!(input.messageID in part)) return part
const next = { ...part }
delete next[input.messageID]
return next
})
}
export const createDirSyncContext = (client: OpencodeClient, directory: string) => {
const globalSync = useGlobalSync()
type Child = ReturnType<(typeof globalSync)["child"]>
type Setter = Child[1]
const current = createMemo(() => globalSync.child(directory))
const target = (directory?: string) => {
if (!directory || directory === directory) return current()
return globalSync.child(directory)
}
const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
const initialMessagePageSize = 80
const historyMessagePageSize = 200
const inflight = new Map<string, Promise<void>>()
const inflightDiff = new Map<string, Promise<void>>()
const inflightTodo = new Map<string, Promise<void>>()
const optimistic = new Map<string, Map<string, OptimisticItem>>()
const maxDirs = 30
const seen = new Map<string, Set<string>>()
const [meta, setMeta] = createStore({
limit: {} as Record<string, number>,
cursor: {} as Record<string, string | undefined>,
complete: {} as Record<string, boolean>,
loading: {} as Record<string, boolean>,
})
const getSession = (sessionID: string) => {
const store = current()[0]
const match = Binary.search(store.session, sessionID, (s) => s.id)
if (match.found) return store.session[match.index]
return undefined
}
const setOptimistic = (directory: string, sessionID: string, item: OptimisticItem) => {
const key = keyFor(directory, sessionID)
const list = optimistic.get(key)
if (list) {
list.set(item.message.id, { message: item.message, parts: sortParts(item.parts) })
return
}
optimistic.set(key, new Map([[item.message.id, { message: item.message, parts: sortParts(item.parts) }]]))
}
const clearOptimistic = (directory: string, sessionID: string, messageID?: string) => {
const key = keyFor(directory, sessionID)
if (!messageID) {
optimistic.delete(key)
return
}
const list = optimistic.get(key)
if (!list) return
list.delete(messageID)
if (list.size === 0) optimistic.delete(key)
}
const getOptimistic = (directory: string, sessionID: string) => [
...(optimistic.get(keyFor(directory, sessionID))?.values() ?? []),
]
const seenFor = (directory: string) => {
const existing = seen.get(directory)
if (existing) {
seen.delete(directory)
seen.set(directory, existing)
return existing
}
const created = new Set<string>()
seen.set(directory, created)
while (seen.size > maxDirs) {
const first = seen.keys().next().value
if (!first) break
const stale = [...(seen.get(first) ?? [])]
seen.delete(first)
const [, setStore] = globalSync.child(first, { bootstrap: false })
evict(first, setStore, stale)
}
return created
}
const clearMeta = (directory: string, sessionIDs: string[]) => {
if (sessionIDs.length === 0) return
for (const sessionID of sessionIDs) {
clearOptimistic(directory, sessionID)
}
setMeta(
produce((draft) => {
for (const sessionID of sessionIDs) {
const key = keyFor(directory, sessionID)
delete draft.limit[key]
delete draft.cursor[key]
delete draft.complete[key]
delete draft.loading[key]
}
}),
)
}
const evict = (directory: string, setStore: Setter, sessionIDs: string[]) => {
if (sessionIDs.length === 0) return
clearSessionPrefetch(directory, sessionIDs)
for (const sessionID of sessionIDs) {
globalSync.todo.set(sessionID, undefined)
}
setStore(
produce((draft) => {
dropSessionCaches(draft, sessionIDs)
}),
)
clearMeta(directory, sessionIDs)
}
const touch = (directory: string, setStore: Setter, sessionID: string) => {
const stale = pickSessionCacheEvictions({
seen: seenFor(directory),
keep: sessionID,
limit: SESSION_CACHE_LIMIT,
})
evict(directory, setStore, stale)
}
const fetchMessages = async (input: { client: typeof client; sessionID: string; limit: number; before?: string }) => {
const messages = await retry(() =>
input.client.session.messages({ sessionID: input.sessionID, limit: input.limit, before: input.before }),
)
const items = (messages.data ?? []).filter((x) => !!x?.info?.id)
const session = items.map((x) => clean(x.info)).sort((a, b) => cmp(a.id, b.id))
const part = items.map((message) => ({ id: message.info.id, part: sortParts(message.parts) }))
const cursor = messages.response.headers.get("x-next-cursor") ?? undefined
return {
session,
part,
cursor,
complete: !cursor,
}
}
const tracked = (directory: string, sessionID: string) => seen.get(directory)?.has(sessionID) ?? false
const loadMessages = async (input: {
directory: string
client: typeof client
setStore: Setter
sessionID: string
limit: number
before?: string
mode?: "replace" | "prepend"
}) => {
const key = keyFor(input.directory, input.sessionID)
if (meta.loading[key]) return
setMeta("loading", key, true)
await fetchMessages(input)
.then((page) => {
if (!tracked(input.directory, input.sessionID)) return
const next = mergeOptimisticPage(page, getOptimistic(input.directory, input.sessionID))
for (const messageID of next.confirmed) {
clearOptimistic(input.directory, input.sessionID, messageID)
}
const [store] = globalSync.child(input.directory, { bootstrap: false })
const cached = input.mode === "prepend" ? (store.message[input.sessionID] ?? []) : []
const message = input.mode === "prepend" ? merge(cached, next.session) : next.session
batch(() => {
input.setStore("message", input.sessionID, reconcile(message, { key: "id" }))
for (const p of next.part) {
const filtered = p.part.filter((x) => !SKIP_PARTS.has(x.type))
if (filtered.length) input.setStore("part", p.id, filtered)
}
setMeta("limit", key, message.length)
setMeta("cursor", key, next.cursor)
setMeta("complete", key, next.complete)
setSessionPrefetch({
directory: input.directory,
sessionID: input.sessionID,
limit: message.length,
cursor: next.cursor,
complete: next.complete,
})
})
})
.finally(() => {
setMeta(
produce((draft) => {
if (!tracked(input.directory, input.sessionID)) {
delete draft.loading[key]
return
}
draft.loading[key] = false
}),
)
})
}
return {
get data() {
return current()[0]
},
get set(): Setter {
return current()[1]
},
get status() {
return current()[0].status
},
get ready() {
return current()[0].status !== "loading"
},
get project() {
const store = current()[0]
const match = Binary.search(globalSync.data.project, store.project, (p) => p.id)
if (match.found) return globalSync.data.project[match.index]
return undefined
},
session: {
get: getSession,
optimistic: {
add(input: { directory?: string; sessionID: string; message: Message; parts: Part[] }) {
const _directory = input.directory ?? directory
const [, setStore] = target(input.directory)
setOptimistic(_directory, input.sessionID, { message: input.message, parts: input.parts })
setOptimisticAdd(setStore as (...args: unknown[]) => void, input)
},
remove(input: { directory?: string; sessionID: string; messageID: string }) {
const _directory = input.directory ?? directory
const [, setStore] = target(input.directory)
clearOptimistic(_directory, input.sessionID, input.messageID)
setOptimisticRemove(setStore as (...args: unknown[]) => void, input)
},
},
addOptimisticMessage(input: {
sessionID: string
messageID: string
parts: Part[]
agent: string
model: { providerID: string; modelID: string }
variant?: string
}) {
const message: Message = {
id: input.messageID,
sessionID: input.sessionID,
role: "user",
time: { created: Date.now() },
agent: input.agent,
model: { ...input.model, variant: input.variant },
}
const [, setStore] = target()
setOptimistic(directory, input.sessionID, { message, parts: input.parts })
setOptimisticAdd(setStore as (...args: unknown[]) => void, {
sessionID: input.sessionID,
message,
parts: input.parts,
})
},
async sync(sessionID: string, opts?: { force?: boolean }) {
const [store, setStore] = globalSync.child(directory)
const key = keyFor(directory, sessionID)
touch(directory, setStore, sessionID)
const seeded = getSessionPrefetch(directory, sessionID)
if (seeded && store.message[sessionID] !== undefined && meta.limit[key] === undefined) {
batch(() => {
setMeta("limit", key, seeded.limit)
setMeta("cursor", key, seeded.cursor)
setMeta("complete", key, seeded.complete)
setMeta("loading", key, false)
})
}
return runInflight(inflight, key, async () => {
const pending = getSessionPrefetchPromise(directory, sessionID)
if (pending) {
await pending
const seeded = getSessionPrefetch(directory, sessionID)
if (seeded && store.message[sessionID] !== undefined && meta.limit[key] === undefined) {
batch(() => {
setMeta("limit", key, seeded.limit)
setMeta("cursor", key, seeded.cursor)
setMeta("complete", key, seeded.complete)
setMeta("loading", key, false)
})
}
}
const hasSession = Binary.search(store.session, sessionID, (s) => s.id).found
const cached = store.message[sessionID] !== undefined && meta.limit[key] !== undefined
if (cached && hasSession && !opts?.force) return
const limit = meta.limit[key] ?? initialMessagePageSize
const sessionReq =
hasSession && !opts?.force
? Promise.resolve()
: retry(() => client.session.get({ sessionID })).then((session) => {
if (!tracked(directory, sessionID)) return
const data = session.data
if (!data) return
setStore(
"session",
produce((draft) => {
const match = Binary.search(draft, sessionID, (s) => s.id)
if (match.found) {
draft[match.index] = data
return
}
draft.splice(match.index, 0, data)
}),
)
})
const messagesReq =
cached && !opts?.force
? Promise.resolve()
: loadMessages({
directory,
client,
setStore,
sessionID,
limit,
})
await Promise.all([sessionReq, messagesReq])
})
},
async diff(sessionID: string, opts?: { force?: boolean }) {
const [store, setStore] = globalSync.child(directory)
touch(directory, setStore, sessionID)
if (store.session_diff[sessionID] !== undefined && !opts?.force) return
const key = keyFor(directory, sessionID)
return runInflight(inflightDiff, key, () =>
retry(() => client.session.diff({ sessionID })).then((diff) => {
if (!tracked(directory, sessionID)) return
setStore("session_diff", sessionID, reconcile(list(diff.data), { key: "file" }))
}),
)
},
async todo(sessionID: string, opts?: { force?: boolean }) {
const [store, setStore] = globalSync.child(directory)
touch(directory, setStore, sessionID)
const existing = store.todo[sessionID]
const cached = globalSync.data.session_todo[sessionID]
if (existing !== undefined) {
if (cached === undefined) {
globalSync.todo.set(sessionID, existing)
}
if (!opts?.force) return
}
if (cached !== undefined) {
setStore("todo", sessionID, reconcile(cached, { key: "id" }))
}
const key = keyFor(directory, sessionID)
return runInflight(inflightTodo, key, () =>
retry(() => client.session.todo({ sessionID })).then((todo) => {
if (!tracked(directory, sessionID)) return
const list = todo.data ?? []
setStore("todo", sessionID, reconcile(list, { key: "id" }))
globalSync.todo.set(sessionID, list)
}),
)
},
history: {
more(sessionID: string) {
const store = current()[0]
const key = keyFor(directory, sessionID)
if (store.message[sessionID] === undefined) return false
if (meta.limit[key] === undefined) return false
if (meta.complete[key]) return false
return !!meta.cursor[key]
},
loading(sessionID: string) {
const key = keyFor(directory, sessionID)
return meta.loading[key] ?? false
},
async loadMore(sessionID: string, count?: number) {
const [, setStore] = globalSync.child(directory)
touch(directory, setStore, sessionID)
const key = keyFor(directory, sessionID)
const step = count ?? historyMessagePageSize
if (meta.loading[key]) return
if (meta.complete[key]) return
const before = meta.cursor[key]
if (!before) return
await loadMessages({
directory,
client,
setStore,
sessionID,
limit: step,
before,
mode: "prepend",
})
},
},
evict(sessionID: string, _directory = directory) {
const [, setStore] = globalSync.child(_directory)
seenFor(_directory).delete(sessionID)
evict(_directory, setStore, [sessionID])
},
fetch: async (count = 10) => {
const [store, setStore] = globalSync.child(directory)
setStore("limit", (x) => x + count)
await client.session.list().then((x) => {
const sessions = (x.data ?? [])
.filter((s) => !!s?.id)
.sort((a, b) => cmp(a.id, b.id))
.slice(0, store.limit)
setStore("session", reconcile(sessions, { key: "id" }))
})
},
more: createMemo(() => current()[0].session.length >= current()[0].limit),
archive: async (sessionID: string) => {
const [, setStore] = globalSync.child(directory)
await client.session.update({ sessionID, time: { archived: Date.now() } })
setStore(
produce((draft) => {
const match = Binary.search(draft.session, sessionID, (s) => s.id)
if (match.found) draft.session.splice(match.index, 1)
}),
)
},
},
absolute,
get directory() {
return current()[0].path.directory
},
}
}
-24
View File
@@ -36,7 +36,6 @@ import { queryOptions, useMutation, useQueries, useQuery, useQueryClient } from
import { createRefreshQueue } from "./global-sync/queue"
import { directoryKey } from "./global-sync/utils"
import { PathKey } from "@/utils/path-key"
import { createDirSyncContext } from "./directory-sync"
type GlobalStore = {
ready: boolean
@@ -432,9 +431,6 @@ function createGlobalSync() {
},
}))
const dirSyncContexts = new Map<string, ReturnType<typeof createDirSyncContext>>()
const dirSyncContextRefCounts = new Map<string, number>()
return {
data: globalStore,
set,
@@ -453,26 +449,6 @@ function createGlobalSync() {
todo: {
set: setSessionTodo,
},
createDirSyncContext: (directory: string) => {
onCleanup(() => {
dirSyncContextRefCounts.set(directory, (dirSyncContextRefCounts.get(directory) ?? 0) - 1)
if (dirSyncContextRefCounts.get(directory) === 0) {
dirSyncContexts.delete(directory)
dirSyncContextRefCounts.delete(directory)
}
})
const cached = dirSyncContexts.get(directory)
if (cached) {
dirSyncContextRefCounts.set(directory, (dirSyncContextRefCounts.get(directory) ?? 0) + 1)
return cached
}
const ctx = createDirSyncContext(globalSDK.createClient({ directory, throwOnError: true }), directory)
dirSyncContexts.set(directory, ctx)
dirSyncContextRefCounts.set(directory, 1)
return ctx
},
}
}
-4
View File
@@ -1,7 +1,6 @@
import { createSimpleContext } from "@opencode-ai/ui/context"
import type { AsyncStorage, SyncStorage } from "@solid-primitives/storage"
import type { Accessor } from "solid-js"
import type { DesktopMenuAction } from "../desktop-menu"
import { ServerConnection } from "./server"
type PickerPaths = string | string[] | null
@@ -83,9 +82,6 @@ export type Platform = {
/** Webview zoom level (desktop only) */
webviewZoom?: Accessor<number>
/** Run a desktop-only menu action from the app chrome */
runDesktopMenuAction?(action: DesktopMenuAction): Promise<void> | void
/** Check if an editor app exists (desktop only) */
checkAppExists?(appName: string): Promise<boolean>
+454 -1
View File
@@ -1,8 +1,19 @@
import { batch, createMemo } from "solid-js"
import { createStore, produce, reconcile } from "solid-js/store"
import { Binary } from "@opencode-ai/core/util/binary"
import { retry } from "@opencode-ai/core/util/retry"
import { createSimpleContext } from "@opencode-ai/ui/context"
import {
clearSessionPrefetch,
getSessionPrefetch,
getSessionPrefetchPromise,
setSessionPrefetch,
} from "./global-sync/session-prefetch"
import { useGlobalSync } from "./global-sync"
import { useSDK } from "./sdk"
import type { Message, Part } from "@opencode-ai/sdk/v2/client"
import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
import { diffs as list, message as clean } from "@/utils/diffs"
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
@@ -161,6 +172,448 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
const globalSync = useGlobalSync()
const sdk = useSDK()
return globalSync.createDirSyncContext(sdk.directory)
type Child = ReturnType<(typeof globalSync)["child"]>
type Setter = Child[1]
const current = createMemo(() => globalSync.child(sdk.directory))
const target = (directory?: string) => {
if (!directory || directory === sdk.directory) return current()
return globalSync.child(directory)
}
const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
const initialMessagePageSize = 80
const historyMessagePageSize = 200
const inflight = new Map<string, Promise<void>>()
const inflightDiff = new Map<string, Promise<void>>()
const inflightTodo = new Map<string, Promise<void>>()
const optimistic = new Map<string, Map<string, OptimisticItem>>()
const maxDirs = 30
const seen = new Map<string, Set<string>>()
const [meta, setMeta] = createStore({
limit: {} as Record<string, number>,
cursor: {} as Record<string, string | undefined>,
complete: {} as Record<string, boolean>,
loading: {} as Record<string, boolean>,
})
const getSession = (sessionID: string) => {
const store = current()[0]
const match = Binary.search(store.session, sessionID, (s) => s.id)
if (match.found) return store.session[match.index]
return undefined
}
const setOptimistic = (directory: string, sessionID: string, item: OptimisticItem) => {
const key = keyFor(directory, sessionID)
const list = optimistic.get(key)
if (list) {
list.set(item.message.id, { message: item.message, parts: sortParts(item.parts) })
return
}
optimistic.set(key, new Map([[item.message.id, { message: item.message, parts: sortParts(item.parts) }]]))
}
const clearOptimistic = (directory: string, sessionID: string, messageID?: string) => {
const key = keyFor(directory, sessionID)
if (!messageID) {
optimistic.delete(key)
return
}
const list = optimistic.get(key)
if (!list) return
list.delete(messageID)
if (list.size === 0) optimistic.delete(key)
}
const getOptimistic = (directory: string, sessionID: string) => [
...(optimistic.get(keyFor(directory, sessionID))?.values() ?? []),
]
const seenFor = (directory: string) => {
const existing = seen.get(directory)
if (existing) {
seen.delete(directory)
seen.set(directory, existing)
return existing
}
const created = new Set<string>()
seen.set(directory, created)
while (seen.size > maxDirs) {
const first = seen.keys().next().value
if (!first) break
const stale = [...(seen.get(first) ?? [])]
seen.delete(first)
const [, setStore] = globalSync.child(first, { bootstrap: false })
evict(first, setStore, stale)
}
return created
}
const clearMeta = (directory: string, sessionIDs: string[]) => {
if (sessionIDs.length === 0) return
for (const sessionID of sessionIDs) {
clearOptimistic(directory, sessionID)
}
setMeta(
produce((draft) => {
for (const sessionID of sessionIDs) {
const key = keyFor(directory, sessionID)
delete draft.limit[key]
delete draft.cursor[key]
delete draft.complete[key]
delete draft.loading[key]
}
}),
)
}
const evict = (directory: string, setStore: Setter, sessionIDs: string[]) => {
if (sessionIDs.length === 0) return
clearSessionPrefetch(directory, sessionIDs)
for (const sessionID of sessionIDs) {
globalSync.todo.set(sessionID, undefined)
}
setStore(
produce((draft) => {
dropSessionCaches(draft, sessionIDs)
}),
)
clearMeta(directory, sessionIDs)
}
const touch = (directory: string, setStore: Setter, sessionID: string) => {
const stale = pickSessionCacheEvictions({
seen: seenFor(directory),
keep: sessionID,
limit: SESSION_CACHE_LIMIT,
})
evict(directory, setStore, stale)
}
const fetchMessages = async (input: {
client: typeof sdk.client
sessionID: string
limit: number
before?: string
}) => {
const messages = await retry(() =>
input.client.session.messages({ sessionID: input.sessionID, limit: input.limit, before: input.before }),
)
const items = (messages.data ?? []).filter((x) => !!x?.info?.id)
const session = items.map((x) => clean(x.info)).sort((a, b) => cmp(a.id, b.id))
const part = items.map((message) => ({ id: message.info.id, part: sortParts(message.parts) }))
const cursor = messages.response.headers.get("x-next-cursor") ?? undefined
return {
session,
part,
cursor,
complete: !cursor,
}
}
const tracked = (directory: string, sessionID: string) => seen.get(directory)?.has(sessionID) ?? false
const loadMessages = async (input: {
directory: string
client: typeof sdk.client
setStore: Setter
sessionID: string
limit: number
before?: string
mode?: "replace" | "prepend"
}) => {
const key = keyFor(input.directory, input.sessionID)
if (meta.loading[key]) return
setMeta("loading", key, true)
await fetchMessages(input)
.then((page) => {
if (!tracked(input.directory, input.sessionID)) return
const next = mergeOptimisticPage(page, getOptimistic(input.directory, input.sessionID))
for (const messageID of next.confirmed) {
clearOptimistic(input.directory, input.sessionID, messageID)
}
const [store] = globalSync.child(input.directory, { bootstrap: false })
const cached = input.mode === "prepend" ? (store.message[input.sessionID] ?? []) : []
const message = input.mode === "prepend" ? merge(cached, next.session) : next.session
batch(() => {
input.setStore("message", input.sessionID, reconcile(message, { key: "id" }))
for (const p of next.part) {
const filtered = p.part.filter((x) => !SKIP_PARTS.has(x.type))
if (filtered.length) input.setStore("part", p.id, filtered)
}
setMeta("limit", key, message.length)
setMeta("cursor", key, next.cursor)
setMeta("complete", key, next.complete)
setSessionPrefetch({
directory: input.directory,
sessionID: input.sessionID,
limit: message.length,
cursor: next.cursor,
complete: next.complete,
})
})
})
.finally(() => {
setMeta(
produce((draft) => {
if (!tracked(input.directory, input.sessionID)) {
delete draft.loading[key]
return
}
draft.loading[key] = false
}),
)
})
}
return {
get data() {
return current()[0]
},
get set(): Setter {
return current()[1]
},
get status() {
return current()[0].status
},
get ready() {
return current()[0].status !== "loading"
},
get project() {
const store = current()[0]
const match = Binary.search(globalSync.data.project, store.project, (p) => p.id)
if (match.found) return globalSync.data.project[match.index]
return undefined
},
session: {
get: getSession,
optimistic: {
add(input: { directory?: string; sessionID: string; message: Message; parts: Part[] }) {
const directory = input.directory ?? sdk.directory
const [, setStore] = target(input.directory)
setOptimistic(directory, input.sessionID, { message: input.message, parts: input.parts })
setOptimisticAdd(setStore as (...args: unknown[]) => void, input)
},
remove(input: { directory?: string; sessionID: string; messageID: string }) {
const directory = input.directory ?? sdk.directory
const [, setStore] = target(input.directory)
clearOptimistic(directory, input.sessionID, input.messageID)
setOptimisticRemove(setStore as (...args: unknown[]) => void, input)
},
},
addOptimisticMessage(input: {
sessionID: string
messageID: string
parts: Part[]
agent: string
model: { providerID: string; modelID: string }
variant?: string
}) {
const message: Message = {
id: input.messageID,
sessionID: input.sessionID,
role: "user",
time: { created: Date.now() },
agent: input.agent,
model: { ...input.model, variant: input.variant },
}
const [, setStore] = target()
setOptimistic(sdk.directory, input.sessionID, { message, parts: input.parts })
setOptimisticAdd(setStore as (...args: unknown[]) => void, {
sessionID: input.sessionID,
message,
parts: input.parts,
})
},
async sync(sessionID: string, opts?: { force?: boolean }) {
const directory = sdk.directory
const client = sdk.client
const [store, setStore] = globalSync.child(directory)
const key = keyFor(directory, sessionID)
touch(directory, setStore, sessionID)
const seeded = getSessionPrefetch(directory, sessionID)
if (seeded && store.message[sessionID] !== undefined && meta.limit[key] === undefined) {
batch(() => {
setMeta("limit", key, seeded.limit)
setMeta("cursor", key, seeded.cursor)
setMeta("complete", key, seeded.complete)
setMeta("loading", key, false)
})
}
return runInflight(inflight, key, async () => {
const pending = getSessionPrefetchPromise(directory, sessionID)
if (pending) {
await pending
const seeded = getSessionPrefetch(directory, sessionID)
if (seeded && store.message[sessionID] !== undefined && meta.limit[key] === undefined) {
batch(() => {
setMeta("limit", key, seeded.limit)
setMeta("cursor", key, seeded.cursor)
setMeta("complete", key, seeded.complete)
setMeta("loading", key, false)
})
}
}
const hasSession = Binary.search(store.session, sessionID, (s) => s.id).found
const cached = store.message[sessionID] !== undefined && meta.limit[key] !== undefined
if (cached && hasSession && !opts?.force) return
const limit = meta.limit[key] ?? initialMessagePageSize
const sessionReq =
hasSession && !opts?.force
? Promise.resolve()
: retry(() => client.session.get({ sessionID })).then((session) => {
if (!tracked(directory, sessionID)) return
const data = session.data
if (!data) return
setStore(
"session",
produce((draft) => {
const match = Binary.search(draft, sessionID, (s) => s.id)
if (match.found) {
draft[match.index] = data
return
}
draft.splice(match.index, 0, data)
}),
)
})
const messagesReq =
cached && !opts?.force
? Promise.resolve()
: loadMessages({
directory,
client,
setStore,
sessionID,
limit,
})
await Promise.all([sessionReq, messagesReq])
})
},
async diff(sessionID: string, opts?: { force?: boolean }) {
const directory = sdk.directory
const client = sdk.client
const [store, setStore] = globalSync.child(directory)
touch(directory, setStore, sessionID)
if (store.session_diff[sessionID] !== undefined && !opts?.force) return
const key = keyFor(directory, sessionID)
return runInflight(inflightDiff, key, () =>
retry(() => client.session.diff({ sessionID })).then((diff) => {
if (!tracked(directory, sessionID)) return
setStore("session_diff", sessionID, reconcile(list(diff.data), { key: "file" }))
}),
)
},
async todo(sessionID: string, opts?: { force?: boolean }) {
const directory = sdk.directory
const client = sdk.client
const [store, setStore] = globalSync.child(directory)
touch(directory, setStore, sessionID)
const existing = store.todo[sessionID]
const cached = globalSync.data.session_todo[sessionID]
if (existing !== undefined) {
if (cached === undefined) {
globalSync.todo.set(sessionID, existing)
}
if (!opts?.force) return
}
if (cached !== undefined) {
setStore("todo", sessionID, reconcile(cached, { key: "id" }))
}
const key = keyFor(directory, sessionID)
return runInflight(inflightTodo, key, () =>
retry(() => client.session.todo({ sessionID })).then((todo) => {
if (!tracked(directory, sessionID)) return
const list = todo.data ?? []
setStore("todo", sessionID, reconcile(list, { key: "id" }))
globalSync.todo.set(sessionID, list)
}),
)
},
history: {
more(sessionID: string) {
const store = current()[0]
const key = keyFor(sdk.directory, sessionID)
if (store.message[sessionID] === undefined) return false
if (meta.limit[key] === undefined) return false
if (meta.complete[key]) return false
return !!meta.cursor[key]
},
loading(sessionID: string) {
const key = keyFor(sdk.directory, sessionID)
return meta.loading[key] ?? false
},
async loadMore(sessionID: string, count?: number) {
const directory = sdk.directory
const client = sdk.client
const [, setStore] = globalSync.child(directory)
touch(directory, setStore, sessionID)
const key = keyFor(directory, sessionID)
const step = count ?? historyMessagePageSize
if (meta.loading[key]) return
if (meta.complete[key]) return
const before = meta.cursor[key]
if (!before) return
await loadMessages({
directory,
client,
setStore,
sessionID,
limit: step,
before,
mode: "prepend",
})
},
},
evict(sessionID: string, directory = sdk.directory) {
const [, setStore] = globalSync.child(directory)
seenFor(directory).delete(sessionID)
evict(directory, setStore, [sessionID])
},
fetch: async (count = 10) => {
const directory = sdk.directory
const client = sdk.client
const [store, setStore] = globalSync.child(directory)
setStore("limit", (x) => x + count)
await client.session.list().then((x) => {
const sessions = (x.data ?? [])
.filter((s) => !!s?.id)
.sort((a, b) => cmp(a.id, b.id))
.slice(0, store.limit)
setStore("session", reconcile(sessions, { key: "id" }))
})
},
more: createMemo(() => current()[0].session.length >= current()[0].limit),
archive: async (sessionID: string) => {
const directory = sdk.directory
const client = sdk.client
const [, setStore] = globalSync.child(directory)
await client.session.update({ sessionID, time: { archived: Date.now() } })
setStore(
produce((draft) => {
const match = Binary.search(draft.session, sessionID, (s) => s.id)
if (match.found) draft.session.splice(match.index, 1)
}),
)
},
},
absolute,
get directory() {
return current()[0].path.directory
},
}
},
})
-221
View File
@@ -1,221 +0,0 @@
export type DesktopMenuPlatform = "macos" | "windows"
export type DesktopMenuAction =
| "app.checkForUpdates"
| "app.relaunch"
| "edit.undo"
| "edit.redo"
| "edit.cut"
| "edit.copy"
| "edit.paste"
| "edit.delete"
| "edit.selectAll"
| "view.reload"
| "view.toggleDevTools"
| "view.resetZoom"
| "view.zoomIn"
| "view.zoomOut"
| "view.toggleFullscreen"
| "window.new"
| "window.close"
| "window.minimize"
| "window.toggleMaximize"
export type DesktopMenuRole =
| "about"
| "close"
| "copy"
| "cut"
| "hide"
| "hideOthers"
| "paste"
| "quit"
| "redo"
| "reload"
| "resetZoom"
| "selectAll"
| "toggleDevTools"
| "togglefullscreen"
| "undo"
| "unhide"
| "windowMenu"
| "zoomIn"
| "zoomOut"
export type DesktopMenuItem = {
type: "item"
label?: string
command?: string
action?: DesktopMenuAction
role?: DesktopMenuRole
href?: string
accelerator?: Partial<Record<DesktopMenuPlatform, string>>
enabled?: "updater"
platforms?: DesktopMenuPlatform[]
}
export type DesktopMenuSeparator = {
type: "separator"
platforms?: DesktopMenuPlatform[]
}
export type DesktopMenuEntry = DesktopMenuItem | DesktopMenuSeparator
export type DesktopMenu = {
id: string
label: string
role?: DesktopMenuRole
items?: DesktopMenuEntry[]
platforms?: DesktopMenuPlatform[]
}
export const DESKTOP_MENU: DesktopMenu[] = [
{
id: "app",
label: "OpenCode",
platforms: ["macos"],
items: [
{ type: "item", role: "about" },
{ type: "item", label: "Check for Updates...", action: "app.checkForUpdates", enabled: "updater" },
{ type: "item", label: "Settings", command: "settings.open", accelerator: { macos: "Cmd+," } },
{ type: "item", label: "Reload Webview", action: "view.reload" },
{ type: "item", label: "Restart", action: "app.relaunch" },
{ type: "separator" },
{ type: "item", role: "hide" },
{ type: "item", role: "hideOthers" },
{ type: "item", role: "unhide" },
{ type: "separator" },
{ type: "item", role: "quit" },
],
},
{
id: "file",
label: "File",
items: [
{
type: "item",
label: "New Session",
command: "session.new",
accelerator: { macos: "Shift+Cmd+S" },
},
{ type: "item", label: "Open Project...", command: "project.open", accelerator: { macos: "Cmd+O" } },
{
type: "item",
label: "Settings",
command: "settings.open",
accelerator: { windows: "Ctrl+," },
platforms: ["windows"],
},
{
type: "item",
label: "New Window",
action: "window.new",
accelerator: { macos: "Cmd+Shift+N", windows: "Ctrl+Shift+N" },
},
{ type: "separator" },
{ type: "item", label: "Close Window", action: "window.close", role: "close" },
],
},
{
id: "edit",
label: "Edit",
items: [
{ type: "item", label: "Undo", action: "edit.undo", role: "undo", accelerator: { windows: "Ctrl+Z" } },
{ type: "item", label: "Redo", action: "edit.redo", role: "redo", accelerator: { windows: "Ctrl+Y" } },
{ type: "separator" },
{ type: "item", label: "Cut", action: "edit.cut", role: "cut", accelerator: { windows: "Ctrl+X" } },
{ type: "item", label: "Copy", action: "edit.copy", role: "copy", accelerator: { windows: "Ctrl+C" } },
{ type: "item", label: "Paste", action: "edit.paste", role: "paste", accelerator: { windows: "Ctrl+V" } },
{ type: "item", label: "Delete", action: "edit.delete" },
{
type: "item",
label: "Select All",
action: "edit.selectAll",
role: "selectAll",
accelerator: { windows: "Ctrl+A" },
},
],
},
{
id: "view",
label: "View",
items: [
{ type: "item", label: "Toggle Sidebar", command: "sidebar.toggle", accelerator: { macos: "Cmd+B" } },
{ type: "item", label: "Toggle Terminal", command: "terminal.toggle", accelerator: { macos: "Ctrl+`" } },
{ type: "item", label: "Toggle File Tree", command: "fileTree.toggle" },
{ type: "separator" },
{ type: "item", label: "Reload", action: "view.reload", role: "reload" },
{ type: "item", label: "Toggle Developer Tools", action: "view.toggleDevTools", role: "toggleDevTools" },
{ type: "separator" },
{
type: "item",
label: "Actual Size",
action: "view.resetZoom",
role: "resetZoom",
accelerator: { windows: "Ctrl+0" },
},
{ type: "item", label: "Zoom In", action: "view.zoomIn", role: "zoomIn", accelerator: { windows: "Ctrl++" } },
{ type: "item", label: "Zoom Out", action: "view.zoomOut", role: "zoomOut", accelerator: { windows: "Ctrl+-" } },
{ type: "separator" },
{ type: "item", label: "Toggle Full Screen", action: "view.toggleFullscreen", role: "togglefullscreen" },
],
},
{
id: "go",
label: "Go",
items: [
{ type: "item", label: "Back", command: "common.goBack", accelerator: { macos: "Cmd+[" } },
{ type: "item", label: "Forward", command: "common.goForward", accelerator: { macos: "Cmd+]" } },
{ type: "separator" },
{ type: "item", label: "Previous Session", command: "session.previous", accelerator: { macos: "Option+Up" } },
{ type: "item", label: "Next Session", command: "session.next", accelerator: { macos: "Option+Down" } },
{ type: "separator" },
{
type: "item",
label: "Previous Project",
command: "project.previous",
accelerator: { macos: "Cmd+Option+Up" },
},
{
type: "item",
label: "Next Project",
command: "project.next",
accelerator: { macos: "Cmd+Option+Down" },
},
],
},
{
id: "window",
label: "Window",
role: "windowMenu",
items: [
{ type: "item", label: "Minimize", action: "window.minimize" },
{ type: "item", label: "Maximize", action: "window.toggleMaximize" },
{ type: "separator" },
{ type: "item", label: "Close Window", action: "window.close" },
],
},
{
id: "help",
label: "Help",
items: [
{ type: "item", label: "OpenCode Documentation", href: "https://opencode.ai/docs" },
{ type: "item", label: "Support Forum", href: "https://discord.com/invite/opencode" },
{ type: "separator" },
{
type: "item",
label: "Share Feedback",
href: "https://github.com/anomalyco/opencode/issues/new?template=feature_request.yml",
},
{
type: "item",
label: "Report a Bug",
href: "https://github.com/anomalyco/opencode/issues/new?template=bug_report.yml",
},
],
},
]
export function desktopMenuVisible(item: { platforms?: DesktopMenuPlatform[] }, platform: DesktopMenuPlatform) {
return !item.platforms || item.platforms.includes(platform)
}
-58
View File
@@ -1,5 +1,4 @@
@import "@opencode-ai/ui/styles/tailwind";
@import "@opencode-ai/ui/v2/styles/tailwind.css";
@font-face {
font-family: "JetBrainsMono Nerd Font Mono";
@@ -54,63 +53,6 @@
container-name: getting-started;
}
[data-component="dropdown-menu-content"].desktop-app-menu,
[data-component="dropdown-menu-sub-content"].desktop-app-menu {
min-width: 160px;
padding: 2px;
}
[data-component="dropdown-menu-content"].desktop-app-menu {
width: 160px;
}
[data-component="dropdown-menu-sub-content"].desktop-app-menu {
width: max-content;
min-width: 240px;
max-width: min(320px, calc(100vw - 24px));
}
[data-component="dropdown-menu-content"].desktop-app-menu [data-slot="dropdown-menu-group-label"] {
display: flex;
align-items: center;
height: 28px;
padding: 0 12px;
font-size: var(--font-size-x-small);
font-weight: var(--font-weight-medium);
line-height: 1;
color: var(--text-weak);
}
[data-component="dropdown-menu-content"].desktop-app-menu [data-slot="dropdown-menu-item"],
[data-component="dropdown-menu-content"].desktop-app-menu [data-slot="dropdown-menu-sub-trigger"],
[data-component="dropdown-menu-sub-content"].desktop-app-menu [data-slot="dropdown-menu-item"],
[data-component="dropdown-menu-sub-content"].desktop-app-menu [data-slot="dropdown-menu-sub-trigger"] {
min-height: 28px;
padding: 0 12px;
gap: 8px;
font-weight: var(--font-weight-regular);
line-height: 1;
}
[data-component="dropdown-menu-content"].desktop-app-menu [data-slot="dropdown-menu-item-label"],
[data-component="dropdown-menu-sub-content"].desktop-app-menu [data-slot="dropdown-menu-item-label"] {
white-space: nowrap;
}
[data-slot="desktop-app-menu-keybind"] {
margin-left: auto;
color: var(--text-weak);
font-size: var(--font-size-x-small);
font-weight: var(--font-weight-regular);
white-space: nowrap;
}
[data-slot="desktop-app-menu-chevron"] {
display: flex;
margin-left: auto;
color: var(--icon-base);
}
[data-component="getting-started-actions"] {
display: flex;
flex-direction: column;
+1 -11
View File
@@ -8,7 +8,6 @@ import { LocalProvider } from "@/context/local"
import { SDKProvider } from "@/context/sdk"
import { SyncProvider, useSync } from "@/context/sync"
import { decode64 } from "@/utils/base64"
import { Schema } from "effect"
function DirectoryDataProvider(props: ParentProps<{ directory: string }>) {
const location = useLocation()
@@ -41,15 +40,6 @@ function DirectoryDataProvider(props: ParentProps<{ directory: string }>) {
)
}
export const ProjectDirString = Schema.String.pipe(Schema.brand("ProjectDirString"))
export type ProjectDirString = Schema.Schema.Type<typeof ProjectDirString>
export function decodeDirectory(dir: string): ProjectDirString | undefined {
const decoded = decode64(dir)
if (!decoded) return
return ProjectDirString.make(decoded)
}
export default function Layout(props: ParentProps) {
const params = useParams()
const language = useLanguage()
@@ -58,7 +48,7 @@ export default function Layout(props: ParentProps) {
const resolved = createMemo(() => {
if (!params.dir) return ""
return decodeDirectory(params.dir) ?? ""
return decode64(params.dir) ?? ""
})
createEffect(() => {
@@ -1,289 +0,0 @@
[data-component="go-credit-confirm"] {
display: flex;
flex-direction: column;
gap: var(--space-4);
min-width: min(34rem, calc(100vw - var(--space-8)));
p {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-sm);
line-height: 1.6;
}
[data-slot="usage-preview"] {
display: flex;
flex-direction: column;
gap: var(--space-5);
padding: var(--space-4);
border: 1px solid var(--color-border);
border-radius: var(--border-radius-sm);
background-color: var(--color-bg-surface);
}
[data-slot="usage-preview-item"] {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
[data-slot="usage-preview-header"] {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-3);
}
[data-slot="usage-preview-label"] {
color: var(--color-text);
font-size: var(--font-size-sm);
font-weight: 500;
}
[data-slot="usage-preview-value"] {
display: inline-flex;
align-items: center;
gap: var(--space-1);
color: var(--color-text-muted);
font-family: var(--font-mono);
font-size: var(--font-size-xs);
white-space: nowrap;
}
[data-slot="usage-preview-after-value"] {
color: var(--color-accent);
font-weight: 600;
}
[data-slot="usage-preview-progress"] {
position: relative;
height: 8px;
overflow: hidden;
border-radius: var(--border-radius-sm);
background-color: var(--color-bg);
}
[data-slot="usage-preview-before"],
[data-slot="usage-preview-after"] {
position: absolute;
top: 0;
bottom: 0;
left: 0;
border-radius: var(--border-radius-sm);
}
[data-slot="usage-preview-before"] {
background-color: var(--color-border);
}
[data-slot="usage-preview-after"] {
background-color: var(--color-accent);
transition: width 0.35s ease;
}
[data-slot="usage-preview-reset"] {
color: var(--color-text-muted);
font-size: var(--font-size-xs);
}
[data-slot="modal-actions"] {
display: flex;
justify-content: flex-end;
gap: var(--space-3);
}
}
[data-slot="invite-link-box"] {
display: flex;
flex-direction: column;
gap: var(--space-3);
> div {
display: flex;
align-items: center;
gap: var(--space-3);
border-radius: var(--border-radius-sm);
@media (max-width: 40rem) {
align-items: stretch;
flex-direction: column;
}
}
code {
flex: 1;
min-width: 0;
padding: var(--space-3);
border: 1px solid var(--color-border);
border-radius: var(--border-radius-sm);
background-color: var(--color-bg);
color: var(--color-text);
font-family: var(--font-mono);
font-size: var(--font-size-sm);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@media (max-width: 40rem) {
padding: var(--space-2-5);
font-size: var(--font-size-xs);
}
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
min-width: 130px;
white-space: nowrap;
@media (max-width: 40rem) {
min-width: 96px;
padding: var(--space-2-5) var(--space-3);
font-size: var(--font-size-xs);
}
}
}
[data-slot="instructions"] {
display: flex;
flex-direction: column;
gap: var(--space-3);
ol {
display: flex;
flex-direction: column;
gap: var(--space-2);
margin: 0;
padding-left: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-md);
list-style-position: inside;
line-height: 1.5;
}
}
[data-component="go-referral-section"] {
[data-component="go-referral-overview"] {
display: flex;
flex-direction: column;
gap: var(--space-8);
padding: var(--space-6);
border: 1px dashed var(--color-border);
border-radius: var(--border-radius-sm);
background-color: var(--color-bg-surface);
@media (max-width: 30rem) {
gap: var(--space-8);
padding: var(--space-4);
}
}
[data-component="go-referral-overview"] + [data-slot="section-title"] {
margin-top: var(--space-4);
}
[data-slot="referrals-table"] {
overflow-x: auto;
}
[data-component="empty-state"] {
padding: var(--space-4);
border: 1px solid var(--color-border);
border-radius: var(--border-radius-sm);
background-color: var(--color-bg-surface);
color: var(--color-text-muted);
font-size: var(--font-size-sm);
}
[data-slot="referrals-table-element"] {
width: 100%;
border-collapse: collapse;
font-size: var(--font-size-sm);
thead {
border-bottom: 1px solid var(--color-border);
}
th {
padding: var(--space-3) var(--space-4);
text-align: left;
font-weight: normal;
color: var(--color-text-muted);
text-transform: uppercase;
&:nth-child(1) {
width: 120px;
}
&:nth-child(3) {
width: 180px;
}
&:nth-child(4) {
width: 140px;
}
}
td {
padding: var(--space-3) var(--space-4);
border-bottom: 1px solid var(--color-border-muted);
color: var(--color-text-muted);
font-family: var(--font-mono);
&[data-slot="referral-amount"] {
color: var(--color-text);
font-weight: 500;
}
&[data-slot="referral-source"] {
color: var(--color-text-secondary);
font-family: var(--font-sans);
white-space: nowrap;
}
&[data-slot="referral-action"] {
text-align: right;
font-family: var(--font-sans);
white-space: nowrap;
button {
min-width: 96px;
}
}
}
tbody tr {
&[data-status="applied"] {
td:not([data-slot="referral-action"]) {
opacity: 0.68;
}
}
&[data-status="pending"] {
td[data-slot="referral-amount"],
td[data-slot="referral-date"] {
color: var(--color-text-muted);
}
td[data-slot="referral-source"] {
color: var(--color-text);
}
}
&:last-child td {
border-bottom: none;
}
}
@media (max-width: 40rem) {
th,
td {
padding: var(--space-2) var(--space-3);
font-size: var(--font-size-xs);
}
}
}
}
@@ -1,300 +0,0 @@
import { action, json, query, useAction, useSubmission } from "@solidjs/router"
import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js"
import { getRequestEvent } from "solid-js/web"
import { Referral } from "@opencode-ai/console-core/referral.js"
import { withActor } from "~/context/auth.withActor"
import { Modal } from "~/component/modal"
import { IconCheck, IconCopy } from "~/component/icon"
import { useI18n } from "~/context/i18n"
import { useLanguage } from "~/context/language"
import { formatResetTime, liteResetTimeKeys } from "~/lib/format-reset-time"
import { queryLiteSubscription } from "~/routes/workspace/[id]/go/lite-section"
import "./go-referral.css"
type GoReferralSummary = Awaited<ReturnType<typeof Referral.summary>>
type GoReferralReward = GoReferralSummary["rewards"][number]
type GoLiteSubscription = Awaited<ReturnType<typeof queryLiteSubscription>>
type GoReferralUsagePreview = NonNullable<Awaited<ReturnType<typeof Referral.usagePreview>>>
type GoReferralUsagePreviewItem = GoReferralUsagePreview["rollingUsage"]
const emptyUsagePreview = {
rollingUsage: { beforePercent: 0, afterPercent: 0, resetInSec: 0 },
weeklyUsage: { beforePercent: 0, afterPercent: 0, resetInSec: 0 },
monthlyUsage: { beforePercent: 0, afterPercent: 0, resetInSec: 0 },
} satisfies GoReferralUsagePreview
export const queryGoReferral = query(async (workspaceID: string) => {
"use server"
return withActor(() => Referral.summary(), workspaceID)
}, "go.referral.get")
export const queryGoReferralUsagePreview = query(async (workspaceID: string, referralID?: string) => {
"use server"
if (!referralID) return null
return withActor(() => Referral.usagePreview({ referralID }), workspaceID)
}, "go.referral.usagePreview")
export const applyGoReferralReward = action(async (workspaceID: string, referralID: string) => {
"use server"
return json(await withActor(() => Referral.applyReward({ referralID }), workspaceID), {
revalidate: [queryGoReferral.key, queryGoReferralUsagePreview.key, queryLiteSubscription.key],
})
}, "go.referral.reward.apply")
function currentUsagePreview(usage: { resetInSec: number; usagePercent: number }) {
return {
beforePercent: usage.usagePercent,
afterPercent: usage.usagePercent,
resetInSec: usage.resetInSec,
}
}
function formatCurrency(amount: number) {
if (amount % 100 === 0) return `$${amount / 100}`
return `$${(amount / 100).toFixed(2)}`
}
function formatDate(value: string | Date, locale: string) {
return new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric" }).format(new Date(value))
}
function rewardDescriptionKey(source: GoReferralReward["source"]) {
if (source === "invitee") return "workspace.referral.reward.description.invitee" as const
return "workspace.referral.reward.description.inviter" as const
}
function rewardActionKey(reward: GoReferralReward, hasActiveGo: boolean) {
if (reward.status === "applied") return "workspace.referral.reward.action.applied" as const
if (reward.status === "pending" || !hasActiveGo) return "workspace.referral.reward.action.subscribeUnlock" as const
return "workspace.referral.reward.action.view" as const
}
function CopyInviteLink(props: { summary: GoReferralSummary }) {
const i18n = useI18n()
const [copied, setCopied] = createSignal(false)
const event = getRequestEvent()
const origin = event
? new URL(event.request.url).origin
: typeof window === "object"
? window.location.origin
: undefined
const inviteUrl = createMemo(() => {
const path = `/go?ref=${props.summary.referralCode}`
if (!origin) return path
return new URL(path, origin).toString()
})
async function copy() {
if (typeof navigator !== "object") return
await navigator.clipboard.writeText(inviteUrl())
setCopied(true)
window.setTimeout(() => setCopied(false), 1600)
}
return (
<div data-slot="invite-link-box">
<div>
<code title={inviteUrl()}>{inviteUrl()}</code>
<button type="button" onClick={copy}>
<Show
when={copied()}
fallback={
<>
<IconCopy style={{ width: "16px", height: "16px" }} /> {i18n.t("workspace.referral.copyLink")}
</>
}
>
<IconCheck style={{ width: "16px", height: "16px" }} /> {i18n.t("workspace.referral.copied")}
</Show>
</button>
</div>
</div>
)
}
export function GoReferralSection(props: {
workspaceID: string
summary: GoReferralSummary
lite: GoLiteSubscription | undefined
}) {
const i18n = useI18n()
const language = useLanguage()
const apply = useAction(applyGoReferralReward)
const submission = useSubmission(applyGoReferralReward)
const [selected, setSelected] = createSignal<GoReferralReward>()
const [preview, setPreview] = createSignal<GoReferralUsagePreview | null>()
const displayPreview = createMemo(() => {
const loaded = preview()
if (loaded) return loaded
const current = props.lite
if (!current) return emptyUsagePreview
return {
rollingUsage: currentUsagePreview(current.rollingUsage),
weeklyUsage: currentUsagePreview(current.weeklyUsage),
monthlyUsage: currentUsagePreview(current.monthlyUsage),
} satisfies GoReferralUsagePreview
})
createEffect(() => {
const reward = selected()
if (!reward) {
setPreview(undefined)
return
}
const request = { cancelled: false }
setPreview(undefined)
queryGoReferralUsagePreview(props.workspaceID, reward.id).then((result) => {
if (request.cancelled) return
setPreview(result)
})
onCleanup(() => {
request.cancelled = true
})
})
async function onApply() {
const reward = selected()
if (!reward) return
await apply(props.workspaceID, reward.id)
setSelected(undefined)
}
return (
<>
<Show when={props.lite || props.summary.hasReferral}>
<section data-component="go-referral-section">
<Show when={props.lite}>
<div data-slot="section-title">
<h2>{i18n.t("workspace.referral.overview.title")}</h2>
<p>{i18n.t("workspace.referral.overview.subtitle")}</p>
</div>
<div data-component="go-referral-overview">
<CopyInviteLink summary={props.summary} />
<div data-slot="instructions">
<ol>
<li>{i18n.t("workspace.referral.instructions.share")}</li>
<li>{i18n.t("workspace.referral.instructions.subscribe")}</li>
<li>{i18n.t("workspace.referral.instructions.claim")}</li>
</ol>
</div>
</div>
</Show>
<Show when={props.summary.hasReferral}>
<div data-slot="section-title">
<h2>{i18n.t("workspace.referral.rewards.title")}</h2>
<p>{i18n.t("workspace.referral.rewards.description")}</p>
</div>
<div data-slot="referrals-table">
<table data-slot="referrals-table-element">
<thead>
<tr>
<th>{i18n.t("workspace.referral.table.reward")}</th>
<th>{i18n.t("workspace.referral.table.referral")}</th>
<th>{i18n.t("workspace.referral.table.date")}</th>
<th></th>
</tr>
</thead>
<tbody>
<For each={props.summary.rewards}>
{(reward) => {
const earnedAt = () => formatDate(reward.timeCreated, language.tag(language.locale()))
return (
<tr data-status={reward.status} data-source={reward.source}>
<td data-slot="referral-amount">{formatCurrency(reward.amount)}</td>
<td data-slot="referral-source">
{i18n.t(rewardDescriptionKey(reward.source), { email: reward.email ?? "" })}
</td>
<td data-slot="referral-date" title={earnedAt()}>
{earnedAt()}
</td>
<td data-slot="referral-action">
<button
type="button"
disabled={reward.status !== "available" || !props.lite || submission.pending}
onClick={() => setSelected(reward)}
>
{i18n.t(rewardActionKey(reward, !!props.lite))}
</button>
</td>
</tr>
)
}}
</For>
</tbody>
</table>
</div>
</Show>
</section>
</Show>
<Modal
open={!!selected()}
onClose={() => setSelected(undefined)}
title={i18n.t("workspace.referral.apply.confirmTitle")}
>
<div data-component="go-credit-confirm">
<p>
{i18n.t("workspace.referral.apply.confirmBody", {
amount: formatCurrency(selected()?.amount ?? 0),
})}
</p>
<GoReferralUsagePreview preview={displayPreview()} />
<div data-slot="modal-actions">
<button type="button" onClick={() => setSelected(undefined)}>
{i18n.t("common.cancel")}
</button>
<button type="button" data-color="primary" disabled={submission.pending} onClick={onApply}>
{submission.pending ? i18n.t("workspace.lite.loading") : i18n.t("workspace.referral.apply.confirmAction")}
</button>
</div>
</div>
</Modal>
</>
)
}
function GoReferralUsagePreview(props: { preview: GoReferralUsagePreview }) {
const i18n = useI18n()
return (
<div data-slot="usage-preview">
<GoReferralUsagePreviewRow
label={i18n.t("workspace.lite.subscription.rollingUsage")}
usage={props.preview.rollingUsage}
/>
<GoReferralUsagePreviewRow
label={i18n.t("workspace.lite.subscription.weeklyUsage")}
usage={props.preview.weeklyUsage}
/>
<GoReferralUsagePreviewRow
label={i18n.t("workspace.lite.subscription.monthlyUsage")}
usage={props.preview.monthlyUsage}
/>
</div>
)
}
function GoReferralUsagePreviewRow(props: { label: string; usage: GoReferralUsagePreviewItem }) {
const i18n = useI18n()
return (
<div data-slot="usage-preview-item">
<div data-slot="usage-preview-header">
<span data-slot="usage-preview-label">{props.label}</span>
<span data-slot="usage-preview-value">
<span>{props.usage.beforePercent}%</span>
<span aria-hidden="true">-&gt;</span>
<span data-slot="usage-preview-after-value">{props.usage.afterPercent}%</span>
</span>
</div>
<div data-slot="usage-preview-progress">
<div data-slot="usage-preview-before" style={{ width: `${props.usage.beforePercent}%` }} />
<div data-slot="usage-preview-after" style={{ width: `${props.usage.afterPercent}%` }} />
</div>
<span data-slot="usage-preview-reset">
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
{formatResetTime(props.usage.resetInSec, i18n, liteResetTimeKeys)}
</span>
</div>
)
}
@@ -55,61 +55,6 @@
@media (prefers-color-scheme: dark) {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--space-3) var(--space-4);
border: 1px solid var(--color-border);
border-radius: var(--border-radius-sm);
background-color: var(--color-bg);
color: var(--color-text);
font-size: var(--font-size-sm);
font-family: var(--font-sans);
font-weight: 500;
line-height: 1;
cursor: pointer;
transition: all 0.15s ease;
&:hover:not(:disabled) {
background-color: var(--color-surface-hover);
border-color: var(--color-accent);
}
&:active:not(:disabled) {
transform: translateY(1px);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
&[data-color="primary"] {
background-color: var(--color-primary);
border-color: var(--color-primary);
color: var(--color-primary-text);
&:hover:not(:disabled) {
background-color: var(--color-primary-hover);
border-color: var(--color-primary-hover);
}
}
&[data-color="ghost"] {
background-color: transparent;
border-color: transparent;
color: var(--color-text-muted);
&:hover:not(:disabled) {
background-color: var(--color-surface-hover);
border-color: var(--color-border);
color: var(--color-text);
}
}
}
}
[data-slot="title"] {
@@ -119,16 +64,4 @@
color: var(--color-text);
text-align: center;
}
[data-slot="content"][data-variant="black"] {
background-color: #000;
border-color: rgba(255, 255, 255, 0.17);
color: rgba(255, 255, 255, 0.92);
font-family: var(--font-mono);
[data-slot="title"] {
color: rgba(255, 255, 255, 0.92);
font-family: var(--font-mono);
}
}
}
+8 -30
View File
@@ -1,4 +1,3 @@
import { Dialog as Kobalte } from "@kobalte/core/dialog"
import { JSX, Show } from "solid-js"
import "./modal.css"
@@ -6,41 +5,20 @@ interface ModalProps {
open: boolean
onClose: () => void
title?: string
variant?: "black"
children: JSX.Element
}
export function Modal(props: ModalProps) {
return (
<Show when={props.open}>
<Kobalte
modal
open={props.open}
preventScroll={false}
onOpenChange={(open) => {
if (!open) props.onClose()
}}
>
<Kobalte.Portal>
<Kobalte.Overlay data-component="modal" data-slot="overlay" onClick={props.onClose}>
<Kobalte.Content
data-slot="content"
data-variant={props.variant}
onClick={(e) => e.stopPropagation()}
onOpenAutoFocus={(e) => {
e.preventDefault()
const target = e.currentTarget as HTMLElement | null
target?.focus({ preventScroll: true })
}}
>
<Show when={props.title}>
<Kobalte.Title data-slot="title">{props.title}</Kobalte.Title>
</Show>
{props.children}
</Kobalte.Content>
</Kobalte.Overlay>
</Kobalte.Portal>
</Kobalte>
<div data-component="modal" data-slot="overlay" onClick={props.onClose}>
<div data-slot="content" onClick={(e) => e.stopPropagation()}>
<Show when={props.title}>
<h2 data-slot="title">{props.title}</h2>
</Show>
{props.children}
</div>
</div>
</Show>
)
}
-33
View File
@@ -660,39 +660,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "طرق دفع أخرى",
"workspace.lite.promo.selectMethod": "اختر طريقة الدفع",
"workspace.referral.copyLink": "نسخ الرابط",
"workspace.referral.copied": "تم النسخ",
"workspace.referral.overview.title": "ادعُ أصدقاءك",
"workspace.referral.overview.subtitle": "احصل على $5 عند اشتراك صديق. وسيحصل هو أيضًا على $5.",
"workspace.referral.instructions.share": "شارك رابط الإحالة الخاص بك",
"workspace.referral.instructions.subscribe": "ينضم صديقك ويشترك في Go",
"workspace.referral.instructions.claim": "تحصلان كلاكما على رصيد استخدام بقيمة $5 لتطبيقه على حدود استخدام Go",
"workspace.referral.rewards.title": "مكافآت الإحالة",
"workspace.referral.rewards.description": "طبّق أرصدة الإحالة المتاحة على استخدامك لـ Go.",
"workspace.referral.rewards.subtitle": "تم تطبيق {{applied}} / {{total}} من المكافآت.",
"workspace.referral.rewards.empty": "لا توجد مكافآت إحالة بعد.",
"workspace.referral.table.reward": "المكافأة",
"workspace.referral.table.referral": "الوصف",
"workspace.referral.table.date": "التاريخ",
"workspace.referral.reward.description.inviter": "تمت دعوة {{email}}",
"workspace.referral.reward.description.invitee": "تمت دعوتك بواسطة {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "اشترك لإلغاء القفل",
"workspace.referral.reward.action.view": "عرض المكافأة",
"workspace.referral.reward.action.applied": "تم تطبيق المكافأة",
"workspace.referral.reward.source.pendingInviter": "بانتظار اشتراكه",
"workspace.referral.reward.source.pendingInvitee": "اشترك لإلغاء قفل المكافأة",
"workspace.referral.reward.source.available": "المكافأة جاهزة للتطبيق",
"workspace.referral.reward.source.applied": "تم تطبيق المكافأة",
"workspace.referral.reward.status.applied": "تم تطبيق المكافأة",
"workspace.referral.reward.status.pendingInviter": "اشترك لإلغاء القفل",
"workspace.referral.reward.status.pendingInvitee": "اشترك لإلغاء القفل",
"workspace.referral.apply.noGo": "اشترك لإلغاء القفل",
"workspace.referral.apply.preview": "عرض المكافأة",
"workspace.referral.apply.action": "تطبيق",
"workspace.referral.apply.confirmTitle": "تطبيق المكافأة",
"workspace.referral.apply.confirmBody": "طبِّق {{amount}} لتقليل الاستخدام الحالي في مساحة العمل هذه.",
"workspace.referral.apply.confirmAction": "تطبيق",
"download.title": "OpenCode | تنزيل",
"download.meta.description": "نزّل OpenCode لـ macOS، Windows، وLinux",
"download.hero.title": "تنزيل OpenCode",
-34
View File
@@ -670,40 +670,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Outros métodos de pagamento",
"workspace.lite.promo.selectMethod": "Selecionar método de pagamento",
"workspace.referral.copyLink": "Copiar link",
"workspace.referral.copied": "Copiado",
"workspace.referral.overview.title": "Convide amigos",
"workspace.referral.overview.subtitle": "Ganhe $5 quando um amigo assinar. Ele também ganha $5.",
"workspace.referral.instructions.share": "Compartilhe seu link de indicação",
"workspace.referral.instructions.subscribe": "Seu amigo entra e assina o Go",
"workspace.referral.instructions.claim":
"Vocês dois ganham um crédito de uso de $5 para aplicar aos seus limites de uso do Go",
"workspace.referral.rewards.title": "Recompensas de indicação",
"workspace.referral.rewards.description": "Aplique os créditos de indicação disponíveis no seu uso do Go.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} recompensas aplicadas.",
"workspace.referral.rewards.empty": "Ainda não há recompensas de indicação.",
"workspace.referral.table.reward": "Recompensa",
"workspace.referral.table.referral": "Descrição",
"workspace.referral.table.date": "Data",
"workspace.referral.reward.description.inviter": "Convidou {{email}}",
"workspace.referral.reward.description.invitee": "Convidado por {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Assine para desbloquear",
"workspace.referral.reward.action.view": "Ver recompensa",
"workspace.referral.reward.action.applied": "Recompensa aplicada",
"workspace.referral.reward.source.pendingInviter": "Aguardando ele assinar",
"workspace.referral.reward.source.pendingInvitee": "Assine para desbloquear a recompensa",
"workspace.referral.reward.source.available": "Recompensa pronta para usar",
"workspace.referral.reward.source.applied": "Recompensa aplicada",
"workspace.referral.reward.status.applied": "Recompensa aplicada",
"workspace.referral.reward.status.pendingInviter": "Assine para desbloquear",
"workspace.referral.reward.status.pendingInvitee": "Assine para desbloquear",
"workspace.referral.apply.noGo": "Assine para desbloquear",
"workspace.referral.apply.preview": "Ver recompensa",
"workspace.referral.apply.action": "Aplicar",
"workspace.referral.apply.confirmTitle": "Aplicar recompensa",
"workspace.referral.apply.confirmBody": "Aplique {{amount}} para reduzir o uso atual deste workspace.",
"workspace.referral.apply.confirmAction": "Aplicar",
"download.title": "OpenCode | Baixar",
"download.meta.description": "Baixe o OpenCode para macOS, Windows e Linux",
"download.hero.title": "Baixar OpenCode",
-33
View File
@@ -666,39 +666,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Andre betalingsmetoder",
"workspace.lite.promo.selectMethod": "Vælg betalingsmetode",
"workspace.referral.copyLink": "Kopiér link",
"workspace.referral.copied": "Kopieret",
"workspace.referral.overview.title": "Inviter venner",
"workspace.referral.overview.subtitle": "Få $5, når en ven abonnerer. De får også $5.",
"workspace.referral.instructions.share": "Del dit henvisningslink",
"workspace.referral.instructions.subscribe": "Din ven tilmelder sig og abonnerer på Go",
"workspace.referral.instructions.claim": "I får begge $5 i forbrugskredit til at bruge på jeres Go-forbrugsgrænser",
"workspace.referral.rewards.title": "Henvisningsbelønninger",
"workspace.referral.rewards.description": "Brug tilgængelige henvisningskreditter på dit Go-forbrug.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} belønninger brugt.",
"workspace.referral.rewards.empty": "Ingen henvisningsbelønninger endnu.",
"workspace.referral.table.reward": "Belønning",
"workspace.referral.table.referral": "Beskrivelse",
"workspace.referral.table.date": "Dato",
"workspace.referral.reward.description.inviter": "Inviterede {{email}}",
"workspace.referral.reward.description.invitee": "Inviteret af {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Abonner for at låse op",
"workspace.referral.reward.action.view": "Vis belønning",
"workspace.referral.reward.action.applied": "Belønning brugt",
"workspace.referral.reward.source.pendingInviter": "Venter på, at de abonnerer",
"workspace.referral.reward.source.pendingInvitee": "Abonner for at låse belønningen op",
"workspace.referral.reward.source.available": "Belønning klar til brug",
"workspace.referral.reward.source.applied": "Belønning brugt",
"workspace.referral.reward.status.applied": "Belønning brugt",
"workspace.referral.reward.status.pendingInviter": "Abonner for at låse op",
"workspace.referral.reward.status.pendingInvitee": "Abonner for at låse op",
"workspace.referral.apply.noGo": "Abonner for at låse op",
"workspace.referral.apply.preview": "Vis belønning",
"workspace.referral.apply.action": "Brug",
"workspace.referral.apply.confirmTitle": "Brug belønning",
"workspace.referral.apply.confirmBody": "Brug {{amount}} til at reducere dette workspaces nuværende forbrug.",
"workspace.referral.apply.confirmAction": "Brug",
"download.title": "OpenCode | Download",
"download.meta.description": "Download OpenCode til macOS, Windows og Linux",
"download.hero.title": "Download OpenCode",
-35
View File
@@ -669,41 +669,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Andere Zahlungsmethoden",
"workspace.lite.promo.selectMethod": "Zahlungsmethode auswählen",
"workspace.referral.copyLink": "Link kopieren",
"workspace.referral.copied": "Kopiert",
"workspace.referral.overview.title": "Freunde einladen",
"workspace.referral.overview.subtitle": "Erhalte $5, wenn ein Freund abonniert. Er bekommt ebenfalls $5.",
"workspace.referral.instructions.share": "Teile deinen Empfehlungslink",
"workspace.referral.instructions.subscribe": "Dein Freund tritt bei und abonniert Go",
"workspace.referral.instructions.claim":
"Ihr erhaltet beide ein Nutzungsguthaben von $5, das ihr auf eure Go-Nutzungslimits anrechnen könnt",
"workspace.referral.rewards.title": "Empfehlungsbelohnungen",
"workspace.referral.rewards.description": "Verfügbare Empfehlungsguthaben auf deine Go-Nutzung anwenden.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} Belohnungen eingelöst.",
"workspace.referral.rewards.empty": "Noch keine Empfehlungsbelohnungen.",
"workspace.referral.table.reward": "Belohnung",
"workspace.referral.table.referral": "Beschreibung",
"workspace.referral.table.date": "Datum",
"workspace.referral.reward.description.inviter": "{{email}} eingeladen",
"workspace.referral.reward.description.invitee": "Eingeladen von {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Abonnieren zum Freischalten",
"workspace.referral.reward.action.view": "Belohnung ansehen",
"workspace.referral.reward.action.applied": "Belohnung eingelöst",
"workspace.referral.reward.source.pendingInviter": "Warten auf das Abo des Freundes",
"workspace.referral.reward.source.pendingInvitee": "Abonnieren, um Belohnung freizuschalten",
"workspace.referral.reward.source.available": "Belohnung kann eingelöst werden",
"workspace.referral.reward.source.applied": "Belohnung eingelöst",
"workspace.referral.reward.status.applied": "Belohnung eingelöst",
"workspace.referral.reward.status.pendingInviter": "Abonnieren zum Freischalten",
"workspace.referral.reward.status.pendingInvitee": "Abonnieren zum Freischalten",
"workspace.referral.apply.noGo": "Abonnieren zum Freischalten",
"workspace.referral.apply.preview": "Belohnung ansehen",
"workspace.referral.apply.action": "Einlösen",
"workspace.referral.apply.confirmTitle": "Belohnung einlösen",
"workspace.referral.apply.confirmBody":
"Löse {{amount}} ein, um die aktuelle Nutzung dieses Workspace zu reduzieren.",
"workspace.referral.apply.confirmAction": "Einlösen",
"download.title": "OpenCode | Download",
"download.meta.description": "Lade OpenCode für macOS, Windows und Linux herunter",
"download.hero.title": "OpenCode herunterladen",
-33
View File
@@ -662,39 +662,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Other payment methods",
"workspace.lite.promo.selectMethod": "Select payment method",
"workspace.referral.copyLink": "Copy Link",
"workspace.referral.copied": "Copied",
"workspace.referral.overview.title": "Invite friends",
"workspace.referral.overview.subtitle": "Earn $5 when a friend subscribes. Theyll get $5 too.",
"workspace.referral.instructions.share": "Share your referral link",
"workspace.referral.instructions.subscribe": "Your friend joins and subscribes to Go",
"workspace.referral.instructions.claim": "You both get a $5 usage credit to apply toward your Go usage limits",
"workspace.referral.rewards.title": "Referral rewards",
"workspace.referral.rewards.description": "Apply available referral credits toward your Go usage.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} rewards applied.",
"workspace.referral.rewards.empty": "No referral rewards yet.",
"workspace.referral.table.reward": "Reward",
"workspace.referral.table.referral": "Description",
"workspace.referral.table.date": "Date",
"workspace.referral.reward.description.inviter": "Invited {{email}}",
"workspace.referral.reward.description.invitee": "Invited by {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Subscribe to unlock",
"workspace.referral.reward.action.view": "View Reward",
"workspace.referral.reward.action.applied": "Reward Applied",
"workspace.referral.reward.source.pendingInviter": "Waiting for them to subscribe",
"workspace.referral.reward.source.pendingInvitee": "Subscribe to unlock reward",
"workspace.referral.reward.source.available": "Reward ready to apply",
"workspace.referral.reward.source.applied": "Reward applied",
"workspace.referral.reward.status.applied": "Reward Applied",
"workspace.referral.reward.status.pendingInviter": "Subscribe to unlock",
"workspace.referral.reward.status.pendingInvitee": "Subscribe to unlock",
"workspace.referral.apply.noGo": "Subscribe to unlock",
"workspace.referral.apply.preview": "View Reward",
"workspace.referral.apply.action": "Apply",
"workspace.referral.apply.confirmTitle": "Apply reward",
"workspace.referral.apply.confirmBody": "Apply {{amount}} to reduce this workspace's current usage.",
"workspace.referral.apply.confirmAction": "Apply",
"download.title": "OpenCode | Download",
"download.meta.description": "Download OpenCode for macOS, Windows, and Linux",
"download.hero.title": "Download OpenCode",
-34
View File
@@ -670,40 +670,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Otros métodos de pago",
"workspace.lite.promo.selectMethod": "Seleccionar método de pago",
"workspace.referral.copyLink": "Copiar enlace",
"workspace.referral.copied": "Copiado",
"workspace.referral.overview.title": "Invita amigos",
"workspace.referral.overview.subtitle": "Gana $5 cuando un amigo se suscriba. Él también recibirá $5.",
"workspace.referral.instructions.share": "Comparte tu enlace de referido",
"workspace.referral.instructions.subscribe": "Tu amigo se une y se suscribe a Go",
"workspace.referral.instructions.claim":
"Ambos reciben un crédito de uso de $5 para aplicar a sus límites de uso de Go",
"workspace.referral.rewards.title": "Recompensas por referidos",
"workspace.referral.rewards.description": "Aplica los créditos por referidos disponibles a tu uso de Go.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} recompensas aplicadas.",
"workspace.referral.rewards.empty": "Aún no hay recompensas por referidos.",
"workspace.referral.table.reward": "Recompensa",
"workspace.referral.table.referral": "Descripción",
"workspace.referral.table.date": "Fecha",
"workspace.referral.reward.description.inviter": "Invitaste a {{email}}",
"workspace.referral.reward.description.invitee": "Invitado por {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Suscríbete para desbloquear",
"workspace.referral.reward.action.view": "Ver recompensa",
"workspace.referral.reward.action.applied": "Recompensa aplicada",
"workspace.referral.reward.source.pendingInviter": "Esperando a que se suscriba",
"workspace.referral.reward.source.pendingInvitee": "Suscríbete para desbloquear la recompensa",
"workspace.referral.reward.source.available": "Recompensa lista para aplicar",
"workspace.referral.reward.source.applied": "Recompensa aplicada",
"workspace.referral.reward.status.applied": "Recompensa aplicada",
"workspace.referral.reward.status.pendingInviter": "Suscríbete para desbloquear",
"workspace.referral.reward.status.pendingInvitee": "Suscríbete para desbloquear",
"workspace.referral.apply.noGo": "Suscríbete para desbloquear",
"workspace.referral.apply.preview": "Ver recompensa",
"workspace.referral.apply.action": "Aplicar",
"workspace.referral.apply.confirmTitle": "Aplicar recompensa",
"workspace.referral.apply.confirmBody": "Aplica {{amount}} para reducir el uso actual de este workspace.",
"workspace.referral.apply.confirmAction": "Aplicar",
"download.title": "OpenCode | Descargar",
"download.meta.description": "Descarga OpenCode para macOS, Windows y Linux",
"download.hero.title": "Descargar OpenCode",
-35
View File
@@ -676,41 +676,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Autres méthodes de paiement",
"workspace.lite.promo.selectMethod": "Sélectionner la méthode de paiement",
"workspace.referral.copyLink": "Copier le lien",
"workspace.referral.copied": "Copié",
"workspace.referral.overview.title": "Inviter des amis",
"workspace.referral.overview.subtitle": "Gagnez $5 lorsqu'un ami s'abonne. Il recevra également $5.",
"workspace.referral.instructions.share": "Partagez votre lien de parrainage",
"workspace.referral.instructions.subscribe": "Votre ami rejoint et s'abonne à Go",
"workspace.referral.instructions.claim":
"Vous recevez tous les deux un crédit d'utilisation de $5 à appliquer à vos limites d'utilisation Go",
"workspace.referral.rewards.title": "Récompenses de parrainage",
"workspace.referral.rewards.description":
"Utilisez les crédits de parrainage disponibles pour votre utilisation de Go.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} récompenses utilisées.",
"workspace.referral.rewards.empty": "Aucune récompense de parrainage pour l'instant.",
"workspace.referral.table.reward": "Récompense",
"workspace.referral.table.referral": "Description",
"workspace.referral.table.date": "Date",
"workspace.referral.reward.description.inviter": "Vous avez invité {{email}}",
"workspace.referral.reward.description.invitee": "Invité par {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Abonnez-vous pour débloquer",
"workspace.referral.reward.action.view": "Voir la récompense",
"workspace.referral.reward.action.applied": "Récompense utilisée",
"workspace.referral.reward.source.pendingInviter": "En attente de son abonnement",
"workspace.referral.reward.source.pendingInvitee": "Abonnez-vous pour débloquer la récompense",
"workspace.referral.reward.source.available": "Récompense prête à utiliser",
"workspace.referral.reward.source.applied": "Récompense utilisée",
"workspace.referral.reward.status.applied": "Récompense utilisée",
"workspace.referral.reward.status.pendingInviter": "Abonnez-vous pour débloquer",
"workspace.referral.reward.status.pendingInvitee": "Abonnez-vous pour débloquer",
"workspace.referral.apply.noGo": "Abonnez-vous pour débloquer",
"workspace.referral.apply.preview": "Voir la récompense",
"workspace.referral.apply.action": "Utiliser",
"workspace.referral.apply.confirmTitle": "Utiliser la récompense",
"workspace.referral.apply.confirmBody": "Utilisez {{amount}} pour réduire l'utilisation actuelle de ce workspace.",
"workspace.referral.apply.confirmAction": "Utiliser",
"download.title": "OpenCode | Téléchargement",
"download.meta.description": "Téléchargez OpenCode pour macOS, Windows et Linux",
"download.hero.title": "Télécharger OpenCode",
-34
View File
@@ -668,40 +668,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Altri metodi di pagamento",
"workspace.lite.promo.selectMethod": "Seleziona metodo di pagamento",
"workspace.referral.copyLink": "Copia link",
"workspace.referral.copied": "Copiato",
"workspace.referral.overview.title": "Invita amici",
"workspace.referral.overview.subtitle": "Guadagna $5 quando un amico si abbona. Anche lui riceverà $5.",
"workspace.referral.instructions.share": "Condividi il tuo link di referral",
"workspace.referral.instructions.subscribe": "Il tuo amico si iscrive e si abbona a Go",
"workspace.referral.instructions.claim":
"Entrambi ricevete un credito di utilizzo di $5 da applicare ai vostri limiti di utilizzo Go",
"workspace.referral.rewards.title": "Premi referral",
"workspace.referral.rewards.description": "Applica i crediti referral disponibili al tuo utilizzo di Go.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} premi utilizzati.",
"workspace.referral.rewards.empty": "Nessun premio referral ancora.",
"workspace.referral.table.reward": "Premio",
"workspace.referral.table.referral": "Descrizione",
"workspace.referral.table.date": "Data",
"workspace.referral.reward.description.inviter": "Hai invitato {{email}}",
"workspace.referral.reward.description.invitee": "Invitato da {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Abbonati per sbloccare",
"workspace.referral.reward.action.view": "Vedi premio",
"workspace.referral.reward.action.applied": "Premio utilizzato",
"workspace.referral.reward.source.pendingInviter": "In attesa che si abboni",
"workspace.referral.reward.source.pendingInvitee": "Abbonati per sbloccare il premio",
"workspace.referral.reward.source.available": "Premio pronto da utilizzare",
"workspace.referral.reward.source.applied": "Premio utilizzato",
"workspace.referral.reward.status.applied": "Premio utilizzato",
"workspace.referral.reward.status.pendingInviter": "Abbonati per sbloccare",
"workspace.referral.reward.status.pendingInvitee": "Abbonati per sbloccare",
"workspace.referral.apply.noGo": "Abbonati per sbloccare",
"workspace.referral.apply.preview": "Vedi premio",
"workspace.referral.apply.action": "Utilizza",
"workspace.referral.apply.confirmTitle": "Utilizza premio",
"workspace.referral.apply.confirmBody": "Utilizza {{amount}} per ridurre l'utilizzo attuale di questo workspace.",
"workspace.referral.apply.confirmAction": "Utilizza",
"download.title": "OpenCode | Download",
"download.meta.description": "Scarica OpenCode per macOS, Windows e Linux",
"download.hero.title": "Scarica OpenCode",
-33
View File
@@ -668,39 +668,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "その他の支払い方法",
"workspace.lite.promo.selectMethod": "支払い方法を選択",
"workspace.referral.copyLink": "リンクをコピー",
"workspace.referral.copied": "コピーしました",
"workspace.referral.overview.title": "友達を招待",
"workspace.referral.overview.subtitle": "友達がサブスクライブすると $5 を獲得。友達にも $5 が付与されます。",
"workspace.referral.instructions.share": "リファラルリンクをシェア",
"workspace.referral.instructions.subscribe": "友達が参加して Go にサブスクライブ",
"workspace.referral.instructions.claim": "二人とも $5 の利用クレジットを獲得し、Go の利用上限に充当できます",
"workspace.referral.rewards.title": "リファラル特典",
"workspace.referral.rewards.description": "利用可能なリファラルクレジットを Go の利用に適用します。",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} 件の特典を適用済み。",
"workspace.referral.rewards.empty": "リファラル特典はまだありません。",
"workspace.referral.table.reward": "特典",
"workspace.referral.table.referral": "説明",
"workspace.referral.table.date": "日付",
"workspace.referral.reward.description.inviter": "{{email}} を招待しました",
"workspace.referral.reward.description.invitee": "{{email}} に招待されました",
"workspace.referral.reward.action.subscribeUnlock": "サブスクライブしてアンロック",
"workspace.referral.reward.action.view": "特典を表示",
"workspace.referral.reward.action.applied": "特典を適用済み",
"workspace.referral.reward.source.pendingInviter": "友達のサブスクライブ待ち",
"workspace.referral.reward.source.pendingInvitee": "サブスクライブして特典をアンロック",
"workspace.referral.reward.source.available": "特典は適用可能です",
"workspace.referral.reward.source.applied": "特典を適用済み",
"workspace.referral.reward.status.applied": "特典を適用済み",
"workspace.referral.reward.status.pendingInviter": "サブスクライブしてアンロック",
"workspace.referral.reward.status.pendingInvitee": "サブスクライブしてアンロック",
"workspace.referral.apply.noGo": "サブスクライブしてアンロック",
"workspace.referral.apply.preview": "特典を表示",
"workspace.referral.apply.action": "適用",
"workspace.referral.apply.confirmTitle": "特典を適用",
"workspace.referral.apply.confirmBody": "{{amount}} を適用して、このワークスペースの現在の使用量を減らします。",
"workspace.referral.apply.confirmAction": "適用",
"download.title": "OpenCode | ダウンロード",
"download.meta.description": "OpenCode を macOS、Windows、Linux 向けにダウンロード",
"download.hero.title": "OpenCode をダウンロード",
-33
View File
@@ -660,39 +660,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "기타 결제 수단",
"workspace.lite.promo.selectMethod": "결제 수단 선택",
"workspace.referral.copyLink": "링크 복사",
"workspace.referral.copied": "복사됨",
"workspace.referral.overview.title": "친구 초대",
"workspace.referral.overview.subtitle": "친구가 구독하면 $5를 받으세요. 친구도 $5를 받습니다.",
"workspace.referral.instructions.share": "추천 링크 공유",
"workspace.referral.instructions.subscribe": "친구가 가입하고 Go를 구독",
"workspace.referral.instructions.claim": "두 분 모두 $5 사용 크레딧을 받아 Go 사용 한도에 적용할 수 있습니다",
"workspace.referral.rewards.title": "추천 보상",
"workspace.referral.rewards.description": "사용 가능한 추천 크레딧을 Go 사용량에 적용합니다.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}}개 보상 사용됨.",
"workspace.referral.rewards.empty": "아직 추천 보상이 없습니다.",
"workspace.referral.table.reward": "보상",
"workspace.referral.table.referral": "설명",
"workspace.referral.table.date": "날짜",
"workspace.referral.reward.description.inviter": "{{email}} 초대됨",
"workspace.referral.reward.description.invitee": "{{email}}님이 초대",
"workspace.referral.reward.action.subscribeUnlock": "구독하여 잠금 해제",
"workspace.referral.reward.action.view": "보상 보기",
"workspace.referral.reward.action.applied": "보상 사용됨",
"workspace.referral.reward.source.pendingInviter": "친구의 구독을 기다리는 중",
"workspace.referral.reward.source.pendingInvitee": "구독하여 보상 잠금 해제",
"workspace.referral.reward.source.available": "보상 사용 가능",
"workspace.referral.reward.source.applied": "보상 사용됨",
"workspace.referral.reward.status.applied": "보상 사용됨",
"workspace.referral.reward.status.pendingInviter": "구독하여 잠금 해제",
"workspace.referral.reward.status.pendingInvitee": "구독하여 잠금 해제",
"workspace.referral.apply.noGo": "구독하여 잠금 해제",
"workspace.referral.apply.preview": "보상 보기",
"workspace.referral.apply.action": "사용",
"workspace.referral.apply.confirmTitle": "보상 사용",
"workspace.referral.apply.confirmBody": "{{amount}}를 사용하여 이 워크스페이스의 현재 사용량을 줄입니다.",
"workspace.referral.apply.confirmAction": "사용",
"download.title": "OpenCode | 다운로드",
"download.meta.description": "macOS, Windows, Linux용 OpenCode 다운로드",
"download.hero.title": "OpenCode 다운로드",
-33
View File
@@ -667,39 +667,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Andre betalingsmetoder",
"workspace.lite.promo.selectMethod": "Velg betalingsmetode",
"workspace.referral.copyLink": "Kopier lenke",
"workspace.referral.copied": "Kopiert",
"workspace.referral.overview.title": "Inviter venner",
"workspace.referral.overview.subtitle": "Få $5 når en venn abonnerer. De får også $5.",
"workspace.referral.instructions.share": "Del henvisningslenken din",
"workspace.referral.instructions.subscribe": "Vennen din blir med og abonnerer på Go",
"workspace.referral.instructions.claim": "Dere får begge $5 i brukskreditt å bruke på Go-bruksgrensene deres",
"workspace.referral.rewards.title": "Henvisningsbelønninger",
"workspace.referral.rewards.description": "Bruk tilgjengelige henvisningskreditter på Go-bruken din.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} belønninger brukt.",
"workspace.referral.rewards.empty": "Ingen henvisningsbelønninger ennå.",
"workspace.referral.table.reward": "Belønning",
"workspace.referral.table.referral": "Beskrivelse",
"workspace.referral.table.date": "Dato",
"workspace.referral.reward.description.inviter": "Inviterte {{email}}",
"workspace.referral.reward.description.invitee": "Invitert av {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Abonner for å låse opp",
"workspace.referral.reward.action.view": "Vis belønning",
"workspace.referral.reward.action.applied": "Belønning brukt",
"workspace.referral.reward.source.pendingInviter": "Venter på at de abonnerer",
"workspace.referral.reward.source.pendingInvitee": "Abonner for å låse opp belønningen",
"workspace.referral.reward.source.available": "Belønning klar til bruk",
"workspace.referral.reward.source.applied": "Belønning brukt",
"workspace.referral.reward.status.applied": "Belønning brukt",
"workspace.referral.reward.status.pendingInviter": "Abonner for å låse opp",
"workspace.referral.reward.status.pendingInvitee": "Abonner for å låse opp",
"workspace.referral.apply.noGo": "Abonner for å låse opp",
"workspace.referral.apply.preview": "Vis belønning",
"workspace.referral.apply.action": "Bruk",
"workspace.referral.apply.confirmTitle": "Bruk belønning",
"workspace.referral.apply.confirmBody": "Bruk {{amount}} for å redusere dette workspacets nåværende forbruk.",
"workspace.referral.apply.confirmAction": "Bruk",
"download.title": "OpenCode | Last ned",
"download.meta.description": "Last ned OpenCode for macOS, Windows og Linux",
"download.hero.title": "Last ned OpenCode",
-33
View File
@@ -668,39 +668,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Inne metody płatności",
"workspace.lite.promo.selectMethod": "Wybierz metodę płatności",
"workspace.referral.copyLink": "Kopiuj link",
"workspace.referral.copied": "Skopiowano",
"workspace.referral.overview.title": "Zaproś znajomych",
"workspace.referral.overview.subtitle": "Zdobądź $5, gdy znajomy się zasubskrybuje. On też dostanie $5.",
"workspace.referral.instructions.share": "Udostępnij swój link polecający",
"workspace.referral.instructions.subscribe": "Twój znajomy dołącza i subskrybuje Go",
"workspace.referral.instructions.claim": "Oboje otrzymujecie kredyt $5 do wykorzystania na limity użycia Go",
"workspace.referral.rewards.title": "Nagrody za polecenia",
"workspace.referral.rewards.description": "Wykorzystaj dostępne środki za polecenia na swoje użycie Go.",
"workspace.referral.rewards.subtitle": "Wykorzystano {{applied}} / {{total}} nagród.",
"workspace.referral.rewards.empty": "Brak nagród za polecenia.",
"workspace.referral.table.reward": "Nagroda",
"workspace.referral.table.referral": "Opis",
"workspace.referral.table.date": "Data",
"workspace.referral.reward.description.inviter": "Zaproszono {{email}}",
"workspace.referral.reward.description.invitee": "Zaproszony przez {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Subskrybuj, aby odblokować",
"workspace.referral.reward.action.view": "Zobacz nagrodę",
"workspace.referral.reward.action.applied": "Nagroda wykorzystana",
"workspace.referral.reward.source.pendingInviter": "Oczekiwanie na jego subskrypcję",
"workspace.referral.reward.source.pendingInvitee": "Subskrybuj, aby odblokować nagrodę",
"workspace.referral.reward.source.available": "Nagroda gotowa do wykorzystania",
"workspace.referral.reward.source.applied": "Nagroda wykorzystana",
"workspace.referral.reward.status.applied": "Nagroda wykorzystana",
"workspace.referral.reward.status.pendingInviter": "Subskrybuj, aby odblokować",
"workspace.referral.reward.status.pendingInvitee": "Subskrybuj, aby odblokować",
"workspace.referral.apply.noGo": "Subskrybuj, aby odblokować",
"workspace.referral.apply.preview": "Zobacz nagrodę",
"workspace.referral.apply.action": "Wykorzystaj",
"workspace.referral.apply.confirmTitle": "Wykorzystaj nagrodę",
"workspace.referral.apply.confirmBody": "Wykorzystaj {{amount}}, aby zmniejszyć aktualne użycie w tym workspace.",
"workspace.referral.apply.confirmAction": "Wykorzystaj",
"download.title": "OpenCode | Pobierz",
"download.meta.description": "Pobierz OpenCode na macOS, Windows i Linux",
"download.hero.title": "Pobierz OpenCode",
-35
View File
@@ -674,41 +674,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Другие способы оплаты",
"workspace.lite.promo.selectMethod": "Выберите способ оплаты",
"workspace.referral.copyLink": "Копировать ссылку",
"workspace.referral.copied": "Скопировано",
"workspace.referral.overview.title": "Пригласите друзей",
"workspace.referral.overview.subtitle": "Получите $5, когда друг оформит подписку. Он тоже получит $5.",
"workspace.referral.instructions.share": "Поделитесь своей реферальной ссылкой",
"workspace.referral.instructions.subscribe": "Ваш друг присоединяется и оформляет подписку на Go",
"workspace.referral.instructions.claim":
"Вы оба получаете кредит на использование $5, который можно применить к лимитам использования Go",
"workspace.referral.rewards.title": "Реферальные награды",
"workspace.referral.rewards.description": "Используйте доступные реферальные кредиты для оплаты использования Go.",
"workspace.referral.rewards.subtitle": "Использовано {{applied}} / {{total}} наград.",
"workspace.referral.rewards.empty": "Реферальных наград пока нет.",
"workspace.referral.table.reward": "Награда",
"workspace.referral.table.referral": "Описание",
"workspace.referral.table.date": "Дата",
"workspace.referral.reward.description.inviter": "Приглашён {{email}}",
"workspace.referral.reward.description.invitee": "Приглашены пользователем {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "Оформите подписку для разблокировки",
"workspace.referral.reward.action.view": "Посмотреть награду",
"workspace.referral.reward.action.applied": "Награда использована",
"workspace.referral.reward.source.pendingInviter": "Ожидание его подписки",
"workspace.referral.reward.source.pendingInvitee": "Подпишитесь, чтобы разблокировать награду",
"workspace.referral.reward.source.available": "Награда готова к применению",
"workspace.referral.reward.source.applied": "Награда использована",
"workspace.referral.reward.status.applied": "Награда использована",
"workspace.referral.reward.status.pendingInviter": "Оформите подписку для разблокировки",
"workspace.referral.reward.status.pendingInvitee": "Оформите подписку для разблокировки",
"workspace.referral.apply.noGo": "Оформите подписку для разблокировки",
"workspace.referral.apply.preview": "Посмотреть награду",
"workspace.referral.apply.action": "Применить",
"workspace.referral.apply.confirmTitle": "Применить награду",
"workspace.referral.apply.confirmBody":
"Используйте {{amount}}, чтобы уменьшить текущее использование этого workspace.",
"workspace.referral.apply.confirmAction": "Применить",
"download.title": "OpenCode | Скачать",
"download.meta.description": "Скачать OpenCode для macOS, Windows и Linux",
"download.hero.title": "Скачать OpenCode",
-33
View File
@@ -663,39 +663,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "วิธีการชำระเงินอื่นๆ",
"workspace.lite.promo.selectMethod": "เลือกวิธีการชำระเงิน",
"workspace.referral.copyLink": "คัดลอกลิงก์",
"workspace.referral.copied": "คัดลอกแล้ว",
"workspace.referral.overview.title": "ชวนเพื่อน",
"workspace.referral.overview.subtitle": "รับ $5 เมื่อเพื่อนสมัครสมาชิก เพื่อนก็จะได้รับ $5 เช่นกัน",
"workspace.referral.instructions.share": "แชร์ลิงก์แนะนำของคุณ",
"workspace.referral.instructions.subscribe": "เพื่อนของคุณเข้าร่วมและสมัครสมาชิก Go",
"workspace.referral.instructions.claim": "คุณทั้งคู่จะได้รับเครดิตการใช้งาน $5 เพื่อใช้กับขีดจำกัดการใช้งาน Go",
"workspace.referral.rewards.title": "รางวัลการแนะนำ",
"workspace.referral.rewards.description": "ใช้เครดิตการแนะนำที่มีอยู่กับการใช้งาน Go ของคุณ",
"workspace.referral.rewards.subtitle": "ใช้แล้ว {{applied}} / {{total}} รางวัล",
"workspace.referral.rewards.empty": "ยังไม่มีรางวัลการแนะนำ",
"workspace.referral.table.reward": "รางวัล",
"workspace.referral.table.referral": "คำอธิบาย",
"workspace.referral.table.date": "วันที่",
"workspace.referral.reward.description.inviter": "เชิญ {{email}}",
"workspace.referral.reward.description.invitee": "ได้รับเชิญจาก {{email}}",
"workspace.referral.reward.action.subscribeUnlock": "สมัครสมาชิกเพื่อปลดล็อก",
"workspace.referral.reward.action.view": "ดูรางวัล",
"workspace.referral.reward.action.applied": "ใช้รางวัลแล้ว",
"workspace.referral.reward.source.pendingInviter": "รอเพื่อนสมัครสมาชิก",
"workspace.referral.reward.source.pendingInvitee": "สมัครสมาชิกเพื่อปลดล็อกรางวัล",
"workspace.referral.reward.source.available": "รางวัลพร้อมใช้งาน",
"workspace.referral.reward.source.applied": "ใช้รางวัลแล้ว",
"workspace.referral.reward.status.applied": "ใช้รางวัลแล้ว",
"workspace.referral.reward.status.pendingInviter": "สมัครสมาชิกเพื่อปลดล็อก",
"workspace.referral.reward.status.pendingInvitee": "สมัครสมาชิกเพื่อปลดล็อก",
"workspace.referral.apply.noGo": "สมัครสมาชิกเพื่อปลดล็อก",
"workspace.referral.apply.preview": "ดูรางวัล",
"workspace.referral.apply.action": "ใช้",
"workspace.referral.apply.confirmTitle": "ใช้รางวัล",
"workspace.referral.apply.confirmBody": "ใช้ {{amount}} เพื่อลดการใช้งานปัจจุบันของ workspace นี้",
"workspace.referral.apply.confirmAction": "ใช้",
"download.title": "OpenCode | ดาวน์โหลด",
"download.meta.description": "ดาวน์โหลด OpenCode สำหรับ macOS, Windows และ Linux",
"download.hero.title": "ดาวน์โหลด OpenCode",
-34
View File
@@ -670,40 +670,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "Diğer ödeme yöntemleri",
"workspace.lite.promo.selectMethod": "Ödeme yöntemini seçin",
"workspace.referral.copyLink": "Bağlantıyı Kopyala",
"workspace.referral.copied": "Kopyalandı",
"workspace.referral.overview.title": "Arkadaşlarını davet et",
"workspace.referral.overview.subtitle": "Bir arkadaşın abone olduğunda $5 kazan. O da $5 alacak.",
"workspace.referral.instructions.share": "Referans bağlantını paylaş",
"workspace.referral.instructions.subscribe": "Arkadaşın katılır ve Go'ya abone olur",
"workspace.referral.instructions.claim":
"İkiniz de Go kullanım limitlerinize uygulamak için $5 kullanım kredisi alırsınız",
"workspace.referral.rewards.title": "Davet ödülleri",
"workspace.referral.rewards.description": "Mevcut davet kredilerini Go kullanımınıza uygulayın.",
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} ödül kullanıldı.",
"workspace.referral.rewards.empty": "Henüz davet ödülü yok.",
"workspace.referral.table.reward": "Ödül",
"workspace.referral.table.referral": "Açıklama",
"workspace.referral.table.date": "Tarih",
"workspace.referral.reward.description.inviter": "{{email}} davet edildi",
"workspace.referral.reward.description.invitee": "{{email}} tarafından davet edildi",
"workspace.referral.reward.action.subscribeUnlock": "Kilidi açmak için abone ol",
"workspace.referral.reward.action.view": "Ödülü Görüntüle",
"workspace.referral.reward.action.applied": "Ödül Kullanıldı",
"workspace.referral.reward.source.pendingInviter": "Abone olması bekleniyor",
"workspace.referral.reward.source.pendingInvitee": "Ödülün kilidini açmak için abone ol",
"workspace.referral.reward.source.available": "Ödül kullanıma hazır",
"workspace.referral.reward.source.applied": "Ödül kullanıldı",
"workspace.referral.reward.status.applied": "Ödül Kullanıldı",
"workspace.referral.reward.status.pendingInviter": "Kilidi açmak için abone ol",
"workspace.referral.reward.status.pendingInvitee": "Kilidi açmak için abone ol",
"workspace.referral.apply.noGo": "Kilidi açmak için abone ol",
"workspace.referral.apply.preview": "Ödülü Görüntüle",
"workspace.referral.apply.action": "Kullan",
"workspace.referral.apply.confirmTitle": "Ödülü kullan",
"workspace.referral.apply.confirmBody": "Bu workspace'in mevcut kullanımını azaltmak için {{amount}} kullan.",
"workspace.referral.apply.confirmAction": "Kullan",
"download.title": "OpenCode | İndir",
"download.meta.description": "OpenCode'u macOS, Windows ve Linux için indirin",
"download.hero.title": "OpenCode'u İndir",
-33
View File
@@ -643,39 +643,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "其他付款方式",
"workspace.lite.promo.selectMethod": "选择付款方式",
"workspace.referral.copyLink": "复制链接",
"workspace.referral.copied": "已复制",
"workspace.referral.overview.title": "邀请好友",
"workspace.referral.overview.subtitle": "好友订阅后,您可获得 $5,对方也可获得 $5。",
"workspace.referral.instructions.share": "分享您的推荐链接。",
"workspace.referral.instructions.subscribe": "好友加入并订阅 Go。",
"workspace.referral.instructions.claim": "你们都将获得 $5 使用额度,可用于您的 Go 使用限额。",
"workspace.referral.rewards.title": "邀请奖励",
"workspace.referral.rewards.description": "将可用的邀请积分应用到您的 Go 用量。",
"workspace.referral.rewards.subtitle": "已使用 {{applied}} / {{total}} 个奖励。",
"workspace.referral.rewards.empty": "暂无邀请奖励。",
"workspace.referral.table.reward": "奖励",
"workspace.referral.table.referral": "描述",
"workspace.referral.table.date": "日期",
"workspace.referral.reward.description.inviter": "已邀请 {{email}}",
"workspace.referral.reward.description.invitee": "由 {{email}} 邀请",
"workspace.referral.reward.action.subscribeUnlock": "订阅以解锁",
"workspace.referral.reward.action.view": "查看奖励",
"workspace.referral.reward.action.applied": "奖励已使用",
"workspace.referral.reward.source.pendingInviter": "等待对方订阅",
"workspace.referral.reward.source.pendingInvitee": "订阅即可解锁奖励",
"workspace.referral.reward.source.available": "奖励可使用",
"workspace.referral.reward.source.applied": "奖励已使用",
"workspace.referral.reward.status.applied": "奖励已使用",
"workspace.referral.reward.status.pendingInviter": "订阅以解锁",
"workspace.referral.reward.status.pendingInvitee": "订阅以解锁",
"workspace.referral.apply.noGo": "订阅以解锁",
"workspace.referral.apply.preview": "查看奖励",
"workspace.referral.apply.action": "使用",
"workspace.referral.apply.confirmTitle": "使用奖励",
"workspace.referral.apply.confirmBody": "使用 {{amount}} 抵扣当前工作区的用量。",
"workspace.referral.apply.confirmAction": "使用",
"download.title": "OpenCode | 下载",
"download.meta.description": "下载适用于 macOS, Windows, 和 Linux 的 OpenCode",
"download.hero.title": "下载 OpenCode",
-33
View File
@@ -643,39 +643,6 @@ export const dict = {
"workspace.lite.promo.otherMethods": "其他付款方式",
"workspace.lite.promo.selectMethod": "選擇付款方式",
"workspace.referral.copyLink": "複製連結",
"workspace.referral.copied": "已複製",
"workspace.referral.overview.title": "邀請朋友",
"workspace.referral.overview.subtitle": "朋友訂閱後,您可獲得 $5,對方也可獲得 $5。",
"workspace.referral.instructions.share": "分享您的推薦連結。",
"workspace.referral.instructions.subscribe": "朋友加入並訂閱 Go。",
"workspace.referral.instructions.claim": "你們都將獲得 $5 使用額度,可用於您的 Go 使用限額。",
"workspace.referral.rewards.title": "邀請獎勵",
"workspace.referral.rewards.description": "將可用的邀請點數套用至您的 Go 使用量。",
"workspace.referral.rewards.subtitle": "已使用 {{applied}} / {{total}} 個獎勵。",
"workspace.referral.rewards.empty": "暫無邀請獎勵。",
"workspace.referral.table.reward": "獎勵",
"workspace.referral.table.referral": "描述",
"workspace.referral.table.date": "日期",
"workspace.referral.reward.description.inviter": "已邀請 {{email}}",
"workspace.referral.reward.description.invitee": "由 {{email}} 邀請",
"workspace.referral.reward.action.subscribeUnlock": "訂閱以解鎖",
"workspace.referral.reward.action.view": "查看獎勵",
"workspace.referral.reward.action.applied": "獎勵已使用",
"workspace.referral.reward.source.pendingInviter": "等待對方訂閱",
"workspace.referral.reward.source.pendingInvitee": "訂閱即可解鎖獎勵",
"workspace.referral.reward.source.available": "獎勵可使用",
"workspace.referral.reward.source.applied": "獎勵已使用",
"workspace.referral.reward.status.applied": "獎勵已使用",
"workspace.referral.reward.status.pendingInviter": "訂閱以解鎖",
"workspace.referral.reward.status.pendingInvitee": "訂閱以解鎖",
"workspace.referral.apply.noGo": "訂閱以解鎖",
"workspace.referral.apply.preview": "查看獎勵",
"workspace.referral.apply.action": "使用",
"workspace.referral.apply.confirmTitle": "使用獎勵",
"workspace.referral.apply.confirmBody": "使用 {{amount}} 抵扣目前工作區的用量。",
"workspace.referral.apply.confirmAction": "使用",
"download.title": "OpenCode | 下載",
"download.meta.description": "下載適用於 macOS、Windows 與 Linux 的 OpenCode",
"download.hero.title": "下載 OpenCode",
@@ -1,47 +0,0 @@
import type { Key } from "~/i18n"
import type { useI18n } from "~/context/i18n"
type ResetTimeKeys = {
day: Key
days: Key
hour: Key
hours: Key
minute: Key
minutes: Key
fewSeconds: Key
}
export const liteResetTimeKeys = {
day: "workspace.lite.time.day",
days: "workspace.lite.time.days",
hour: "workspace.lite.time.hour",
hours: "workspace.lite.time.hours",
minute: "workspace.lite.time.minute",
minutes: "workspace.lite.time.minutes",
fewSeconds: "workspace.lite.time.fewSeconds",
} satisfies ResetTimeKeys
export const blackResetTimeKeys = {
day: "workspace.black.time.day",
days: "workspace.black.time.days",
hour: "workspace.black.time.hour",
hours: "workspace.black.time.hours",
minute: "workspace.black.time.minute",
minutes: "workspace.black.time.minutes",
fewSeconds: "workspace.black.time.fewSeconds",
} satisfies ResetTimeKeys
export function formatResetTime(seconds: number, i18n: ReturnType<typeof useI18n>, keys: ResetTimeKeys) {
const days = Math.floor(seconds / 86400)
if (days >= 1) {
const hours = Math.floor((seconds % 86400) / 3600)
return `${days} ${days === 1 ? i18n.t(keys.day) : i18n.t(keys.days)} ${hours} ${hours === 1 ? i18n.t(keys.hour) : i18n.t(keys.hours)}`
}
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
if (hours >= 1)
return `${hours} ${hours === 1 ? i18n.t(keys.hour) : i18n.t(keys.hours)} ${minutes} ${minutes === 1 ? i18n.t(keys.minute) : i18n.t(keys.minutes)}`
if (minutes === 0) return i18n.t(keys.fewSeconds)
return `${minutes} ${minutes === 1 ? i18n.t(keys.minute) : i18n.t(keys.minutes)}`
}
@@ -1,28 +0,0 @@
import { Referral } from "@opencode-ai/console-core/referral.js"
const REFERRAL_COOKIE = "oc_referral"
const REFERRAL_MAX_AGE = 60 * 60 * 24 * 30
export function normalizeReferralCode(code?: string | null) {
return Referral.normalizeCode(code)
}
export function referralCookie(code: string) {
return `${REFERRAL_COOKIE}=${encodeURIComponent(code)}; Path=/; Max-Age=${REFERRAL_MAX_AGE}; SameSite=Lax; HttpOnly`
}
export function clearReferralCookie() {
return `${REFERRAL_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly`
}
export function referralCodeFromCookieHeader(header: string | null) {
if (!header) return undefined
return normalizeReferralCode(
header
.split(";")
.map((x) => x.trim())
.find((x) => x.startsWith(`${REFERRAL_COOKIE}=`))
?.slice(`${REFERRAL_COOKIE}=`.length),
)
}
+6 -10
View File
@@ -1,20 +1,16 @@
import { createMiddleware } from "@solidjs/start/middleware"
import { LOCALE_HEADER, cookie, fromPathname, strip } from "~/lib/language"
import { normalizeReferralCode, referralCookie } from "~/lib/referral-invite"
export default createMiddleware({
onRequest(event) {
const url = new URL(event.request.url)
const locale = fromPathname(url.pathname)
if (locale) {
url.pathname = strip(url.pathname)
const request = new Request(url, event.request)
request.headers.set(LOCALE_HEADER, locale)
event.request = request
event.response.headers.append("set-cookie", cookie(locale))
}
if (!locale) return
const referralCode = normalizeReferralCode(url.searchParams.get("ref"))
if (referralCode) event.response.headers.append("set-cookie", referralCookie(referralCode))
url.pathname = strip(url.pathname)
const request = new Request(url, event.request)
request.headers.set(LOCALE_HEADER, locale)
event.request = request
event.response.headers.append("set-cookie", cookie(locale))
},
})
@@ -1,11 +1,9 @@
import { redirect } from "@solidjs/router"
import type { APIEvent } from "@solidjs/start/server"
import { Referral } from "@opencode-ai/console-core/referral.js"
import { AuthClient } from "~/context/auth"
import { useAuthSession } from "~/context/auth"
import { i18n } from "~/i18n"
import { localeFromRequest, route } from "~/lib/language"
import { clearReferralCookie, referralCodeFromCookieHeader } from "~/lib/referral-invite"
export async function GET(input: APIEvent) {
const url = new URL(input.request.url)
@@ -19,7 +17,6 @@ export async function GET(input: APIEvent) {
if (result.err) throw new Error(result.err.message)
const decoded = AuthClient.decode(result.tokens.access, {} as any)
if (decoded.err) throw new Error(decoded.err.message)
const referralCode = referralCodeFromCookieHeader(input.request.headers.get("cookie"))
const session = await useAuthSession()
const id = decoded.subject.properties.accountID
await session.update((value) => {
@@ -35,15 +32,8 @@ export async function GET(input: APIEvent) {
current: id,
}
})
if (decoded.subject.properties.newAccount && referralCode) {
await Referral.createFromAccount({ accountID: id, referralCode }).catch((error) => {
console.error("Referral create failed", error)
})
}
const next = url.pathname === "/auth/callback" ? "/auth" : url.pathname.replace("/auth/callback", "")
const response = redirect(route(locale, next))
if (referralCode) response.headers.append("set-cookie", clearReferralCookie())
return response
return redirect(route(locale, next))
} catch (e: any) {
return new Response(
JSON.stringify({
+59 -61
View File
@@ -700,6 +700,65 @@
text-decoration: underline;
}
}
[data-slot="workspace-picker"] {
[data-slot="workspace-list"] {
width: 100%;
padding: 0;
margin: 0;
list-style: none;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
align-self: stretch;
outline: none;
overflow-y: auto;
max-height: 240px;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
[data-slot="workspace-item"] {
width: 100%;
display: flex;
padding: 8px 12px;
align-items: center;
gap: 8px;
align-self: stretch;
cursor: pointer;
[data-slot="selected-icon"] {
visibility: hidden;
color: rgba(255, 255, 255, 0.39);
font-family: "IBM Plex Mono", monospace;
font-size: 16px;
font-style: normal;
font-weight: 400;
line-height: 160%;
}
span:last-child {
color: rgba(255, 255, 255, 0.92);
font-size: 16px;
font-style: normal;
font-weight: 400;
line-height: 160%;
}
&:hover,
&[data-active="true"] {
background: #161616;
[data-slot="selected-icon"] {
visibility: visible;
}
}
}
}
}
}
}
@@ -780,64 +839,3 @@
}
}
}
[data-component="black-workspace-picker-modal"] {
font-family: var(--font-mono);
[data-slot="workspace-list"] {
width: 100%;
padding: 0;
margin: 0;
list-style: none;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
align-self: stretch;
outline: none;
overflow-y: auto;
max-height: 240px;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
}
[data-slot="workspace-item"] {
width: 100%;
display: flex;
padding: 8px 12px;
align-items: center;
gap: 8px;
align-self: stretch;
cursor: pointer;
[data-slot="selected-icon"] {
visibility: hidden;
color: rgba(255, 255, 255, 0.39);
font-family: "IBM Plex Mono", monospace;
font-size: 16px;
font-style: normal;
font-weight: 400;
line-height: 160%;
}
span:last-child {
color: rgba(255, 255, 255, 0.92);
font-size: 16px;
font-style: normal;
font-weight: 400;
line-height: 160%;
}
&:hover,
&[data-active="true"] {
background: #161616;
[data-slot="selected-icon"] {
visibility: visible;
}
}
}
}
@@ -444,13 +444,8 @@ export default function BlackSubscribe() {
</div>
{/* Workspace picker modal */}
<Modal
open={showWorkspacePicker() ?? false}
onClose={() => {}}
title={i18n.t("black.workspace.selectPlan")}
variant="black"
>
<div data-component="black-workspace-picker-modal" data-slot="workspace-picker">
<Modal open={showWorkspacePicker() ?? false} onClose={() => {}} title={i18n.t("black.workspace.selectPlan")}>
<div data-slot="workspace-picker">
<ul
ref={listRef}
data-slot="workspace-list"
@@ -9,7 +9,7 @@ import { Actor } from "@opencode-ai/console-core/actor.js"
import { Resource } from "@opencode-ai/console-resource"
import { LiteData } from "@opencode-ai/console-core/lite.js"
import { BlackData } from "@opencode-ai/console-core/black.js"
import { Referral } from "@opencode-ai/console-core/referral.js"
import { User } from "@opencode-ai/console-core/user.js"
export async function POST(input: APIEvent) {
const body = await Billing.stripe().webhooks.constructEventAsync(
@@ -174,13 +174,6 @@ export async function POST(input: APIEvent) {
}
}
})
await Referral.completeFromLiteSubscription({
workspaceID,
userID,
}).catch((error) => {
console.error("Referral sync failed", error)
})
})
}
}
@@ -34,10 +34,6 @@
background-color: var(--color-bg-surface);
}
}
}
[data-component="workspace-create-modal"] {
width: 100%;
[data-slot="create-form"] {
width: 100%;
@@ -1,5 +1,6 @@
import { query, useParams, action, createAsync, redirect, useSubmission } from "@solidjs/router"
import { For, createEffect, createSignal } from "solid-js"
import { For, createEffect } from "solid-js"
import { createStore } from "solid-js/store"
import { withActor } from "~/context/auth.withActor"
import { Actor } from "@opencode-ai/console-core/actor.js"
import { and, Database, eq, isNull } from "@opencode-ai/console-core/drizzle/index.js"
@@ -50,7 +51,9 @@ export function WorkspacePicker() {
const i18n = useI18n()
const workspaces = createAsync(() => getWorkspaces())
const submission = useSubmission(createWorkspace)
const [showForm, setShowForm] = createSignal(false)
const [store, setStore] = createStore({
showForm: false,
})
let inputRef: HTMLInputElement | undefined
const currentWorkspace = () => {
@@ -58,8 +61,12 @@ export function WorkspacePicker() {
return ws ? ws.name : i18n.t("workspace.select")
}
const handleWorkspaceNew = () => {
setStore("showForm", true)
}
createEffect(() => {
if (showForm() && inputRef) {
if (store.showForm && inputRef) {
setTimeout(() => inputRef?.focus(), 0)
}
})
@@ -72,7 +79,7 @@ export function WorkspacePicker() {
// Reset signals when workspace ID changes
createEffect(() => {
params.id
setShowForm(false)
setStore("showForm", false)
})
return (
@@ -85,34 +92,32 @@ export function WorkspacePicker() {
</DropdownItem>
)}
</For>
<button data-slot="create-item" type="button" onClick={() => setShowForm(true)}>
<button data-slot="create-item" type="button" onClick={() => handleWorkspaceNew()}>
{i18n.t("workspace.createNew")}
</button>
</Dropdown>
<Modal open={showForm()} onClose={() => setShowForm(false)} title={i18n.t("workspace.modal.title")}>
<div data-component="workspace-create-modal">
<form data-slot="create-form" action={createWorkspace} method="post">
<div data-slot="create-input-group">
<input
ref={inputRef}
data-slot="create-input"
type="text"
name="workspaceName"
placeholder={i18n.t("workspace.modal.placeholder")}
required
/>
<div data-slot="button-group">
<button type="button" data-color="ghost" onClick={() => setShowForm(false)}>
{i18n.t("common.cancel")}
</button>
<button type="submit" data-color="primary" disabled={submission.pending}>
{submission.pending ? i18n.t("common.creating") : i18n.t("common.create")}
</button>
</div>
<Modal open={store.showForm} onClose={() => setStore("showForm", false)} title={i18n.t("workspace.modal.title")}>
<form data-slot="create-form" action={createWorkspace} method="post">
<div data-slot="create-input-group">
<input
ref={inputRef}
data-slot="create-input"
type="text"
name="workspaceName"
placeholder={i18n.t("workspace.modal.placeholder")}
required
/>
<div data-slot="button-group">
<button type="button" data-color="ghost" onClick={() => setStore("showForm", false)}>
{i18n.t("common.cancel")}
</button>
<button type="submit" data-color="primary" disabled={submission.pending}>
{submission.pending ? i18n.t("common.creating") : i18n.t("common.create")}
</button>
</div>
</form>
</div>
</div>
</form>
</Modal>
</div>
)
@@ -25,7 +25,6 @@
&:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
@@ -13,7 +13,6 @@ import styles from "./black-section.module.css"
import waitlistStyles from "./black-waitlist-section.module.css"
import { useI18n } from "~/context/i18n"
import { formError } from "~/lib/form-error"
import { blackResetTimeKeys, formatResetTime } from "~/lib/format-reset-time"
const querySubscription = query(async (workspaceID: string) => {
"use server"
@@ -53,6 +52,20 @@ const querySubscription = query(async (workspaceID: string) => {
}, workspaceID)
}, "subscription.get")
function formatResetTime(seconds: number, i18n: ReturnType<typeof useI18n>) {
const days = Math.floor(seconds / 86400)
if (days >= 1) {
const hours = Math.floor((seconds % 86400) / 3600)
return `${days} ${days === 1 ? i18n.t("workspace.black.time.day") : i18n.t("workspace.black.time.days")} ${hours} ${hours === 1 ? i18n.t("workspace.black.time.hour") : i18n.t("workspace.black.time.hours")}`
}
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
if (hours >= 1)
return `${hours} ${hours === 1 ? i18n.t("workspace.black.time.hour") : i18n.t("workspace.black.time.hours")} ${minutes} ${minutes === 1 ? i18n.t("workspace.black.time.minute") : i18n.t("workspace.black.time.minutes")}`
if (minutes === 0) return i18n.t("workspace.black.time.fewSeconds")
return `${minutes} ${minutes === 1 ? i18n.t("workspace.black.time.minute") : i18n.t("workspace.black.time.minutes")}`
}
const cancelWaitlist = action(async (workspaceID: string) => {
"use server"
return json(
@@ -196,7 +209,7 @@ export function BlackSection() {
</div>
<span data-slot="reset-time">
{i18n.t("workspace.black.subscription.resetsIn")}{" "}
{formatResetTime(sub().rollingUsage.resetInSec, i18n, blackResetTimeKeys)}
{formatResetTime(sub().rollingUsage.resetInSec, i18n)}
</span>
</div>
<div data-slot="usage-item">
@@ -209,7 +222,7 @@ export function BlackSection() {
</div>
<span data-slot="reset-time">
{i18n.t("workspace.black.subscription.resetsIn")}{" "}
{formatResetTime(sub().weeklyUsage.resetInSec, i18n, blackResetTimeKeys)}
{formatResetTime(sub().weeklyUsage.resetInSec, i18n)}
</span>
</div>
</div>
@@ -1,17 +1,11 @@
import { createAsync, useParams } from "@solidjs/router"
import { Show } from "solid-js"
import { IconGo } from "~/component/icon"
import { GoReferralSection, queryGoReferral } from "~/component/go-referral"
import { useI18n } from "~/context/i18n"
import { useLanguage } from "~/context/language"
import { LiteSection, queryLiteSubscription } from "./lite-section"
import { LiteSection } from "./lite-section"
export default function () {
const params = useParams()
const i18n = useI18n()
const language = useLanguage()
const referral = createAsync(() => queryGoReferral(params.id!))
const lite = createAsync(() => queryLiteSubscription(params.id!))
return (
<div data-page="workspace-[id]">
@@ -29,10 +23,7 @@ export default function () {
</section>
<div data-slot="sections">
<LiteSection lite={lite()} />
<Show when={referral()} fallback={<section>{i18n.t("workspace.lite.loading")}</section>}>
{(summary) => <GoReferralSection workspaceID={params.id!} summary={summary()} lite={lite()} />}
</Show>
<LiteSection />
</div>
</div>
)
@@ -211,9 +211,7 @@
align-items: center;
gap: 4px;
}
}
.paymentMethodModal {
[data-slot="modal-actions"] {
display: flex;
gap: var(--space-3);
@@ -14,11 +14,10 @@ import styles from "./lite-section.module.css"
import { useI18n } from "~/context/i18n"
import { useLanguage } from "~/context/language"
import { formError } from "~/lib/form-error"
import { formatResetTime, liteResetTimeKeys } from "~/lib/format-reset-time"
import { IconAlipay, IconUpi } from "~/component/icon"
export const queryLiteSubscription = query(async (workspaceID: string) => {
const queryLiteSubscription = query(async (workspaceID: string) => {
"use server"
return withActor(async () => {
const row = await Database.use((tx) =>
@@ -68,7 +67,19 @@ export const queryLiteSubscription = query(async (workspaceID: string) => {
}, workspaceID)
}, "lite.subscription.get")
type LiteSubscription = Awaited<ReturnType<typeof queryLiteSubscription>>
function formatResetTime(seconds: number, i18n: ReturnType<typeof useI18n>) {
const days = Math.floor(seconds / 86400)
if (days >= 1) {
const hours = Math.floor((seconds % 86400) / 3600)
return `${days} ${days === 1 ? i18n.t("workspace.lite.time.day") : i18n.t("workspace.lite.time.days")} ${hours} ${hours === 1 ? i18n.t("workspace.lite.time.hour") : i18n.t("workspace.lite.time.hours")}`
}
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
if (hours >= 1)
return `${hours} ${hours === 1 ? i18n.t("workspace.lite.time.hour") : i18n.t("workspace.lite.time.hours")} ${minutes} ${minutes === 1 ? i18n.t("workspace.lite.time.minute") : i18n.t("workspace.lite.time.minutes")}`
if (minutes === 0) return i18n.t("workspace.lite.time.fewSeconds")
return `${minutes} ${minutes === 1 ? i18n.t("workspace.lite.time.minute") : i18n.t("workspace.lite.time.minutes")}`
}
const createLiteCheckoutUrl = action(
async (workspaceID: string, successUrl: string, cancelUrl: string, method?: "alipay" | "upi") => {
@@ -129,32 +140,13 @@ const setLiteUseBalance = action(async (form: FormData) => {
)
}, "setLiteUseBalance")
function LiteUsageItem(props: { label: string; usage: { usagePercent: number; resetInSec: number } }) {
const i18n = useI18n()
return (
<div data-slot="usage-item">
<div data-slot="usage-header">
<span data-slot="usage-label">{props.label}</span>
<span data-slot="usage-value">{props.usage.usagePercent}%</span>
</div>
<div data-slot="progress">
<div data-slot="progress-bar" style={{ width: `${props.usage.usagePercent}%` }} />
</div>
<span data-slot="reset-time">
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
{formatResetTime(props.usage.resetInSec, i18n, liteResetTimeKeys)}
</span>
</div>
)
}
export function LiteSection(props: { lite: LiteSubscription | undefined }) {
export function LiteSection() {
const params = useParams()
const i18n = useI18n()
const language = useLanguage()
const billingInfo = createAsync(() => queryBillingInfo(params.id!))
const isBlack = createMemo(() => billingInfo()?.subscriptionID || billingInfo()?.timeSubscriptionBooked)
const lite = createAsync(() => queryLiteSubscription(params.id!))
const sessionAction = useAction(createSessionUrl)
const sessionSubmission = useSubmission(createSessionUrl)
const checkoutAction = useAction(createLiteCheckoutUrl)
@@ -194,7 +186,7 @@ export function LiteSection(props: { lite: LiteSubscription | undefined }) {
<p data-slot="other-message">{i18n.t("workspace.lite.black.message")}</p>
</section>
</Show>
<Show when={!isBlack() && props.lite && props.lite.mine && props.lite}>
<Show when={!isBlack() && lite() && lite()!.mine && lite()!}>
{(sub) => (
<section class={styles.root}>
<div data-slot="section-title">
@@ -215,9 +207,44 @@ export function LiteSection(props: { lite: LiteSubscription | undefined }) {
.
</div>
<div data-slot="usage">
<LiteUsageItem label={i18n.t("workspace.lite.subscription.rollingUsage")} usage={sub().rollingUsage} />
<LiteUsageItem label={i18n.t("workspace.lite.subscription.weeklyUsage")} usage={sub().weeklyUsage} />
<LiteUsageItem label={i18n.t("workspace.lite.subscription.monthlyUsage")} usage={sub().monthlyUsage} />
<div data-slot="usage-item">
<div data-slot="usage-header">
<span data-slot="usage-label">{i18n.t("workspace.lite.subscription.rollingUsage")}</span>
<span data-slot="usage-value">{sub().rollingUsage.usagePercent}%</span>
</div>
<div data-slot="progress">
<div data-slot="progress-bar" style={{ width: `${sub().rollingUsage.usagePercent}%` }} />
</div>
<span data-slot="reset-time">
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
{formatResetTime(sub().rollingUsage.resetInSec, i18n)}
</span>
</div>
<div data-slot="usage-item">
<div data-slot="usage-header">
<span data-slot="usage-label">{i18n.t("workspace.lite.subscription.weeklyUsage")}</span>
<span data-slot="usage-value">{sub().weeklyUsage.usagePercent}%</span>
</div>
<div data-slot="progress">
<div data-slot="progress-bar" style={{ width: `${sub().weeklyUsage.usagePercent}%` }} />
</div>
<span data-slot="reset-time">
{i18n.t("workspace.lite.subscription.resetsIn")} {formatResetTime(sub().weeklyUsage.resetInSec, i18n)}
</span>
</div>
<div data-slot="usage-item">
<div data-slot="usage-header">
<span data-slot="usage-label">{i18n.t("workspace.lite.subscription.monthlyUsage")}</span>
<span data-slot="usage-value">{sub().monthlyUsage.usagePercent}%</span>
</div>
<div data-slot="progress">
<div data-slot="progress-bar" style={{ width: `${sub().monthlyUsage.usagePercent}%` }} />
</div>
<span data-slot="reset-time">
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
{formatResetTime(sub().monthlyUsage.resetInSec, i18n)}
</span>
</div>
</div>
<form action={setLiteUseBalance} method="post" data-slot="setting-row">
<p>{i18n.t("workspace.lite.subscription.useBalance")}</p>
@@ -236,12 +263,12 @@ export function LiteSection(props: { lite: LiteSubscription | undefined }) {
</section>
)}
</Show>
<Show when={!isBlack() && props.lite && !props.lite.mine}>
<Show when={!isBlack() && lite() && !lite()!.mine}>
<section class={styles.root}>
<p data-slot="other-message">{i18n.t("workspace.lite.other.message")}</p>
</section>
</Show>
<Show when={!isBlack() && props.lite === null}>
<Show when={!isBlack() && lite() === null}>
<section class={styles.root}>
<p data-slot="promo-description">
<For
@@ -303,33 +330,31 @@ export function LiteSection(props: { lite: LiteSubscription | undefined }) {
onClose={() => setStore("showModal", false)}
title={i18n.t("workspace.lite.promo.selectMethod")}
>
<div class={styles.paymentMethodModal}>
<div data-slot="modal-actions">
<button
type="button"
data-slot="method-button"
data-color="ghost"
disabled={checkoutSubmission.pending || busy()}
onClick={() => onClickSubscribe("alipay")}
>
<Show when={store.loading !== "alipay"}>
<IconAlipay style={{ width: "24px", height: "24px" }} />
</Show>
{store.loading === "alipay" ? i18n.t("workspace.lite.promo.subscribing") : "Alipay"}
</button>
<button
type="button"
data-slot="method-button"
data-color="ghost"
disabled={checkoutSubmission.pending || busy()}
onClick={() => onClickSubscribe("upi")}
>
<Show when={store.loading !== "upi"}>
<IconUpi style={{ width: "auto", height: "16px" }} />
</Show>
{store.loading === "upi" ? i18n.t("workspace.lite.promo.subscribing") : "UPI"}
</button>
</div>
<div data-slot="modal-actions">
<button
type="button"
data-slot="method-button"
data-color="ghost"
disabled={checkoutSubmission.pending || busy()}
onClick={() => onClickSubscribe("alipay")}
>
<Show when={store.loading !== "alipay"}>
<IconAlipay style={{ width: "24px", height: "24px" }} />
</Show>
{store.loading === "alipay" ? i18n.t("workspace.lite.promo.subscribing") : "Alipay"}
</button>
<button
type="button"
data-slot="method-button"
data-color="ghost"
disabled={checkoutSubmission.pending || busy()}
onClick={() => onClickSubscribe("upi")}
>
<Show when={store.loading !== "upi"}>
<IconUpi style={{ width: "auto", height: "16px" }} />
</Show>
{store.loading === "upi" ? i18n.t("workspace.lite.promo.subscribing") : "UPI"}
</button>
</div>
</Modal>
</section>
@@ -170,10 +170,6 @@ export async function handler(
if (v === "$ip") return [[k, ip]]
if (v === "$workspace") return authInfo?.workspaceID ? [[k, authInfo?.workspaceID]] : []
if (v === "$session") return sessionId ? [[k, sessionId]] : []
if (v === "$user") {
const user = sessionId ?? authInfo?.workspaceID ?? ip
return user ? [[k, user]] : []
}
if (v.startsWith("$header.")) {
const headerValue = input.request.headers.get(v.slice(8))
return headerValue ? [[k, headerValue]] : []
@@ -1,47 +0,0 @@
CREATE TABLE `referral_code` (
`id` varchar(30) NOT NULL,
`workspace_id` varchar(30) NOT NULL,
`time_created` timestamp(3) NOT NULL DEFAULT (now()),
`time_updated` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
`time_deleted` timestamp(3),
`code` varchar(10) NOT NULL,
CONSTRAINT PRIMARY KEY(`workspace_id`,`id`),
CONSTRAINT `referral_code_workspace_id` UNIQUE INDEX(`workspace_id`),
CONSTRAINT `referral_code_code` UNIQUE INDEX(`code`)
);
--> statement-breakpoint
CREATE TABLE `referral_reward` (
`id` varchar(30) NOT NULL,
`workspace_id` varchar(30) NOT NULL,
`time_created` timestamp(3) NOT NULL DEFAULT (now()),
`time_updated` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
`time_deleted` timestamp(3),
`referral_id` varchar(30) NOT NULL,
`source` enum('inviter','invitee') NOT NULL,
`amount` bigint NOT NULL,
`applied_by_user_id` varchar(30),
`time_applied` timestamp(3),
CONSTRAINT PRIMARY KEY(`workspace_id`,`id`),
CONSTRAINT `referral_reward_referral_source` UNIQUE INDEX(`referral_id`,`source`)
);
--> statement-breakpoint
CREATE TABLE `referral` (
`id` varchar(30) NOT NULL,
`workspace_id` varchar(30) NOT NULL,
`time_created` timestamp(3) NOT NULL DEFAULT (now()),
`time_updated` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
`time_deleted` timestamp(3),
`inviter_workspace_id` varchar(30) NOT NULL,
`invitee_account_id` varchar(30) NOT NULL,
`invitee_user_id` varchar(30) NOT NULL,
`referral_code_id` varchar(30) NOT NULL,
`stripe_customer_id` varchar(255) NOT NULL,
`stripe_subscription_id` varchar(255) NOT NULL,
CONSTRAINT PRIMARY KEY(`workspace_id`,`id`),
CONSTRAINT `referral_invitee_account_id` UNIQUE INDEX(`invitee_account_id`),
CONSTRAINT `referral_stripe_subscription_id` UNIQUE INDEX(`stripe_subscription_id`)
);
--> statement-breakpoint
CREATE INDEX `referral_reward_workspace_time` ON `referral_reward` (`workspace_id`,`time_created`);--> statement-breakpoint
CREATE INDEX `referral_inviter_workspace_id` ON `referral` (`inviter_workspace_id`);--> statement-breakpoint
CREATE INDEX `referral_code_id` ON `referral` (`referral_code_id`);
File diff suppressed because it is too large Load Diff
@@ -1,20 +0,0 @@
DROP TABLE `referral_code`;--> statement-breakpoint
DROP INDEX `referral_reward_referral_source` ON `referral_reward`;--> statement-breakpoint
DROP INDEX `referral_stripe_subscription_id` ON `referral`;--> statement-breakpoint
DROP INDEX `referral_inviter_workspace_id` ON `referral`;--> statement-breakpoint
DROP INDEX `referral_code_id` ON `referral`;--> statement-breakpoint
ALTER TABLE `referral_reward` DROP PRIMARY KEY;--> statement-breakpoint
ALTER TABLE `referral` DROP PRIMARY KEY;--> statement-breakpoint
ALTER TABLE `referral_reward` MODIFY COLUMN `workspace_id` varchar(30);--> statement-breakpoint
ALTER TABLE `workspace` ADD `referral_code` varchar(16);--> statement-breakpoint
ALTER TABLE `referral_reward` ADD PRIMARY KEY (`id`);--> statement-breakpoint
ALTER TABLE `referral` ADD PRIMARY KEY (`id`);--> statement-breakpoint
CREATE INDEX `referral_workspace_id` ON `referral` (`workspace_id`);--> statement-breakpoint
CREATE UNIQUE INDEX `workspace_referral_code` ON `workspace` (`referral_code`);--> statement-breakpoint
ALTER TABLE `referral_reward` DROP COLUMN `source`;--> statement-breakpoint
ALTER TABLE `referral_reward` DROP COLUMN `applied_by_user_id`;--> statement-breakpoint
ALTER TABLE `referral` DROP COLUMN `inviter_workspace_id`;--> statement-breakpoint
ALTER TABLE `referral` DROP COLUMN `invitee_user_id`;--> statement-breakpoint
ALTER TABLE `referral` DROP COLUMN `referral_code_id`;--> statement-breakpoint
ALTER TABLE `referral` DROP COLUMN `stripe_customer_id`;--> statement-breakpoint
ALTER TABLE `referral` DROP COLUMN `stripe_subscription_id`;
File diff suppressed because it is too large Load Diff
@@ -1,4 +0,0 @@
DROP INDEX `referral_reward_workspace_time` ON `referral_reward`;--> statement-breakpoint
ALTER TABLE `referral_reward` DROP PRIMARY KEY;--> statement-breakpoint
ALTER TABLE `referral_reward` ADD PRIMARY KEY (`workspace_id`,`referral_id`);--> statement-breakpoint
ALTER TABLE `referral_reward` DROP COLUMN `id`;
File diff suppressed because it is too large Load Diff
@@ -1,3 +0,0 @@
DROP INDEX `referral_workspace_id` ON `referral`;--> statement-breakpoint
ALTER TABLE `referral` DROP PRIMARY KEY;--> statement-breakpoint
ALTER TABLE `referral` ADD PRIMARY KEY (`workspace_id`,`id`);
@@ -1,2 +0,0 @@
UPDATE `workspace` SET `referral_code` = NULL WHERE CHAR_LENGTH(`referral_code`) > 10;--> statement-breakpoint
ALTER TABLE `workspace` MODIFY COLUMN `referral_code` varchar(10);
@@ -1,2 +0,0 @@
DROP INDEX `workspace_referral_code` ON `workspace`;--> statement-breakpoint
CREATE UNIQUE INDEX `referral_code` ON `workspace` (`referral_code`);
File diff suppressed because it is too large Load Diff
-20
View File
@@ -155,26 +155,6 @@ export namespace Billing {
return amountInMicroCents
}
export const subtractLiteUsage = async (workspaceID: string, amountInMicroCents: number) => {
await Database.transaction(async (tx) => {
const lite = await tx
.select({ id: LiteTable.id })
.from(LiteTable)
.where(and(eq(LiteTable.workspaceID, workspaceID), isNull(LiteTable.timeDeleted)))
.then((rows) => rows[0])
if (!lite) throw new Error("Subscribe to Go before applying referral rewards")
await tx
.update(LiteTable)
.set({
monthlyUsage: sql`GREATEST(0, COALESCE(${LiteTable.monthlyUsage}, 0) - ${amountInMicroCents})`,
weeklyUsage: sql`GREATEST(0, COALESCE(${LiteTable.weeklyUsage}, 0) - ${amountInMicroCents})`,
rollingUsage: sql`GREATEST(0, COALESCE(${LiteTable.rollingUsage}, 0) - ${amountInMicroCents})`,
})
.where(and(eq(LiteTable.workspaceID, workspaceID), isNull(LiteTable.timeDeleted)))
})
}
export const redeemCoupon = async (email: string, type: (typeof CouponType)[number]) => {
// validate coupon type
await (async () => {
-1
View File
@@ -12,7 +12,6 @@ export namespace Identifier {
model: "mod",
payment: "pay",
provider: "prv",
referral: "ref",
subscription: "sub",
usage: "usg",
user: "usr",
-398
View File
@@ -1,398 +0,0 @@
import { z } from "zod"
import { and, asc, eq, isNull, sql, Database } from "./drizzle"
import { Actor } from "./actor"
import { Identifier } from "./identifier"
import { LiteTable } from "./schema/billing.sql"
import { ReferralRewardTable, ReferralTable } from "./schema/referral.sql"
import { AuthTable } from "./schema/auth.sql"
import { UserTable } from "./schema/user.sql"
import { WorkspaceTable } from "./schema/workspace.sql"
import { centsToMicroCents, microCentsToCents } from "./util/price"
import { fn } from "./util/fn"
import { Billing } from "./billing"
import { LiteData } from "./lite"
import { Subscription } from "./subscription"
import { ulid } from "ulid"
export namespace Referral {
export const REWARD_AMOUNT = centsToMicroCents(500)
export const CODE_LENGTH = 10
export function normalizeCode(code?: string | null) {
return code
?.toUpperCase()
.replace(/[^A-Z0-9]/g, "")
.slice(0, CODE_LENGTH)
}
function generateCode() {
return ulid().slice(-CODE_LENGTH)
}
async function ensureCode(workspaceID = Actor.workspace()) {
return Database.transaction(async (tx) => {
const existing = await tx
.select({ code: WorkspaceTable.referralCode })
.from(WorkspaceTable)
.where(and(eq(WorkspaceTable.id, workspaceID), isNull(WorkspaceTable.timeDeleted)))
.then((rows) => rows[0])
if (!existing) throw new Error("Workspace not found")
if (existing.code) return { code: existing.code }
for (const _ of Array.from({ length: 5 })) {
await tx
.update(WorkspaceTable)
.set({ referralCode: generateCode() })
.where(
and(
eq(WorkspaceTable.id, workspaceID),
isNull(WorkspaceTable.referralCode),
isNull(WorkspaceTable.timeDeleted),
),
)
const created = await tx
.select({ code: WorkspaceTable.referralCode })
.from(WorkspaceTable)
.where(and(eq(WorkspaceTable.id, workspaceID), isNull(WorkspaceTable.timeDeleted)))
.then((rows) => rows[0])
if (created?.code) return { code: created.code }
}
throw new Error("Failed to generate referral code")
})
}
export const summary = fn(z.void(), async () => {
const workspaceID = Actor.workspace()
const accountID = Actor.account()
const code = await ensureCode(workspaceID)
const rows = await Database.use(async (tx) => {
const [rewards, invites, inviteeReferral, inviteeRewards] = await Promise.all([
tx
.select({
referralID: ReferralRewardTable.referralID,
workspaceID: ReferralRewardTable.workspaceID,
referralWorkspaceID: ReferralTable.workspaceID,
inviteeEmail: AuthTable.subject,
amount: ReferralRewardTable.amount,
timeCreated: ReferralRewardTable.timeCreated,
timeApplied: ReferralRewardTable.timeApplied,
})
.from(ReferralRewardTable)
.innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
.innerJoin(
AuthTable,
and(eq(AuthTable.accountID, ReferralTable.inviteeAccountID), eq(AuthTable.provider, "email")),
)
.where(
and(
eq(ReferralRewardTable.workspaceID, workspaceID),
isNull(ReferralRewardTable.timeDeleted),
isNull(ReferralTable.timeDeleted),
),
),
tx
.select({ id: ReferralTable.id, inviteeEmail: AuthTable.subject, timeCreated: ReferralTable.timeCreated })
.from(ReferralTable)
.innerJoin(
AuthTable,
and(eq(AuthTable.accountID, ReferralTable.inviteeAccountID), eq(AuthTable.provider, "email")),
)
.where(and(eq(ReferralTable.workspaceID, workspaceID), isNull(ReferralTable.timeDeleted))),
tx
.select({ id: ReferralTable.id, inviterEmail: AuthTable.subject, timeCreated: ReferralTable.timeCreated })
.from(ReferralTable)
.leftJoin(
UserTable,
and(
eq(UserTable.workspaceID, ReferralTable.workspaceID),
eq(UserTable.role, "admin"),
isNull(UserTable.timeDeleted),
),
)
.leftJoin(AuthTable, and(eq(AuthTable.accountID, UserTable.accountID), eq(AuthTable.provider, "email")))
.where(and(eq(ReferralTable.inviteeAccountID, accountID), isNull(ReferralTable.timeDeleted)))
.orderBy(asc(UserTable.timeCreated))
.then((rows) => rows.find((row) => row.inviterEmail) ?? rows[0]),
tx
.select({ referralID: ReferralRewardTable.referralID })
.from(ReferralRewardTable)
.innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
.where(
and(
eq(ReferralTable.inviteeAccountID, accountID),
isNull(ReferralRewardTable.timeDeleted),
isNull(ReferralTable.timeDeleted),
),
),
])
return { inviteeReferral, inviteeRewards, invites, rewards }
})
const rewardReferralIDs = new Set(rows.rewards.map((reward) => reward.referralID))
const inviteeRewardReferralIDs = new Set(rows.inviteeRewards.map((reward) => reward.referralID))
const rewards = rows.rewards.map((reward) => {
const source = reward.workspaceID === reward.referralWorkspaceID ? ("inviter" as const) : ("invitee" as const)
return {
id: reward.referralID,
source,
status: reward.timeApplied ? ("applied" as const) : ("available" as const),
email: source === "invitee" ? (rows.inviteeReferral?.inviterEmail ?? null) : reward.inviteeEmail,
amount: microCentsToCents(reward.amount),
timeCreated: reward.timeCreated,
timeApplied: reward.timeApplied,
}
})
const pending = [
...rows.invites
.filter((referral) => !rewardReferralIDs.has(referral.id))
.map((referral) => ({
id: `${referral.id}:inviter`,
source: "inviter" as const,
status: "pending" as const,
email: referral.inviteeEmail,
amount: microCentsToCents(REWARD_AMOUNT),
timeCreated: referral.timeCreated,
timeApplied: null,
})),
...(rows.inviteeReferral && !inviteeRewardReferralIDs.has(rows.inviteeReferral.id)
? [
{
id: `${rows.inviteeReferral.id}:invitee`,
source: "invitee" as const,
status: "pending" as const,
email: rows.inviteeReferral.inviterEmail,
amount: microCentsToCents(REWARD_AMOUNT),
timeCreated: rows.inviteeReferral.timeCreated,
timeApplied: null,
},
]
: []),
]
const allRewards = [...pending, ...rewards].sort(
(a, b) => new Date(b.timeCreated).getTime() - new Date(a.timeCreated).getTime(),
)
return {
referralCode: code.code,
hasReferral: allRewards.length > 0,
rewardAmount: microCentsToCents(REWARD_AMOUNT),
rewards: allRewards,
}
})
export const applyReward = fn(z.object({ referralID: z.string() }), async (input) => {
const workspaceID = Actor.workspace()
return Database.transaction(async (tx) => {
const reward = await tx
.select({ amount: ReferralRewardTable.amount, timeApplied: ReferralRewardTable.timeApplied })
.from(ReferralRewardTable)
.where(
and(
eq(ReferralRewardTable.workspaceID, workspaceID),
eq(ReferralRewardTable.referralID, input.referralID),
isNull(ReferralRewardTable.timeDeleted),
),
)
.then((rows) => rows[0])
if (!reward) throw new Error("Referral reward not found")
if (reward.timeApplied) throw new Error("Referral reward already applied")
const update = await tx
.update(ReferralRewardTable)
.set({
timeApplied: sql`now()`,
})
.where(
and(
eq(ReferralRewardTable.workspaceID, workspaceID),
eq(ReferralRewardTable.referralID, input.referralID),
isNull(ReferralRewardTable.timeApplied),
isNull(ReferralRewardTable.timeDeleted),
),
)
if (update.rowsAffected === 0) throw new Error("Referral reward already applied")
await Billing.subtractLiteUsage(workspaceID, reward.amount)
return { amount: microCentsToCents(reward.amount) }
})
})
export const usagePreview = fn(z.object({ referralID: z.string() }), async (input) => {
const row = await Database.use((tx) =>
tx
.select({
rewardAmount: ReferralRewardTable.amount,
rollingUsage: LiteTable.rollingUsage,
weeklyUsage: LiteTable.weeklyUsage,
monthlyUsage: LiteTable.monthlyUsage,
timeRollingUpdated: LiteTable.timeRollingUpdated,
timeWeeklyUpdated: LiteTable.timeWeeklyUpdated,
timeMonthlyUpdated: LiteTable.timeMonthlyUpdated,
timeCreated: LiteTable.timeCreated,
})
.from(ReferralRewardTable)
.innerJoin(LiteTable, eq(LiteTable.workspaceID, ReferralRewardTable.workspaceID))
.where(
and(
eq(ReferralRewardTable.workspaceID, Actor.workspace()),
eq(ReferralRewardTable.referralID, input.referralID),
isNull(ReferralRewardTable.timeApplied),
isNull(ReferralRewardTable.timeDeleted),
isNull(LiteTable.timeDeleted),
),
)
.then((rows) => rows[0]),
)
if (!row) return null
const limits = LiteData.getLimits()
return {
rollingUsage: usagePreviewItem(
Subscription.analyzeRollingUsage({
limit: limits.rollingLimit,
window: limits.rollingWindow,
usage: row.rollingUsage ?? 0,
timeUpdated: row.timeRollingUpdated ?? new Date(),
}),
Subscription.analyzeRollingUsage({
limit: limits.rollingLimit,
window: limits.rollingWindow,
usage: Math.max(0, (row.rollingUsage ?? 0) - row.rewardAmount),
timeUpdated: row.timeRollingUpdated ?? new Date(),
}),
),
weeklyUsage: usagePreviewItem(
Subscription.analyzeWeeklyUsage({
limit: limits.weeklyLimit,
usage: row.weeklyUsage ?? 0,
timeUpdated: row.timeWeeklyUpdated ?? new Date(),
}),
Subscription.analyzeWeeklyUsage({
limit: limits.weeklyLimit,
usage: Math.max(0, (row.weeklyUsage ?? 0) - row.rewardAmount),
timeUpdated: row.timeWeeklyUpdated ?? new Date(),
}),
),
monthlyUsage: usagePreviewItem(
Subscription.analyzeMonthlyUsage({
limit: limits.monthlyLimit,
usage: row.monthlyUsage ?? 0,
timeUpdated: row.timeMonthlyUpdated ?? new Date(),
timeSubscribed: row.timeCreated,
}),
Subscription.analyzeMonthlyUsage({
limit: limits.monthlyLimit,
usage: Math.max(0, (row.monthlyUsage ?? 0) - row.rewardAmount),
timeUpdated: row.timeMonthlyUpdated ?? new Date(),
timeSubscribed: row.timeCreated,
}),
),
}
})
export async function createFromAccount(input: { accountID: string; referralCode?: string }) {
const referralCode = normalizeCode(input.referralCode)
if (!referralCode) return
return Database.transaction(async (tx) => {
const code = await tx
.select({ workspaceID: WorkspaceTable.id })
.from(WorkspaceTable)
.where(and(eq(WorkspaceTable.referralCode, referralCode), isNull(WorkspaceTable.timeDeleted)))
.then((rows) => rows[0])
if (!code) throw new Error("Referral code invalid")
const existingReferral = await tx
.select({ id: ReferralTable.id })
.from(ReferralTable)
.where(and(eq(ReferralTable.inviteeAccountID, input.accountID), isNull(ReferralTable.timeDeleted)))
.then((rows) => rows[0])
if (existingReferral) throw new Error("Referral already redeemed")
const selfReferral = await tx
.select({ id: UserTable.id })
.from(UserTable)
.where(
and(
eq(UserTable.workspaceID, code.workspaceID),
eq(UserTable.accountID, input.accountID),
isNull(UserTable.timeDeleted),
),
)
.then((rows) => rows[0])
if (selfReferral) throw new Error("Self-referral is not allowed")
const referralID = Identifier.create("referral")
await tx.insert(ReferralTable).ignore().values({
workspaceID: code.workspaceID,
id: referralID,
inviteeAccountID: input.accountID,
})
const referral = await tx
.select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID })
.from(ReferralTable)
.where(and(eq(ReferralTable.inviteeAccountID, input.accountID), isNull(ReferralTable.timeDeleted)))
.then((rows) => rows[0])
if (!referral) throw new Error("Referral not created")
if (referral.id !== referralID) throw new Error("Referral already redeemed")
})
}
export async function completeFromLiteSubscription(input: { workspaceID: string; userID: string }) {
return Database.transaction(async (tx) => {
const invitee = await tx
.select({ accountID: UserTable.accountID })
.from(UserTable)
.where(
and(
eq(UserTable.workspaceID, input.workspaceID),
eq(UserTable.id, input.userID),
isNull(UserTable.timeDeleted),
),
)
.then((rows) => rows[0])
if (!invitee?.accountID) throw new Error("Referral invitee account missing")
const referral = await tx
.select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID })
.from(ReferralTable)
.where(and(eq(ReferralTable.inviteeAccountID, invitee.accountID), isNull(ReferralTable.timeDeleted)))
.then((rows) => rows[0])
if (!referral) throw new Error("Referral not found")
const result = await tx
.insert(ReferralRewardTable)
.ignore()
.values([
{
workspaceID: referral.workspaceID,
referralID: referral.id,
amount: REWARD_AMOUNT,
},
{
workspaceID: input.workspaceID,
referralID: referral.id,
amount: REWARD_AMOUNT,
},
])
if (result.rowsAffected === 0) throw new Error("Referral already completed")
})
}
function usagePreviewItem(
before: { usagePercent: number; resetInSec: number },
after: { usagePercent: number; resetInSec: number },
) {
return {
beforePercent: before.usagePercent,
afterPercent: after.usagePercent,
resetInSec: after.resetInSec,
}
}
}
@@ -1,25 +0,0 @@
import { bigint, mysqlTable, primaryKey, uniqueIndex } from "drizzle-orm/mysql-core"
import { timestamps, ulid, utc, workspaceColumns } from "../drizzle/types"
import { workspaceIndexes } from "./workspace.sql"
export const ReferralTable = mysqlTable(
"referral",
{
...workspaceColumns,
...timestamps,
inviteeAccountID: ulid("invitee_account_id").notNull(),
},
(table) => [...workspaceIndexes(table), uniqueIndex("referral_invitee_account_id").on(table.inviteeAccountID)],
)
export const ReferralRewardTable = mysqlTable(
"referral_reward",
{
workspaceID: ulid("workspace_id").notNull(),
referralID: ulid("referral_id").notNull(),
...timestamps,
amount: bigint("amount", { mode: "number" }).notNull(),
timeApplied: utc("time_applied"),
},
(table) => [primaryKey({ columns: [table.workspaceID, table.referralID] })],
)
@@ -6,11 +6,10 @@ export const WorkspaceTable = mysqlTable(
{
id: ulid("id").notNull().primaryKey(),
slug: varchar("slug", { length: 255 }),
referralCode: varchar("referral_code", { length: 10 }),
name: varchar("name", { length: 255 }).notNull(),
...timestamps,
},
(table) => [uniqueIndex("slug").on(table.slug), uniqueIndex("referral_code").on(table.referralCode)],
(table) => [uniqueIndex("slug").on(table.slug)],
)
export function workspaceIndexes(table: any) {
+1 -4
View File
@@ -26,7 +26,6 @@ export const subjects = createSubjects({
account: z.object({
accountID: z.string(),
email: z.string(),
newAccount: z.boolean().optional(),
}),
user: z.object({
userID: z.string(),
@@ -143,7 +142,6 @@ export default {
}
// Get account
let newAccount = false
const accountID = await (async () => {
const matches = await Database.use(async (tx) =>
tx
@@ -168,7 +166,6 @@ export default {
if (!accountID) {
console.log("creating account for", email)
accountID = await Account.create({})
newAccount = true
}
await Database.use(async (tx) =>
@@ -218,7 +215,7 @@ export default {
await Workspace.create({ name: "Default" })
}
})
return ctx.subject("account", accountID, { accountID, email, newAccount })
return ctx.subject("account", accountID, { accountID, email })
},
}).fetch(request, env, ctx)
return result
+1 -3
View File
@@ -21,6 +21,7 @@ export const Flag = {
OPENCODE_DISABLE_PRUNE: truthy("OPENCODE_DISABLE_PRUNE"),
OPENCODE_DISABLE_TERMINAL_TITLE: truthy("OPENCODE_DISABLE_TERMINAL_TITLE"),
OPENCODE_SHOW_TTFD: truthy("OPENCODE_SHOW_TTFD"),
OPENCODE_PERMISSION: process.env["OPENCODE_PERMISSION"],
OPENCODE_DISABLE_AUTOCOMPACT: truthy("OPENCODE_DISABLE_AUTOCOMPACT"),
OPENCODE_DISABLE_MODELS_FETCH: truthy("OPENCODE_DISABLE_MODELS_FETCH"),
OPENCODE_DISABLE_MOUSE: truthy("OPENCODE_DISABLE_MOUSE"),
@@ -58,9 +59,6 @@ export const Flag = {
get OPENCODE_PURE() {
return truthy("OPENCODE_PURE")
},
get OPENCODE_PERMISSION() {
return process.env["OPENCODE_PERMISSION"]
},
get OPENCODE_PLUGIN_META_FILE() {
return process.env["OPENCODE_PLUGIN_META_FILE"]
},
@@ -1,84 +0,0 @@
import { BrowserWindow } from "electron"
import type { DesktopMenuAction } from "@opencode-ai/app/desktop-menu"
import { createMainWindow, updateTitlebar } from "./windows"
export type DesktopMenuActionHandlers = Partial<{
checkForUpdates: () => void
relaunch: () => void
}>
export function runDesktopMenuAction(
win: BrowserWindow | null,
action: DesktopMenuAction,
handlers: DesktopMenuActionHandlers = {},
) {
switch (action) {
case "app.checkForUpdates":
handlers.checkForUpdates?.()
return
case "app.relaunch":
handlers.relaunch?.()
return
case "window.new":
createMainWindow()
return
case "window.close":
win?.close()
return
case "window.minimize":
win?.minimize()
return
case "window.toggleMaximize":
if (win?.isMaximized()) {
win.unmaximize()
return
}
win?.maximize()
return
case "view.reload":
win?.reload()
return
case "view.toggleDevTools":
win?.webContents.toggleDevTools()
return
case "view.resetZoom":
setZoom(win, 1)
return
case "view.zoomIn":
setZoom(win, (win?.webContents.getZoomFactor() ?? 1) + 0.2)
return
case "view.zoomOut":
setZoom(win, (win?.webContents.getZoomFactor() ?? 1) - 0.2)
return
case "view.toggleFullscreen":
win?.setFullScreen(!win.isFullScreen())
return
case "edit.undo":
win?.webContents.undo()
return
case "edit.redo":
win?.webContents.redo()
return
case "edit.cut":
win?.webContents.cut()
return
case "edit.copy":
win?.webContents.copy()
return
case "edit.paste":
win?.webContents.paste()
return
case "edit.delete":
win?.webContents.delete()
return
case "edit.selectAll":
win?.webContents.selectAll()
return
}
}
function setZoom(win: BrowserWindow | null, value: number) {
if (!win) return
win.webContents.setZoomFactor(Math.min(Math.max(value, 0.2), 10))
updateTitlebar(win)
}
+2 -4
View File
@@ -345,13 +345,11 @@ const main = Effect.gen(function* () {
mainWindow = createMainWindow()
if (mainWindow) {
createMenu({
trigger: (id) => {
const win = BrowserWindow.getFocusedWindow() ?? mainWindow
if (win) sendMenuCommand(win, id)
},
trigger: (id) => mainWindow && sendMenuCommand(mainWindow, id),
checkForUpdates: () => {
void checkForUpdates(true, killSidecar)
},
reload: () => mainWindow?.reload(),
relaunch: () => {
void killSidecar().finally(() => {
app.relaunch()
-5
View File
@@ -1,7 +1,6 @@
import { execFile } from "node:child_process"
import { BrowserWindow, Notification, app, clipboard, dialog, ipcMain, shell } from "electron"
import type { IpcMainEvent, IpcMainInvokeEvent } from "electron"
import type { DesktopMenuAction } from "@opencode-ai/app/desktop-menu"
import type {
InitStep,
@@ -11,7 +10,6 @@ import type {
WindowConfig,
WslConfig,
} from "../preload/types"
import { runDesktopMenuAction } from "./desktop-menu-actions"
import { getStore } from "./store"
import { setTitlebar, updateTitlebar } from "./windows"
@@ -200,9 +198,6 @@ export function registerIpcHandlers(deps: Deps) {
if (!win) return
setTitlebar(win, theme)
})
ipcMain.handle("run-desktop-menu-action", (event: IpcMainInvokeEvent, action: DesktopMenuAction) => {
runDesktopMenuAction(BrowserWindow.fromWebContents(event.sender), action)
})
}
export function sendSqliteMigrationProgress(win: BrowserWindow, progress: SqliteMigrationProgress) {
+126 -52
View File
@@ -1,67 +1,141 @@
import { BrowserWindow, Menu, shell } from "electron"
import type { MenuItemConstructorOptions } from "electron"
import {
DESKTOP_MENU,
desktopMenuVisible,
type DesktopMenuEntry,
type DesktopMenuRole,
} from "@opencode-ai/app/desktop-menu"
import { Menu, shell } from "electron"
import { UPDATER_ENABLED } from "./constants"
import { runDesktopMenuAction } from "./desktop-menu-actions"
import { createMainWindow } from "./windows"
type Deps = {
trigger: (id: string) => void
checkForUpdates: () => void
reload: () => void
relaunch: () => void
}
export function createMenu(deps: Deps) {
if (process.platform !== "darwin") return
const template = DESKTOP_MENU.filter((menu) => desktopMenuVisible(menu, "macos")).map((menu) => {
if (menu.role) return { role: nativeRole(menu.role) }
return {
label: menu.label,
submenu: menu.items
?.filter((entry) => desktopMenuVisible(entry, "macos"))
.map((entry) => nativeItem(entry, deps)),
}
})
const template: Electron.MenuItemConstructorOptions[] = [
{
label: "OpenCode",
submenu: [
{ role: "about" },
{
label: "Check for Updates...",
enabled: UPDATER_ENABLED,
click: () => deps.checkForUpdates(),
},
{
label: "Settings",
accelerator: "Cmd+,",
click: () => deps.trigger("settings.open"),
},
{
label: "Reload Webview",
click: () => deps.reload(),
},
{
label: "Restart",
click: () => deps.relaunch(),
},
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
},
{
label: "File",
submenu: [
{ label: "New Session", accelerator: "Shift+Cmd+S", click: () => deps.trigger("session.new") },
{ label: "Open Project...", accelerator: "Cmd+O", click: () => deps.trigger("project.open") },
{
label: "New Window",
accelerator: "Cmd+Shift+N",
click: () => createMainWindow(),
},
{ type: "separator" },
{ role: "close" },
],
},
{
label: "Edit",
submenu: [
{ role: "undo" },
{ role: "redo" },
{ type: "separator" },
{ role: "cut" },
{ role: "copy" },
{ role: "paste" },
{ role: "selectAll" },
],
},
{
label: "View",
submenu: [
{ label: "Toggle Sidebar", accelerator: "Cmd+B", click: () => deps.trigger("sidebar.toggle") },
{ label: "Toggle Terminal", accelerator: "Ctrl+`", click: () => deps.trigger("terminal.toggle") },
{ label: "Toggle File Tree", click: () => deps.trigger("fileTree.toggle") },
{ type: "separator" },
{ role: "reload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn" },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
{
label: "Go",
submenu: [
{ label: "Back", accelerator: "Cmd+[", click: () => deps.trigger("common.goBack") },
{ label: "Forward", accelerator: "Cmd+]", click: () => deps.trigger("common.goForward") },
{ type: "separator" },
{
label: "Previous Session",
accelerator: "Option+Up",
click: () => deps.trigger("session.previous"),
},
{
label: "Next Session",
accelerator: "Option+Down",
click: () => deps.trigger("session.next"),
},
{ type: "separator" },
{
label: "Previous Project",
accelerator: "Cmd+Option+Up",
click: () => deps.trigger("project.previous"),
},
{
label: "Next Project",
accelerator: "Cmd+Option+Down",
click: () => deps.trigger("project.next"),
},
],
},
{ role: "windowMenu" },
{
label: "Help",
submenu: [
{ label: "OpenCode Documentation", click: () => shell.openExternal("https://opencode.ai/docs") },
{ label: "Support Forum", click: () => shell.openExternal("https://discord.com/invite/opencode") },
{ type: "separator" },
{ type: "separator" },
{
label: "Share Feedback",
click: () =>
shell.openExternal("https://github.com/anomalyco/opencode/issues/new?template=feature_request.yml"),
},
{
label: "Report a Bug",
click: () => shell.openExternal("https://github.com/anomalyco/opencode/issues/new?template=bug_report.yml"),
},
],
},
]
Menu.setApplicationMenu(Menu.buildFromTemplate(template))
}
function nativeItem(entry: DesktopMenuEntry, deps: Deps): MenuItemConstructorOptions {
if (entry.type === "separator") return { type: "separator" }
if (entry.role) return { role: nativeRole(entry.role) }
const item: MenuItemConstructorOptions = {
label: entry.label,
accelerator: entry.accelerator?.macos,
enabled: entry.enabled === "updater" ? UPDATER_ENABLED : undefined,
}
if (entry.command) {
const command = entry.command
item.click = () => deps.trigger(command)
}
if (entry.action) {
const action = entry.action
item.click = () =>
runDesktopMenuAction(BrowserWindow.getFocusedWindow(), action, {
checkForUpdates: deps.checkForUpdates,
relaunch: deps.relaunch,
})
}
if (entry.href) {
const href = entry.href
item.click = () => shell.openExternal(href)
}
return item
}
function nativeRole(role: DesktopMenuRole) {
return role as NonNullable<MenuItemConstructorOptions["role"]>
}
-1
View File
@@ -61,7 +61,6 @@ const api: ElectronAPI = {
getZoomFactor: () => ipcRenderer.invoke("get-zoom-factor"),
setZoomFactor: (factor) => ipcRenderer.invoke("set-zoom-factor", factor),
setTitlebar: (theme) => ipcRenderer.invoke("set-titlebar", theme),
runDesktopMenuAction: (action) => ipcRenderer.invoke("run-desktop-menu-action", action),
loadingWindowComplete: () => ipcRenderer.send("loading-window-complete"),
runUpdater: (alertOnFail) => ipcRenderer.invoke("run-updater", alertOnFail),
checkUpdate: () => ipcRenderer.invoke("check-update"),
+1 -3
View File
@@ -1,5 +1,3 @@
import type { DesktopMenuAction } from "@opencode-ai/app/desktop-menu"
export type InitStep = { phase: "server_waiting" } | { phase: "sqlite_waiting" } | { phase: "done" }
export type ServerReadyData = {
@@ -16,6 +14,7 @@ export type LinuxDisplayBackend = "wayland" | "auto"
export type TitlebarTheme = {
mode: "light" | "dark"
}
export type WindowConfig = {
updaterEnabled: boolean
}
@@ -72,7 +71,6 @@ export type ElectronAPI = {
getZoomFactor: () => Promise<number>
setZoomFactor: (factor: number) => Promise<void>
setTitlebar: (theme: TitlebarTheme) => Promise<void>
runDesktopMenuAction: (action: DesktopMenuAction) => Promise<void>
loadingWindowComplete: () => void
runUpdater: (alertOnFail: boolean) => Promise<void>
checkUpdate: () => Promise<{ updateAvailable: boolean; version?: string }>
+1 -19
View File
@@ -21,7 +21,7 @@ import { createEffect, createResource, onCleanup, onMount, Show } from "solid-js
import { render } from "solid-js/web"
import pkg from "../../package.json"
import { initI18n, t } from "./i18n"
import { resetZoom, webviewZoom, zoomIn, zoomOut } from "./webview-zoom"
import { webviewZoom } from "./webview-zoom"
import "./styles.css"
import { useTheme } from "@opencode-ai/ui/theme"
@@ -100,22 +100,6 @@ const createPlatform = (): Platform => {
return window.api.wslPath(result, "linux").catch(() => result) as any
}
const runDesktopMenuAction: Platform["runDesktopMenuAction"] = (action) => {
switch (action) {
case "view.resetZoom":
resetZoom()
return
case "view.zoomIn":
zoomIn()
return
case "view.zoomOut":
zoomOut()
return
}
return window.api.runDesktopMenuAction(action)
}
const storage = (() => {
const cache = new Map<string, AsyncStorage>()
@@ -270,8 +254,6 @@ const createPlatform = (): Platform => {
webviewZoom,
runDesktopMenuAction,
checkAppExists: async (appName: string) => {
return window.api.checkAppExists(appName)
},
@@ -33,27 +33,23 @@ const applyZoom = (next: number) => {
})
}
const resetZoom = () => applyZoom(1)
const zoomIn = () => applyZoom(clamp(requestedZoom + 0.2))
const zoomOut = () => applyZoom(clamp(requestedZoom - 0.2))
window.addEventListener("keydown", (event) => {
if (!(OS_NAME === "macos" ? event.metaKey : event.ctrlKey)) return
if (event.key === "-") {
event.preventDefault()
zoomOut()
applyZoom(clamp(requestedZoom - 0.2))
return
}
if (event.key === "=" || event.key === "+") {
event.preventDefault()
zoomIn()
applyZoom(clamp(requestedZoom + 0.2))
return
}
if (event.key === "0") {
event.preventDefault()
resetZoom()
applyZoom(1)
}
})
export { webviewZoom, resetZoom, zoomIn, zoomOut }
export { webviewZoom }
@@ -0,0 +1,95 @@
#!/usr/bin/env bun
// Build a pre-compiled `opencode` binary for subprocess tests, then expose
// it at `dist/test-cli/bin/opencode` for the harness to consume.
//
// Why: each `bun run --conditions=browser src/index.ts <cmd>` spawn pays
// ~15s of JIT + plugin init + DB migration in isolation mode. The
// pre-compiled binary cuts that to ~5s — a 3x improvement on subprocess
// tests that touch the DB (mcp, providers list, etc.).
//
// Usage:
// bun script/prebuild-test-cli.ts
// export OPENCODE_TEST_CLI_PATH="$PWD/dist/test-cli/bin/opencode"
// bun test test/cli/
//
// The harness (see test/lib/cli-process.ts) reads OPENCODE_TEST_CLI_PATH; if
// set, it spawns the binary directly instead of `bun run src/index.ts`. If
// unset, it falls back to dev mode — so this script is strictly opt-in.
//
// Build cost amortizes after ~1 spawn that touches the DB. Recommended for
// CI, manual `bun test test/cli/` runs, and any local iteration where the
// CLI surface itself isn't under change. Skip for normal src/* editing — the
// dev path picks up source changes without rebuild.
import { $ } from "bun"
import fs from "node:fs/promises"
import path from "node:path"
const dir = path.resolve(import.meta.dirname, "..")
process.chdir(dir)
const platform = process.platform === "win32" ? "win32" : process.platform === "darwin" ? "darwin" : "linux"
const arch = process.arch === "x64" ? "x64" : process.arch === "arm64" ? "arm64" : "x64"
const targetDir = path.join(dir, "dist", `opencode-${platform}-${arch}`)
const binaryName = process.platform === "win32" ? "opencode.exe" : "opencode"
const builtBinary = path.join(targetDir, "bin", binaryName)
const stableBinary = path.join(dir, "dist", "test-cli", "bin", binaryName)
const force = process.argv.includes("--force")
// Walk src/ and return the newest mtime seen. Faster than `git status` for
// the freshness check and works for uncommitted edits. Returns 0 on error
// so a missing src/ tree forces a rebuild via the comparison below.
async function newestMtimeMs(root: string): Promise<number> {
let max = 0
async function walk(p: string) {
let entries: { name: string; isDirectory: () => boolean; isFile: () => boolean }[]
try {
entries = await fs.readdir(p, { withFileTypes: true })
} catch {
return
}
for (const entry of entries) {
const full = path.join(p, entry.name)
if (entry.isDirectory()) {
if (entry.name === "node_modules" || entry.name === "dist") continue
await walk(full)
} else if (entry.isFile()) {
const stat = await fs.stat(full).catch(() => null)
if (stat && stat.mtimeMs > max) max = stat.mtimeMs
}
}
}
await walk(root)
return max
}
async function fresh(): Promise<boolean> {
const binStat = await fs.stat(builtBinary).catch(() => null)
if (!binStat) return false
const srcMs = await newestMtimeMs(path.join(dir, "src"))
return binStat.mtimeMs > srcMs
}
if (!force && (await fresh())) {
console.log(`Test CLI binary is up to date: ${builtBinary}`)
} else {
console.log(`Building test CLI binary for ${platform}-${arch}...`)
const start = Date.now()
await $`bun script/build.ts --single --skip-embed-web-ui --skip-install`
console.log(`Build complete in ${Date.now() - start}ms: ${builtBinary}`)
}
// Verify the binary exists and is executable before symlinking — catches
// a silently-failed build that left a stale or partial output behind.
await fs.access(builtBinary, fs.constants.X_OK).catch(() => {
throw new Error(`Built binary missing or not executable: ${builtBinary}`)
})
await fs.mkdir(path.dirname(stableBinary), { recursive: true })
await fs.rm(stableBinary, { force: true })
await fs.symlink(builtBinary, stableBinary)
console.log(`Symlinked stable path: ${stableBinary}`)
console.log(``)
console.log(`To use in tests:`)
console.log(` export OPENCODE_TEST_CLI_PATH="${stableBinary}"`)
console.log(` bun test test/cli/`)
+4 -11
View File
@@ -7,10 +7,8 @@ import { SessionTable, MessageTable, PartTable } from "../../session/session.sql
import { InstanceRef } from "@/effect/instance-ref"
import { ShareNext } from "@/share/share-next"
import { EOL } from "os"
import path from "path"
import { AppFileSystem } from "@opencode-ai/core/filesystem"
import { Effect, Schema } from "effect"
import type { InstanceContext } from "@/project/instance-context"
const decodeMessageInfo = Schema.decodeUnknownSync(MessageV2.Info)
const decodePart = Schema.decodeUnknownSync(MessageV2.Part)
@@ -91,11 +89,11 @@ export const ImportCommand = effectCmd({
handler: Effect.fn("Cli.import")(function* (args) {
const ctx = yield* InstanceRef
if (!ctx) return yield* Effect.die("InstanceRef not provided")
return yield* runImport(args.file, ctx)
return yield* runImport(args.file, ctx.project.id)
}),
})
const runImport = Effect.fn("Cli.import.body")(function* (file: string, ctx: InstanceContext) {
const runImport = Effect.fn("Cli.import.body")(function* (file: string, projectID: string) {
const share = yield* ShareNext.Service
const fs = yield* AppFileSystem.Service
@@ -170,19 +168,14 @@ const runImport = Effect.fn("Cli.import.body")(function* (file: string, ctx: Ins
const info = Schema.decodeUnknownSync(Session.Info)({
...exportData.info,
projectID: ctx.project.id,
directory: ctx.directory,
path: path.relative(path.resolve(ctx.worktree), ctx.directory).replaceAll("\\", "/"),
projectID,
}) as Session.Info
const row = Session.toRow(info)
Database.use((db) =>
db
.insert(SessionTable)
.values(row)
.onConflictDoUpdate({
target: SessionTable.id,
set: { project_id: row.project_id, directory: row.directory, path: row.path },
})
.onConflictDoUpdate({ target: SessionTable.id, set: { project_id: row.project_id } })
.run(),
)
@@ -88,7 +88,6 @@ type PromptInput = {
export type PromptState = {
placeholder: Accessor<StyledText | string>
bindings: Accessor<KeyBinding[]>
shell: Accessor<boolean>
visible: Accessor<boolean>
options: Accessor<PromptOption[]>
selected: Accessor<number>
@@ -111,14 +110,9 @@ function clonePrompt(prompt: RunPrompt): RunPrompt {
return {
text: prompt.text,
parts: structuredClone(prompt.parts),
...(prompt.mode ? { mode: prompt.mode } : {}),
}
}
function emptyPrompt(shell: boolean): RunPrompt {
return shell ? { text: "", parts: [], mode: "shell" } : { text: "", parts: [] }
}
function removeLineRange(input: string) {
const hash = input.lastIndexOf("#")
return hash === -1 ? input : input.slice(0, hash)
@@ -280,12 +274,7 @@ export function RunPromptBody(props: {
export function createPromptState(input: PromptInput): PromptState {
const keys = createMemo(() => promptKeys(input.keybinds))
const bindings = createMemo(() => keys().bindings)
const [shell, setShell] = createSignal(false)
const placeholder = createMemo(() => {
if (shell()) {
return new StyledText([bg(input.theme().surface)(fg(input.theme().muted)('Run a command... "git status"'))])
}
if (!input.state().first) {
return ""
}
@@ -312,11 +301,6 @@ export function createPromptState(input: PromptInput): PromptState {
const [query, setQuery] = createSignal("")
const visible = createMemo(() => mode() !== false)
const setShellMode = (value: boolean) => {
setShell(value)
draft = value ? { ...draft, mode: "shell" } : { text: draft.text, parts: structuredClone(draft.parts) }
}
const width = createMemo(() => Math.max(20, input.width() - 8))
const agents = createMemo<Auto[]>(() => {
return input
@@ -593,7 +577,6 @@ export function createPromptState(input: PromptInput): PromptState {
const restore = (value: RunPrompt, cursor = Bun.stringWidth(value.text)) => {
draft = clonePrompt(value)
setShell(value.mode === "shell")
if (!area || area.isDestroyed) {
return
}
@@ -613,7 +596,7 @@ export function createPromptState(input: PromptInput): PromptState {
clearParts()
hide()
draft = emptyPrompt(shell())
draft = { text: "", parts: [] }
if (!area || area.isDestroyed) {
return
}
@@ -623,7 +606,7 @@ export function createPromptState(input: PromptInput): PromptState {
}
const replaceDraft = (text: string) => {
draft = shell() ? { text, parts: [], mode: "shell" } : { text, parts: [] }
draft = { text, parts: [] }
if (!area || area.isDestroyed) {
return
}
@@ -631,7 +614,7 @@ export function createPromptState(input: PromptInput): PromptState {
hide()
area.setText(text)
clearParts()
draft = shell() ? { text: area.plainText, parts: [], mode: "shell" } : { text: area.plainText, parts: [] }
draft = { text: area.plainText, parts: [] }
area.cursorOffset = Math.min(Bun.stringWidth(text), Bun.stringWidth(area.plainText))
scheduleRows()
area.focus()
@@ -722,16 +705,10 @@ export function createPromptState(input: PromptInput): PromptState {
}
syncParts()
draft = shell()
? {
text: area.plainText,
parts: structuredClone(parts),
mode: "shell",
}
: {
text: area.plainText,
parts: structuredClone(parts),
}
draft = {
text: area.plainText,
parts: structuredClone(parts),
}
}
const push = (value: RunPrompt) => {
@@ -966,35 +943,6 @@ export function createPromptState(input: PromptInput): PromptState {
}
}
if (
key.name === "!" &&
!shell() &&
!event.ctrl &&
!event.meta &&
!event.super &&
area &&
!area.isDestroyed &&
area.cursorOffset === 0
) {
event.preventDefault()
setShellMode(true)
return
}
if (shell() && !visible()) {
if (key.name === "escape") {
event.preventDefault()
setShellMode(false)
return
}
if (key.name === "backspace" && area && !area.isDestroyed && area.cursorOffset === 0) {
event.preventDefault()
setShellMode(false)
return
}
}
if (promptHit(keys().clear, key)) {
const handled = requestExit()
if (handled) {
@@ -1080,29 +1028,23 @@ export function createPromptState(input: PromptInput): PromptState {
return
}
if (next.mode !== "shell" && isExitCommand(next.text)) {
if (isExitCommand(next.text)) {
input.onExit()
return
}
const parsed =
next.mode === "shell" || isNewCommand(next.text) ? undefined : parseSlashCommand(next.text, input.commands())
const parsed = isNewCommand(next.text) ? undefined : parseSlashCommand(next.text, input.commands())
if (parsed?.type === "pending") {
input.onStatus("loading commands")
return
}
const submit = parsed?.type === "command" ? { ...next, command: parsed.command } : next
const shellMode = next.mode === "shell"
resetDraft()
queueMicrotask(async () => {
if (await input.onSubmit(submit)) {
push(next)
if (shellMode) {
setShellMode(false)
draft = emptyPrompt(false)
}
return
}
@@ -1179,7 +1121,6 @@ export function createPromptState(input: PromptInput): PromptState {
return {
placeholder,
bindings,
shell,
visible,
options,
selected: menu.selected,
@@ -265,7 +265,6 @@ export function RunFooterView(props: RunFooterViewProps) {
onRows: props.onRows,
onStatus: props.onStatus,
})
const shell = createMemo(() => prompt() && composer.shell())
const menu = createMemo(() => prompt() && composer.visible())
createEffect(() => {
@@ -488,20 +487,18 @@ export function RunFooterView(props: RunFooterViewProps) {
paddingTop={1}
>
<text id="run-direct-footer-agent" fg={theme().highlight} wrapMode="none" truncate flexShrink={0}>
{shell() ? "Shell" : props.agent}
{props.agent}
</text>
<text
id="run-direct-footer-model"
fg={theme().text}
wrapMode="none"
truncate
flexGrow={1}
flexShrink={1}
>
{props.state().model}
</text>
<Show when={!shell()}>
<text
id="run-direct-footer-model"
fg={theme().text}
wrapMode="none"
truncate
flexGrow={1}
flexShrink={1}
>
{props.state().model}
</text>
</Show>
</box>
</Show>
</box>
@@ -632,30 +629,19 @@ export function RunFooterView(props: RunFooterViewProps) {
flexShrink={0}
justifyContent="flex-end"
>
<Show
when={shell()}
fallback={
<>
<Show when={queue() > 0}>
<text id="run-direct-footer-queue" fg={theme().muted} wrapMode="none" truncate>
{queue()} queued
</text>
</Show>
<Show when={usage().length > 0}>
<text id="run-direct-footer-usage" fg={theme().muted} wrapMode="none" truncate>
{usage()}
</text>
</Show>
<Show when={command().length > 0 && hints().command}>
<text id="run-direct-footer-hint-command" fg={theme().text} wrapMode="none" truncate>
{command()} <span style={{ fg: theme().muted }}>commands</span>
</text>
</Show>
</>
}
>
<text id="run-direct-footer-hint-shell" fg={theme().text} wrapMode="none" truncate>
esc <span style={{ fg: theme().muted }}>exit shell mode</span>
<Show when={queue() > 0}>
<text id="run-direct-footer-queue" fg={theme().muted} wrapMode="none" truncate>
{queue()} queued
</text>
</Show>
<Show when={usage().length > 0}>
<text id="run-direct-footer-usage" fg={theme().muted} wrapMode="none" truncate>
{usage()}
</text>
</Show>
<Show when={command().length > 0 && hints().command}>
<text id="run-direct-footer-hint-command" fg={theme().text} wrapMode="none" truncate>
{command()} <span style={{ fg: theme().muted }}>commands</span>
</text>
</Show>
</box>
@@ -65,12 +65,11 @@ export function promptCopy(prompt: RunPrompt): RunPrompt {
return {
text: prompt.text,
parts: structuredClone(prompt.parts),
...(prompt.mode ? { mode: prompt.mode } : {}),
}
}
export function promptSame(a: RunPrompt, b: RunPrompt): boolean {
return a.mode === b.mode && a.text === b.text && JSON.stringify(a.parts) === JSON.stringify(b.parts)
return a.text === b.text && JSON.stringify(a.parts) === JSON.stringify(b.parts)
}
function promptKey(binding: ReturnType<typeof parseBindings>[number]): PromptInfo | undefined {
@@ -102,7 +102,7 @@ export async function runPromptQueue(input: QueueInput): Promise<void> {
continue
}
if (prompt.mode !== "shell" && isNewCommand(prompt.text)) {
if (isNewCommand(prompt.text)) {
emit(
{
type: "queue",
@@ -167,11 +167,9 @@ export async function runPromptQueue(input: QueueInput): Promise<void> {
break
}
if (prompt.mode !== "shell") {
const commit = { kind: "user", text: prompt.text, phase: "start", source: "system" } as const
input.trace?.write("ui.commit", commit)
input.footer.append(commit)
}
const commit = { kind: "user", text: prompt.text, phase: "start", source: "system" } as const
input.trace?.write("ui.commit", commit)
input.footer.append(commit)
input.onSend?.(prompt)
if (state.closed) {
@@ -236,7 +234,7 @@ export async function runPromptQueue(input: QueueInput): Promise<void> {
return
}
if (prompt.mode !== "shell" && isExitCommand(prompt.text)) {
if (isExitCommand(prompt.text)) {
input.footer.close()
return
}
@@ -251,7 +249,7 @@ export async function runPromptQueue(input: QueueInput): Promise<void> {
queue: state.queue.length,
},
)
if (prompt.mode !== "shell" && isNewCommand(prompt.text)) {
if (isNewCommand(prompt.text)) {
drain()
return
}
@@ -61,20 +61,13 @@ type SessionCommit = StreamCommit
// - text: part ID → full accumulated text so far
// - sent: part ID → byte offset of last flushed text (for incremental output)
// - end: part IDs whose time.end has arrived (part is finished)
// - shell: shell call ID → chosen transcript source for direct shell calls
// - echo: message ID → bash outputs to strip from the next assistant chunk
type ShellCall = {
source: "shell" | "tool"
command?: string
}
export type SessionData = {
includeUserText: boolean
announced: boolean
ids: Set<string>
tools: Set<string>
call: Map<string, Dict>
shell: Map<string, ShellCall>
permissions: PermissionRequest[]
questions: QuestionRequest[]
role: Map<string, MessageRole>
@@ -111,7 +104,6 @@ export function createSessionData(
ids: new Set(),
tools: new Set(),
call: new Map(),
shell: new Map(),
permissions: [],
questions: [],
role: new Map(),
@@ -629,87 +621,6 @@ function toolCommit(
}
}
function shellPartID(callID: string): string {
return `shell:${callID}`
}
function claimShell(data: SessionData, callID: string, source: ShellCall["source"], command?: string): ShellCall {
const current = data.shell.get(callID)
if (current) {
if (command && !current.command) {
current.command = command
}
return current
}
const next = {
source,
...(command ? { command } : {}),
} satisfies ShellCall
data.shell.set(callID, next)
return next
}
function bashCommand(part: ToolPart): string | undefined {
if (part.tool !== "bash") {
return undefined
}
const input = part.state.input
if (!input || typeof input !== "object" || Array.isArray(input)) {
return undefined
}
const command = Reflect.get(input, "command")
return typeof command === "string" ? command : undefined
}
function shellCommit(
input: {
callID: string
command: string
},
next: Pick<SessionCommit, "text" | "phase" | "toolState">,
): SessionCommit {
return {
kind: "tool",
source: "tool",
partID: shellPartID(input.callID),
tool: "bash",
shell: input,
...next,
}
}
function startShell(callID: string, command: string): SessionCommit {
return shellCommit(
{
callID,
command,
},
{
text: "running shell",
phase: "start",
toolState: "running",
},
)
}
function doneShell(callID: string, command: string, output: string): SessionCommit {
return shellCommit(
{
callID,
command,
},
{
text: output,
phase: "progress",
toolState: "completed",
},
)
}
function startTool(part: ToolPart): SessionCommit {
return toolCommit(part, {
text: toolStatus(part),
@@ -770,53 +681,6 @@ export function reduceSessionData(input: SessionDataInput): SessionDataOutput {
const data = input.data
const event = input.event
if (event.type === "session.next.shell.started") {
if (event.properties.sessionID !== input.sessionID) {
return out(data, commits)
}
const shell = claimShell(data, event.properties.callID, "shell", event.properties.command)
if (shell.source !== "shell") {
return out(data, commits)
}
const partID = shellPartID(event.properties.callID)
if (data.ids.has(partID) || data.tools.has(partID)) {
return out(data, commits, patch({ status: "running shell" }))
}
data.tools.add(partID)
commits.push(startShell(event.properties.callID, shell.command ?? event.properties.command))
return out(data, commits, patch({ status: "running shell" }))
}
if (event.type === "session.next.shell.ended") {
if (event.properties.sessionID !== input.sessionID) {
return out(data, commits)
}
const shell = claimShell(data, event.properties.callID, "shell")
if (shell.source !== "shell") {
return out(data, commits)
}
const partID = shellPartID(event.properties.callID)
const seen = data.tools.has(partID)
const command = shell.command ?? ""
data.tools.delete(partID)
if (data.ids.has(partID)) {
return out(data, commits)
}
if (!seen && command) {
commits.push(startShell(event.properties.callID, command))
}
data.ids.add(partID)
commits.push(doneShell(event.properties.callID, command, event.properties.output))
return out(data, commits)
}
if (event.type === "message.updated") {
if (event.properties.sessionID !== input.sessionID) {
return out(data, commits)
@@ -918,11 +782,6 @@ export function reduceSessionData(input: SessionDataInput): SessionDataOutput {
if (part.type === "tool") {
const view = syncPermission(data, part) ?? syncQuestion(data, part)
if (part.tool === "bash" && part.callID) {
if (claimShell(data, part.callID, "tool", bashCommand(part)).source === "shell") {
return out(data, commits, view)
}
}
if (part.state.status === "running") {
if (data.ids.has(part.id)) {
@@ -132,8 +132,6 @@ function sid(event: Event): string | undefined {
}
if (
event.type === "session.next.shell.started" ||
event.type === "session.next.shell.ended" ||
event.type === "permission.asked" ||
event.type === "permission.replied" ||
event.type === "question.asked" ||
@@ -515,27 +513,6 @@ function createLayer(input: StreamInput) {
state.footerView = current
}
const resolveShellAgent = Effect.fn("RunStreamTransport.resolveShellAgent")(function* (
agent: string | undefined,
) {
if (agent) {
return agent
}
const list = yield* Effect.promise(() =>
input.sdk.app.agents(input.directory ? { directory: input.directory } : undefined, { throwOnError: true }),
).pipe(
Effect.map((item) => item.data ?? []),
Effect.orElseSucceed(() => []),
)
const next = list.find((item) => item.mode !== "subagent" && item.hidden !== true)?.name
if (next) {
return next
}
return yield* Effect.fail(new Error("no primary agent available for shell mode"))
})
const recoverQuestion = Effect.fn("RunStreamTransport.recoverQuestion")(function* (partID: string) {
if (recovering.has(partID)) {
return
@@ -1028,108 +1005,66 @@ function createLayer(input: StreamInput) {
],
}
const command = next.prompt.command
const send =
next.prompt.mode === "shell"
? Effect.sync(() => {
input.trace?.write("send.shell", {
sessionID: input.sessionID,
command: next.prompt.text,
})
}).pipe(
Effect.andThen(
resolveShellAgent(next.agent)
.pipe(
Effect.flatMap((agent) =>
Effect.promise(() =>
input.sdk.session.shell(
{
sessionID: input.sessionID,
agent,
model: next.model,
command: next.prompt.text,
},
{ signal: turn.signal, throwOnError: true },
),
const send = command
? Effect.sync(() => {
input.trace?.write("send.command", { sessionID: input.sessionID, command: command.name })
}).pipe(
Effect.andThen(
Effect.promise(() =>
input.sdk.session.command(
{
sessionID: input.sessionID,
agent: next.agent,
model: next.model ? `${next.model.providerID}/${next.model.modelID}` : undefined,
variant: next.variant,
command: command.name,
arguments: command.arguments,
parts: [
...(next.includeFiles ? next.files : []),
...next.prompt.parts.filter(
(item): item is Extract<RunPromptPart, { type: "file" }> => item.type === "file",
),
),
)
.pipe(
Effect.tap(() =>
Effect.sync(() => {
input.trace?.write("send.shell.ok", {
sessionID: input.sessionID,
})
item.armed = true
item.live = true
}),
),
Effect.flatMap(() => Deferred.succeed(item.done, undefined).pipe(Effect.ignore)),
Effect.catch((error) => Deferred.fail(item.done, error).pipe(Effect.ignore)),
Effect.forkIn(scope, { startImmediately: true }),
Effect.asVoid,
),
),
)
: command
? Effect.sync(() => {
input.trace?.write("send.command", { sessionID: input.sessionID, command: command.name })
}).pipe(
Effect.andThen(
Effect.promise(() =>
input.sdk.session.command(
{
sessionID: input.sessionID,
agent: next.agent,
model: next.model ? `${next.model.providerID}/${next.model.modelID}` : undefined,
variant: next.variant,
command: command.name,
arguments: command.arguments,
parts: [
...(next.includeFiles ? next.files : []),
...next.prompt.parts.filter(
(item): item is Extract<RunPromptPart, { type: "file" }> => item.type === "file",
),
],
},
{ signal: turn.signal },
),
).pipe(
Effect.tap(() =>
Effect.sync(() => {
input.trace?.write("send.command.ok", {
sessionID: input.sessionID,
command: command.name,
})
item.armed = true
item.live = true
}),
),
Effect.flatMap(() => Deferred.succeed(item.done, undefined).pipe(Effect.ignore)),
Effect.catch((error) => Deferred.fail(item.done, error).pipe(Effect.ignore)),
Effect.forkIn(scope, { startImmediately: true }),
Effect.asVoid,
),
),
)
: Effect.sync(() => {
input.trace?.write("send.prompt", req)
}).pipe(
Effect.andThen(
Effect.promise(() =>
input.sdk.session.promptAsync(req, {
signal: turn.signal,
}),
),
],
},
{ signal: turn.signal },
),
).pipe(
Effect.tap(() =>
Effect.sync(() => {
input.trace?.write("send.prompt.ok", {
input.trace?.write("send.command.ok", {
sessionID: input.sessionID,
command: command.name,
})
item.armed = true
item.live = true
}),
),
)
Effect.flatMap(() => Deferred.succeed(item.done, undefined).pipe(Effect.ignore)),
Effect.catch((error) => Deferred.fail(item.done, error).pipe(Effect.ignore)),
Effect.forkIn(scope, { startImmediately: true }),
Effect.asVoid,
),
),
)
: Effect.sync(() => {
input.trace?.write("send.prompt", req)
}).pipe(
Effect.andThen(
Effect.promise(() =>
input.sdk.session.promptAsync(req, {
signal: turn.signal,
}),
),
),
Effect.tap(() =>
Effect.sync(() => {
input.trace?.write("send.prompt.ok", {
sessionID: input.sessionID,
})
item.armed = true
}),
),
)
yield* send.pipe(
Effect.flatMap(() => {
+3 -32
View File
@@ -35,7 +35,7 @@ import { webSearchProviderLabel, type WebSearchTool } from "@/tool/websearch"
import type { WriteTool } from "@/tool/write"
import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
import * as Locale from "@/util/locale"
import type { RunEntryBody, StreamCommit, ToolSnapshot } from "./types"
import type { RunDiffStyle, RunEntryBody, StreamCommit, ToolSnapshot } from "./types"
export type ToolView = {
output: boolean
@@ -626,10 +626,6 @@ function scrollBashStart(p: ToolProps<typeof BashTool>): string {
const desc = p.input.description || "Shell"
const wd = p.input.workdir ?? ""
const dir = wd && wd !== "." ? toolPath(wd) : ""
if (cmd && desc === "Shell" && !dir) {
return `$ ${cmd}`
}
const title = dir && !desc.includes(dir) ? `${desc} in ${dir}` : desc
if (!cmd) {
@@ -1252,7 +1248,7 @@ function frame(part: ToolPart): ToolFrame {
raw: "",
name: part.tool,
input: dict(state.input),
meta: "metadata" in part.state ? dict(part.state.metadata) : {},
meta: dict(state.metadata),
state,
status: text(state.status),
error: text(state.error),
@@ -1265,7 +1261,7 @@ export function toolFrame(commit: StreamCommit, raw: string): ToolFrame {
raw,
name: commit.tool || commit.part?.tool || "tool",
input: dict(state.input),
meta: commit.part?.state && "metadata" in commit.part.state ? dict(commit.part.state.metadata) : {},
meta: dict(state.metadata),
state,
status: commit.toolState ?? text(state.status),
error: (commit.toolError ?? "").trim(),
@@ -1407,32 +1403,7 @@ function structuredBody(commit: StreamCommit, raw: string): RunEntryBody | undef
}
}
function shellOutput(command: string, raw: string): string | undefined {
const body = stripAnsi(raw).replace(/^\n+/, "").replace(/\n+$/, "")
if (!body) {
return undefined
}
if (!command) {
return body
}
return `\n${body}`
}
export function toolEntryBody(commit: StreamCommit, raw: string): RunEntryBody | undefined {
if (commit.shell) {
if (commit.phase === "start") {
return textBody(`$ ${commit.shell.command}`)
}
if (commit.phase === "progress") {
return textBody(shellOutput(commit.shell.command, raw) ?? "")
}
return undefined
}
const ctx = toolFrame(commit, raw)
const view = toolView(ctx.name)
@@ -34,7 +34,6 @@ export type RunProvider = NonNullable<Awaited<ReturnType<OpencodeClient["provide
export type RunPrompt = {
text: string
parts: RunPromptPart[]
mode?: "shell"
command?: {
name: string
arguments: string
@@ -303,10 +302,6 @@ export type StreamCommit = {
interrupted?: boolean
toolState?: StreamToolState
toolError?: string
shell?: {
callID: string
command: string
}
}
// The public contract between the stream transport / prompt queue and
+1 -3
View File
@@ -25,7 +25,7 @@ import { DialogProvider, useDialog } from "@tui/ui/dialog"
import { DialogProvider as DialogProviderList } from "@tui/component/dialog-provider"
import { ErrorComponent } from "@tui/component/error-component"
import { PluginRouteMissing } from "@tui/component/plugin-route-missing"
import { ProjectProvider, useProject } from "@tui/context/project"
import { ProjectProvider } from "@tui/context/project"
import { EditorContextProvider } from "@tui/context/editor"
import { useEvent } from "@tui/context/event"
import { SDKProvider, useSDK } from "@tui/context/sdk"
@@ -279,7 +279,6 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
const themeState = useTheme()
const { theme, mode, setMode, locked, lock, unlock } = themeState
const sync = useSync()
const project = useProject()
const exit = useExit()
const promptRef = usePromptRef()
const routes: RouteMap = new Map()
@@ -305,7 +304,6 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
toast,
renderer,
attention,
project,
})
const [ready, setReady] = createSignal(false)
TuiPluginRuntime.init({
@@ -59,17 +59,6 @@ export const Definitions = {
command_list: keybind("ctrl+p", "List available commands"),
help_show: keybind("none", "Open help dialog"),
docs_open: keybind("none", "Open documentation"),
diff_close: keybind("escape,q", "Close diff viewer"),
diff_toggle: keybind("enter,space", "Toggle diff viewer item"),
diff_expand: keybind("right", "Expand diff viewer item"),
diff_collapse: keybind("left", "Collapse diff viewer item"),
diff_switch_focus: keybind("tab", "Switch diff viewer focus"),
diff_next_file: keybind("n", "Jump to next diff file"),
diff_previous_file: keybind("p", "Jump to previous diff file"),
diff_toggle_file_tree: keybind("b", "Toggle diff viewer file tree"),
diff_single_patch: keybind("s", "Toggle single patch view"),
diff_switch_diff: keybind("d", "Switch diff viewer source"),
diff_toggle_view: keybind("v", "Toggle diff viewer split or unified view"),
editor_open: keybind("<leader>e", "Open external editor"),
theme_list: keybind("<leader>t", "List available themes"),
@@ -256,17 +245,6 @@ export const CommandMap = {
command_list: "command.palette.show",
help_show: "help.show",
docs_open: "docs.open",
diff_close: "diff.close",
diff_toggle: "diff.toggle",
diff_expand: "diff.expand",
diff_collapse: "diff.collapse",
diff_switch_focus: "diff.switch_focus",
diff_next_file: "diff.next_file",
diff_previous_file: "diff.previous_file",
diff_toggle_file_tree: "diff.toggle_file_tree",
diff_single_patch: "diff.single_patch",
diff_switch_diff: "diff.switch_diff",
diff_toggle_view: "diff.toggle_view",
editor_open: "prompt.editor",
theme_list: "theme.switch",
theme_switch_mode: "theme.switch_mode",
@@ -1,155 +0,0 @@
// Paths branch softly through the screen,
// A quiet tree of changed designs;
// Each leaf remembers what has been,
// And waits where careful light aligns.
export type FileTreeItem = {
readonly file: string
}
export type FileTreeNode = {
readonly id: number
readonly name: string
readonly parent: number | undefined
readonly children: number[]
readonly depth: number
readonly kind: "directory" | "file"
readonly fileIndex?: number
}
export type FileTree = {
readonly roots: number[]
readonly nodes: FileTreeNode[]
}
export type FileTreeRow = {
readonly id: number
readonly depth: number
readonly kind: "directory" | "file"
readonly name: string
readonly fileIndex?: number
}
export function buildFileTree(files: readonly FileTreeItem[]): FileTree {
const roots: number[] = []
const nodes: FileTreeNode[] = []
const directoryByPath = new Map<string, number>()
files.forEach((file, fileIndex) => {
const segments = file.file.split("/").filter(Boolean)
if (segments.length === 0) return
const parent = segments.slice(0, -1).reduce(
(state, segment) => {
const directoryPath = state.path ? `${state.path}/${segment}` : segment
const existing = directoryByPath.get(directoryPath)
if (existing !== undefined) return { id: existing, path: directoryPath, depth: state.depth + 1 }
const id = addFileTreeNode(nodes, roots, {
name: segment,
parent: state.id,
depth: state.depth,
kind: "directory",
})
directoryByPath.set(directoryPath, id)
return { id, path: directoryPath, depth: state.depth + 1 }
},
{ id: undefined as number | undefined, path: "", depth: 0 },
)
addFileTreeNode(nodes, roots, {
name: segments[segments.length - 1]!,
parent: parent.id,
depth: parent.depth,
kind: "file",
fileIndex,
})
})
const tree = { roots, nodes }
tree.roots.sort((left, right) => compareFileTreeNodes(tree, left, right))
tree.nodes.forEach((node) => node.children.sort((left, right) => compareFileTreeNodes(tree, left, right)))
return tree
}
export function flattenFileTree(tree: FileTree, expanded?: ReadonlySet<number>): FileTreeRow[] {
const rows: FileTreeRow[] = []
const visit = (id: number) => {
const node = tree.nodes[id]!
rows.push({
id: node.id,
depth: node.depth,
kind: node.kind,
name: node.name,
fileIndex: node.fileIndex,
})
if (node.kind === "directory" && (!expanded || expanded.has(node.id))) node.children.forEach(visit)
}
tree.roots.forEach(visit)
return rows
}
export function compareFileTreeNodes(tree: FileTree, left: number, right: number) {
const leftNode = tree.nodes[left]!
const rightNode = tree.nodes[right]!
if (leftNode.kind !== rightNode.kind) return leftNode.kind === "directory" ? -1 : 1
if (leftNode.name < rightNode.name) return -1
if (leftNode.name > rightNode.name) return 1
return left - right
}
export function moveFileTreeSelection(rows: readonly FileTreeRow[], selected: number | undefined, offset: number) {
if (rows.length === 0) return undefined
const index = selected === undefined ? -1 : rows.findIndex((row) => row.id === selected)
if (index === -1) return rows[0]!.id
return rows[Math.max(0, Math.min(rows.length - 1, index + offset))]!.id
}
export function moveFileTreeSelectionToFile(
rows: readonly FileTreeRow[],
selected: number | undefined,
offset: number,
) {
const fileRows = rows.filter((row) => row.fileIndex !== undefined)
if (fileRows.length === 0) return undefined
const selectedIndex = selected === undefined ? -1 : rows.findIndex((row) => row.id === selected)
if (selectedIndex === -1) return offset < 0 ? fileRows[fileRows.length - 1]!.id : fileRows[0]!.id
const next =
offset < 0
? fileRows.findLast((row) => rows.findIndex((item) => item.id === row.id) < selectedIndex)
: fileRows.find((row) => rows.findIndex((item) => item.id === row.id) > selectedIndex)
return next?.id ?? (offset < 0 ? fileRows[0]!.id : fileRows[fileRows.length - 1]!.id)
}
export function allExpandedFileTreeDirectories(tree: FileTree) {
return new Set(tree.nodes.filter((node) => node.kind === "directory").map((node) => node.id))
}
export function toggleFileTreeDirectory(tree: FileTree, expanded: ReadonlySet<number>, selected: number | undefined) {
if (selected === undefined || tree.nodes[selected]?.kind !== "directory") return expanded
const next = new Set(expanded)
if (next.has(selected)) next.delete(selected)
else next.add(selected)
return next
}
export function setFileTreeDirectoryExpanded(
tree: FileTree,
expanded: ReadonlySet<number>,
selected: number | undefined,
value: boolean,
) {
if (selected === undefined || tree.nodes[selected]?.kind !== "directory") return expanded
const next = new Set(expanded)
if (value) next.add(selected)
else next.delete(selected)
return next
}
function addFileTreeNode(nodes: FileTreeNode[], roots: number[], input: Omit<FileTreeNode, "id" | "children">) {
const id = nodes.length
nodes.push({ ...input, id, children: [] })
if (input.parent === undefined) roots.push(id)
else nodes[input.parent]!.children.push(id)
return id
}
@@ -1,103 +0,0 @@
/** @jsxImportSource @opentui/solid */
import type { ColorInput, ScrollBoxRenderable } from "@opentui/core"
import { createEffect, createMemo, For, Match, Switch } from "solid-js"
import { buildFileTree, flattenFileTree, type FileTreeItem } from "./diff-viewer-file-tree-utils"
export type DiffViewerFileTreeTheme = {
readonly background: ColorInput
readonly backgroundPanel: ColorInput
readonly backgroundElement: ColorInput
readonly primary: ColorInput
readonly selectedListItemText: ColorInput
readonly text: ColorInput
readonly textMuted: ColorInput
readonly error: ColorInput
}
export type DiffViewerFileTreeProps = {
readonly files: readonly FileTreeItem[]
readonly loading: boolean
readonly error: unknown
readonly theme: DiffViewerFileTreeTheme
readonly focused?: boolean
readonly highlightedNode?: number
readonly expandedNodes?: ReadonlySet<number>
}
export function DiffViewerFileTree(props: DiffViewerFileTreeProps) {
const tree = createMemo(() => buildFileTree(props.files))
const rows = createMemo(() => flattenFileTree(tree(), props.expandedNodes))
let scroll: ScrollBoxRenderable | undefined
createEffect(() => {
const node = props.highlightedNode
if (node === undefined) return
const selectedIndex = rows().findIndex((row) => row.id === node)
if (selectedIndex === -1) return
const scrollSelectedIntoView = () => scrollFileTreeRowIntoView(scroll, selectedIndex)
scrollSelectedIntoView()
requestAnimationFrame(scrollSelectedIntoView)
})
return (
<box
width={32}
flexShrink={0}
backgroundColor={props.theme.backgroundPanel}
paddingLeft={1}
paddingRight={1}
paddingTop={1}
gap={1}
minHeight={0}
>
<scrollbox
ref={(element: ScrollBoxRenderable) => (scroll = element)}
flexGrow={1}
minHeight={0}
verticalScrollbarOptions={{ visible: false }}
horizontalScrollbarOptions={{ visible: false }}
>
<Switch>
<Match when={props.loading || props.error}>
<text />
</Match>
<Match when={props.files.length === 0}>
<text fg={props.theme.text}>No files</text>
</Match>
<Match when={props.files.length > 0}>
<For each={rows()}>
{(row) => {
const highlighted = () => props.focused && props.highlightedNode === row.id
return (
<box flexDirection="row">
<text fg={row.kind === "directory" ? props.theme.textMuted : props.theme.text} wrapMode="none">
{`${" ".repeat(row.depth)}${row.kind === "directory" ? (props.expandedNodes && !props.expandedNodes.has(row.id) ? "▸ " : "▾ ") : " "}`}
</text>
<text
fg={highlighted() ? props.theme.background : row.kind === "directory" ? props.theme.textMuted : props.theme.text}
bg={highlighted() ? props.theme.primary : undefined}
wrapMode="none"
>
{row.name}
</text>
</box>
)
}}
</For>
</Match>
</Switch>
</scrollbox>
</box>
)
}
function scrollFileTreeRowIntoView(scroll: ScrollBoxRenderable | undefined, index: number) {
if (!scroll) return
if (index < scroll.scrollTop) {
scroll.scrollTo(index)
return
}
if (index >= scroll.scrollTop + scroll.viewport.height) {
scroll.scrollTo(index - scroll.viewport.height + 1)
}
}
@@ -1,697 +0,0 @@
/** @jsxImportSource @opentui/solid */
import type { TuiPlugin, TuiPluginApi, TuiRouteCurrent } from "@opencode-ai/plugin/tui"
import type { SnapshotFileDiff, VcsFileDiff } from "@opencode-ai/sdk/v2"
import type { BoxRenderable, ScrollBoxRenderable } from "@opentui/core"
import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
import { useBindings, useCommandShortcut } from "@tui/keymap"
import { useTheme } from "@tui/context/theme"
import { useTerminalDimensions } from "@opentui/solid"
import path from "path"
import { createEffect, createMemo, createResource, createSignal, For, Match, Show, Switch } from "solid-js"
import { DiffViewerFileTree } from "./diff-viewer-file-tree"
import { DialogSelect } from "@tui/ui/dialog-select"
import {
allExpandedFileTreeDirectories,
buildFileTree,
flattenFileTree,
moveFileTreeSelection,
moveFileTreeSelectionToFile,
setFileTreeDirectoryExpanded,
toggleFileTreeDirectory,
} from "./diff-viewer-file-tree-utils"
const ROUTE = "diff"
const MIN_SPLIT_WIDTH = 100
type DiffMode = "git" | "last-turn"
type DiffViewerFocus = "patches" | "files"
type DiffFile = {
readonly file: string
readonly patch?: string
readonly additions: number
readonly deletions: number
readonly status: "added" | "deleted" | "modified"
}
const normalizeDiffs = (diffs: readonly (VcsFileDiff | SnapshotFileDiff)[]): DiffFile[] =>
diffs.flatMap((item) =>
item.file
? [
{
file: item.file,
patch: item.patch,
additions: item.additions,
deletions: item.deletions,
status: item.status ?? "modified",
} satisfies DiffFile,
]
: [],
)
function filetype(input?: string) {
if (!input) return "none"
const language = LANGUAGE_EXTENSIONS[path.extname(input)]
if (["typescriptreact", "javascriptreact", "javascript"].includes(language)) return "typescript"
return language
}
function DiffViewer(props: { api: TuiPluginApi }) {
const dimensions = useTerminalDimensions()
const themeState = useTheme()
const theme = () => props.api.theme.current
const params = () =>
("params" in props.api.route.current ? props.api.route.current.params : undefined) as
| { mode?: DiffMode; sessionID?: string; messageID?: string; returnTo?: TuiRouteCurrent }
| undefined
const mode = () => params()?.mode ?? "git"
const diffInput = createMemo(() => ({
mode: mode(),
sessionID: params()?.sessionID,
messageID: params()?.messageID,
}))
const [diff] = createResource(diffInput, async (input) => {
if (input.mode === "last-turn") {
const sessionID = input.sessionID
if (!sessionID) return []
const result = await props.api.client.session.diff(
{ sessionID, messageID: input.messageID },
{ throwOnError: true },
)
return normalizeDiffs(result.data ?? [])
}
const result = await props.api.client.vcs.diff(
{ mode: "git", workspace: props.api.workspace.current() },
{ throwOnError: true },
)
return normalizeDiffs(result.data ?? [])
})
const files = createMemo(() => diff() ?? [])
const [focus, setFocus] = createSignal<DiffViewerFocus>("patches")
const [showFileTree, setShowFileTree] = createSignal(true)
const [singlePatch, setSinglePatch] = createSignal(false)
const patchPaneWidth = createMemo(() => dimensions().width - (showFileTree() ? 33 : 0) - 4)
const splitAvailable = createMemo(() => patchPaneWidth() >= MIN_SPLIT_WIDTH)
const defaultView = createMemo(() => {
if (props.api.tuiConfig.diff_style === "stacked") return "unified"
return splitAvailable() ? "split" : "unified"
})
const [viewOverride, setViewOverride] = createSignal<"split" | "unified">()
const view = createMemo(() => (splitAvailable() ? (viewOverride() ?? defaultView()) : "unified"))
const fileTree = createMemo(() => buildFileTree(files()))
const [expandedFileNodes, setExpandedFileNodes] = createSignal<ReadonlySet<number>>(new Set())
const [highlightedFileNode, setHighlightedFileNode] = createSignal<number | undefined>()
const [lastHighlightedFileNode, setLastHighlightedFileNode] = createSignal<number | undefined>()
const [activePatchFileIndex, setActivePatchFileIndex] = createSignal<number | undefined>()
const fileRows = createMemo(() => flattenFileTree(fileTree(), expandedFileNodes()))
const focusRunner = (input: Record<DiffViewerFocus, () => void>) => () => input[focus()]()
const switchFocusShortcut = useCommandShortcut("diff.switch_focus")
const nextFileShortcut = useCommandShortcut("diff.next_file")
const previousFileShortcut = useCommandShortcut("diff.previous_file")
const toggleFileTreeShortcut = useCommandShortcut("diff.toggle_file_tree")
const singlePatchShortcut = useCommandShortcut("diff.single_patch")
const switchDiffShortcut = useCommandShortcut("diff.switch_diff")
const toggleViewShortcut = useCommandShortcut("diff.toggle_view")
let scroll: ScrollBoxRenderable | undefined
const patchNodeByFileIndex = new Map<number, BoxRenderable>()
const [pendingPatchScrollFileIndex, setPendingPatchScrollFileIndex] = createSignal<number | undefined>()
createEffect(() => {
setExpandedFileNodes(allExpandedFileTreeDirectories(fileTree()))
setHighlightedFileNode(undefined)
setLastHighlightedFileNode(undefined)
setActivePatchFileIndex(undefined)
})
const ensureHighlightedFileNode = () => {
const highlighted = highlightedFileNode()
if (highlighted !== undefined && fileRows().some((row) => row.id === highlighted)) return
const lastHighlighted = lastHighlightedFileNode()
const next =
lastHighlighted !== undefined && fileRows().some((row) => row.id === lastHighlighted)
? lastHighlighted
: fileRows()[0]?.id
setHighlightedFileNode(next)
}
const setHighlighted = (node: number | undefined) => {
setHighlightedFileNode(node)
if (node !== undefined) setLastHighlightedFileNode(node)
}
const moveFileSelection = (offset: number) =>
setHighlighted(moveFileTreeSelection(fileRows(), highlightedFileNode(), offset))
const clearFileTreePatchState = () => {
setHighlightedFileNode(undefined)
setActivePatchFileIndex(undefined)
}
const scrollPatchNodeToTop = (patchNode: BoxRenderable) => {
if (!scroll) return
scroll.scrollBy(patchNode.y - scroll.viewport.y)
requestAnimationFrame(() => {
if (scroll) scroll.scrollBy(patchNode.y - scroll.viewport.y)
})
}
const revealFileTreeFile = (fileIndex: number) => {
const node = fileTree().nodes.find((item) => item.kind === "file" && item.fileIndex === fileIndex)
if (!node) return
setExpandedFileNodes((expanded) => {
const next = new Set(expanded)
for (let parent = node.parent; parent !== undefined; parent = fileTree().nodes[parent]?.parent) {
next.add(parent)
}
return next
})
setHighlighted(node.id)
}
const scrollToFileIndex = (fileIndex: number | undefined) => {
if (fileIndex === undefined) return
setActivePatchFileIndex(fileIndex)
const patchNode = patchNodeByFileIndex.get(fileIndex)
if (patchNode) scrollPatchNodeToTop(patchNode)
}
const jumpToFileIndex = (fileIndex: number | undefined) => {
if (fileIndex === undefined) return
revealFileTreeFile(fileIndex)
scrollToFileIndex(fileIndex)
}
const currentPatchFileIndex = () => {
if (!scroll) return undefined
const entries = files()
.map((_, fileIndex) => ({ fileIndex, node: patchNodeByFileIndex.get(fileIndex) }))
.filter((entry): entry is { fileIndex: number; node: BoxRenderable } => Boolean(entry.node))
.sort((left, right) => left.node.y - right.node.y)
return entries.findLast((entry) => entry.node.y <= scroll!.viewport.y + 1)?.fileIndex ?? entries[0]?.fileIndex
}
const jumpRelativePatchFile = (offset: number) => {
const current = focus() === "files" ? highlightedFileNode() : undefined
const nextFromSelection =
current === undefined ? undefined : moveFileTreeSelectionToFile(fileRows(), current, offset)
if (nextFromSelection !== undefined) {
jumpToFileIndex(fileRows().find((row) => row.id === nextFromSelection)?.fileIndex)
return
}
const currentFileIndex = activePatchFileIndex() ?? currentPatchFileIndex()
const currentRow = fileRows().find((row) => row.fileIndex === currentFileIndex)
scrollToFileIndex(
fileRows().find((row) => row.id === moveFileTreeSelectionToFile(fileRows(), currentRow?.id, offset))?.fileIndex,
)
}
const highlightedPatchFileIndex = () => fileRows().find((row) => row.id === highlightedFileNode())?.fileIndex
const firstPatchFileIndex = () => fileRows().find((row) => row.fileIndex !== undefined)?.fileIndex
const visiblePatchFiles = createMemo(() => {
if (!singlePatch()) return files().map((file, fileIndex) => ({ file, fileIndex }))
const fileIndex = activePatchFileIndex() ?? currentPatchFileIndex() ?? firstPatchFileIndex()
const file = fileIndex === undefined ? undefined : files()[fileIndex]
return file && fileIndex !== undefined ? [{ file, fileIndex }] : []
})
const ensureHighlightedPatchFile = () => {
if (activePatchFileIndex() !== undefined) return
const fileIndex = currentPatchFileIndex() ?? firstPatchFileIndex()
if (fileIndex !== undefined) setActivePatchFileIndex(fileIndex)
}
const scrollToHighlightedPatchFile = () => {
const fileIndex = activePatchFileIndex()
if (fileIndex === undefined) return
setPendingPatchScrollFileIndex(fileIndex)
}
const registerPatchNode = (fileIndex: number, element: BoxRenderable) => {
patchNodeByFileIndex.set(fileIndex, element)
if (pendingPatchScrollFileIndex() !== fileIndex) return
requestAnimationFrame(() => {
scrollPatchNodeToTop(element)
requestAnimationFrame(() => {
scrollPatchNodeToTop(element)
setPendingPatchScrollFileIndex(undefined)
})
})
}
const toggleSelectedFileTreeRow = () => {
const highlighted = fileRows().find((row) => row.id === highlightedFileNode())
if (highlighted?.fileIndex !== undefined) {
jumpToFileIndex(highlighted.fileIndex)
return
}
setExpandedFileNodes((expanded) => toggleFileTreeDirectory(fileTree(), expanded, highlightedFileNode()))
}
const commands = [
{
name: "diff.close",
title: "Close diff viewer",
category: "VCS",
run() {
const target = params()?.returnTo ?? ({ name: "home" } satisfies TuiRouteCurrent)
props.api.route.navigate(target.name, "params" in target ? target.params : undefined)
},
},
{
name: "diff.down",
title: "Move diff viewer down",
category: "VCS",
run: focusRunner({
files() {
moveFileSelection(1)
},
patches() {
clearFileTreePatchState()
scroll?.scrollBy(1)
},
}),
},
{
name: "diff.up",
title: "Move diff viewer up",
category: "VCS",
run: focusRunner({
files() {
moveFileSelection(-1)
},
patches() {
clearFileTreePatchState()
scroll?.scrollBy(-1)
},
}),
},
{
name: "diff.page.down",
title: "Page diff viewer down",
category: "VCS",
run: focusRunner({
files() {
moveFileSelection(8)
},
patches() {
clearFileTreePatchState()
if (scroll) scroll.scrollBy(scroll.height)
},
}),
},
{
name: "diff.page.up",
title: "Page diff viewer up",
category: "VCS",
run: focusRunner({
files() {
moveFileSelection(-8)
},
patches() {
clearFileTreePatchState()
if (scroll) scroll.scrollBy(-scroll.height)
},
}),
},
{
name: "diff.toggle",
title: "Toggle diff viewer item",
category: "VCS",
run: focusRunner({
files() {
toggleSelectedFileTreeRow()
},
patches() {},
}),
},
{
name: "diff.expand",
title: "Expand diff viewer item",
category: "VCS",
run: focusRunner({
files() {
setExpandedFileNodes((expanded) =>
setFileTreeDirectoryExpanded(fileTree(), expanded, highlightedFileNode(), true),
)
},
patches() {},
}),
},
{
name: "diff.collapse",
title: "Collapse diff viewer item",
category: "VCS",
run: focusRunner({
files() {
setExpandedFileNodes((expanded) =>
setFileTreeDirectoryExpanded(fileTree(), expanded, highlightedFileNode(), false),
)
},
patches() {},
}),
},
{
name: "diff.next_file",
title: "Jump to next diff file",
category: "VCS",
run() {
jumpRelativePatchFile(1)
},
},
{
name: "diff.previous_file",
title: "Jump to previous diff file",
category: "VCS",
run() {
jumpRelativePatchFile(-1)
},
},
{
name: "diff.switch_focus",
title: "Switch diff viewer focus",
category: "VCS",
run() {
if (!showFileTree()) return
setFocus((current) => {
if (current === "files") return "patches"
ensureHighlightedFileNode()
return "files"
})
},
},
{
name: "diff.toggle_file_tree",
title: "Toggle diff viewer file tree",
category: "VCS",
run() {
setShowFileTree((value) => {
if (value) setFocus("patches")
return !value
})
},
},
{
name: "diff.single_patch",
title: "Toggle single patch view",
category: "VCS",
run() {
setSinglePatch((value) => {
const next = !value
if (next) ensureHighlightedPatchFile()
else scrollToHighlightedPatchFile()
return next
})
},
},
{
name: "diff.switch_diff",
title: "Switch diff viewer source",
category: "VCS",
run() {
openSwitchDiffDialog()
},
},
{
name: "diff.toggle_view",
title: "Toggle diff viewer split or unified view",
category: "VCS",
run() {
if (!splitAvailable()) return
setViewOverride(view() === "split" ? "unified" : "split")
},
},
]
const switchDiffOptions = createMemo(() => [
{
title: "Working tree",
value: "git" as const,
description: "Show current git changes",
},
{
title: "Last turn",
value: "last-turn" as const,
description: "Show changes from the last assistant turn",
},
])
const openSwitchDiffDialog = () => {
props.api.ui.dialog.replace(() => (
<DialogSelect
title="Switch diff"
skipFilter={true}
renderFilter={false}
current={mode()}
options={switchDiffOptions().map((option) => ({
...option,
onSelect(dialog) {
dialog.clear()
props.api.route.navigate(ROUTE, {
mode: option.value,
sessionID: params()?.sessionID,
messageID: params()?.messageID,
returnTo: params()?.returnTo,
})
},
}))}
/>
))
}
useBindings(() => ({
commands,
bindings: [
{ key: "j,down", cmd: "diff.down", desc: "Move diff viewer down" },
{ key: "k,up", cmd: "diff.up", desc: "Move diff viewer up" },
{ key: "pagedown,ctrl+f", cmd: "diff.page.down", desc: "Page diff viewer down" },
{ key: "pageup,ctrl+b", cmd: "diff.page.up", desc: "Page diff viewer up" },
...props.api.tuiConfig.keybinds.gather(
"diff",
commands.map((command) => command.name),
),
],
}))
return (
<box
position="absolute"
zIndex={2500}
left={0}
top={0}
width={dimensions().width}
height={dimensions().height}
backgroundColor={theme().background}
paddingLeft={1}
paddingRight={1}
paddingTop={1}
paddingBottom={1}
gap={1}
>
<box flexDirection="row" justifyContent="space-between" flexShrink={0}>
<box flexDirection="row" gap={1}>
<text fg={theme().text}>Diff</text>
<text fg={theme().textMuted}>{mode() === "last-turn" ? "last turn" : "working tree"}</text>
</box>
</box>
<Switch>
<Match when={diff.loading}>
<box flexGrow={1} alignItems="center" justifyContent="center">
<text fg={theme().textMuted}>Loading diff...</text>
</box>
</Match>
<Match when={!diff.loading}>
<box flexDirection="row" flexGrow={1} minHeight={0} gap={1}>
<Show when={showFileTree()}>
<DiffViewerFileTree
files={files()}
loading={diff.loading}
error={diff.error}
theme={theme()}
focused={focus() === "files"}
highlightedNode={highlightedFileNode()}
expandedNodes={expandedFileNodes()}
/>
</Show>
<box
flexGrow={1}
minWidth={0}
backgroundColor={theme().background}
paddingLeft={0}
paddingRight={2}
gap={1}
>
<Switch>
<Match when={diff.error}>
<box paddingTop={1}>
<text fg={theme().error}>Failed to load diff</text>
</box>
</Match>
<Match when={files().length === 0}>
<box paddingTop={1}>
<text fg={theme().textMuted}>No diff to show</text>
</box>
</Match>
<Match when={files().length > 0}>
<scrollbox
ref={(element: ScrollBoxRenderable) => (scroll = element)}
flexGrow={1}
minHeight={0}
verticalScrollbarOptions={{ visible: false }}
horizontalScrollbarOptions={{ visible: false }}
>
<For each={visiblePatchFiles()}>
{(entry) => (
<box
ref={(element: BoxRenderable) => registerPatchNode(entry.fileIndex, element)}
marginBottom={1}
backgroundColor={theme().backgroundPanel}
>
<box
flexDirection="row"
gap={2}
flexShrink={0}
paddingTop={1}
paddingBottom={1}
paddingLeft={2}
paddingRight={1}
backgroundColor={theme().backgroundPanel}
>
<text fg={theme().text}>{entry.file.file}</text>
<text fg={theme().diffAdded}>+{entry.file.additions}</text>
<text fg={theme().diffRemoved}>-{entry.file.deletions}</text>
</box>
<Show
when={entry.file.patch}
fallback={<text fg={theme().textMuted}>No patch available for this file.</text>}
>
{(patch) => (
<diff
diff={patch()}
view={view()}
filetype={filetype(entry.file.file)}
syntaxStyle={themeState.syntax()}
showLineNumbers={true}
width="100%"
wrapMode="word"
fg={theme().text}
addedBg={theme().diffAddedBg}
removedBg={theme().diffRemovedBg}
contextBg={theme().diffContextBg}
addedSignColor={theme().diffHighlightAdded}
removedSignColor={theme().diffHighlightRemoved}
lineNumberFg={theme().diffLineNumber}
lineNumberBg={theme().diffContextBg}
addedLineNumberBg={theme().diffAddedLineNumberBg}
removedLineNumberBg={theme().diffRemovedLineNumberBg}
/>
)}
</Show>
</box>
)}
</For>
</scrollbox>
</Match>
</Switch>
</box>
</box>
</Match>
</Switch>
<box flexDirection="row" gap={2} flexShrink={0}>
<Show when={switchFocusShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()} <span style={{ fg: theme().textMuted }}>focus file tree</span>
</text>
)}
</Show>
<Show when={nextFileShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()} <span style={{ fg: theme().textMuted }}>next file</span>
</text>
)}
</Show>
<Show when={previousFileShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()} <span style={{ fg: theme().textMuted }}>previous file</span>
</text>
)}
</Show>
<Show when={toggleFileTreeShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()}{" "}
<span style={{ fg: theme().textMuted }}>{showFileTree() ? "hide file tree" : "show file tree"}</span>
</text>
)}
</Show>
<Show when={singlePatchShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()}{" "}
<span style={{ fg: theme().textMuted }}>{singlePatch() ? "all patches" : "single patch"}</span>
</text>
)}
</Show>
<Show when={switchDiffShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()} <span style={{ fg: theme().textMuted }}>switch diff</span>
</text>
)}
</Show>
<Show when={toggleViewShortcut()}>
{(shortcut) => (
<text fg={theme().text}>
{shortcut()}{" "}
<span style={{ fg: theme().textMuted }}>{view() === "split" ? "unified view" : "split view"}</span>
</text>
)}
</Show>
</box>
</box>
)
}
const tui: TuiPlugin = async (api) => {
api.route.register([
{
name: ROUTE,
render: () => <DiffViewer api={api} />,
},
])
api.keymap.registerLayer({
commands: [
{
name: "diff.open",
title: "Open diff viewer",
slashName: "diff",
category: "VCS",
namespace: "palette",
run() {
api.route.navigate(ROUTE, {
mode: "git",
sessionID: "params" in api.route.current ? api.route.current.params?.sessionID : undefined,
returnTo: {
name: api.route.current.name,
...("params" in api.route.current && api.route.current.params
? { params: api.route.current.params }
: {}),
},
})
api.ui.dialog.clear()
},
},
],
})
}
export default {
id: "diff-viewer",
tui,
}
@@ -8,7 +8,6 @@ import { Dialog as DialogUI, type useDialog } from "@tui/ui/dialog"
import type { TuiConfig } from "@/cli/cmd/tui/config/tui"
import type { useOpencodeKeymap } from "../keymap"
import type { useKV } from "../context/kv"
import type { useProject } from "../context/project"
import { DialogAlert } from "../ui/dialog-alert"
import { DialogConfirm } from "../ui/dialog-confirm"
import { DialogPrompt } from "../ui/dialog-prompt"
@@ -42,7 +41,6 @@ type Input = {
toast: ReturnType<typeof useToast>
renderer: TuiPluginApi["renderer"]
attention: TuiPluginApi["attention"]
project: ReturnType<typeof useProject>
}
function routeRegister(routes: RouteMap, list: TuiRouteDefinition[], bump: () => void) {
@@ -229,11 +227,6 @@ export function createTuiApi(input: Input): TuiPluginApi {
return Keymap.getOpencodeModeStack(input.keymap).push(mode)
},
},
workspace: {
current() {
return input.project.workspace.current()
},
},
route: {
register(list) {
return routeRegister(input.routes, list, input.bump)
@@ -10,7 +10,6 @@ import PluginManager from "../feature-plugins/system/plugins"
import Notifications from "../feature-plugins/system/notifications"
import SessionV2Debug from "../feature-plugins/system/session-v2"
import WhichKey from "../feature-plugins/system/which-key"
import DiffViewer from "../feature-plugins/system/diff-viewer"
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
import type { RuntimeFlags } from "@/effect/runtime-flags"
@@ -20,7 +19,7 @@ export type InternalTuiPlugin = Omit<TuiPluginModule, "id"> & {
enabled?: boolean
}
export function internalTuiPlugins(flags: Pick<RuntimeFlags.Info, "diffViewer" | "experimentalEventSystem">): InternalTuiPlugin[] {
export function internalTuiPlugins(flags: Pick<RuntimeFlags.Info, "experimentalEventSystem">): InternalTuiPlugin[] {
return [
HomeFooter,
HomeTips,
@@ -33,7 +32,6 @@ export function internalTuiPlugins(flags: Pick<RuntimeFlags.Info, "diffViewer" |
Notifications,
PluginManager,
WhichKey,
...(flags.diffViewer ? [DiffViewer] : []),
...(flags.experimentalEventSystem ? [SessionV2Debug] : []),
]
}
@@ -628,7 +628,6 @@ function pluginApi(runtime: RuntimeState, plugin: PluginEntry, scope: PluginScop
keys: api.keys,
keymap,
mode: createScopedMode(api.mode, scope),
workspace: api.workspace,
route,
ui: api.ui,
tuiConfig: api.tuiConfig,
+3 -3
View File
@@ -1,6 +1,5 @@
export * as ConfigAgent from "./agent"
import path from "path"
import { Exit, Schema, SchemaGetter } from "effect"
import { PositiveInt } from "@opencode-ai/core/schema"
import * as Log from "@opencode-ai/core/util/log"
@@ -117,7 +116,8 @@ export async function load(dir: string) {
})
if (!md) continue
const name = configEntryNameFromPath(path.relative(dir, item), ["agent/", "agents/"])
const patterns = ["/.opencode/agent/", "/.opencode/agents/", "/agent/", "/agents/"]
const name = configEntryNameFromPath(item, patterns)
const config = {
name,
@@ -144,7 +144,7 @@ export async function loadMode(dir: string) {
if (!md) continue
const config = {
name: configEntryNameFromPath(path.relative(dir, item), ["mode/", "modes/"]),
name: configEntryNameFromPath(item, []),
...md.data,
prompt: md.content.trim(),
}
+2 -2
View File
@@ -1,6 +1,5 @@
export * as ConfigCommand from "./command"
import path from "path"
import * as Log from "@opencode-ai/core/util/log"
import { Cause, Exit, Schema } from "effect"
import { Glob } from "@opencode-ai/core/util/glob"
@@ -37,7 +36,8 @@ export async function load(dir: string) {
})
if (!md) continue
const name = configEntryNameFromPath(path.relative(dir, item), ["command/", "commands/"])
const patterns = ["/.opencode/command/", "/.opencode/commands/", "/command/", "/commands/"]
const name = configEntryNameFromPath(item, patterns)
const config = {
name,
+1 -5
View File
@@ -703,11 +703,7 @@ export const layer = Layer.effect(
}
if (Flag.OPENCODE_PERMISSION) {
try {
result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.OPENCODE_PERMISSION))
} catch (err) {
log.warn("OPENCODE_PERMISSION contains invalid JSON, skipping", { err })
}
result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.OPENCODE_PERMISSION))
}
if (result.tools) {
+8 -11
View File
@@ -1,19 +1,16 @@
import path from "path"
// Strips a known prefix from an already-relative path. Callers should pass the
// path relative to the directory they scanned (e.g. `path.relative(dir, item)`)
// so the prefix match is anchored. Matching anywhere in an absolute path used
// to mis-key agents whose home/parent segments coincidentally contained one of
// the prefix names (see #25713).
function stripPrefix(relativePath: string, prefixes: string[]) {
const normalized = relativePath.replaceAll("\\", "/")
for (const prefix of prefixes) {
if (normalized.startsWith(prefix)) return normalized.slice(prefix.length)
function sliceAfterMatch(filePath: string, searchRoots: string[]) {
const normalizedPath = filePath.replaceAll("\\", "/")
for (const searchRoot of searchRoots) {
const index = normalizedPath.indexOf(searchRoot)
if (index === -1) continue
return normalizedPath.slice(index + searchRoot.length)
}
}
export function configEntryNameFromPath(relativePath: string, prefixes: string[]) {
const candidate = stripPrefix(relativePath, prefixes) ?? path.basename(relativePath)
export function configEntryNameFromPath(filePath: string, searchRoots: string[]) {
const candidate = sliceAfterMatch(filePath, searchRoots) ?? path.basename(filePath)
const ext = path.extname(candidate)
return ext.length ? candidate.slice(0, -ext.length) : candidate
}
@@ -15,7 +15,6 @@ export class Service extends ConfigService.Service<Service>()("@opencode/Runtime
autoShare: bool("OPENCODE_AUTO_SHARE"),
pure: bool("OPENCODE_PURE"),
disableDefaultPlugins: bool("OPENCODE_DISABLE_DEFAULT_PLUGINS"),
diffViewer: bool("OPENCODE_DIFF_VIEWER"),
disableChannelDb: bool("OPENCODE_DISABLE_CHANNEL_DB"),
disableEmbeddedWebUi: bool("OPENCODE_DISABLE_EMBEDDED_WEB_UI"),
disableExternalSkills: bool("OPENCODE_DISABLE_EXTERNAL_SKILLS"),
+1
View File
@@ -0,0 +1 @@
README.md
@@ -29,10 +29,7 @@ import { normalizeForSnapshot, PATH_SEP } from "../../lib/snapshot"
function normalize(text: string): string {
return normalizeForSnapshot(text, {
pathReplacements: [
// Mixed-case [A-Za-z0-9] because node's mkdtemp suffix is mixed-case
// (the harness now uses FileSystem.makeTempDirectoryScoped under the
// hood). A `[a-z0-9]+` regex would leave uppercase chars trailing.
[new RegExp(`<TMPDIR>${PATH_SEP}oc-cli-[A-Za-z0-9]+`, "g"), "<HOME>"],
[new RegExp(`<TMPDIR>${PATH_SEP}oc-cli-[a-z0-9]+`, "g"), "<HOME>"],
[/\s+\[string\] \[default: "<HOME>"\]/g, ' [string] [default: "<HOME>"]'],
],
})
@@ -124,7 +121,9 @@ describe("opencode CLI help-text snapshots", () => {
expect(normalize(result.stderr)).toMatchSnapshot(`opencode ${argv.join(" ")} --help`)
}
if (failures.length > 0) {
throw new Error(`Help text failed for:\n ${failures.join("\n ")}`)
// Keep the failure in the Effect channel — symmetric with the
// Effect.fail inside the partition above, not a defect.
yield* Effect.fail(new Error(`Help text failed for:\n ${failures.join("\n ")}`))
}
}),
180_000,
@@ -359,73 +359,6 @@ describe("run entry body", () => {
})
})
test("renders command-only bash starts without the shell header", () => {
expect(
entryBody(
toolCommit({
tool: "bash",
phase: "start",
toolState: "running",
text: "running shell",
state: {
status: "running",
input: {
command: "ls",
},
time: { start: 1 },
},
}),
),
).toEqual({
type: "text",
content: "$ ls",
})
})
test("renders direct shell commits without a synthetic shell header", () => {
expect(
entryBody(
commit({
kind: "tool",
text: "running shell",
phase: "start",
source: "tool",
tool: "bash",
partID: "shell:call-1",
toolState: "running",
shell: {
callID: "call-1",
command: "pwd",
},
}),
),
).toEqual({
type: "text",
content: "$ pwd",
})
expect(
entryBody(
commit({
kind: "tool",
text: "/tmp/demo\n",
phase: "progress",
source: "tool",
tool: "bash",
partID: "shell:call-1",
toolState: "completed",
shell: {
callID: "call-1",
command: "pwd",
},
}),
),
).toEqual({
type: "text",
content: "\n/tmp/demo",
})
})
test("falls back to patch summary when apply_patch has no visible diff items", () => {
expect(
entryBody(

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