Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/app/src/context/open-file-path.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { createSimpleContext } from "@opencode-ai/ui/context"
import { usePlatform } from "@/context/platform"
import { openFilePath, type OpenFileInput } from "@/utils/open-file-path"

export const { use: useOpenFilePath, provider: OpenFilePathProvider } = createSimpleContext({
name: "OpenFilePath",
init: (props: { directory: string }) => {
const platform = usePlatform()

return {
open(input: OpenFileInput) {
return openFilePath({
directory: props.directory,
input,
platform,
})
},
}
},
})
48 changes: 3 additions & 45 deletions packages/app/src/pages/directory-layout.tsx
Original file line number Diff line number Diff line change
@@ -1,46 +1,10 @@
import { DataProvider } from "@opencode-ai/ui/context"
import { showToast } from "@opencode-ai/ui/toast"
import { base64Encode } from "@opencode-ai/util/encode"
import { useLocation, useNavigate, useParams } from "@solidjs/router"
import { useNavigate, useParams } from "@solidjs/router"
import { createEffect, createMemo, type ParentProps, Show } from "solid-js"
import { useLanguage } from "@/context/language"
import { LocalProvider } from "@/context/local"
import { SDKProvider } from "@/context/sdk"
import { SyncProvider, useSync } from "@/context/sync"
import { DirectoryProviders } from "@/pages/directory-providers"
import { decode64 } from "@/utils/base64"

function DirectoryDataProvider(props: ParentProps<{ directory: string }>) {
const location = useLocation()
const navigate = useNavigate()
const params = useParams()
const sync = useSync()
const slug = createMemo(() => base64Encode(props.directory))

createEffect(() => {
const next = sync.data.path.directory
if (!next || next === props.directory) return
const path = location.pathname.slice(slug().length + 1)
navigate(`/${base64Encode(next)}${path}${location.search}${location.hash}`, { replace: true })
})

createEffect(() => {
const id = params.id
if (!id) return
void sync.session.sync(id)
})

return (
<DataProvider
data={sync.data}
directory={props.directory}
onNavigateToSession={(sessionID: string) => navigate(`/${slug()}/session/${sessionID}`)}
onSessionHref={(sessionID: string) => `/${slug()}/session/${sessionID}`}
>
<LocalProvider>{props.children}</LocalProvider>
</DataProvider>
)
}

export default function Layout(props: ParentProps) {
const params = useParams()
const language = useLanguage()
Expand Down Expand Up @@ -71,13 +35,7 @@ export default function Layout(props: ParentProps) {

return (
<Show when={resolved()} keyed>
{(resolved) => (
<SDKProvider directory={() => resolved}>
<SyncProvider>
<DirectoryDataProvider directory={resolved}>{props.children}</DirectoryDataProvider>
</SyncProvider>
</SDKProvider>
)}
{(resolved) => <DirectoryProviders directory={resolved}>{props.children}</DirectoryProviders>}
</Show>
)
}
54 changes: 54 additions & 0 deletions packages/app/src/pages/directory-providers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { DataProvider } from "@opencode-ai/ui/context"
import { base64Encode } from "@opencode-ai/util/encode"
import { useLocation, useNavigate, useParams } from "@solidjs/router"
import { createEffect, createMemo, type ParentProps } from "solid-js"
import { LocalProvider } from "@/context/local"
import { OpenFilePathProvider, useOpenFilePath } from "@/context/open-file-path"
import { SDKProvider } from "@/context/sdk"
import { SyncProvider, useSync } from "@/context/sync"

function DirectoryData(props: ParentProps<{ directory: string }>) {
const location = useLocation()
const navigate = useNavigate()
const params = useParams()
const sync = useSync()
const slug = createMemo(() => base64Encode(props.directory))
const open = useOpenFilePath()

createEffect(() => {
const next = sync.data.path.directory
if (!next || next === props.directory) return
const path = location.pathname.slice(slug().length + 1)
navigate(`/${base64Encode(next)}${path}${location.search}${location.hash}`, { replace: true })
})

createEffect(() => {
const id = params.id
if (!id) return
void sync.session.sync(id)
})

return (
<DataProvider
data={sync.data}
directory={props.directory}
onNavigateToSession={(sessionID: string) => navigate(`/${slug()}/session/${sessionID}`)}
onSessionHref={(sessionID: string) => `/${slug()}/session/${sessionID}`}
onOpenFilePath={open.open}
>
<LocalProvider>{props.children}</LocalProvider>
</DataProvider>
)
}

export function DirectoryProviders(props: ParentProps<{ directory: string }>) {
return (
<SDKProvider directory={() => props.directory}>
<SyncProvider>
<OpenFilePathProvider directory={props.directory}>
<DirectoryData directory={props.directory}>{props.children}</DirectoryData>
</OpenFilePathProvider>
</SyncProvider>
</SDKProvider>
)
}
12 changes: 12 additions & 0 deletions packages/app/src/pages/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import { SessionSidePanel } from "@/pages/session/session-side-panel"
import { TerminalPanel } from "@/pages/session/terminal-panel"
import { useSessionCommands } from "@/pages/session/use-session-commands"
import { useSessionHashScroll } from "@/pages/session/use-session-hash-scroll"
import { useSessionOpenFile } from "@/pages/session/use-session-open-file"
import { Identifier } from "@/utils/id"
import { Persist, persisted } from "@/utils/persist"
import { extractPromptFromParts } from "@/utils/prompt"
Expand Down Expand Up @@ -958,12 +959,23 @@ export default function Page() {

const openReviewFile = createOpenReviewFile({
showAllFiles,
openReviewPanel,
tabForPath: file.tab,
openTab: tabs().open,
setActive: tabs().setActive,
getFile: file.get,
setSelectedLines: file.setSelectedLines,
onLineError: ({ path, line, max }) => {
showToast({
variant: "default",
title: "Line unavailable",
description: `${path}:${line} is out of range, opened line ${max} instead.`,
})
},
loadFile: file.load,
})

useSessionOpenFile(openReviewFile)
const changesOptions = ["session", "turn"] as const
const changesOptionsList = [...changesOptions]

Expand Down
50 changes: 49 additions & 1 deletion packages/app/src/pages/session/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,66 @@ describe("createOpenReviewFile", () => {
const calls: string[] = []
const openReviewFile = createOpenReviewFile({
showAllFiles: () => calls.push("show"),
openReviewPanel: () => calls.push("review"),
tabForPath: (path) => {
calls.push(`tab:${path}`)
return `file://${path}`
},
openTab: (tab) => calls.push(`open:${tab}`),
setActive: (tab) => calls.push(`active:${tab}`),
getFile: () => ({ content: { content: "one\ntwo" } }),
setSelectedLines: (path, range) => calls.push(`select:${path}:${range ? `${range.start}-${range.end}` : "none"}`),
loadFile: (path) => calls.push(`load:${path}`),
})

openReviewFile("src/a.ts")

expect(calls).toEqual(["show", "load:src/a.ts", "tab:src/a.ts", "open:file://src/a.ts", "active:file://src/a.ts"])
expect(calls).toEqual([
"tab:src/a.ts",
"show",
"review",
"load:src/a.ts",
"open:file://src/a.ts",
"active:file://src/a.ts",
"select:src/a.ts:none",
])
})

test("selects the requested line when provided", () => {
const calls: string[] = []
const openReviewFile = createOpenReviewFile({
showAllFiles: () => calls.push("show"),
openReviewPanel: () => calls.push("review"),
tabForPath: (path) => `file://${path}`,
openTab: () => calls.push("open"),
setActive: () => calls.push("active"),
getFile: () => ({ content: { content: "one\n".repeat(20) } }),
setSelectedLines: (_path, range) => calls.push(`select:${range?.start}-${range?.end}`),
loadFile: () => calls.push("load"),
})

openReviewFile("src/a.ts", 12)

expect(calls).toContain("select:12-12")
})

test("clamps out of range lines", () => {
const calls: string[] = []
const openReviewFile = createOpenReviewFile({
showAllFiles: () => undefined,
openReviewPanel: () => undefined,
tabForPath: (path) => `file://${path}`,
openTab: () => undefined,
setActive: () => undefined,
getFile: () => ({ content: { content: "one\ntwo" } }),
setSelectedLines: (_path, range) => calls.push(`select:${range?.start}-${range?.end}`),
onLineError: ({ line, max }) => calls.push(`warn:${line}->${max}`),
loadFile: () => undefined,
})

openReviewFile("src/a.ts", 12)

expect(calls).toEqual(["warn:12->2", "select:2-2"])
})
})

Expand Down
27 changes: 22 additions & 5 deletions packages/app/src/pages/session/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,36 @@ export const createOpenReviewFile = (input: {
tabForPath: (path: string) => string
openTab: (tab: string) => void
setActive: (tab: string) => void
openReviewPanel: () => void
setSelectedLines: (path: string, range: { start: number; end: number } | null) => void
getFile: (path: string) => { content?: { content?: unknown } } | undefined
onLineError?: (input: { path: string; line: number; max: number }) => void
loadFile: (path: string) => any | Promise<void>
}) => {
return (path: string) => {
const lines = (value: unknown) => {
if (typeof value === "string") return Math.max(1, value.split("\n").length - (value.endsWith("\n") ? 1 : 0))
if (Array.isArray(value)) return Math.max(1, value.length)
if (value == null) return 0
const text = String(value)
return Math.max(1, text.split("\n").length - (text.endsWith("\n") ? 1 : 0))
}

return (path: string, line?: number) => {
const tab = input.tabForPath(path)
batch(() => {
input.showAllFiles()
input.openReviewPanel()
const maybePromise = input.loadFile(path)
const open = () => {
const tab = input.tabForPath(path)
const openTab = () => {
const max = lines(input.getFile(path)?.content?.content)
const next = typeof line === "number" && max > 0 ? Math.max(1, Math.min(line, max)) : undefined
if (typeof line === "number" && max > 0 && next !== line) input.onLineError?.({ path, line, max })
input.openTab(tab)
input.setActive(tab)
input.setSelectedLines(path, next ? { start: next, end: next } : null)
}
if (maybePromise instanceof Promise) maybePromise.then(open)
else open()
if (maybePromise instanceof Promise) maybePromise.then(openTab)
else openTab()
})
}
}
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/pages/session/review-tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
SessionReviewCommentUpdate,
} from "@opencode-ai/ui/session-review"
import type { SelectedLineRange } from "@/context/file"
import { useOpenFilePath } from "@/context/open-file-path"
import { useSDK } from "@/context/sdk"
import { useLayout } from "@/context/layout"
import type { LineComment } from "@/context/comments"
Expand Down Expand Up @@ -45,6 +46,7 @@ export function SessionReviewTab(props: SessionReviewTabProps) {

const sdk = useSDK()
const layout = useLayout()
const open = useOpenFilePath()

const readFile = async (path: string) => {
return sdk.client.file
Expand Down Expand Up @@ -156,6 +158,7 @@ export function SessionReviewTab(props: SessionReviewTabProps) {
diffStyle={props.diffStyle}
onDiffStyleChange={props.onDiffStyleChange}
onViewFile={props.onViewFile}
onOpenFile={(file) => open.open({ path: file })}
focusedFile={props.focusedFile}
readFile={readFile}
onLineComment={props.onLineComment}
Expand Down
15 changes: 15 additions & 0 deletions packages/app/src/pages/session/use-session-open-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { onCleanup, onMount } from "solid-js"
import { OPEN_FILE_PATH_EVENT } from "@/utils/open-file-path"

export const useSessionOpenFile = (open: (path: string, line?: number) => void) => {
onMount(() => {
const onOpen = (event: Event) => {
const detail = (event as CustomEvent<{ path?: string; line?: number }>).detail
if (!detail?.path) return
open(detail.path, detail.line)
}

window.addEventListener(OPEN_FILE_PATH_EVENT, onOpen)
onCleanup(() => window.removeEventListener(OPEN_FILE_PATH_EVENT, onOpen))
})
}
33 changes: 33 additions & 0 deletions packages/app/src/utils/open-file-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { OpenFilePathFn } from "@opencode-ai/ui/context"
import { showToast } from "@opencode-ai/ui/toast"
import type { Platform } from "@/context/platform"

export type OpenFileInput = Parameters<OpenFilePathFn>[0]

export const OPEN_FILE_PATH_EVENT = "opencode:open-file-path"

export function dispatchOpenFilePath(input: OpenFileInput) {
window.dispatchEvent(new CustomEvent<OpenFileInput>(OPEN_FILE_PATH_EVENT, { detail: input }))
}

export function resolveOpenFilePath(dir: string, path: string) {
const file = path.replace(/^[\\/]+/, "")
const separator = dir.includes("\\") ? "\\" : "/"
return dir.endsWith(separator) ? dir + file : dir + separator + file
}

export async function openFilePath(opts: { directory: string; input: OpenFileInput; platform: Platform }) {
if (opts.platform.platform !== "desktop" || !opts.platform.openPath) {
dispatchOpenFilePath(opts.input)
return
}

await opts.platform.openPath(resolveOpenFilePath(opts.directory, opts.input.path)).catch((err) => {
showToast({
variant: "error",
title: "Open failed",
description: err instanceof Error ? err.message : String(err),
})
dispatchOpenFilePath(opts.input)
})
}
Loading
Loading