refactor(app): delete unused shell, workspace, composer, and stories modules (#58237)

This commit is contained in:
Kit Langton
2026-10-22 15:02:33 -07:00
committed by GitHub
Unverified
parent 0131c2955b
commit 80e5e9687c
17 changed files with 141 additions and 993 deletions
+3 -8
View File
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test"
import { getCursorPosition, getTextLength, setCursorPosition } from "./dom"
import { setCursorPosition } from "./dom"
const br = () => document.createElement("br")
@@ -15,11 +15,10 @@ const pill = () => {
// Breaks count as one character and zero-width characters count as none.
// Each caret row is [position, anchor child index or null for the container, anchor offset].
test.each<{ name: string; nodes: () => Node[]; length: number; caret: [number, number | null, number][] }>([
test.each<{ name: string; nodes: () => Node[]; caret: [number, number | null, number][] }>([
{
name: "zero-width characters",
nodes: () => [text("ab\u200B"), br(), text("cd")],
length: 5,
caret: [
[3, 2, 0],
[4, 2, 1],
@@ -28,7 +27,6 @@ test.each<{ name: string; nodes: () => Node[]; length: number; caret: [number, n
{
name: "pills and breaks",
nodes: () => [text("ab"), pill(), br(), text("cd")],
length: 10,
caret: [
[2, 0, 2],
[7, null, 2],
@@ -38,24 +36,21 @@ test.each<{ name: string; nodes: () => Node[]; length: number; caret: [number, n
{
name: "blank lines",
nodes: () => [text("a"), br(), br(), text("b")],
length: 4,
caret: [
[2, null, 2],
[3, 3, 0],
],
},
])("maps text length and the caret across $name", (row) => {
])("maps the caret across $name", (row) => {
const container = document.createElement("div")
container.append(...row.nodes())
document.body.appendChild(container)
expect(getTextLength(container)).toBe(row.length)
row.caret.forEach(([position, child, offset]) => {
setCursorPosition(container, position)
const selection = window.getSelection()
expect(selection?.anchorNode).toBe(child === null ? container : container.childNodes[child]!)
expect(selection?.anchorOffset).toBe(offset)
expect(getCursorPosition(container)).toBe(position)
})
container.remove()
-27
View File
@@ -4,33 +4,6 @@ function getNodeLength(node: Node): number {
return (node.textContent ?? "").replace(/\u200B/g, "").length
}
export function getTextLength(node: Node): number {
if (node.nodeType === Node.TEXT_NODE) return (node.textContent ?? "").replace(/\u200B/g, "").length
if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR") return 1
let length = 0
for (const child of Array.from(node.childNodes)) {
length += getTextLength(child)
}
return length
}
export function getCursorPosition(parent: HTMLElement): number {
const selection = window.getSelection()
if (!selection || selection.rangeCount === 0) return 0
const range = selection.getRangeAt(0)
if (!parent.contains(range.startContainer)) return 0
const preCaretRange = range.cloneRange()
preCaretRange.selectNodeContents(parent)
preCaretRange.setEnd(range.startContainer, range.startOffset)
return getTextLength(preCaretRange.cloneContents())
}
export function setCursorPosition(parent: HTMLElement, position: number) {
let remaining = position
let node = parent.firstChild
+1 -101
View File
@@ -1,109 +1,9 @@
import { Tooltip } from "@opencode/ui/tooltip"
import { Icon } from "@opencode/ui/icon"
import { Spinner } from "@opencode/ui/spinner"
import { useLanguage } from "@/runtime/i18n/language"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import {
children,
createEffect,
createMemo,
createSignal,
type JSXElement,
onMount,
type ParentProps,
Show,
} from "solid-js"
import { type ServerConnection, serverName } from "@/runtime/server/registry"
import { Show } from "solid-js"
import type { ServerHealth } from "@/runtime/server/health"
interface ServerRowProps extends ParentProps {
conn: ServerConnection.Any
status?: ServerHealth
class?: string
nameClass?: string
versionClass?: string
dimmed?: boolean
badge?: JSXElement
showCredentials?: boolean
}
export function ServerRow(props: ServerRowProps) {
const [truncated, setTruncated] = createSignal(false)
let nameRef: HTMLSpanElement | undefined
let versionRef: HTMLSpanElement | undefined
const name = createMemo(() => serverName(props.conn))
const check = () => {
const nameTruncated = nameRef ? nameRef.scrollWidth > nameRef.clientWidth : false
const versionTruncated = versionRef ? versionRef.scrollWidth > versionRef.clientWidth : false
setTruncated(nameTruncated || versionTruncated)
}
createEffect(() => {
name()
props.conn.http.url
props.status?.version
queueMicrotask(check)
})
onMount(() => {
if (typeof ResizeObserver !== "function") return
createResizeObserver([nameRef, versionRef], check)
check()
})
const tooltipValue = () => (
<span class="flex items-center gap-2">
<span>{serverName(props.conn, true)}</span>
<Show when={props.status?.version}>
<span class="text-text-invert-weak">v{props.status?.version}</span>
</Show>
</span>
)
const badge = children(() => props.badge)
return (
<Tooltip
appearance="standard"
class="flex-1 min-w-0"
value={tooltipValue()}
contentStyle={{ "max-width": "none", "white-space": "nowrap" }}
placement="top-start"
inactive={!truncated() && !props.conn.displayName}
>
<div class={props.class} classList={{ "opacity-50": props.dimmed }}>
<div class="flex flex-col items-start min-w-0 w-full">
<div class="flex flex-row items-center gap-2 min-w-0 w-full">
<span ref={nameRef} class={`${props.nameClass ?? "truncate"} min-w-0`}>
{name()}
</span>
<Show
when={badge()}
fallback={
<Show when={props.status?.version}>
<span
ref={versionRef}
class={`${props.versionClass ?? "text-text-weak text-14-regular truncate"} min-w-0`}
>
v{props.status?.version}
</span>
</Show>
}
>
{(badge) => badge()}
</Show>
</div>
<Show when={props.showCredentials && props.conn.type === "http" && props.conn.http.password}>
<span class="text-text-weak">••••••••</span>
</Show>
</div>
{props.children}
</div>
</Tooltip>
)
}
export function ServerHealthIndicator(props: {
health?: ServerHealth
connecting?: boolean
@@ -1,49 +0,0 @@
import "@/index.css"
import { render } from "solid-js/web"
import { DialogProvider } from "@opencode/ui/context/dialog"
import { ThemeProvider, useTheme } from "@opencode/ui/theme"
import { LanguageProvider, UiI18nBridge } from "@/runtime/i18n/language"
import { motionTuning } from "@opencode/ui/motion-tuning"
import { Experiments } from "./activity-chips.stories"
function Preview() {
useTheme().setColorScheme("dark")
return <Experiments.render />
}
render(
() => (
<ThemeProvider>
<LanguageProvider locale="en">
<UiI18nBridge>
<DialogProvider>
<Preview />
</DialogProvider>
</UiI18nBridge>
</LanguageProvider>
</ThemeProvider>
),
document.getElementById("root")!,
)
function choose(mode: string, corners: string) {
for (const [id, value] of [
["activity.chip", mode],
["activity.chip.corners", corners],
]) {
const knob = motionTuning.list().find((item) => item.id === id)
if (!knob || knob.kind !== "choice" || !knob.options.includes(value))
throw new Error(`Invalid choice ${id}: ${value}`)
motionTuning.set(knob, value)
}
}
declare global {
interface Window {
chipExperiment: typeof choose
}
}
window.chipExperiment = choose
@@ -1,53 +0,0 @@
/** Coordinates focus restoration and actions that must run after menu content unmounts. */
export function createMenuDismissController(content: () => HTMLElement | undefined) {
let restoreTrigger = true
let pending: (() => void) | undefined
const run = () => {
const callback = pending
pending = undefined
callback?.()
}
return {
/** Allows the menu primitive to restore focus to its trigger when closing. */
allowTriggerRestore() {
restoreTrigger = true
},
/** Keeps focus at its current or next destination instead of returning it to the trigger. */
preventTriggerRestore() {
restoreTrigger = false
},
/** Applies the current restoration policy during the menu primitive's close-focus event. */
onCloseAutoFocus(event: Event) {
if (restoreTrigger) return
event.preventDefault()
const focused = document.activeElement
// Kobalte's dropdown focuses its trigger after this handler anyway, so undo that before the next paint.
queueMicrotask(() => {
const trigger = document.activeElement
if (trigger !== focused && trigger instanceof HTMLElement) trigger.blur()
run()
})
},
/** Runs an action after the menu unmounts and its focus-close work has settled. */
afterClose(callback: () => void) {
pending = callback
const complete = () => {
if (!pending) return
if (content()?.isConnected) {
requestAnimationFrame(complete)
return
}
requestAnimationFrame(() => requestAnimationFrame(run))
}
requestAnimationFrame(complete)
},
}
}
@@ -1,143 +0,0 @@
const editableSelector = "input, textarea, select, [contenteditable=''], [contenteditable='true']"
export function handleDocumentSearchKeydown(
input: HTMLInputElement | undefined,
event: KeyboardEvent,
inputValue: string,
setInputValue: (value: string) => void,
) {
if (!input) return false
if (event.defaultPrevented || event.isComposing) return false
if (event.target === input) return false
if (event.target instanceof Element && event.target.closest(editableSelector)) return false
const action = searchKeyAction(event)
if (!action) return false
event.preventDefault()
event.stopPropagation()
input.focus()
const start = input.selectionStart ?? inputValue.length
const end = input.selectionEnd ?? inputValue.length
if (action.type === "selectAll") {
input.setSelectionRange(0, inputValue.length)
return true
}
if (action.type === "move") {
moveSelection(input, inputValue, action.delta, event.shiftKey)
return true
}
if (action.type === "home") {
setBoundarySelection(input, start, 0, event.shiftKey)
return true
}
if (action.type === "end") {
setBoundarySelection(input, start, inputValue.length, event.shiftKey)
return true
}
if (action.type === "deleteBackward") {
if (start !== end)
return updateValue(input, inputValue.slice(0, start) + inputValue.slice(end), start, setInputValue)
if (start === 0) return true
return updateValue(input, inputValue.slice(0, start - 1) + inputValue.slice(end), start - 1, setInputValue)
}
if (action.type === "deleteForward") {
if (start !== end)
return updateValue(input, inputValue.slice(0, start) + inputValue.slice(end), start, setInputValue)
if (end === inputValue.length) return true
return updateValue(input, inputValue.slice(0, start) + inputValue.slice(end + 1), start, setInputValue)
}
return updateValue(
input,
inputValue.slice(0, start) + action.value + inputValue.slice(end),
start + action.value.length,
setInputValue,
)
}
function searchKeyAction(event: KeyboardEvent) {
if ((event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "a") {
return { type: "selectAll" } as const
}
if (event.ctrlKey || event.metaKey || event.altKey) return undefined
if (event.key.length === 1) return { type: "insert", value: event.key } as const
if (event.key === "Backspace") return { type: "deleteBackward" } as const
if (event.key === "Delete") return { type: "deleteForward" } as const
if (event.key === "ArrowLeft") return { type: "move", delta: -1 } as const
if (event.key === "ArrowRight") return { type: "move", delta: 1 } as const
if (event.key === "Home") return { type: "home" } as const
if (event.key === "End") return { type: "end" } as const
return undefined
}
function moveSelection(input: HTMLInputElement, inputValue: string, delta: -1 | 1, extend: boolean) {
const start = input.selectionStart ?? inputValue.length
const end = input.selectionEnd ?? inputValue.length
if (!extend && start !== end) {
const caret = delta < 0 ? start : end
input.setSelectionRange(caret, caret)
return
}
if (!extend) {
const caret = Math.max(0, Math.min(inputValue.length, start + delta))
input.setSelectionRange(caret, caret)
return
}
const backward = input.selectionDirection === "backward"
const anchor = backward ? end : start
const focus = backward ? start : end
const next = Math.max(0, Math.min(inputValue.length, focus + delta))
input.setSelectionRange(Math.min(anchor, next), Math.max(anchor, next), next < anchor ? "backward" : "forward")
}
function setBoundarySelection(input: HTMLInputElement, anchor: number, focus: number, extend: boolean) {
if (!extend) {
input.setSelectionRange(focus, focus)
return
}
input.setSelectionRange(Math.min(anchor, focus), Math.max(anchor, focus), focus < anchor ? "backward" : "forward")
}
function updateValue(input: HTMLInputElement, value: string, caret: number, setInputValue: (value: string) => void) {
input.value = value
setInputValue(value)
input.setSelectionRange(caret, caret)
return true
}
+99 -102
View File
@@ -7,7 +7,6 @@ import { Titlebar } from "@/shell/titlebar/titlebar"
import { usePlatform } from "@/runtime/platform/platform"
import { ToastRegion } from "@/shell/notifications/toast"
import { UploadToastHost } from "@/composer/attachments/uploads"
import { TitlebarRightProvider } from "@/shell/titlebar/right-slot"
import { useSettingsSurface } from "@/settings/surface"
import { useSettings } from "@/settings/model"
import { ExtensionServerCover } from "@/runtime/extension/server-shell"
@@ -133,108 +132,106 @@ export default function Layout(props: ParentProps) {
const dragInset = () => windowDragEnabled(platform) && !mobile()
return (
<TitlebarRightProvider>
<div
class="relative bg-v2-background-bg-deep flex-1 min-h-0 min-w-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text"
style={{
// Mobile panels only need clearance for their outer border.
"--shell-inline-inset": mobile() ? "1px" : "8px",
// A bottom mobile titlebar leaves main's top edge to the safe area. Native Windows chrome supplies the gap;
// retain outer-outline clearance.
"--shell-top-inset": bottomTitlebar()
? "0px"
: platform.platform === "desktop" && platform.os === "windows"
? "1px"
: "8px",
"--shell-bottom-inset": bottomTitlebar()
? "8px"
: "max(0px, calc(8px - var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))))",
}}
>
<Titlebar verticalTabs={verticalTabs() ? { mount: state.tabsMount } : undefined} />
<div class="relative flex flex-1 min-h-0 min-w-0 flex-row">
{/* The empty inset above the panels moves the window, as the titlebar does. */}
<Show when={dragInset()}>
<div
data-slot="shell-drag-inset"
aria-hidden="true"
class="absolute inset-x-0 top-0 h-[var(--shell-top-inset,8px)]"
data-tauri-drag-region
/>
</Show>
<Show when={verticalTabs()}>
<aside
id="vertical-tabs-sidebar"
data-slot="vertical-tabs-sidebar"
data-state={preferences.appearance.sidebarOpen() ? "open" : "closed"}
data-peek={peek.shown() ? "" : undefined}
style={{ "--sidebar-peek-width": `${state.tabsWidth}px` }}
ref={(element) => setState("tabsAside", element)}
class="relative z-10 h-full min-h-0 shrink-0"
>
{/* Skipped rather than display: none or inert, so neither direction restyles the sidebar's contents and
a reopen reuses their layout. */}
<div
ref={(element) => setState("tabsPanel", element)}
data-slot="vertical-tabs-panel"
class="absolute inset-0 overflow-hidden [contain:layout_style_paint]"
classList={{ "[content-visibility:hidden]": !sidebarMotion.present() && !peek.shown() }}
// Under James the sidebar keeps its landing width (start edge held) while the layout moves.
style={{ width: sidebarMotion.pinned() ? `${state.tabsWidth}px` : undefined }}
>
<div
ref={(element) => setState("tabsMount", element)}
data-slot="vertical-tabs-mount"
class="absolute inset-y-0 end-0 contain-strict will-change-[opacity] flex min-h-0 flex-col bg-v2-background-bg-deep pe-0.5 ps-2.5 pb-[var(--shell-bottom-inset,8px)] pt-[var(--shell-top-inset,8px)]"
style={{
width: `${state.tabsWidth}px`,
"padding-bottom": "max(10px, var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)))",
}}
/>
</div>
{/* Takes the pointer while the sidebar closes, without restyling its contents. */}
<div
class="absolute inset-0 z-20"
classList={{ hidden: preferences.appearance.sidebarOpen() || !sidebarMotion.present() }}
/>
<Show when={preferences.appearance.sidebarOpen()}>
<ResizeHandle
class="-end-1"
direction="horizontal"
size={state.tabsWidth}
min={120}
max={640}
onResize={(width) => setState("tabsWidth", width)}
/>
</Show>
</aside>
</Show>
{/* Size containment collapses percentage-height descendants in WebKit. */}
<main
class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-content"
// Under James the sidebar stays at its landing box during a flight, under the content as the layout moves.
classList={{ "z-20": sidebarMotion.pinned() }}
style={{
"padding-top": bottomTitlebar() ? "env(safe-area-inset-top, 0px)" : "0px",
"padding-bottom":
bottomTitlebar() || settings.active()
? "0px"
: "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))",
"--settings-bottom-inset": bottomTitlebar()
? "40px"
: "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))",
}}
<div
class="relative bg-v2-background-bg-deep flex-1 min-h-0 min-w-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text"
style={{
// Mobile panels only need clearance for their outer border.
"--shell-inline-inset": mobile() ? "1px" : "8px",
// A bottom mobile titlebar leaves main's top edge to the safe area. Native Windows chrome supplies the gap;
// retain outer-outline clearance.
"--shell-top-inset": bottomTitlebar()
? "0px"
: platform.platform === "desktop" && platform.os === "windows"
? "1px"
: "8px",
"--shell-bottom-inset": bottomTitlebar()
? "8px"
: "max(0px, calc(8px - var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))))",
}}
>
<Titlebar verticalTabs={verticalTabs() ? { mount: state.tabsMount } : undefined} />
<div class="relative flex flex-1 min-h-0 min-w-0 flex-row">
{/* The empty inset above the panels moves the window, as the titlebar does. */}
<Show when={dragInset()}>
<div
data-slot="shell-drag-inset"
aria-hidden="true"
class="absolute inset-x-0 top-0 h-[var(--shell-top-inset,8px)]"
data-tauri-drag-region
/>
</Show>
<Show when={verticalTabs()}>
<aside
id="vertical-tabs-sidebar"
data-slot="vertical-tabs-sidebar"
data-state={preferences.appearance.sidebarOpen() ? "open" : "closed"}
data-peek={peek.shown() ? "" : undefined}
style={{ "--sidebar-peek-width": `${state.tabsWidth}px` }}
ref={(element) => setState("tabsAside", element)}
class="relative z-10 h-full min-h-0 shrink-0"
>
<ExtensionServerCover>
<Suspense>{props.children}</Suspense>
</ExtensionServerCover>
</main>
<CollapsedSidebarToggle />
</div>
<ExtensionSlot at="window.bottom" input={{}} />
<ToastRegion />
<UploadToastHost />
{/* Skipped rather than display: none or inert, so neither direction restyles the sidebar's contents and
a reopen reuses their layout. */}
<div
ref={(element) => setState("tabsPanel", element)}
data-slot="vertical-tabs-panel"
class="absolute inset-0 overflow-hidden [contain:layout_style_paint]"
classList={{ "[content-visibility:hidden]": !sidebarMotion.present() && !peek.shown() }}
// Under James the sidebar keeps its landing width (start edge held) while the layout moves.
style={{ width: sidebarMotion.pinned() ? `${state.tabsWidth}px` : undefined }}
>
<div
ref={(element) => setState("tabsMount", element)}
data-slot="vertical-tabs-mount"
class="absolute inset-y-0 end-0 contain-strict will-change-[opacity] flex min-h-0 flex-col bg-v2-background-bg-deep pe-0.5 ps-2.5 pb-[var(--shell-bottom-inset,8px)] pt-[var(--shell-top-inset,8px)]"
style={{
width: `${state.tabsWidth}px`,
"padding-bottom": "max(10px, var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)))",
}}
/>
</div>
{/* Takes the pointer while the sidebar closes, without restyling its contents. */}
<div
class="absolute inset-0 z-20"
classList={{ hidden: preferences.appearance.sidebarOpen() || !sidebarMotion.present() }}
/>
<Show when={preferences.appearance.sidebarOpen()}>
<ResizeHandle
class="-end-1"
direction="horizontal"
size={state.tabsWidth}
min={120}
max={640}
onResize={(width) => setState("tabsWidth", width)}
/>
</Show>
</aside>
</Show>
{/* Size containment collapses percentage-height descendants in WebKit. */}
<main
class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-content"
// Under James the sidebar stays at its landing box during a flight, under the content as the layout moves.
classList={{ "z-20": sidebarMotion.pinned() }}
style={{
"padding-top": bottomTitlebar() ? "env(safe-area-inset-top, 0px)" : "0px",
"padding-bottom":
bottomTitlebar() || settings.active()
? "0px"
: "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))",
"--settings-bottom-inset": bottomTitlebar()
? "40px"
: "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))",
}}
>
<ExtensionServerCover>
<Suspense>{props.children}</Suspense>
</ExtensionServerCover>
</main>
<CollapsedSidebarToggle />
</div>
</TitlebarRightProvider>
<ExtensionSlot at="window.bottom" input={{}} />
<ToastRegion />
<UploadToastHost />
</div>
)
}
@@ -1,27 +0,0 @@
import { describe, expect, test } from "bun:test"
import { createRoot } from "solid-js"
import { createTitlebarRightSlot } from "./right-slot"
describe("titlebar right slot", () => {
test("selects the latest owner and restores the previous owner after overlap", () => {
createRoot((dispose) => {
const slot = createTitlebarRightSlot()
const committed = slot.createRegistration()
committed.register()
expect(committed.active()).toBe(true)
const shadow = slot.createRegistration()
shadow.register()
expect(committed.active()).toBe(false)
expect(shadow.active()).toBe(true)
shadow.unregister()
expect(committed.active()).toBe(true)
expect(shadow.active()).toBe(false)
committed.unregister()
expect(committed.active()).toBe(false)
dispose()
})
})
})
@@ -1,76 +0,0 @@
import { createContext, onCleanup, onMount, Show, useContext, type ParentProps } from "solid-js"
import { createStore } from "solid-js/store"
import { Portal } from "solid-js/web"
type Registration = {
active: () => boolean
register: () => void
unregister: () => void
}
type TitlebarRightSlot = {
createRegistration: () => Registration
mount: () => HTMLElement | undefined
setMount: (mount: HTMLElement) => void
}
const TitlebarRightContext = createContext<TitlebarRightSlot>()
export function TitlebarRightProvider(props: ParentProps) {
return (
<TitlebarRightContext.Provider value={createTitlebarRightSlot()}>{props.children}</TitlebarRightContext.Provider>
)
}
export function createTitlebarRightSlot(): TitlebarRightSlot {
const [store, setStore] = createStore<{ mount?: HTMLElement; registrations: symbol[] }>({ registrations: [] })
return {
mount: () => store.mount,
setMount: (mount) => setStore("mount", mount),
createRegistration() {
const id = Symbol()
return {
active: () => store.registrations.at(-1) === id,
register: () => setStore("registrations", (items) => [...items, id]),
unregister: () => setStore("registrations", (items) => items.filter((item) => item !== id)),
}
},
}
}
export function TitlebarRightMount(props: { vertical?: boolean }) {
const slot = useTitlebarRightSlot()
return (
<div
ref={slot.setMount}
id="opencode-titlebar-right"
class={props.vertical ? "flex w-full shrink-0 flex-col" : "flex shrink-0 items-center justify-end gap-0"}
/>
)
}
export function TitlebarRight(props: ParentProps) {
const slot = useTitlebarRightSlot()
const registration = slot.createRegistration()
onMount(() => {
registration.register()
onCleanup(registration.unregister)
})
return (
<Show when={registration.active() && slot.mount()} keyed>
{(mount) => <Portal mount={mount}>{props.children}</Portal>}
</Show>
)
}
function useTitlebarRightSlot() {
const slot = useContext(TitlebarRightContext)
if (!slot) throw new Error("TitlebarRight must be used within TitlebarRightProvider")
return slot
}
@@ -26,7 +26,6 @@ import { ServerConnection } from "@/runtime/server/registry"
import { tabKey, useTabs } from "@/shell/tabs/tabs"
import type { ComposerState } from "@/composer/persistence"
import "./titlebar.css"
import { TitlebarRightMount } from "@/shell/titlebar/right-slot"
import { MobileDrawer, MobileDrawerContent, MobileDrawerLabel, MobileDrawerTrigger } from "@/shell/mobile-drawer"
import { sessionTabTitle } from "./tab-title"
import { SessionTabAvatar } from "@/shell/layout/session-tab-avatar"
@@ -877,7 +876,6 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
<Show when={!props.verticalTabs}>
<div class="relative z-20 flex shrink-0 items-center justify-end gap-0 overflow-visible">
<TitlebarItems items={titlebarItems} />
<TitlebarRightMount />
</div>
</Show>
</div>
@@ -3,7 +3,6 @@ import {
absoluteTreePath,
activeTreeNavigation,
nextSuggestionIndex,
nextTreeScrollTop,
pickerFileSearchQuery,
pickerMode,
selectedTreePath,
@@ -113,12 +112,32 @@ test.each([
["relative input", pickerAbsoluteInput("src", "C:/Users/luke", "C:/Users/luke/repo"), "C:/Users/luke/repo/src"],
["file search", pickerFileSearchQuery("/home/luke/repos", "/home/luke/repos/src/in", "/home/luke"), "src/in"],
["file search", pickerFileSearchQuery("/home/luke", "~/repos/op", "/home/luke"), "repos/op"],
["recent short 2-level tilde", shortenPickerRecentPath("/home/luke/Developer/opencode", "/home/luke"), "~/Developer/opencode"],
["recent deep tilde", shortenPickerRecentPath("/home/luke/workspaces/anomalyco/opencode/packages/app", "/home/luke"), "~/…/packages/app"],
["recent short 2-level root", shortenPickerRecentPath("/workspace/billing-api", "/home/luke"), "/workspace/billing-api"],
["recent deep root", shortenPickerRecentPath("/srv/clients/acme/services/payments-gateway", "/home/luke"), "/srv/…/services/payments-gateway"],
[
"recent short 2-level tilde",
shortenPickerRecentPath("/home/luke/Developer/opencode", "/home/luke"),
"~/Developer/opencode",
],
[
"recent deep tilde",
shortenPickerRecentPath("/home/luke/workspaces/anomalyco/opencode/packages/app", "/home/luke"),
"~/…/packages/app",
],
[
"recent short 2-level root",
shortenPickerRecentPath("/workspace/billing-api", "/home/luke"),
"/workspace/billing-api",
],
[
"recent deep root",
shortenPickerRecentPath("/srv/clients/acme/services/payments-gateway", "/home/luke"),
"/srv/…/services/payments-gateway",
],
["recent short Windows", shortenPickerRecentPath("C:/OpenCode/NewProject", ""), "C:\\OpenCode\\NewProject"],
["recent deep Windows", shortenPickerRecentPath("C:/Users/luke/work/acme/repo", "C:/Users/luke"), "C:\\…\\acme\\repo"],
[
"recent deep Windows",
shortenPickerRecentPath("C:/Users/luke/work/acme/repo", "C:/Users/luke"),
"C:\\…\\acme\\repo",
],
])("uses the selected server path format for %s: %p", (_name, actual, expected) => {
expect(actual).toBe(expected)
})
@@ -440,14 +459,6 @@ test.each([
expect(activeTreeNavigation(request, current)).toBe(expected)
})
test.each([
[100, 40, 140],
[10, -40, 0],
[290, 40, 300],
])("bridged wheel scrolling from %p by %p clamps to %p", (current, delta, expected) => {
expect(nextTreeScrollTop(current, delta, 500, 200)).toBe(expected)
})
test("wraps autocomplete keyboard navigation", () => {
expect(nextSuggestionIndex(-1, 1, 4)).toBe(0)
expect(nextSuggestionIndex(3, 1, 4)).toBe(0)
@@ -219,10 +219,6 @@ export function createPriorityTaskQueue<T>(concurrency: number) {
return { schedule, promote }
}
export function nextTreeScrollTop(current: number, delta: number, scrollHeight: number, clientHeight: number) {
return Math.min(Math.max(0, scrollHeight - clientHeight), Math.max(0, current + delta))
}
export function nextSuggestionIndex(current: number, delta: -1 | 1, count: number) {
if (count === 0) return -1
@@ -257,7 +253,7 @@ export function selectedTreePath(root: string, path: string, mode: "directory" |
return directory ? nativePickerPath(absoluteTreePath(root, path)) : undefined
}
export function nativePickerPath(path: string) {
function nativePickerPath(path: string) {
const value = trimPickerPath(path)
if (/^[A-Za-z]:\//.test(value) || value.startsWith("//")) return value.replaceAll("/", "\\")
@@ -275,7 +271,7 @@ export function cleanPickerInput(value: string) {
return first.replace(/[\u0000-\u001F\u007F]/g, "").trim()
}
export function normalizePickerPath(input: string) {
function normalizePickerPath(input: string) {
const value = input.replaceAll("\\", "/")
if (value.startsWith("//") && !value.startsWith("///")) return "//" + value.slice(2).replace(/\/+/g, "/")
@@ -283,7 +279,7 @@ export function normalizePickerPath(input: string) {
return value.replace(/\/+/g, "/")
}
export function normalizePickerDrive(input: string) {
function normalizePickerDrive(input: string) {
const value = normalizePickerPath(input)
if (/^[A-Za-z]:$/.test(value)) return value + "/"
@@ -291,7 +287,7 @@ export function normalizePickerDrive(input: string) {
return value
}
export function trimPickerPath(input: string) {
function trimPickerPath(input: string) {
const value = normalizePickerDrive(input)
if (value === "/" || value === "//" || /^[A-Za-z]:\/$/.test(value)) return value
@@ -299,7 +295,7 @@ export function trimPickerPath(input: string) {
return value.replace(/\/+$/, "")
}
export function joinPickerPath(base: string | undefined, relative: string) {
function joinPickerPath(base: string | undefined, relative: string) {
const root = trimPickerPath(base ?? "")
const path = trimPickerPath(relative).replace(/^\/+/, "")
-117
View File
@@ -1,117 +0,0 @@
import { Icon } from "@opencode/ui/icon"
import { Menu } from "@opencode/ui/menu"
import { getFilename } from "@opencode/util/path"
import { createMemo, For, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
export function WorkspaceSubmenu(props: {
directories: string[]
selected?: string
disabled?: boolean
onSelect: (directory: string) => void
onViewAll?: () => void
}) {
const language = useLanguage()
const [store, setStore] = createStore({ search: "", holdSearchFocus: false })
let input: HTMLInputElement | undefined
let list: HTMLDivElement | undefined
const searchable = () => props.directories.length >= 10
const directories = createMemo(() => {
const query = store.search.trim().toLowerCase()
return props.directories.filter((directory) => getFilename(directory).toLowerCase().includes(query))
})
const focusSearch = () => {
if (!searchable()) return
setStore("holdSearchFocus", true)
input?.focus({ preventScroll: true })
}
return (
<Menu.Sub
gutter={0}
overlap
overflowPadding={24}
onOpenChange={(open) => {
if (!open) setStore({ search: "", holdSearchFocus: false })
}}
>
<Menu.SubTrigger
onClick={focusSearch}
onKeyDown={(event) => {
if (["ArrowRight", "ArrowLeft", "Enter", " "].includes(event.key)) focusSearch()
}}
>
<Icon name="outline-worktree" />
<span class="min-w-0 flex-1 truncate">{language.t("session.new.workspace.existingLabel")}</span>
</Menu.SubTrigger>
<Menu.Portal>
<Menu.SubContent
data-slot="workspace-submenu"
class="max-h-[min(320px,calc(100dvh-48px))] w-[200px] overflow-hidden"
// Kobalte autofocuses a submenu's content or first item a tick after it opens. Send that focus back to the
// search field until the user moves the pointer into the submenu or arrows out of the field.
onFocusIn={(event) => {
if (store.holdSearchFocus && event.target !== input) input?.focus({ preventScroll: true })
}}
oncapture:pointermove={() => setStore("holdSearchFocus", false)}
>
<Show when={searchable()}>
<div class="flex h-7 shrink-0 items-center gap-2 rounded-sm ps-3 pe-2 text-v2-icon-icon-muted">
<Icon name="magnifying-glass" size="small" class="shrink-0" />
<input
ref={input}
value={store.search}
placeholder={language.t("session.new.workspace.search.placeholder")}
aria-label={language.t("session.new.workspace.search.placeholder")}
class="h-7 min-w-0 flex-1 border-0 bg-transparent text-[13px] font-[440] leading-text-compact tracking-[-0.04px] text-v2-text-text-base outline-none placeholder:text-v2-text-text-faint"
onInput={(event) => setStore("search", event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault()
event.stopPropagation()
setStore("holdSearchFocus", false)
const items = list?.querySelectorAll<HTMLElement>('[role="menuitem"]:not([data-disabled])')
items?.[event.key === "ArrowDown" ? 0 : items.length - 1]?.focus()
return
}
if (["Escape", "Enter"].includes(event.key)) return
event.stopPropagation()
}}
/>
</div>
</Show>
<div ref={list} data-slot="workspace-submenu-list" class="min-h-0 overflow-y-auto overscroll-contain">
<For each={directories()}>
{(directory) => (
<Menu.Item disabled={props.disabled} onSelect={() => props.onSelect(directory)}>
<Icon name="outline-worktree" />
<span class="min-w-0 flex-1 truncate">{getFilename(directory)}</span>
<Show when={props.selected === directory}>
<Icon name="check" size="small" class="shrink-0" />
</Show>
</Menu.Item>
)}
</For>
<Show when={store.search.trim() && directories().length === 0}>
<div class="px-3 py-4 text-center text-[13px] font-[440] leading-5 text-v2-text-text-muted">
{language.t("session.new.workspace.search.empty")}
</div>
</Show>
</div>
<Show when={props.onViewAll}>
<Menu.Separator class="h-[0.5px] shrink-0" />
<Menu.Item onSelect={() => props.onViewAll?.()}>
<span class="min-w-0 flex-1 truncate">{language.t("common.viewAll")}</span>
</Menu.Item>
</Show>
</Menu.SubContent>
</Menu.Portal>
</Menu.Sub>
)
}
+8 -27
View File
@@ -9,8 +9,6 @@ import { marks } from "../lifecycle/marks"
const MAX_LOG_AGE_DAYS = 7
const TAIL_LINES = 1000
const EXPORT_WINDOW = 24 * 60 * 60 * 1000
const MAX_EXPORT_FILE_SIZE = 50 * 1024 * 1024
@@ -77,10 +75,9 @@ const nativeLogger = Logger.make((options) => {
}
const messages = Array.isArray(options.message) ? options.message : [options.message]
log.scope(safeLogName(scope))[methods[options.logLevel]](
...messages,
...(Object.keys(context).length === 0 ? [] : [context]),
)
log
.scope(safeLogName(scope))
[methods[options.logLevel]](...messages, ...(Object.keys(context).length === 0 ? [] : [context]))
} catch {
// Logging must not interrupt application work.
}
@@ -137,9 +134,9 @@ function startNetLog(path: Path.Path) {
const target = path.join(run, "network.netlog")
netLogPath = target
return Effect.tryPromise(() => netLog.startLogging(target, { captureMode: "default", maxFileSize: NET_LOG_SIZE })).pipe(
Effect.tap(() => scoped("network", Effect.logInfo("net log started", { path: target }))),
)
return Effect.tryPromise(() =>
netLog.startLogging(target, { captureMode: "default", maxFileSize: NET_LOG_SIZE }),
).pipe(Effect.tap(() => scoped("network", Effect.logInfo("net log started", { path: target }))))
}
function exportDebugLogsEffect(fs: FileSystem.FileSystem, path: Path.Path) {
@@ -175,9 +172,7 @@ function exportDebugLogsEffect(fs: FileSystem.FileSystem, path: Path.Path) {
Effect.ensuring(
restartNetLog
? startNetLog(path).pipe(
Effect.catch((error) =>
scoped("network", Effect.logWarning("failed to restart net log", { error })),
),
Effect.catch((error) => scoped("network", Effect.logWarning("failed to restart net log", { error }))),
)
: Effect.void,
),
@@ -185,18 +180,6 @@ function exportDebugLogsEffect(fs: FileSystem.FileSystem, path: Path.Path) {
})
}
export const tail = Effect.fn("DesktopLogging.tail")(function* () {
const fs = yield* FileSystem.FileSystem
return yield* Effect.gen(function* () {
const path = log.transports.file.getFile().path
const contents = yield* fs.readFileString(path)
const lines = contents.split("\n")
return lines.slice(Math.max(0, lines.length - TAIL_LINES)).join("\n")
}).pipe(Effect.orElseSucceed(() => ""))
})
function initRunDirectory(fs: FileSystem.FileSystem, path: Path.Path) {
root = path.join(app.getPath("userData"), "logs")
run = path.join(root, stamp())
@@ -258,9 +241,7 @@ function manifest(path: Path.Path) {
function serverLogRoots(path: Path.Path) {
const xdgData = process.env.XDG_DATA_HOME || path.join(homedir(), ".local", "share")
return [
...new Set([path.join(xdgData, "opencode", "log"), path.join(app.getPath("userData"), "opencode", "log")]),
]
return [...new Set([path.join(xdgData, "opencode", "log"), path.join(app.getPath("userData"), "opencode", "log")])]
}
type Entry = { name: string; path: string; offset: number } | { name: string; data: Uint8Array }
@@ -1,29 +0,0 @@
const provider = {
all: [
{
id: "anthropic",
models: {
"claude-3-7-sonnet": {
id: "claude-3-7-sonnet",
name: "Claude 3.7 Sonnet",
cost: { input: 1, output: 1 },
},
},
},
],
connected: ["anthropic"],
default: { anthropic: "claude-3-7-sonnet" },
}
export function useQueryOptions() {
return {
agents: (directory: string) => ({
queryKey: [directory, "agents"],
queryFn: async () => [],
}),
providers: (directory: string | null) => ({
queryKey: [directory, "providers"],
queryFn: async () => provider,
}),
}
}
@@ -1,208 +0,0 @@
import { chromium, expect } from "@playwright/test"
import { mkdir, rm } from "node:fs/promises"
import path from "node:path"
import { build } from "vite"
import solid from "vite-plugin-solid"
import tailwind from "@tailwindcss/vite"
import type {} from "../../app/src/session/composer/activity-chips.fixture"
// Production components and the story server's service mocks, bundled without a dev server.
const out = path.resolve("captures/chip-orb-flag")
const verify = process.argv.includes("--verify-only")
const root = path.resolve("packages/stories/node_modules/.cache/chip-orb-proof")
const mocks = path.resolve("packages/stories/mocks")
await mkdir(out, { recursive: true })
await mkdir(root, { recursive: true })
await Bun.write(
path.join(root, "index.html"),
`<div id="root"></div><script type="module" src="${path.resolve("packages/app/src/session/composer/activity-chips.fixture.tsx")}"></script>`,
)
await build({
configFile: false,
root,
publicDir: path.resolve("packages/app/public"),
plugins: [solid(), tailwind()],
resolve: {
dedupe: ["solid-js", "solid-js/web", "@solidjs/meta", "@tanstack/solid-query"],
alias: [
{ find: "@solidjs/router", replacement: path.join(mocks, "solid-router.tsx") },
...Object.entries({
"providers/models/selection": "context/local.ts",
"workspaces/files/model": "context/file.ts",
"shell/state/layout": "context/layout.ts",
"workspaces/location": "context/location.ts",
"composer/comments": "context/comments.ts",
"shell/commands/command": "context/command.ts",
"runtime/platform/platform": "context/platform.ts",
"runtime/server/global-sync": "context/global-sync.ts",
"runtime/server/sync": "context/server-sync.ts",
"runtime/server/client": "context/server-sdk.ts",
"runtime/server/current": "context/server-current.ts",
"providers/catalog/providers": "hooks/use-providers.ts",
"providers/models/unpaid": "components/dialog-select-model-unpaid.tsx",
}).map(([find, file]) => ({ find: `@/${find}`, replacement: path.join(mocks, "app", file) })),
{ find: "@", replacement: path.resolve("packages/app/src") },
],
},
build: { outDir: "dist", minify: true },
worker: { format: "es" },
})
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch: (request) => {
const pathname = new URL(request.url).pathname
return new Response(Bun.file(path.join(root, "dist", pathname === "/" ? "index.html" : pathname)))
},
})
const browser = await chromium.launch()
const context = await browser.newContext({
viewport: { width: 1200, height: 800 },
deviceScaleFactor: 2,
recordVideo: verify ? undefined : { dir: path.join(out, "video"), size: { width: 1200, height: 800 } },
})
const page = await context.newPage()
const errors: string[] = []
const orbRequests: string[] = []
page.on("request", (request) => {
if (request.url().includes("css-agent-orb")) orbRequests.push(request.url())
})
page.on("pageerror", (error) => {
errors.push(error.message)
console.error(error.message)
})
try {
await page.goto(String(server.url))
const chip = page.locator('[data-slot="session-activity-chip"]')
await chip.waitFor({ timeout: 30_000 }).catch(async (error) => {
console.error(await page.locator("body").innerHTML())
throw error
})
await page.evaluate(() => document.fonts.ready.then(() => undefined))
await page.getByText("Chip corners", { exact: true }).waitFor()
const choose = (mode: string, corners: string) =>
page.evaluate(({ mode, corners }) => window.chipExperiment(mode, corners), { mode, corners })
const initial = await chip.evaluate((chip) => ({
transition: getComputedStyle(chip).transitionProperty,
duration: getComputedStyle(chip).transitionDuration,
orbs: document.querySelectorAll('[data-component="css-agent-orb"]').length,
animations: document
.getAnimations()
.filter((animation) => animation instanceof CSSAnimation && animation.animationName.startsWith("css-orb")).length,
}))
if (
initial.transition !== "all" ||
initial.duration !== "0.15s" ||
initial.orbs ||
initial.animations ||
orbRequests.length
)
throw new Error(`Default changed: ${JSON.stringify({ initial, orbRequests })}`)
const geometry = []
for (const mode of ["today", "orb"]) {
for (const corners of ["capsule", "composer"]) {
await choose(mode, corners)
if (mode === "orb") await chip.locator('[data-component="css-agent-orb"]').waitFor()
await expect(chip).toHaveCSS(
"border-top-left-radius",
mode === "today" ? "12px" : corners === "capsule" ? "9999px" : "10px",
)
geometry.push({
mode,
corners,
...(await page.evaluate(() => {
const chip = document.querySelector<HTMLElement>('[data-slot="session-activity-chip"]')!
const composer = document.querySelector<HTMLElement>('[data-component="composer"]')!
const rect = chip.getBoundingClientRect()
return {
height: rect.height,
radius: getComputedStyle(chip).borderTopLeftRadius,
composerRadius: getComputedStyle(composer).borderTopLeftRadius,
composerY: composer.getBoundingClientRect().y,
glyphOffset:
chip.querySelector('[data-slot="activity-glyph"]')!.getBoundingClientRect().x +
8 -
rect.x -
rect.height / 2,
orb: chip.dataset.orb,
}
})),
})
if (!verify) await page.screenshot({ path: path.join(out, `${mode}-${corners}.png`) })
}
}
await page.reload()
await chip.waitFor()
if ((await chip.getAttribute("data-orb")) !== "true") throw new Error("Choice did not persist")
await choose("today", "capsule")
await page.waitForTimeout(250)
if ((await chip.locator('[data-component="css-agent-orb"]').count()) !== 1)
throw new Error("Opted-in orb was unmounted")
const fade = await page.evaluate(async () => {
const chip = document.querySelector('[data-slot="session-activity-chip"]')!
const orb = chip.querySelector('[data-slot="activity-glyph-orb"]')!
const today = chip.querySelector('[data-slot="activity-glyph-today"]')!
window.chipExperiment("orb", "capsule")
const frames: number[][] = []
await new Promise<void>((resolve) => {
const frame = () => {
frames.push([Number(getComputedStyle(today).opacity), Number(getComputedStyle(orb).opacity)])
if (frames.length === 20) return resolve()
requestAnimationFrame(frame)
}
requestAnimationFrame(frame)
})
return frames
})
if (!fade.some(([a, b]) => a > 0 && b > 0) || fade.some(([a, b]) => a + b < 0.99))
throw new Error("Glyph swap popped or blanked")
if (!verify) await page.waitForTimeout(5000)
await page.evaluate(() => (document.documentElement.dataset.motion = "reduce"))
const explicitReduced = await chip
.locator('[data-component="css-agent-orb"]')
.evaluate((orb) => orb.getAnimations({ subtree: true }).length)
if (explicitReduced !== 0) throw new Error("Explicit reduced motion orb still animates")
await page.evaluate(() => delete document.documentElement.dataset.motion)
await page.emulateMedia({ reducedMotion: "reduce" })
const reduced = await chip
.locator('[data-component="css-agent-orb"]')
.evaluate((orb) => orb.getAnimations({ subtree: true }).length)
if (reduced !== 0) throw new Error("Reduced motion orb still animates")
if (!verify) await page.screenshot({ path: path.join(out, "reduced.png") })
await Bun.write(
path.join(out, verify ? "verification.json" : "proof.json"),
JSON.stringify({ initial, orbRequests, geometry, fade, reduced, explicitReduced, errors }, null, 2),
)
console.log(JSON.stringify({ initial, orbRequests, geometry, reduced, explicitReduced, errors }, null, 2))
if (errors.length) throw new Error(errors.join("\n"))
} finally {
const video = page.video()
await context.close()
await video?.saveAs(path.join(out, "real-time.webm"))
await browser.close()
server.stop()
await rm(root, { recursive: true, force: true })
}
if (!verify) {
const video = Bun.spawn(
[
"ffmpeg",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-i",
path.join(out, "real-time.webm"),
"-an",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
path.join(out, "real-time.mp4"),
],
{ stdout: "ignore", stderr: "inherit" },
)
if (await video.exited) throw new Error("Video encode failed")
}
-1
View File
@@ -56,7 +56,6 @@ export default defineConfig({
{ find: /^@\/composer\/comments$/, replacement: path.resolve(mocks, "app/context/comments.ts") },
{ find: /^@\/shell\/commands\/command$/, replacement: path.resolve(mocks, "app/context/command.ts") },
{ find: /^@\/runtime\/platform\/platform$/, replacement: path.resolve(mocks, "app/context/platform.ts") },
{ find: /^@\/runtime\/server\/global-sync$/, replacement: path.resolve(mocks, "app/context/global-sync.ts") },
{ find: /^@\/runtime\/server\/sync$/, replacement: path.resolve(mocks, "app/context/server-sync.ts") },
{ find: /^@\/runtime\/server\/client$/, replacement: path.resolve(mocks, "app/context/server-sdk.ts") },
{ find: /^@\/runtime\/server\/current$/, replacement: path.resolve(mocks, "app/context/server-current.ts") },