import { For, onCleanup, onMount, Show, Match, Switch, createMemo, createEffect, createSignal, on, type JSX, } from "solid-js" import { createMediaQuery } from "@solid-primitives/media" import { createResizeObserver } from "@solid-primitives/resize-observer" import { Dynamic } from "solid-js/web" import { useLocal } from "@/context/local" import { selectionFromLines, useFile, type FileSelection, type SelectedLineRange } from "@/context/file" import { createStore, produce } from "solid-js/store" import { PromptInput } from "@/components/prompt-input" import { SessionContextUsage } from "@/components/session-context-usage" import { IconButton } from "@opencode-ai/ui/icon-button" import { Button } from "@opencode-ai/ui/button" import { Icon } from "@opencode-ai/ui/icon" import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip" import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu" import { Dialog } from "@opencode-ai/ui/dialog" import { InlineInput } from "@opencode-ai/ui/inline-input" import { ResizeHandle } from "@opencode-ai/ui/resize-handle" import { Tabs } from "@opencode-ai/ui/tabs" import { Select } from "@opencode-ai/ui/select" import { useCodeComponent } from "@opencode-ai/ui/context/code" import { LineComment as LineCommentView, LineCommentEditor } from "@opencode-ai/ui/line-comment" import { SessionTurn } from "@opencode-ai/ui/session-turn" import { BasicTool } from "@opencode-ai/ui/basic-tool" import { createAutoScroll } from "@opencode-ai/ui/hooks" import { SessionReview } from "@opencode-ai/ui/session-review" import { Mark } from "@opencode-ai/ui/logo" import { QuestionDock } from "@/components/question-dock" import { DragDropProvider, DragDropSensors, DragOverlay, SortableProvider, closestCenter } from "@thisbeyond/solid-dnd" import type { DragEvent } from "@thisbeyond/solid-dnd" import { useSync } from "@/context/sync" import { useTerminal, type LocalPTY } from "@/context/terminal" import { useLayout } from "@/context/layout" import { Terminal } from "@/components/terminal" import { checksum, base64Encode } from "@opencode-ai/util/encode" import { findLast } from "@opencode-ai/util/array" import { useDialog } from "@opencode-ai/ui/context/dialog" import { DialogSelectFile } from "@/components/dialog-select-file" import FileTree from "@/components/file-tree" import { DialogSelectModel } from "@/components/dialog-select-model" import { DialogSelectMcp } from "@/components/dialog-select-mcp" import { DialogFork } from "@/components/dialog-fork" import { useCommand } from "@/context/command" import { useLanguage } from "@/context/language" import { useNavigate, useParams } from "@solidjs/router" import { UserMessage } from "@opencode-ai/sdk/v2" import type { FileDiff } from "@opencode-ai/sdk/v2" import { useSDK } from "@/context/sdk" import { usePrompt } from "@/context/prompt" import { useComments, type LineComment } from "@/context/comments" import { extractPromptFromParts } from "@/utils/prompt" import { ConstrainDragYAxis, getDraggableId } from "@/utils/solid-dnd" import { usePermission } from "@/context/permission" import { decode64 } from "@/utils/base64" import { showToast } from "@opencode-ai/ui/toast" import { SessionHeader, SessionContextTab, SortableTab, FileVisual, SortableTerminalTab, NewSessionView, } from "@/components/session" import { navMark, navParams } from "@/utils/perf" import { same } from "@/utils/same" type DiffStyle = "unified" | "split" type HandoffSession = { prompt: string files: Record } const HANDOFF_MAX = 40 const handoff = { session: new Map(), terminal: new Map(), } const touch = (map: Map, key: K, value: V) => { map.delete(key) map.set(key, value) while (map.size > HANDOFF_MAX) { const first = map.keys().next().value if (first === undefined) return map.delete(first) } } const setSessionHandoff = (key: string, patch: Partial) => { const prev = handoff.session.get(key) ?? { prompt: "", files: {} } touch(handoff.session, key, { ...prev, ...patch }) } interface SessionReviewTabProps { title?: JSX.Element empty?: JSX.Element diffs: () => FileDiff[] view: () => ReturnType["view"]> diffStyle: DiffStyle onDiffStyleChange?: (style: DiffStyle) => void onViewFile?: (file: string) => void onLineComment?: (comment: { file: string; selection: SelectedLineRange; comment: string; preview?: string }) => void comments?: LineComment[] focusedComment?: { file: string; id: string } | null onFocusedCommentChange?: (focus: { file: string; id: string } | null) => void focusedFile?: string onScrollRef?: (el: HTMLDivElement) => void classes?: { root?: string header?: string container?: string } } function StickyAddButton(props: { children: JSX.Element }) { const [stuck, setStuck] = createSignal(false) let button: HTMLDivElement | undefined createEffect(() => { const node = button if (!node) return const scroll = node.parentElement if (!scroll) return const handler = () => { const rect = node.getBoundingClientRect() const scrollRect = scroll.getBoundingClientRect() setStuck(rect.right >= scrollRect.right && scroll.scrollWidth > scroll.clientWidth) } scroll.addEventListener("scroll", handler, { passive: true }) const observer = new ResizeObserver(handler) observer.observe(scroll) handler() onCleanup(() => { scroll.removeEventListener("scroll", handler) observer.disconnect() }) }) return (
{props.children}
) } function SessionReviewTab(props: SessionReviewTabProps) { let scroll: HTMLDivElement | undefined let frame: number | undefined let pending: { x: number; y: number } | undefined const sdk = useSDK() const readFile = async (path: string) => { return sdk.client.file .read({ path }) .then((x) => x.data) .catch(() => undefined) } const restoreScroll = () => { const el = scroll if (!el) return const s = props.view().scroll("review") if (!s) return if (el.scrollTop !== s.y) el.scrollTop = s.y if (el.scrollLeft !== s.x) el.scrollLeft = s.x } const handleScroll = (event: Event & { currentTarget: HTMLDivElement }) => { pending = { x: event.currentTarget.scrollLeft, y: event.currentTarget.scrollTop, } if (frame !== undefined) return frame = requestAnimationFrame(() => { frame = undefined const next = pending pending = undefined if (!next) return props.view().setScroll("review", next) }) } createEffect( on( () => props.diffs().length, () => { requestAnimationFrame(restoreScroll) }, { defer: true }, ), ) onCleanup(() => { if (frame === undefined) return cancelAnimationFrame(frame) }) return ( { scroll = el props.onScrollRef?.(el) restoreScroll() }} onScroll={handleScroll} onDiffRendered={() => requestAnimationFrame(restoreScroll)} open={props.view().review.open()} onOpenChange={props.view().review.setOpen} classes={{ root: props.classes?.root ?? "pb-40", header: props.classes?.header ?? "px-6", container: props.classes?.container ?? "px-6", }} diffs={props.diffs()} diffStyle={props.diffStyle} onDiffStyleChange={props.onDiffStyleChange} onViewFile={props.onViewFile} focusedFile={props.focusedFile} readFile={readFile} onLineComment={props.onLineComment} comments={props.comments} focusedComment={props.focusedComment} onFocusedCommentChange={props.onFocusedCommentChange} /> ) } export default function Page() { const layout = useLayout() const local = useLocal() const file = useFile() const sync = useSync() const terminal = useTerminal() const dialog = useDialog() const codeComponent = useCodeComponent() const command = useCommand() const language = useLanguage() const params = useParams() const navigate = useNavigate() const sdk = useSDK() const prompt = usePrompt() const comments = useComments() const permission = usePermission() const permRequest = createMemo(() => { const sessionID = params.id if (!sessionID) return return sync.data.permission[sessionID]?.[0] }) const questionRequest = createMemo(() => { const sessionID = params.id if (!sessionID) return return sync.data.question[sessionID]?.[0] }) const blocked = createMemo(() => !!permRequest() || !!questionRequest()) const [ui, setUi] = createStore({ responding: false, pendingMessage: undefined as string | undefined, scrollGesture: 0, autoCreated: false, scroll: { overflow: false, bottom: true, }, }) createEffect( on( () => permRequest()?.id, () => setUi("responding", false), { defer: true }, ), ) const decide = (response: "once" | "always" | "reject") => { const perm = permRequest() if (!perm) return if (ui.responding) return setUi("responding", true) sdk.client.permission .respond({ sessionID: perm.sessionID, permissionID: perm.id, response }) .catch((err: unknown) => { const message = err instanceof Error ? err.message : String(err) showToast({ title: language.t("common.requestFailed"), description: message }) }) .finally(() => setUi("responding", false)) } const sessionKey = createMemo(() => `${params.dir}${params.id ? "/" + params.id : ""}`) const workspaceKey = createMemo(() => params.dir ?? "") const workspaceTabs = createMemo(() => layout.tabs(workspaceKey)) const tabs = createMemo(() => layout.tabs(sessionKey)) const view = createMemo(() => layout.view(sessionKey)) createEffect( on( () => params.id, (id, prev) => { if (!id) return if (prev) return const pending = layout.handoff.tabs() if (!pending) return if (Date.now() - pending.at > 60_000) { layout.handoff.clearTabs() return } if (pending.id !== id) return layout.handoff.clearTabs() if (pending.dir !== (params.dir ?? "")) return const from = workspaceTabs().tabs() if (from.all.length === 0 && !from.active) return const current = tabs().tabs() if (current.all.length > 0 || current.active) return const all = normalizeTabs(from.all) const active = from.active ? normalizeTab(from.active) : undefined tabs().setAll(all) tabs().setActive(active && all.includes(active) ? active : all[0]) workspaceTabs().setAll([]) workspaceTabs().setActive(undefined) }, { defer: true }, ), ) if (import.meta.env.DEV) { createEffect( on( () => [params.dir, params.id] as const, ([dir, id], prev) => { if (!id) return navParams({ dir, from: prev?.[1], to: id }) }, ), ) createEffect(() => { const id = params.id if (!id) return if (!prompt.ready()) return navMark({ dir: params.dir, to: id, name: "storage:prompt-ready" }) }) createEffect(() => { const id = params.id if (!id) return if (!terminal.ready()) return navMark({ dir: params.dir, to: id, name: "storage:terminal-ready" }) }) createEffect(() => { const id = params.id if (!id) return if (!file.ready()) return navMark({ dir: params.dir, to: id, name: "storage:file-view-ready" }) }) createEffect(() => { const id = params.id if (!id) return if (sync.data.message[id] === undefined) return navMark({ dir: params.dir, to: id, name: "session:data-ready" }) }) } const isDesktop = createMediaQuery("(min-width: 768px)") const centered = createMemo(() => isDesktop() && !view().reviewPanel.opened()) function normalizeTab(tab: string) { if (!tab.startsWith("file://")) return tab return file.tab(tab) } function normalizeTabs(list: string[]) { const seen = new Set() const next: string[] = [] for (const item of list) { const value = normalizeTab(item) if (seen.has(value)) continue seen.add(value) next.push(value) } return next } const openTab = (value: string) => { const next = normalizeTab(value) tabs().open(next) const path = file.pathFromTab(next) if (path) file.load(path) } createEffect(() => { const active = tabs().active() if (!active) return const path = file.pathFromTab(active) if (path) file.load(path) }) createEffect(() => { const current = tabs().all() if (current.length === 0) return const next = normalizeTabs(current) if (same(current, next)) return tabs().setAll(next) const active = tabs().active() if (!active) return if (!active.startsWith("file://")) return const normalized = normalizeTab(active) if (active === normalized) return tabs().setActive(normalized) }) const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined)) const diffs = createMemo(() => (params.id ? (sync.data.session_diff[params.id] ?? []) : [])) const reviewCount = createMemo(() => Math.max(info()?.summary?.files ?? 0, diffs().length)) const hasReview = createMemo(() => reviewCount() > 0) const revertMessageID = createMemo(() => info()?.revert?.messageID) const messages = createMemo(() => (params.id ? (sync.data.message[params.id] ?? []) : [])) const messagesReady = createMemo(() => { const id = params.id if (!id) return true return sync.data.message[id] !== undefined }) const historyMore = createMemo(() => { const id = params.id if (!id) return false return sync.session.history.more(id) }) const historyLoading = createMemo(() => { const id = params.id if (!id) return false return sync.session.history.loading(id) }) const [title, setTitle] = createStore({ draft: "", editing: false, saving: false, menuOpen: false, pendingRename: false, }) let titleRef: HTMLInputElement | undefined const errorMessage = (err: unknown) => { if (err && typeof err === "object" && "data" in err) { const data = (err as { data?: { message?: string } }).data if (data?.message) return data.message } if (err instanceof Error) return err.message return language.t("common.requestFailed") } createEffect( on( sessionKey, () => setTitle({ draft: "", editing: false, saving: false, menuOpen: false, pendingRename: false }), { defer: true }, ), ) const openTitleEditor = () => { if (!params.id) return setTitle({ editing: true, draft: info()?.title ?? "" }) requestAnimationFrame(() => { titleRef?.focus() titleRef?.select() }) } const closeTitleEditor = () => { if (title.saving) return setTitle({ editing: false, saving: false }) } const saveTitleEditor = async () => { const sessionID = params.id if (!sessionID) return if (title.saving) return const next = title.draft.trim() if (!next || next === (info()?.title ?? "")) { setTitle({ editing: false, saving: false }) return } setTitle("saving", true) await sdk.client.session .update({ sessionID, title: next }) .then(() => { sync.set( produce((draft) => { const index = draft.session.findIndex((s) => s.id === sessionID) if (index !== -1) draft.session[index].title = next }), ) setTitle({ editing: false, saving: false }) }) .catch((err) => { setTitle("saving", false) showToast({ title: language.t("common.requestFailed"), description: errorMessage(err), }) }) } async function archiveSession(sessionID: string) { const session = sync.session.get(sessionID) if (!session) return const sessions = sync.data.session ?? [] const index = sessions.findIndex((s) => s.id === sessionID) const nextSession = index === -1 ? undefined : (sessions[index + 1] ?? sessions[index - 1]) await sdk.client.session .update({ sessionID, time: { archived: Date.now() } }) .then(() => { sync.set( produce((draft) => { const index = draft.session.findIndex((s) => s.id === sessionID) if (index !== -1) draft.session.splice(index, 1) }), ) if (params.id !== sessionID) return if (session.parentID) { navigate(`/${params.dir}/session/${session.parentID}`) return } if (nextSession) { navigate(`/${params.dir}/session/${nextSession.id}`) return } navigate(`/${params.dir}/session`) }) .catch((err) => { showToast({ title: language.t("common.requestFailed"), description: errorMessage(err), }) }) } async function deleteSession(sessionID: string) { const session = sync.session.get(sessionID) if (!session) return false const sessions = (sync.data.session ?? []).filter((s) => !s.parentID && !s.time?.archived) const index = sessions.findIndex((s) => s.id === sessionID) const nextSession = index === -1 ? undefined : (sessions[index + 1] ?? sessions[index - 1]) const result = await sdk.client.session .delete({ sessionID }) .then((x) => x.data) .catch((err) => { showToast({ title: language.t("session.delete.failed.title"), description: errorMessage(err), }) return false }) if (!result) return false sync.set( produce((draft) => { const removed = new Set([sessionID]) const byParent = new Map() for (const item of draft.session) { const parentID = item.parentID if (!parentID) continue const existing = byParent.get(parentID) if (existing) { existing.push(item.id) continue } byParent.set(parentID, [item.id]) } const stack = [sessionID] while (stack.length) { const parentID = stack.pop() if (!parentID) continue const children = byParent.get(parentID) if (!children) continue for (const child of children) { if (removed.has(child)) continue removed.add(child) stack.push(child) } } draft.session = draft.session.filter((s) => !removed.has(s.id)) }), ) if (params.id !== sessionID) return true if (session.parentID) { navigate(`/${params.dir}/session/${session.parentID}`) return true } if (nextSession) { navigate(`/${params.dir}/session/${nextSession.id}`) return true } navigate(`/${params.dir}/session`) return true } function DialogDeleteSession(props: { sessionID: string }) { const title = createMemo(() => sync.session.get(props.sessionID)?.title ?? language.t("command.session.new")) const handleDelete = async () => { await deleteSession(props.sessionID) dialog.close() } return (
{language.t("session.delete.confirm", { name: title() })}
) } const emptyUserMessages: UserMessage[] = [] const userMessages = createMemo( () => messages().filter((m) => m.role === "user") as UserMessage[], emptyUserMessages, { equals: same }, ) const visibleUserMessages = createMemo( () => { const revert = revertMessageID() if (!revert) return userMessages() return userMessages().filter((m) => m.id < revert) }, emptyUserMessages, { equals: same, }, ) const lastUserMessage = createMemo(() => visibleUserMessages().at(-1)) createEffect( on( () => lastUserMessage()?.id, () => { const msg = lastUserMessage() if (!msg) return if (msg.agent) local.agent.set(msg.agent) if (msg.model) local.model.set(msg.model) }, ), ) const [store, setStore] = createStore({ activeDraggable: undefined as string | undefined, activeTerminalDraggable: undefined as string | undefined, expanded: {} as Record, messageId: undefined as string | undefined, turnStart: 0, mobileTab: "session" as "session" | "changes", changes: "session" as "session" | "turn", newSessionWorktree: "main", promptHeight: 0, }) const turnDiffs = createMemo(() => lastUserMessage()?.summary?.diffs ?? []) const reviewDiffs = createMemo(() => (store.changes === "session" ? diffs() : turnDiffs())) const renderedUserMessages = createMemo( () => { const msgs = visibleUserMessages() const start = store.turnStart if (start <= 0) return msgs if (start >= msgs.length) return emptyUserMessages return msgs.slice(start) }, emptyUserMessages, { equals: same, }, ) const newSessionWorktree = createMemo(() => { if (store.newSessionWorktree === "create") return "create" const project = sync.project if (project && sync.data.path.directory !== project.worktree) return sync.data.path.directory return "main" }) const activeMessage = createMemo(() => { if (!store.messageId) return lastUserMessage() const found = visibleUserMessages()?.find((m) => m.id === store.messageId) return found ?? lastUserMessage() }) const setActiveMessage = (message: UserMessage | undefined) => { setStore("messageId", message?.id) } function navigateMessageByOffset(offset: number) { const msgs = visibleUserMessages() if (msgs.length === 0) return const current = activeMessage() const currentIndex = current ? msgs.findIndex((m) => m.id === current.id) : -1 const targetIndex = currentIndex === -1 ? (offset > 0 ? 0 : msgs.length - 1) : currentIndex + offset if (targetIndex < 0 || targetIndex >= msgs.length) return if (targetIndex === msgs.length - 1) { resumeScroll() return } autoScroll.pause() scrollToMessage(msgs[targetIndex], "auto") } const kinds = createMemo(() => { const merge = (a: "add" | "del" | "mix" | undefined, b: "add" | "del" | "mix") => { if (!a) return b if (a === b) return a return "mix" as const } const normalize = (p: string) => p.replaceAll("\\\\", "/").replace(/\/+$/, "") const out = new Map() for (const diff of diffs()) { const file = normalize(diff.file) const kind = diff.status === "added" ? "add" : diff.status === "deleted" ? "del" : "mix" out.set(file, kind) const parts = file.split("/") for (const [idx] of parts.slice(0, -1).entries()) { const dir = parts.slice(0, idx + 1).join("/") if (!dir) continue out.set(dir, merge(out.get(dir), kind)) } } return out }) const emptyDiffFiles: string[] = [] const diffFiles = createMemo(() => diffs().map((d) => d.file), emptyDiffFiles, { equals: same }) const diffsReady = createMemo(() => { const id = params.id if (!id) return true if (!hasReview()) return true return sync.data.session_diff[id] !== undefined }) const idle = { type: "idle" as const } let inputRef!: HTMLDivElement let promptDock: HTMLDivElement | undefined let scroller: HTMLDivElement | undefined let content: HTMLDivElement | undefined const scrollGestureWindowMs = 250 let touchGesture: number | undefined const markScrollGesture = (target?: EventTarget | null) => { const root = scroller if (!root) return const el = target instanceof Element ? target : undefined const nested = el?.closest("[data-scrollable]") if (nested && nested !== root) return setUi("scrollGesture", Date.now()) } const hasScrollGesture = () => Date.now() - ui.scrollGesture < scrollGestureWindowMs createEffect(() => { sdk.directory const id = params.id if (!id) return sync.session.sync(id) }) createEffect(() => { if (!view().terminal.opened()) { setUi("autoCreated", false) return } if (!terminal.ready() || terminal.all().length !== 0 || ui.autoCreated) return terminal.new() setUi("autoCreated", true) }) createEffect( on( () => terminal.all().length, (count, prevCount) => { if (prevCount !== undefined && prevCount > 0 && count === 0) { if (view().terminal.opened()) { view().terminal.toggle() } } }, ), ) createEffect( on( () => terminal.active(), (activeId) => { if (!activeId || !view().terminal.opened()) return // Immediately remove focus if (document.activeElement instanceof HTMLElement) { document.activeElement.blur() } const wrapper = document.getElementById(`terminal-wrapper-${activeId}`) const element = wrapper?.querySelector('[data-component="terminal"]') as HTMLElement if (!element) return // Find and focus the ghostty textarea (the actual input element) const textarea = element.querySelector("textarea") as HTMLTextAreaElement if (textarea) { textarea.focus() return } // Fallback: focus container and dispatch pointer event element.focus() element.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true })) }, ), ) createEffect( on( () => visibleUserMessages().at(-1)?.id, (lastId, prevLastId) => { if (lastId && prevLastId && lastId > prevLastId) { setStore("messageId", undefined) } }, { defer: true }, ), ) const status = createMemo(() => sync.data.session_status[params.id ?? ""] ?? idle) createEffect( on( sessionKey, () => { setStore("messageId", undefined) setStore("expanded", {}) setStore("changes", "session") setUi("autoCreated", false) }, { defer: true }, ), ) createEffect( on( () => params.dir, (dir) => { if (!dir) return setStore("newSessionWorktree", "main") }, { defer: true }, ), ) createEffect(() => { const id = lastUserMessage()?.id if (!id) return setStore("expanded", id, status().type !== "idle") }) const selectionPreview = (path: string, selection: FileSelection) => { const content = file.get(path)?.content?.content if (!content) return undefined const start = Math.max(1, Math.min(selection.startLine, selection.endLine)) const end = Math.max(selection.startLine, selection.endLine) const lines = content.split("\n").slice(start - 1, end) if (lines.length === 0) return undefined return lines.slice(0, 2).join("\n") } const addSelectionToContext = (path: string, selection: FileSelection) => { const preview = selectionPreview(path, selection) prompt.context.add({ type: "file", path, selection, preview }) } const addCommentToContext = (input: { file: string selection: SelectedLineRange comment: string preview?: string origin?: "review" | "file" }) => { const selection = selectionFromLines(input.selection) const preview = input.preview ?? selectionPreview(input.file, selection) const saved = comments.add({ file: input.file, selection: input.selection, comment: input.comment, }) prompt.context.add({ type: "file", path: input.file, selection, comment: input.comment, commentID: saved.id, commentOrigin: input.origin, preview, }) } command.register(() => [ { id: "session.new", title: language.t("command.session.new"), category: language.t("command.category.session"), keybind: "mod+shift+s", slash: "new", onSelect: () => navigate(`/${params.dir}/session`), }, { id: "file.open", title: language.t("command.file.open"), description: language.t("palette.search.placeholder"), category: language.t("command.category.file"), keybind: "mod+p", slash: "open", onSelect: () => dialog.show(() => showAllFiles()} />), }, { id: "tab.close", title: language.t("command.tab.close"), category: language.t("command.category.file"), keybind: "mod+w", disabled: !tabs().active(), onSelect: () => { const active = tabs().active() if (!active) return tabs().close(active) }, }, { id: "context.addSelection", title: language.t("command.context.addSelection"), description: language.t("command.context.addSelection.description"), category: language.t("command.category.context"), keybind: "mod+shift+l", disabled: (() => { const active = tabs().active() if (!active) return true const path = file.pathFromTab(active) if (!path) return true return file.selectedLines(path) == null })(), onSelect: () => { const active = tabs().active() if (!active) return const path = file.pathFromTab(active) if (!path) return const range = file.selectedLines(path) if (!range) { showToast({ title: language.t("toast.context.noLineSelection.title"), description: language.t("toast.context.noLineSelection.description"), }) return } addSelectionToContext(path, selectionFromLines(range)) }, }, { id: "terminal.toggle", title: language.t("command.terminal.toggle"), description: "", category: language.t("command.category.view"), keybind: "ctrl+`", slash: "terminal", onSelect: () => view().terminal.toggle(), }, { id: "review.toggle", title: language.t("command.review.toggle"), description: "", category: language.t("command.category.view"), keybind: "mod+shift+r", onSelect: () => view().reviewPanel.toggle(), }, { id: "fileTree.toggle", title: language.t("command.fileTree.toggle"), description: "", category: language.t("command.category.view"), onSelect: () => { const opening = !layout.fileTree.opened() if (opening && !view().reviewPanel.opened()) view().reviewPanel.open() layout.fileTree.toggle() }, }, { id: "terminal.new", title: language.t("command.terminal.new"), description: language.t("command.terminal.new.description"), category: language.t("command.category.terminal"), keybind: "ctrl+alt+t", onSelect: () => { if (terminal.all().length > 0) terminal.new() view().terminal.open() }, }, { id: "steps.toggle", title: language.t("command.steps.toggle"), description: language.t("command.steps.toggle.description"), category: language.t("command.category.view"), keybind: "mod+e", slash: "steps", disabled: !params.id, onSelect: () => { const msg = activeMessage() if (!msg) return setStore("expanded", msg.id, (open: boolean | undefined) => !open) }, }, { id: "message.previous", title: language.t("command.message.previous"), description: language.t("command.message.previous.description"), category: language.t("command.category.session"), keybind: "mod+arrowup", disabled: !params.id, onSelect: () => navigateMessageByOffset(-1), }, { id: "message.next", title: language.t("command.message.next"), description: language.t("command.message.next.description"), category: language.t("command.category.session"), keybind: "mod+arrowdown", disabled: !params.id, onSelect: () => navigateMessageByOffset(1), }, { id: "model.choose", title: language.t("command.model.choose"), description: language.t("command.model.choose.description"), category: language.t("command.category.model"), keybind: "mod+'", slash: "model", onSelect: () => dialog.show(() => ), }, { id: "mcp.toggle", title: language.t("command.mcp.toggle"), description: language.t("command.mcp.toggle.description"), category: language.t("command.category.mcp"), keybind: "mod+;", slash: "mcp", onSelect: () => dialog.show(() => ), }, { id: "agent.cycle", title: language.t("command.agent.cycle"), description: language.t("command.agent.cycle.description"), category: language.t("command.category.agent"), keybind: "mod+.", slash: "agent", onSelect: () => local.agent.move(1), }, { id: "agent.cycle.reverse", title: language.t("command.agent.cycle.reverse"), description: language.t("command.agent.cycle.reverse.description"), category: language.t("command.category.agent"), keybind: "shift+mod+.", onSelect: () => local.agent.move(-1), }, { id: "model.variant.cycle", title: language.t("command.model.variant.cycle"), description: language.t("command.model.variant.cycle.description"), category: language.t("command.category.model"), keybind: "shift+mod+d", onSelect: () => { local.model.variant.cycle() }, }, { id: "permissions.autoaccept", title: params.id && permission.isAutoAccepting(params.id, sdk.directory) ? language.t("command.permissions.autoaccept.disable") : language.t("command.permissions.autoaccept.enable"), category: language.t("command.category.permissions"), keybind: "mod+shift+a", disabled: !params.id || !permission.permissionsEnabled(), onSelect: () => { const sessionID = params.id if (!sessionID) return permission.toggleAutoAccept(sessionID, sdk.directory) showToast({ title: permission.isAutoAccepting(sessionID, sdk.directory) ? language.t("toast.permissions.autoaccept.on.title") : language.t("toast.permissions.autoaccept.off.title"), description: permission.isAutoAccepting(sessionID, sdk.directory) ? language.t("toast.permissions.autoaccept.on.description") : language.t("toast.permissions.autoaccept.off.description"), }) }, }, { id: "session.undo", title: language.t("command.session.undo"), description: language.t("command.session.undo.description"), category: language.t("command.category.session"), slash: "undo", disabled: !params.id || visibleUserMessages().length === 0, onSelect: async () => { const sessionID = params.id if (!sessionID) return if (status()?.type !== "idle") { await sdk.client.session.abort({ sessionID }).catch(() => {}) } const revert = info()?.revert?.messageID // Find the last user message that's not already reverted const message = findLast(userMessages(), (x) => !revert || x.id < revert) if (!message) return await sdk.client.session.revert({ sessionID, messageID: message.id }) // Restore the prompt from the reverted message const parts = sync.data.part[message.id] if (parts) { const restored = extractPromptFromParts(parts, { directory: sdk.directory }) prompt.set(restored) } // Navigate to the message before the reverted one (which will be the new last visible message) const priorMessage = findLast(userMessages(), (x) => x.id < message.id) setActiveMessage(priorMessage) }, }, { id: "session.redo", title: language.t("command.session.redo"), description: language.t("command.session.redo.description"), category: language.t("command.category.session"), slash: "redo", disabled: !params.id || !info()?.revert?.messageID, onSelect: async () => { const sessionID = params.id if (!sessionID) return const revertMessageID = info()?.revert?.messageID if (!revertMessageID) return const nextMessage = userMessages().find((x) => x.id > revertMessageID) if (!nextMessage) { // Full unrevert - restore all messages and navigate to last await sdk.client.session.unrevert({ sessionID }) prompt.reset() // Navigate to the last message (the one that was at the revert point) const lastMsg = findLast(userMessages(), (x) => x.id >= revertMessageID) setActiveMessage(lastMsg) return } // Partial redo - move forward to next message await sdk.client.session.revert({ sessionID, messageID: nextMessage.id }) // Navigate to the message before the new revert point const priorMsg = findLast(userMessages(), (x) => x.id < nextMessage.id) setActiveMessage(priorMsg) }, }, { id: "session.compact", title: language.t("command.session.compact"), description: language.t("command.session.compact.description"), category: language.t("command.category.session"), slash: "compact", disabled: !params.id || visibleUserMessages().length === 0, onSelect: async () => { const sessionID = params.id if (!sessionID) return const model = local.model.current() if (!model) { showToast({ title: language.t("toast.model.none.title"), description: language.t("toast.model.none.description"), }) return } await sdk.client.session.summarize({ sessionID, modelID: model.id, providerID: model.provider.id, }) }, }, { id: "session.fork", title: language.t("command.session.fork"), description: language.t("command.session.fork.description"), category: language.t("command.category.session"), slash: "fork", disabled: !params.id || visibleUserMessages().length === 0, onSelect: () => dialog.show(() => ), }, ...(sync.data.config.share !== "disabled" ? [ { id: "session.share", title: language.t("command.session.share"), description: language.t("command.session.share.description"), category: language.t("command.category.session"), slash: "share", disabled: !params.id || !!info()?.share?.url, onSelect: async () => { if (!params.id) return await sdk.client.session .share({ sessionID: params.id }) .then((res) => { navigator.clipboard.writeText(res.data!.share!.url).catch(() => showToast({ title: language.t("toast.session.share.copyFailed.title"), variant: "error", }), ) }) .then(() => showToast({ title: language.t("toast.session.share.success.title"), description: language.t("toast.session.share.success.description"), variant: "success", }), ) .catch(() => showToast({ title: language.t("toast.session.share.failed.title"), description: language.t("toast.session.share.failed.description"), variant: "error", }), ) }, }, { id: "session.unshare", title: language.t("command.session.unshare"), description: language.t("command.session.unshare.description"), category: language.t("command.category.session"), slash: "unshare", disabled: !params.id || !info()?.share?.url, onSelect: async () => { if (!params.id) return await sdk.client.session .unshare({ sessionID: params.id }) .then(() => showToast({ title: language.t("toast.session.unshare.success.title"), description: language.t("toast.session.unshare.success.description"), variant: "success", }), ) .catch(() => showToast({ title: language.t("toast.session.unshare.failed.title"), description: language.t("toast.session.unshare.failed.description"), variant: "error", }), ) }, }, ] : []), ]) const handleKeyDown = (event: KeyboardEvent) => { const activeElement = document.activeElement as HTMLElement | undefined if (activeElement) { const isProtected = activeElement.closest("[data-prevent-autofocus]") const isInput = /^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(activeElement.tagName) || activeElement.isContentEditable if (isProtected || isInput) return } if (dialog.active) return if (activeElement === inputRef) { if (event.key === "Escape") inputRef?.blur() return } // Don't autofocus chat if terminal panel is open if (view().terminal.opened()) return // Only treat explicit scroll keys as potential "user scroll" gestures. if (event.key === "PageUp" || event.key === "PageDown" || event.key === "Home" || event.key === "End") { markScrollGesture() return } if (event.key.length === 1 && event.key !== "Unidentified" && !(event.ctrlKey || event.metaKey)) { if (blocked()) return inputRef?.focus() } } const handleDragStart = (event: unknown) => { const id = getDraggableId(event) if (!id) return setStore("activeDraggable", id) } const handleDragOver = (event: DragEvent) => { const { draggable, droppable } = event if (draggable && droppable) { const currentTabs = tabs().all() const fromIndex = currentTabs?.indexOf(draggable.id.toString()) const toIndex = currentTabs?.indexOf(droppable.id.toString()) if (fromIndex !== toIndex && toIndex !== undefined) { tabs().move(draggable.id.toString(), toIndex) } } } const handleDragEnd = () => { setStore("activeDraggable", undefined) } const handleTerminalDragStart = (event: unknown) => { const id = getDraggableId(event) if (!id) return setStore("activeTerminalDraggable", id) } const handleTerminalDragOver = (event: DragEvent) => { const { draggable, droppable } = event if (draggable && droppable) { const terminals = terminal.all() const fromIndex = terminals.findIndex((t: LocalPTY) => t.id === draggable.id.toString()) const toIndex = terminals.findIndex((t: LocalPTY) => t.id === droppable.id.toString()) if (fromIndex !== -1 && toIndex !== -1 && fromIndex !== toIndex) { terminal.move(draggable.id.toString(), toIndex) } } } const handleTerminalDragEnd = () => { setStore("activeTerminalDraggable", undefined) const activeId = terminal.active() if (!activeId) return setTimeout(() => { const wrapper = document.getElementById(`terminal-wrapper-${activeId}`) const element = wrapper?.querySelector('[data-component="terminal"]') as HTMLElement if (!element) return // Find and focus the ghostty textarea (the actual input element) const textarea = element.querySelector("textarea") as HTMLTextAreaElement if (textarea) { textarea.focus() return } // Fallback: focus container and dispatch pointer event element.focus() element.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true })) }, 0) } const contextOpen = createMemo(() => tabs().active() === "context" || tabs().all().includes("context")) const openedTabs = createMemo(() => tabs() .all() .filter((tab) => tab !== "context" && tab !== "review"), ) const mobileChanges = createMemo(() => !isDesktop() && store.mobileTab === "changes") const reviewTab = createMemo(() => isDesktop() && !layout.fileTree.opened()) const fileTreeTab = () => layout.fileTree.tab() const setFileTreeTab = (value: "changes" | "all") => layout.fileTree.setTab(value) const [tree, setTree] = createStore({ reviewScroll: undefined as HTMLDivElement | undefined, pendingDiff: undefined as string | undefined, activeDiff: undefined as string | undefined, }) createEffect( on( sessionKey, () => { setTree({ reviewScroll: undefined, pendingDiff: undefined, activeDiff: undefined }) }, { defer: true }, ), ) const showAllFiles = () => { if (fileTreeTab() !== "changes") return setFileTreeTab("all") } const changesOptions = ["session", "turn"] as const const changesOptionsList = [...changesOptions] const changesTitle = () => (