import { children, createMemo, createSignal, For, getOwner, runWithOwner, Show, untrack, type JSX } from "solid-js" import { createStore } from "solid-js/store" import { createLatest, usePlugin, type IconName } from "@opencode/plugin/gui" import { choiceLabel, choiceValue, Glyph, profileChoices, type Choice } from "./choices" import { advancedOpen, unvettedSource, verdict } from "./settings-view" import { SiteChooser } from "./site-chooser" import type definition from "./index" import { createProfileJobs, type JobMessage } from "./jobs" import type { ExtensionCompatibility, InstallResult, ProfileExtension, ProfileSource } from "./profile/ipc" import { displayHost } from "./host-display" import { BrowserSites } from "./site-permissions" import { Dialog, DialogBody, DialogFooter, DialogHeader, DialogTitleGroup } from "@opencode/ui/dialog" import { MenuScroll } from "@opencode/ui/menu-scroll" import { showToast } from "@opencode/ui/toast" import type { Job } from "./jobs-machine" /** * Settings › Browser: importing from another browser, the extensions the profile runs and whether links open in the * pane; then, under Advanced, sharing with remote servers, the agent's pages, the cookie-file import, site permissions * and stored data. Every action goes through the jobs machine, so one runs at a time and * each says how it ended beside the control that started it. */ export default function BrowserSettings(props: { target?: string }) { const ctx = usePlugin() const ui = ctx.ui const desktop = ctx.desktop const preferences = ctx.stores.preferences // How each browser's import ended, by choice, kept while the page is open so every row keeps its own answer. const [results, setResults] = createSignal>(new Map()) // Advanced is closed until the person opens it, which this device remembers; a settings search that lands on one of // its rows shows it open as the page arrives. After that the person's own toggle wins: the search's target stays set // for the whole visit, so the one they closed it over no longer opens it. const [closedOver, setClosedOver] = createSignal() const advanced = () => advancedOpen(preferences.value.advanced, props.target === closedOver() ? undefined : props.target) const jobs = createProfileJobs({ cookies: true, finished(finished) { const job = finished.job const message = jobs.describe(finished) if (job.type !== "import-browser" || !message) return setResults((current) => new Map(current).set(resultKey(job.source, job.profile), message)) }, }) const choices = createMemo(() => profileChoices(jobs.sources())) const blocked = () => !jobs.available() || jobs.running() !== undefined // Imported sign-ins that cannot be saved would be gone at the next start. const unsaved = () => jobs.unsaved() !== undefined // The file import and the sign-out say how they ended in their own rows. const fileMessage = () => (jobs.last()?.job.type === "import-file" ? jobs.describe(jobs.last()) : undefined) const clearMessage = () => (jobs.last()?.job.type === "clear" ? jobs.describe(jobs.last()) : undefined) const pickFile = async () => { const [file] = (await desktop?.pick({ title: ctx.t("settings.import.file.pick"), extensions: ["txt", "json"] })) ?? [] if (file) jobs.start({ type: "import-file", path: file }) } // The dialog's import is one of this page's jobs, whose row says how it ended, so the dialog goes with the page. const owner = getOwner() const chooseSites = (choice: Choice) => runWithOwner(owner, () => ctx.dialogs.open((dialog) => dialog.close()} />), ) const addExtension = () => ctx.dialogs.open((dialog) => dialog.close()} />) // The browser pane, its profile and its extensions exist only in the desktop app, which is fixed for the page's life. if (!desktop) return ( {ctx.t("settings.unavailable")}} /> ) // What most people come for is first: bring sign-ins, add extensions, and where links open. The rest waits in // one closed "Advanced" section. return ( {(message) => ( {message().text} } /> )} {(choice, index) => ( 1 ? choice.profile.name : undefined} keep message={ jobs.importing(choice) ? jobs.notice() : results().get(resultKey(choice.source.id, choice.profile.id)) } /> } > {/* One action: its dialog brings everything, or lets the person choose sites. */} chooseSites(choice)}> {ctx.t("settings.import.open")} )} {ctx.t("settings.import.none")}} /> {ctx.t("settings.extensions.note")}} > {(extension) => ( jobs.start({ type: "enable", id: extension.id, enabled })} onRemove={() => jobs.start({ type: "remove", id: extension.id })} /> )} {ctx.t("settings.extensions.add")} preferences.set({ ...preferences.value, links })} /> {/* A section heading like the others, with no card, that is a button: the whole row opens and closes it. The chevron ends the line's text, as in the other disclosures: after the summary while closed, after the heading while open. A summary too long for the window is cut short, so the chevron never wraps or leaves its word. */}

preferences.update((draft) => { draft.agentPages = agentPages }) } /> } > void pickFile()} > {ctx.t("settings.import.file.action")} {(value) => <>{ctx.plural("settings.cookies.count", value().cookies)}} } > {(message) => message().text} } > jobs.start({ type: "clear" })} > {ctx.t("settings.cookies.clear")}
) } /** The Advanced heading's chevron: faint at rest, full strength under the pointer and on keyboard focus. */ const ADVANCED_CHEVRON = "flex shrink-0 opacity-40 group-hover:opacity-100 group-focus-visible:opacity-100 rtl:-scale-x-100" /** * The decisions the user kept for sites, one row per site and feature: the site, the feature under it, and its setting * beside a remove button, in columns that line up whatever the names' length. */ function SitePermissionsSection() { const ctx = usePlugin() const ui = ctx.ui const live = ctx.use(BrowserSites) const client = () => { const current = live() return current.status === "active" ? current.value : undefined } const decisions = () => client()?.state()?.decisions ?? [] // The end of a long host is the site's own domain: shown whole, wrapping, never cut off at the end. const site = (origin: string) => displayHost(origin) || origin const failed = () => showToast({ title: ctx.t("settings.sites.failed") }) return ( {ctx.t("settings.sites.note")}} > {ctx.t("settings.sites.none")}} />}> {(decision, index) => { const names = () => ({ permission: ctx.t(`settings.sites.permission.${decision.permission}`), site: site(decision.origin), }) return ( {site(decision.origin)} {names().permission} } >
void client()?.set({ origin: decision.origin, permission: decision.permission, setting }).catch(failed) } /> void client()?.remove({ origin: decision.origin, permission: decision.permission }).catch(failed) } />
) }}
) } /** A site permission's setting keeps one width whatever it says, so the remove buttons line up. */ const SETTING_COLUMN = "w-28" function ExtensionRow(props: { extension: ProfileExtension disabled: boolean onEnable: (enabled: boolean) => void onRemove: () => void }) { const ctx = usePlugin() const ui = ctx.ui const message = () => { const text = props.extension.changed ? ctx.t("settings.extensions.changed") : props.extension.error return text ? { text, error: true } : undefined } return ( } message={message()} /> } >
) } type InstallJob = Extract type PendingReview = { readonly job: InstallJob; readonly result: Extract } /** * The Add an extension dialog: a store link, or the extensions another Chromium browser has. Loading one from a folder * of its source files is for people who build extensions, so it waits in a closed "For developers" disclosure at the * end. When an install needs confirmation, the dialog switches cleanly into a minimal confirmation step. */ function AddExtension(props: { sources: readonly ProfileSource[]; close: () => void }) { const ctx = usePlugin() const ui = ctx.ui const desktop = ctx.desktop // The page that opened it already lists the browsers. const jobs = createProfileJobs({ profile: false }) const [form, setForm] = createStore<{ link: string; profile?: string }>({ link: "" }) const [approving, setApproving] = createSignal() const choices = createMemo(() => profileChoices(props.sources.filter((source) => source.engine === "chromium"))) const selected = createMemo(() => choices().find((choice) => choiceValue(choice) === form.profile) ?? choices()[0]) const blocked = () => !jobs.available() || jobs.running() !== undefined // Read again after each job, so an extension just added shows as added. const available = createLatest( () => { const choice = selected() const key = jobs.key() return choice && key ? `${key}\n${choiceValue(choice)}` : undefined }, (_value, signal) => { const choice = untrack(selected) return choice ? jobs.browserExtensions(choice.source.id, choice.profile.id, signal) : Promise.resolve([]) }, ) const installing = (id: string) => { const job = jobs.running() return job?.type === "install-browser" && job.id === id } // The install that stopped for the user to confirm: its extension will not work here, or asks for access the user // has not seen yet. const confirming = (): PendingReview | undefined => { const last = jobs.last() if (last?.outcome.type !== "installed") return undefined if (last.outcome.result.type !== "unsupported" && last.outcome.result.type !== "review") return undefined const job = last.job const result = last.outcome.result return job.type === "install-store" || job.type === "install-folder" || job.type === "install-browser" ? { job, result } : undefined } // Keeps the confirmation view steady while the approval token is being installed, then returns to the picker. const runningApproval = (): PendingReview | undefined => { const running = jobs.running() const current = approving() return running && "token" in running && running.token && current && running.token === current.result.token ? current : undefined } const review = () => confirming() ?? runningApproval() const approve = (pending: PendingReview) => { setApproving(pending) jobs.start({ ...pending.job, token: pending.result.token }) } const addLink = () => { const url = form.link.trim() if (!url || blocked()) return jobs.start({ type: "install-store", url }) setForm("link", "") } const pickFolder = async () => { const [folder] = (await desktop?.pick({ title: ctx.t("settings.extensions.folder.pick"), directory: true })) ?? [] if (folder) jobs.start({ type: "install-folder", path: folder }) } return ( } > {(pending) => ( {ctx.t("settings.extensions.confirm.title", { name: pending().result.name })} } /> )}
setForm("link", link)} onSubmit={addLink} class="min-w-0 flex-1" /> {ctx.t("settings.extensions.add")}
{/* The scroller spans the dialog's inset so its thumb sits beside the rows and focus rings stay unclipped. */}
{(message) => (
{message().text}

} > {(compatibility) => ( }>

{message().text}

)}
)}
{(choice) => (
{ctx.t("settings.extensions.browser.title")} 1}> {/* Pulls the inline select's 4px end padding out without shrinking its trigger width. */}
({ value: choiceValue(item), label: choiceLabel(item) }))} value={choiceValue(choice())} onChange={(profile) => setForm("profile", profile)} />
{ctx.t("settings.extensions.browser.empty")} } > {(item) => ( } > jobs.start({ type: "install-browser", source: choice().source.id, profile: choice().profile.id, id: item.id, }) } > {item.installed ? ctx.t("settings.extensions.added") : item.compatibility.level === "unsupported" ? ctx.t("settings.extensions.anyway") : ctx.t("settings.extensions.add")} )}
)}
{ctx.t("settings.developers")}

{ctx.t("settings.extensions.folder.description")}

void pickFolder()} > {ctx.t("settings.extensions.folder.action")}
} > {(pending) => }
{ctx.t("settings.extensions.done")} } > {(pending) => ( <> jobs.dismiss()}> {ctx.t("common.cancel")} approve(pending())} > {pending().result.type === "unsupported" ? ctx.t("settings.extensions.anyway") : ctx.t("settings.extensions.add")} )}
) } /** A disclosure's summary: the app's own chevron in place of the browser's marker. */ const DISCLOSURE = "flex w-fit cursor-pointer list-none items-center gap-1 text-[13px] leading-[var(--line-height-base)] [&::-webkit-details-marker]:hidden" /** * Row buttons share one width whatever they say, so the right-hand action column stays flush. */ const ACTION_COLUMN = "min-w-24 shrink-0 justify-center" /** Extension row: icon and name (with optional compatibility note underneath) take full width; action stays on the right. */ function ChoiceRow(props: { image?: string; name: string; note?: JSX.Element; children: JSX.Element }) { return (
{props.name} {props.note}
{props.children}
) } function InstallReview(props: { review: PendingReview["result"]; job: InstallJob }) { const ctx = usePlugin() const ui = ctx.ui const source = () => props.review.store ?? (props.job.type === "install-browser" ? "browser" : "folder") const unvetted = () => unvettedSource(source()) const hasCompatWarning = () => props.review.compatibility.level !== "supported" const empty = () => props.review.access.length === 0 && !props.review.added && !hasCompatWarning() && !unvetted() && !props.review.replaces return (
0}>

{ctx.t("extensions.access.title")}

    {(item) =>
  • {ctx.t(`extensions.access.${item}`)}
  • }
{/* An update that asks for more stays in sight: the person agreed to less. */} {(added) => (

{ctx.t("review.new")}

    {(item) => (
  • {ctx.t( item === "someSites" || item === "allSites" ? "review.changeSites" : `extensions.access.${item}`, )}
  • )}
    item === "someSites" || item === "allSites")} >
  • {ctx.t("review.moreSites")}
  • {ctx.t("review.morePermissions")}
)}
}>
{(key) =>

{ctx.t(key())}

}
{(name) =>

{ctx.t("settings.extensions.replaces", { name: name() })}

}

{ctx.t("review.summary.none")}

) } /** * Whether an extension works in this browser, in one plain line with a status dot: it works, it may not fully work, * or it probably will not. */ function Verdict(props: { level: ExtensionCompatibility["level"] }) { const ctx = usePlugin() return (

) } /** * A row's subject: its icon, its name, and under it a detail or what the last action on it did; with `keep`, the * detail stays before the message, so rows of one browser still say which profile each is. */ function Identity(props: { image?: string fallback: IconName name: string detail?: string note?: JSX.Element keep?: boolean message?: JobMessage }) { const note = children(() => props.note) return ( {props.name} {(detail) => {detail()}} {note()} } > {(message) => ( {(detail) => {detail()} · } {message().text} )} ) } /** * A quiet note for an extension that partly works here and a warning for one that will not, with what does not work * on hover or focus; nothing for one that works. */ function CompatibilityNote(props: { compatibility: ExtensionCompatibility; stacked?: boolean }) { const ctx = usePlugin() const ui = ctx.ui const level = () => props.compatibility.level return ( {(shown) => ( // The tooltip wraps its trigger in an element of its own, so this one keeps the note compact in its row. }> {ctx.t(shown() === "partial" ? "review.partial" : `extensions.compat.${shown()}`)} )} ) } /** Why an extension will not work here, and each part of it that does not. */ function CompatibilityDetails(props: { compatibility: ExtensionCompatibility }) { const ctx = usePlugin() return ( {(cause) => {ctx.t(`extensions.compat.cause.${cause()}`)}} 0}> {ctx.t("extensions.compat.missing")} {(feature) => {ctx.t(`extensions.compat.feature.${feature}`)}} ) } function Muted(props: { children: JSX.Element }) { return ( {props.children} ) } /** A line under a section's list, for what applies to every row in it. */ function Note(props: { children: JSX.Element }) { return

{props.children}

} function resultKey(source: string, profile: string) { return `${source}\n${profile}` }