layout.tsx 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  1. import {
  2. batch,
  3. createEffect,
  4. createMemo,
  5. createSignal,
  6. For,
  7. Match,
  8. on,
  9. onCleanup,
  10. onMount,
  11. ParentProps,
  12. Show,
  13. Switch,
  14. untrack,
  15. type Accessor,
  16. type JSX,
  17. } from "solid-js"
  18. import { A, useNavigate, useParams } from "@solidjs/router"
  19. import { useLayout, getAvatarColors, LocalProject } from "@/context/layout"
  20. import { useGlobalSync } from "@/context/global-sync"
  21. import { Persist, persisted } from "@/utils/persist"
  22. import { base64Decode, base64Encode } from "@opencode-ai/util/encode"
  23. import { Avatar } from "@opencode-ai/ui/avatar"
  24. import { ResizeHandle } from "@opencode-ai/ui/resize-handle"
  25. import { Button } from "@opencode-ai/ui/button"
  26. import { Icon } from "@opencode-ai/ui/icon"
  27. import { IconButton } from "@opencode-ai/ui/icon-button"
  28. import { InlineInput } from "@opencode-ai/ui/inline-input"
  29. import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
  30. import { HoverCard } from "@opencode-ai/ui/hover-card"
  31. import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu"
  32. import { Collapsible } from "@opencode-ai/ui/collapsible"
  33. import { DiffChanges } from "@opencode-ai/ui/diff-changes"
  34. import { Spinner } from "@opencode-ai/ui/spinner"
  35. import { Dialog } from "@opencode-ai/ui/dialog"
  36. import { getFilename } from "@opencode-ai/util/path"
  37. import { Session } from "@opencode-ai/sdk/v2/client"
  38. import { usePlatform } from "@/context/platform"
  39. import { createStore, produce, reconcile } from "solid-js/store"
  40. import {
  41. DragDropProvider,
  42. DragDropSensors,
  43. DragOverlay,
  44. SortableProvider,
  45. closestCenter,
  46. createSortable,
  47. } from "@thisbeyond/solid-dnd"
  48. import type { DragEvent } from "@thisbeyond/solid-dnd"
  49. import { useProviders } from "@/hooks/use-providers"
  50. import { showToast, Toast, toaster } from "@opencode-ai/ui/toast"
  51. import { useGlobalSDK } from "@/context/global-sdk"
  52. import { useNotification } from "@/context/notification"
  53. import { usePermission } from "@/context/permission"
  54. import { Binary } from "@opencode-ai/util/binary"
  55. import { retry } from "@opencode-ai/util/retry"
  56. import { useDialog } from "@opencode-ai/ui/context/dialog"
  57. import { useTheme, type ColorScheme } from "@opencode-ai/ui/theme"
  58. import { DialogSelectProvider } from "@/components/dialog-select-provider"
  59. import { DialogSelectServer } from "@/components/dialog-select-server"
  60. import { useCommand, type CommandOption } from "@/context/command"
  61. import { ConstrainDragXAxis } from "@/utils/solid-dnd"
  62. import { navStart } from "@/utils/perf"
  63. import { DialogSelectDirectory } from "@/components/dialog-select-directory"
  64. import { DialogEditProject } from "@/components/dialog-edit-project"
  65. import { Titlebar } from "@/components/titlebar"
  66. import { useServer } from "@/context/server"
  67. export default function Layout(props: ParentProps) {
  68. const [store, setStore, , ready] = persisted(
  69. Persist.global("layout.page", ["layout.page.v1"]),
  70. createStore({
  71. lastSession: {} as { [directory: string]: string },
  72. activeProject: undefined as string | undefined,
  73. activeWorkspace: undefined as string | undefined,
  74. workspaceOrder: {} as Record<string, string[]>,
  75. workspaceName: {} as Record<string, string>,
  76. workspaceExpanded: {} as Record<string, boolean>,
  77. }),
  78. )
  79. const pageReady = createMemo(() => ready())
  80. let scrollContainerRef: HTMLDivElement | undefined
  81. const xlQuery = window.matchMedia("(min-width: 1280px)")
  82. const [isLargeViewport, setIsLargeViewport] = createSignal(xlQuery.matches)
  83. const handleViewportChange = (e: MediaQueryListEvent) => setIsLargeViewport(e.matches)
  84. xlQuery.addEventListener("change", handleViewportChange)
  85. onCleanup(() => xlQuery.removeEventListener("change", handleViewportChange))
  86. const params = useParams()
  87. const [autoselect, setAutoselect] = createSignal(!params.dir)
  88. const globalSDK = useGlobalSDK()
  89. const globalSync = useGlobalSync()
  90. const layout = useLayout()
  91. const layoutReady = createMemo(() => layout.ready())
  92. const platform = usePlatform()
  93. const server = useServer()
  94. const notification = useNotification()
  95. const permission = usePermission()
  96. const navigate = useNavigate()
  97. const providers = useProviders()
  98. const dialog = useDialog()
  99. const command = useCommand()
  100. const theme = useTheme()
  101. const initialDir = params.dir
  102. const availableThemeEntries = createMemo(() => Object.entries(theme.themes()))
  103. const colorSchemeOrder: ColorScheme[] = ["system", "light", "dark"]
  104. const colorSchemeLabel: Record<ColorScheme, string> = {
  105. system: "System",
  106. light: "Light",
  107. dark: "Dark",
  108. }
  109. const [editor, setEditor] = createStore({
  110. active: "" as string,
  111. value: "",
  112. })
  113. const editorRef = { current: undefined as HTMLInputElement | undefined }
  114. const editorOpen = (id: string) => editor.active === id
  115. const editorValue = () => editor.value
  116. const openEditor = (id: string, value: string) => {
  117. if (!id) return
  118. setEditor({ active: id, value })
  119. queueMicrotask(() => editorRef.current?.focus())
  120. }
  121. const closeEditor = () => setEditor({ active: "", value: "" })
  122. const saveEditor = (callback: (next: string) => void) => {
  123. const next = editor.value.trim()
  124. if (!next) {
  125. closeEditor()
  126. return
  127. }
  128. closeEditor()
  129. callback(next)
  130. }
  131. const editorKeyDown = (event: KeyboardEvent, callback: (next: string) => void) => {
  132. if (event.key === "Enter") {
  133. event.preventDefault()
  134. saveEditor(callback)
  135. return
  136. }
  137. if (event.key === "Escape") {
  138. event.preventDefault()
  139. closeEditor()
  140. }
  141. }
  142. const InlineEditor = (props: {
  143. id: string
  144. value: Accessor<string>
  145. onSave: (next: string) => void
  146. class?: string
  147. displayClass?: string
  148. editing?: boolean
  149. stopPropagation?: boolean
  150. openOnDblClick?: boolean
  151. }) => {
  152. const isEditing = () => props.editing ?? editorOpen(props.id)
  153. const stopEvents = () => props.stopPropagation ?? false
  154. const allowDblClick = () => props.openOnDblClick ?? true
  155. const stopPropagation = (event: Event) => {
  156. if (!stopEvents()) return
  157. event.stopPropagation()
  158. }
  159. const handleDblClick = (event: MouseEvent) => {
  160. if (!allowDblClick()) return
  161. stopPropagation(event)
  162. openEditor(props.id, props.value())
  163. }
  164. return (
  165. <Show
  166. when={isEditing()}
  167. fallback={
  168. <span
  169. class={props.displayClass ?? props.class}
  170. onDblClick={handleDblClick}
  171. onPointerDown={stopPropagation}
  172. onMouseDown={stopPropagation}
  173. onClick={stopPropagation}
  174. onTouchStart={stopPropagation}
  175. >
  176. {props.value()}
  177. </span>
  178. }
  179. >
  180. <InlineInput
  181. ref={(el) => {
  182. editorRef.current = el
  183. }}
  184. value={editorValue()}
  185. class={props.class}
  186. onInput={(event) => setEditor("value", event.currentTarget.value)}
  187. onKeyDown={(event) => editorKeyDown(event, props.onSave)}
  188. onBlur={() => closeEditor()}
  189. onPointerDown={stopPropagation}
  190. onClick={stopPropagation}
  191. onDblClick={stopPropagation}
  192. onMouseDown={stopPropagation}
  193. onMouseUp={stopPropagation}
  194. onTouchStart={stopPropagation}
  195. />
  196. </Show>
  197. )
  198. }
  199. function cycleTheme(direction = 1) {
  200. const ids = availableThemeEntries().map(([id]) => id)
  201. if (ids.length === 0) return
  202. const currentIndex = ids.indexOf(theme.themeId())
  203. const nextIndex = currentIndex === -1 ? 0 : (currentIndex + direction + ids.length) % ids.length
  204. const nextThemeId = ids[nextIndex]
  205. theme.setTheme(nextThemeId)
  206. const nextTheme = theme.themes()[nextThemeId]
  207. showToast({
  208. title: "Theme switched",
  209. description: nextTheme?.name ?? nextThemeId,
  210. })
  211. }
  212. function cycleColorScheme(direction = 1) {
  213. const current = theme.colorScheme()
  214. const currentIndex = colorSchemeOrder.indexOf(current)
  215. const nextIndex =
  216. currentIndex === -1 ? 0 : (currentIndex + direction + colorSchemeOrder.length) % colorSchemeOrder.length
  217. const next = colorSchemeOrder[nextIndex]
  218. theme.setColorScheme(next)
  219. showToast({
  220. title: "Color scheme",
  221. description: colorSchemeLabel[next],
  222. })
  223. }
  224. onMount(() => {
  225. if (!platform.checkUpdate || !platform.update || !platform.restart) return
  226. let toastId: number | undefined
  227. async function pollUpdate() {
  228. const { updateAvailable, version } = await platform.checkUpdate!()
  229. if (updateAvailable && toastId === undefined) {
  230. toastId = showToast({
  231. persistent: true,
  232. icon: "download",
  233. title: "Update available",
  234. description: `A new version of OpenCode (${version}) is now available to install.`,
  235. actions: [
  236. {
  237. label: "Install and restart",
  238. onClick: async () => {
  239. await platform.update!()
  240. await platform.restart!()
  241. },
  242. },
  243. {
  244. label: "Not yet",
  245. onClick: "dismiss",
  246. },
  247. ],
  248. })
  249. }
  250. }
  251. pollUpdate()
  252. const interval = setInterval(pollUpdate, 10 * 60 * 1000)
  253. onCleanup(() => clearInterval(interval))
  254. })
  255. onMount(() => {
  256. const alerts = {
  257. "permission.asked": {
  258. title: "Permission required",
  259. icon: "checklist" as const,
  260. description: (sessionTitle: string, projectName: string) =>
  261. `${sessionTitle} in ${projectName} needs permission`,
  262. },
  263. "question.asked": {
  264. title: "Question",
  265. icon: "bubble-5" as const,
  266. description: (sessionTitle: string, projectName: string) => `${sessionTitle} in ${projectName} has a question`,
  267. },
  268. }
  269. const toastBySession = new Map<string, number>()
  270. const alertedAtBySession = new Map<string, number>()
  271. const cooldownMs = 5000
  272. const unsub = globalSDK.event.listen((e) => {
  273. if (e.details?.type !== "permission.asked" && e.details?.type !== "question.asked") return
  274. const config = alerts[e.details.type]
  275. const directory = e.name
  276. const props = e.details.properties
  277. if (e.details.type === "permission.asked" && permission.autoResponds(e.details.properties, directory)) return
  278. const [store] = globalSync.child(directory)
  279. const session = store.session.find((s) => s.id === props.sessionID)
  280. const sessionKey = `${directory}:${props.sessionID}`
  281. const sessionTitle = session?.title ?? "New session"
  282. const projectName = getFilename(directory)
  283. const description = config.description(sessionTitle, projectName)
  284. const href = `/${base64Encode(directory)}/session/${props.sessionID}`
  285. const now = Date.now()
  286. const lastAlerted = alertedAtBySession.get(sessionKey) ?? 0
  287. if (now - lastAlerted < cooldownMs) return
  288. alertedAtBySession.set(sessionKey, now)
  289. void platform.notify(config.title, description, href)
  290. const currentDir = params.dir ? base64Decode(params.dir) : undefined
  291. const currentSession = params.id
  292. if (directory === currentDir && props.sessionID === currentSession) return
  293. if (directory === currentDir && session?.parentID === currentSession) return
  294. const existingToastId = toastBySession.get(sessionKey)
  295. if (existingToastId !== undefined) toaster.dismiss(existingToastId)
  296. const toastId = showToast({
  297. persistent: true,
  298. icon: config.icon,
  299. title: config.title,
  300. description,
  301. actions: [
  302. {
  303. label: "Go to session",
  304. onClick: () => navigate(href),
  305. },
  306. {
  307. label: "Dismiss",
  308. onClick: "dismiss",
  309. },
  310. ],
  311. })
  312. toastBySession.set(sessionKey, toastId)
  313. })
  314. onCleanup(unsub)
  315. createEffect(() => {
  316. const currentDir = params.dir ? base64Decode(params.dir) : undefined
  317. const currentSession = params.id
  318. if (!currentDir || !currentSession) return
  319. const sessionKey = `${currentDir}:${currentSession}`
  320. const toastId = toastBySession.get(sessionKey)
  321. if (toastId !== undefined) {
  322. toaster.dismiss(toastId)
  323. toastBySession.delete(sessionKey)
  324. alertedAtBySession.delete(sessionKey)
  325. }
  326. const [store] = globalSync.child(currentDir)
  327. const childSessions = store.session.filter((s) => s.parentID === currentSession)
  328. for (const child of childSessions) {
  329. const childKey = `${currentDir}:${child.id}`
  330. const childToastId = toastBySession.get(childKey)
  331. if (childToastId !== undefined) {
  332. toaster.dismiss(childToastId)
  333. toastBySession.delete(childKey)
  334. alertedAtBySession.delete(childKey)
  335. }
  336. }
  337. })
  338. })
  339. function sortSessions(a: Session, b: Session) {
  340. const now = Date.now()
  341. const oneMinuteAgo = now - 60 * 1000
  342. const aUpdated = a.time.updated ?? a.time.created
  343. const bUpdated = b.time.updated ?? b.time.created
  344. const aRecent = aUpdated > oneMinuteAgo
  345. const bRecent = bUpdated > oneMinuteAgo
  346. if (aRecent && bRecent) return a.id.localeCompare(b.id)
  347. if (aRecent && !bRecent) return -1
  348. if (!aRecent && bRecent) return 1
  349. return bUpdated - aUpdated
  350. }
  351. const [scrollSessionKey, setScrollSessionKey] = createSignal<string | undefined>(undefined)
  352. function scrollToSession(sessionId: string, sessionKey: string) {
  353. if (!scrollContainerRef) return
  354. if (scrollSessionKey() === sessionKey) return
  355. const element = scrollContainerRef.querySelector(`[data-session-id="${sessionId}"]`)
  356. if (!element) return
  357. const containerRect = scrollContainerRef.getBoundingClientRect()
  358. const elementRect = element.getBoundingClientRect()
  359. if (elementRect.top >= containerRect.top && elementRect.bottom <= containerRect.bottom) {
  360. setScrollSessionKey(sessionKey)
  361. return
  362. }
  363. setScrollSessionKey(sessionKey)
  364. element.scrollIntoView({ block: "nearest", behavior: "smooth" })
  365. }
  366. const currentProject = createMemo(() => {
  367. const directory = params.dir ? base64Decode(params.dir) : undefined
  368. if (!directory) return
  369. const projects = layout.projects.list()
  370. const sandbox = projects.find((p) => p.sandboxes?.includes(directory))
  371. if (sandbox) return sandbox
  372. const direct = projects.find((p) => p.worktree === directory)
  373. if (direct) return direct
  374. const [child] = globalSync.child(directory)
  375. const id = child.project
  376. if (!id) return
  377. const meta = globalSync.data.project.find((p) => p.id === id)
  378. const root = meta?.worktree
  379. if (!root) return
  380. return projects.find((p) => p.worktree === root)
  381. })
  382. createEffect(
  383. on(
  384. () => ({ ready: pageReady(), project: currentProject() }),
  385. (value) => {
  386. if (!value.ready) return
  387. const project = value.project
  388. if (!project) return
  389. const last = server.projects.last()
  390. if (last === project.worktree) return
  391. server.projects.touch(project.worktree)
  392. },
  393. { defer: true },
  394. ),
  395. )
  396. createEffect(
  397. on(
  398. () => ({ ready: pageReady(), layoutReady: layoutReady(), dir: params.dir, list: layout.projects.list() }),
  399. (value) => {
  400. if (!value.ready) return
  401. if (!value.layoutReady) return
  402. if (!autoselect()) return
  403. if (initialDir) return
  404. if (value.dir) return
  405. if (value.list.length === 0) return
  406. const last = server.projects.last()
  407. const next = value.list.find((project) => project.worktree === last) ?? value.list[0]
  408. if (!next) return
  409. setAutoselect(false)
  410. openProject(next.worktree, false)
  411. navigateToProject(next.worktree)
  412. },
  413. { defer: true },
  414. ),
  415. )
  416. const workspaceName = (directory: string) => store.workspaceName[directory]
  417. const workspaceLabel = (directory: string, branch?: string) =>
  418. workspaceName(directory) ?? branch ?? getFilename(directory)
  419. const isWorkspaceEditing = () => editor.active.startsWith("workspace:")
  420. const workspaceSetting = createMemo(() => {
  421. const project = currentProject()
  422. if (!project) return false
  423. return layout.sidebar.workspaces(project.worktree)()
  424. })
  425. createEffect(() => {
  426. if (!pageReady()) return
  427. if (!layoutReady()) return
  428. const project = currentProject()
  429. if (!project) return
  430. const dirs = [project.worktree, ...(project.sandboxes ?? [])]
  431. const existing = store.workspaceOrder[project.worktree]
  432. if (!existing) {
  433. setStore("workspaceOrder", project.worktree, dirs)
  434. return
  435. }
  436. const keep = existing.filter((d) => dirs.includes(d))
  437. const missing = dirs.filter((d) => !existing.includes(d))
  438. const merged = [...keep, ...missing]
  439. if (merged.length !== existing.length) {
  440. setStore("workspaceOrder", project.worktree, merged)
  441. return
  442. }
  443. if (merged.some((d, i) => d !== existing[i])) {
  444. setStore("workspaceOrder", project.worktree, merged)
  445. }
  446. })
  447. createEffect(() => {
  448. if (!pageReady()) return
  449. if (!layoutReady()) return
  450. const projects = layout.projects.list()
  451. for (const [directory, expanded] of Object.entries(store.workspaceExpanded)) {
  452. if (!expanded) continue
  453. const project = projects.find((item) => item.worktree === directory || item.sandboxes?.includes(directory))
  454. if (!project) continue
  455. if (layout.sidebar.workspaces(project.worktree)()) continue
  456. setStore("workspaceExpanded", directory, false)
  457. }
  458. })
  459. const currentSessions = createMemo(() => {
  460. const project = currentProject()
  461. if (!project) return [] as Session[]
  462. if (workspaceSetting()) {
  463. const dirs = workspaceIds(project)
  464. const result: Session[] = []
  465. for (const dir of dirs) {
  466. const [dirStore] = globalSync.child(dir)
  467. const dirSessions = dirStore.session
  468. .filter((session) => session.directory === dirStore.path.directory)
  469. .filter((session) => !session.parentID && !session.time?.archived)
  470. .toSorted(sortSessions)
  471. result.push(...dirSessions)
  472. }
  473. return result
  474. }
  475. const [projectStore] = globalSync.child(project.worktree)
  476. return projectStore.session
  477. .filter((session) => session.directory === projectStore.path.directory)
  478. .filter((session) => !session.parentID && !session.time?.archived)
  479. .toSorted(sortSessions)
  480. })
  481. type PrefetchQueue = {
  482. inflight: Set<string>
  483. pending: string[]
  484. pendingSet: Set<string>
  485. running: number
  486. }
  487. const prefetchChunk = 200
  488. const prefetchConcurrency = 1
  489. const prefetchPendingLimit = 6
  490. const prefetchToken = { value: 0 }
  491. const prefetchQueues = new Map<string, PrefetchQueue>()
  492. createEffect(() => {
  493. params.dir
  494. globalSDK.url
  495. prefetchToken.value += 1
  496. for (const q of prefetchQueues.values()) {
  497. q.pending.length = 0
  498. q.pendingSet.clear()
  499. }
  500. })
  501. const queueFor = (directory: string) => {
  502. const existing = prefetchQueues.get(directory)
  503. if (existing) return existing
  504. const created: PrefetchQueue = {
  505. inflight: new Set(),
  506. pending: [],
  507. pendingSet: new Set(),
  508. running: 0,
  509. }
  510. prefetchQueues.set(directory, created)
  511. return created
  512. }
  513. async function prefetchMessages(directory: string, sessionID: string, token: number) {
  514. const [, setStore] = globalSync.child(directory)
  515. return retry(() => globalSDK.client.session.messages({ directory, sessionID, limit: prefetchChunk }))
  516. .then((messages) => {
  517. if (prefetchToken.value !== token) return
  518. const items = (messages.data ?? []).filter((x) => !!x?.info?.id)
  519. const next = items
  520. .map((x) => x.info)
  521. .filter((m) => !!m?.id)
  522. .slice()
  523. .sort((a, b) => a.id.localeCompare(b.id))
  524. batch(() => {
  525. setStore("message", sessionID, reconcile(next, { key: "id" }))
  526. for (const message of items) {
  527. setStore(
  528. "part",
  529. message.info.id,
  530. reconcile(
  531. message.parts
  532. .filter((p) => !!p?.id)
  533. .slice()
  534. .sort((a, b) => a.id.localeCompare(b.id)),
  535. { key: "id" },
  536. ),
  537. )
  538. }
  539. })
  540. })
  541. .catch(() => undefined)
  542. }
  543. const pumpPrefetch = (directory: string) => {
  544. const q = queueFor(directory)
  545. if (q.running >= prefetchConcurrency) return
  546. const sessionID = q.pending.shift()
  547. if (!sessionID) return
  548. q.pendingSet.delete(sessionID)
  549. q.inflight.add(sessionID)
  550. q.running += 1
  551. const token = prefetchToken.value
  552. void prefetchMessages(directory, sessionID, token).finally(() => {
  553. q.running -= 1
  554. q.inflight.delete(sessionID)
  555. pumpPrefetch(directory)
  556. })
  557. }
  558. const prefetchSession = (session: Session, priority: "high" | "low" = "low") => {
  559. const directory = session.directory
  560. if (!directory) return
  561. const [store] = globalSync.child(directory)
  562. if (store.message[session.id] !== undefined) return
  563. const q = queueFor(directory)
  564. if (q.inflight.has(session.id)) return
  565. if (q.pendingSet.has(session.id)) return
  566. if (priority === "high") q.pending.unshift(session.id)
  567. if (priority !== "high") q.pending.push(session.id)
  568. q.pendingSet.add(session.id)
  569. while (q.pending.length > prefetchPendingLimit) {
  570. const dropped = q.pending.pop()
  571. if (!dropped) continue
  572. q.pendingSet.delete(dropped)
  573. }
  574. pumpPrefetch(directory)
  575. }
  576. createEffect(() => {
  577. const sessions = currentSessions()
  578. const id = params.id
  579. if (!id) {
  580. const first = sessions[0]
  581. if (first) prefetchSession(first)
  582. const second = sessions[1]
  583. if (second) prefetchSession(second)
  584. return
  585. }
  586. const index = sessions.findIndex((s) => s.id === id)
  587. if (index === -1) return
  588. const next = sessions[index + 1]
  589. if (next) prefetchSession(next)
  590. const prev = sessions[index - 1]
  591. if (prev) prefetchSession(prev)
  592. })
  593. function navigateSessionByOffset(offset: number) {
  594. const sessions = currentSessions()
  595. if (sessions.length === 0) return
  596. const sessionIndex = params.id ? sessions.findIndex((s) => s.id === params.id) : -1
  597. let targetIndex: number
  598. if (sessionIndex === -1) {
  599. targetIndex = offset > 0 ? 0 : sessions.length - 1
  600. } else {
  601. targetIndex = (sessionIndex + offset + sessions.length) % sessions.length
  602. }
  603. const session = sessions[targetIndex]
  604. if (!session) return
  605. const next = sessions[(targetIndex + 1) % sessions.length]
  606. const prev = sessions[(targetIndex - 1 + sessions.length) % sessions.length]
  607. if (offset > 0) {
  608. if (next) prefetchSession(next, "high")
  609. if (prev) prefetchSession(prev)
  610. }
  611. if (offset < 0) {
  612. if (prev) prefetchSession(prev, "high")
  613. if (next) prefetchSession(next)
  614. }
  615. if (import.meta.env.DEV) {
  616. navStart({
  617. dir: base64Encode(session.directory),
  618. from: params.id,
  619. to: session.id,
  620. trigger: offset > 0 ? "alt+arrowdown" : "alt+arrowup",
  621. })
  622. }
  623. navigateToSession(session)
  624. queueMicrotask(() => scrollToSession(session.id, `${session.directory}:${session.id}`))
  625. }
  626. async function archiveSession(session: Session) {
  627. const [store, setStore] = globalSync.child(session.directory)
  628. const sessions = store.session ?? []
  629. const index = sessions.findIndex((s) => s.id === session.id)
  630. const nextSession = sessions[index + 1] ?? sessions[index - 1]
  631. await globalSDK.client.session.update({
  632. directory: session.directory,
  633. sessionID: session.id,
  634. time: { archived: Date.now() },
  635. })
  636. setStore(
  637. produce((draft) => {
  638. const match = Binary.search(draft.session, session.id, (s) => s.id)
  639. if (match.found) draft.session.splice(match.index, 1)
  640. }),
  641. )
  642. if (session.id === params.id) {
  643. if (nextSession) {
  644. navigate(`/${params.dir}/session/${nextSession.id}`)
  645. } else {
  646. navigate(`/${params.dir}/session`)
  647. }
  648. }
  649. }
  650. command.register(() => {
  651. const commands: CommandOption[] = [
  652. {
  653. id: "sidebar.toggle",
  654. title: "Toggle sidebar",
  655. category: "View",
  656. keybind: "mod+b",
  657. onSelect: () => layout.sidebar.toggle(),
  658. },
  659. {
  660. id: "project.open",
  661. title: "Open project",
  662. category: "Project",
  663. keybind: "mod+o",
  664. onSelect: () => chooseProject(),
  665. },
  666. {
  667. id: "provider.connect",
  668. title: "Connect provider",
  669. category: "Provider",
  670. onSelect: () => connectProvider(),
  671. },
  672. {
  673. id: "server.switch",
  674. title: "Switch server",
  675. category: "Server",
  676. onSelect: () => openServer(),
  677. },
  678. {
  679. id: "session.previous",
  680. title: "Previous session",
  681. category: "Session",
  682. keybind: "alt+arrowup",
  683. onSelect: () => navigateSessionByOffset(-1),
  684. },
  685. {
  686. id: "session.next",
  687. title: "Next session",
  688. category: "Session",
  689. keybind: "alt+arrowdown",
  690. onSelect: () => navigateSessionByOffset(1),
  691. },
  692. {
  693. id: "session.archive",
  694. title: "Archive session",
  695. category: "Session",
  696. keybind: "mod+shift+backspace",
  697. disabled: !params.dir || !params.id,
  698. onSelect: () => {
  699. const session = currentSessions().find((s) => s.id === params.id)
  700. if (session) archiveSession(session)
  701. },
  702. },
  703. {
  704. id: "theme.cycle",
  705. title: "Cycle theme",
  706. category: "Theme",
  707. keybind: "mod+shift+t",
  708. onSelect: () => cycleTheme(1),
  709. },
  710. ]
  711. for (const [id, definition] of availableThemeEntries()) {
  712. commands.push({
  713. id: `theme.set.${id}`,
  714. title: `Use theme: ${definition.name ?? id}`,
  715. category: "Theme",
  716. onSelect: () => theme.commitPreview(),
  717. onHighlight: () => {
  718. theme.previewTheme(id)
  719. return () => theme.cancelPreview()
  720. },
  721. })
  722. }
  723. commands.push({
  724. id: "theme.scheme.cycle",
  725. title: "Cycle color scheme",
  726. category: "Theme",
  727. keybind: "mod+shift+s",
  728. onSelect: () => cycleColorScheme(1),
  729. })
  730. for (const scheme of colorSchemeOrder) {
  731. commands.push({
  732. id: `theme.scheme.${scheme}`,
  733. title: `Use color scheme: ${colorSchemeLabel[scheme]}`,
  734. category: "Theme",
  735. onSelect: () => theme.commitPreview(),
  736. onHighlight: () => {
  737. theme.previewColorScheme(scheme)
  738. return () => theme.cancelPreview()
  739. },
  740. })
  741. }
  742. return commands
  743. })
  744. function connectProvider() {
  745. dialog.show(() => <DialogSelectProvider />)
  746. }
  747. function openServer() {
  748. dialog.show(() => <DialogSelectServer />)
  749. }
  750. function navigateToProject(directory: string | undefined) {
  751. if (!directory) return
  752. server.projects.touch(directory)
  753. const lastSession = store.lastSession[directory]
  754. navigate(`/${base64Encode(directory)}${lastSession ? `/session/${lastSession}` : ""}`)
  755. layout.mobileSidebar.hide()
  756. }
  757. function navigateToSession(session: Session | undefined) {
  758. if (!session) return
  759. navigate(`/${base64Encode(session.directory)}/session/${session.id}`)
  760. layout.mobileSidebar.hide()
  761. }
  762. function openProject(directory: string, navigate = true) {
  763. layout.projects.open(directory)
  764. if (navigate) navigateToProject(directory)
  765. }
  766. const displayName = (project: LocalProject) => project.name || getFilename(project.worktree)
  767. async function renameProject(project: LocalProject, next: string) {
  768. if (!project.id) return
  769. const current = displayName(project)
  770. if (next === current) return
  771. const name = next === getFilename(project.worktree) ? "" : next
  772. await globalSDK.client.project.update({ projectID: project.id, name })
  773. }
  774. async function renameSession(session: Session, next: string) {
  775. if (next === session.title) return
  776. await globalSDK.client.session.update({
  777. directory: session.directory,
  778. sessionID: session.id,
  779. title: next,
  780. })
  781. }
  782. const renameWorkspace = (directory: string, next: string) => {
  783. const current = workspaceName(directory) ?? getFilename(directory)
  784. if (current === next) return
  785. setStore("workspaceName", directory, next)
  786. }
  787. function closeProject(directory: string) {
  788. const index = layout.projects.list().findIndex((x) => x.worktree === directory)
  789. const next = layout.projects.list()[index + 1]
  790. layout.projects.close(directory)
  791. if (next) navigateToProject(next.worktree)
  792. else navigate("/")
  793. }
  794. async function chooseProject() {
  795. function resolve(result: string | string[] | null) {
  796. if (Array.isArray(result)) {
  797. for (const directory of result) {
  798. openProject(directory, false)
  799. }
  800. navigateToProject(result[0])
  801. } else if (result) {
  802. openProject(result)
  803. }
  804. }
  805. if (platform.openDirectoryPickerDialog && server.isLocal()) {
  806. const result = await platform.openDirectoryPickerDialog?.({
  807. title: "Open project",
  808. multiple: true,
  809. })
  810. resolve(result)
  811. } else {
  812. dialog.show(
  813. () => <DialogSelectDirectory multiple={true} onSelect={resolve} />,
  814. () => resolve(null),
  815. )
  816. }
  817. }
  818. const errorMessage = (err: unknown) => {
  819. if (err && typeof err === "object" && "data" in err) {
  820. const data = (err as { data?: { message?: string } }).data
  821. if (data?.message) return data.message
  822. }
  823. if (err instanceof Error) return err.message
  824. return "Request failed"
  825. }
  826. const deleteWorkspace = async (directory: string) => {
  827. const current = currentProject()
  828. if (!current) return
  829. if (directory === current.worktree) return
  830. const result = await globalSDK.client.worktree
  831. .remove({ directory: current.worktree, worktreeRemoveInput: { directory } })
  832. .then((x) => x.data)
  833. .catch((err) => {
  834. showToast({
  835. title: "Failed to delete workspace",
  836. description: errorMessage(err),
  837. })
  838. return false
  839. })
  840. if (!result) return
  841. layout.projects.close(directory)
  842. layout.projects.open(current.worktree)
  843. if (params.dir && base64Decode(params.dir) === directory) {
  844. navigateToProject(current.worktree)
  845. }
  846. }
  847. const resetWorkspace = async (directory: string) => {
  848. const current = currentProject()
  849. if (!current) return
  850. if (directory === current.worktree) return
  851. const reset = globalSDK.client.worktree
  852. .reset({ directory: current.worktree, worktreeResetInput: { directory } })
  853. .then((x) => x.data)
  854. .catch((err) => {
  855. showToast({
  856. title: "Failed to reset workspace",
  857. description: errorMessage(err),
  858. })
  859. return false
  860. })
  861. const href = `/${base64Encode(directory)}/session`
  862. navigate(href)
  863. layout.mobileSidebar.hide()
  864. void (async () => {
  865. const sessions = await globalSDK.client.session
  866. .list({ directory })
  867. .then((x) => x.data ?? [])
  868. .catch(() => [])
  869. if (sessions.length === 0) return
  870. const archivedAt = Date.now()
  871. await Promise.all(
  872. sessions.map((session) =>
  873. globalSDK.client.session
  874. .update({
  875. sessionID: session.id,
  876. directory: session.directory,
  877. time: { archived: archivedAt },
  878. })
  879. .catch(() => undefined),
  880. ),
  881. )
  882. })()
  883. const result = await reset
  884. if (!result) return
  885. showToast({
  886. title: "Workspace reset",
  887. description: "Workspace now matches the default branch.",
  888. })
  889. }
  890. function DialogDeleteWorkspace(props: { directory: string }) {
  891. const name = createMemo(() => getFilename(props.directory))
  892. const [data, setData] = createStore({
  893. status: "loading" as "loading" | "ready" | "error",
  894. dirty: false,
  895. })
  896. onMount(() => {
  897. const current = currentProject()
  898. if (!current) {
  899. setData({ status: "error", dirty: false })
  900. return
  901. }
  902. globalSDK.client.file
  903. .status({ directory: props.directory })
  904. .then((x) => {
  905. const files = x.data ?? []
  906. const dirty = files.length > 0
  907. setData({ status: "ready", dirty })
  908. })
  909. .catch(() => {
  910. setData({ status: "error", dirty: false })
  911. })
  912. })
  913. const handleDelete = async () => {
  914. await deleteWorkspace(props.directory)
  915. dialog.close()
  916. }
  917. const description = () => {
  918. if (data.status === "loading") return "Checking for unmerged changes..."
  919. if (data.status === "error") return "Unable to verify git status."
  920. if (!data.dirty) return "No unmerged changes detected."
  921. return "Unmerged changes detected in this workspace."
  922. }
  923. return (
  924. <Dialog title="Delete workspace" fit>
  925. <div class="flex flex-col gap-4 px-2.5 pb-3">
  926. <div class="flex flex-col gap-1">
  927. <span class="text-14-regular text-text-strong">Delete workspace "{name()}"?</span>
  928. <span class="text-12-regular text-text-weak">{description()}</span>
  929. </div>
  930. <div class="flex justify-end gap-2">
  931. <Button variant="ghost" size="large" onClick={() => dialog.close()}>
  932. Cancel
  933. </Button>
  934. <Button variant="primary" size="large" disabled={data.status === "loading"} onClick={handleDelete}>
  935. Delete workspace
  936. </Button>
  937. </div>
  938. </div>
  939. </Dialog>
  940. )
  941. }
  942. function DialogResetWorkspace(props: { directory: string }) {
  943. const name = createMemo(() => getFilename(props.directory))
  944. const [state, setState] = createStore({
  945. status: "loading" as "loading" | "ready" | "error",
  946. dirty: false,
  947. sessions: [] as Session[],
  948. })
  949. const refresh = async () => {
  950. const sessions = await globalSDK.client.session
  951. .list({ directory: props.directory })
  952. .then((x) => x.data ?? [])
  953. .catch(() => [])
  954. const active = sessions.filter((session) => session.time.archived === undefined)
  955. setState({ sessions: active })
  956. }
  957. onMount(() => {
  958. const current = currentProject()
  959. if (!current) {
  960. setState({ status: "error", dirty: false })
  961. return
  962. }
  963. globalSDK.client.file
  964. .status({ directory: props.directory })
  965. .then((x) => {
  966. const files = x.data ?? []
  967. const dirty = files.length > 0
  968. setState({ status: "ready", dirty })
  969. void refresh()
  970. })
  971. .catch(() => {
  972. setState({ status: "error", dirty: false })
  973. })
  974. })
  975. const handleReset = () => {
  976. dialog.close()
  977. void resetWorkspace(props.directory)
  978. }
  979. const archivedCount = () => state.sessions.length
  980. const description = () => {
  981. if (state.status === "loading") return "Checking for unmerged changes..."
  982. if (state.status === "error") return "Unable to verify git status."
  983. if (!state.dirty) return "No unmerged changes detected."
  984. return "Unmerged changes detected in this workspace."
  985. }
  986. const archivedLabel = () => {
  987. const count = archivedCount()
  988. if (count === 0) return "No active sessions will be archived."
  989. const label = count === 1 ? "1 session" : `${count} sessions`
  990. return `${label} will be archived.`
  991. }
  992. return (
  993. <Dialog title="Reset workspace" fit>
  994. <div class="flex flex-col gap-4 px-2.5 pb-3">
  995. <div class="flex flex-col gap-1">
  996. <span class="text-14-regular text-text-strong">Reset workspace "{name()}"?</span>
  997. <span class="text-12-regular text-text-weak">
  998. {description()} {archivedLabel()} This will reset the workspace to match the default branch.
  999. </span>
  1000. </div>
  1001. <div class="flex justify-end gap-2">
  1002. <Button variant="ghost" size="large" onClick={() => dialog.close()}>
  1003. Cancel
  1004. </Button>
  1005. <Button variant="primary" size="large" disabled={state.status === "loading"} onClick={handleReset}>
  1006. Reset workspace
  1007. </Button>
  1008. </div>
  1009. </div>
  1010. </Dialog>
  1011. )
  1012. }
  1013. createEffect(
  1014. on(
  1015. () => ({ ready: pageReady(), dir: params.dir, id: params.id }),
  1016. (value) => {
  1017. if (!value.ready) return
  1018. const dir = value.dir
  1019. const id = value.id
  1020. if (!dir || !id) return
  1021. const directory = base64Decode(dir)
  1022. setStore("lastSession", directory, id)
  1023. notification.session.markViewed(id)
  1024. const expanded = untrack(() => store.workspaceExpanded[directory])
  1025. if (expanded === false) {
  1026. setStore("workspaceExpanded", directory, true)
  1027. }
  1028. requestAnimationFrame(() => scrollToSession(id, `${directory}:${id}`))
  1029. },
  1030. { defer: true },
  1031. ),
  1032. )
  1033. createEffect(() => {
  1034. const project = currentProject()
  1035. if (!project) return
  1036. if (workspaceSetting()) {
  1037. const dirs = [project.worktree, ...(project.sandboxes ?? [])]
  1038. for (const directory of dirs) {
  1039. globalSync.project.loadSessions(directory)
  1040. }
  1041. return
  1042. }
  1043. globalSync.project.loadSessions(project.worktree)
  1044. })
  1045. function getDraggableId(event: unknown): string | undefined {
  1046. if (typeof event !== "object" || event === null) return undefined
  1047. if (!("draggable" in event)) return undefined
  1048. const draggable = (event as { draggable?: { id?: unknown } }).draggable
  1049. if (!draggable) return undefined
  1050. return typeof draggable.id === "string" ? draggable.id : undefined
  1051. }
  1052. function handleDragStart(event: unknown) {
  1053. const id = getDraggableId(event)
  1054. if (!id) return
  1055. setStore("activeProject", id)
  1056. }
  1057. function handleDragOver(event: DragEvent) {
  1058. const { draggable, droppable } = event
  1059. if (draggable && droppable) {
  1060. const projects = layout.projects.list()
  1061. const fromIndex = projects.findIndex((p) => p.worktree === draggable.id.toString())
  1062. const toIndex = projects.findIndex((p) => p.worktree === droppable.id.toString())
  1063. if (fromIndex !== toIndex && toIndex !== -1) {
  1064. layout.projects.move(draggable.id.toString(), toIndex)
  1065. }
  1066. }
  1067. }
  1068. function handleDragEnd() {
  1069. setStore("activeProject", undefined)
  1070. }
  1071. function workspaceIds(project: LocalProject | undefined) {
  1072. if (!project) return []
  1073. const dirs = [project.worktree, ...(project.sandboxes ?? [])]
  1074. const active = currentProject()
  1075. const directory = active?.worktree === project.worktree && params.dir ? base64Decode(params.dir) : undefined
  1076. const next = directory && directory !== project.worktree && !dirs.includes(directory) ? [...dirs, directory] : dirs
  1077. const existing = store.workspaceOrder[project.worktree]
  1078. if (!existing) return next
  1079. const keep = existing.filter((d) => next.includes(d))
  1080. const missing = next.filter((d) => !existing.includes(d))
  1081. return [...keep, ...missing]
  1082. }
  1083. function handleWorkspaceDragStart(event: unknown) {
  1084. const id = getDraggableId(event)
  1085. if (!id) return
  1086. setStore("activeWorkspace", id)
  1087. }
  1088. function handleWorkspaceDragOver(event: DragEvent) {
  1089. const { draggable, droppable } = event
  1090. if (!draggable || !droppable) return
  1091. const project = currentProject()
  1092. if (!project) return
  1093. const ids = workspaceIds(project)
  1094. const fromIndex = ids.findIndex((dir) => dir === draggable.id.toString())
  1095. const toIndex = ids.findIndex((dir) => dir === droppable.id.toString())
  1096. if (fromIndex === -1 || toIndex === -1) return
  1097. if (fromIndex === toIndex) return
  1098. const result = ids.slice()
  1099. const [item] = result.splice(fromIndex, 1)
  1100. if (!item) return
  1101. result.splice(toIndex, 0, item)
  1102. setStore("workspaceOrder", project.worktree, result)
  1103. }
  1104. function handleWorkspaceDragEnd() {
  1105. setStore("activeWorkspace", undefined)
  1106. }
  1107. const ProjectIcon = (props: { project: LocalProject; class?: string; notify?: boolean }): JSX.Element => {
  1108. const notification = useNotification()
  1109. const notifications = createMemo(() => notification.project.unseen(props.project.worktree))
  1110. const hasError = createMemo(() => notifications().some((n) => n.type === "error"))
  1111. const name = createMemo(() => props.project.name || getFilename(props.project.worktree))
  1112. const mask = "radial-gradient(circle 5px at calc(100% - 4px) 4px, transparent 5px, black 5.5px)"
  1113. const opencode = "4b0ea68d7af9a6031a7ffda7ad66e0cb83315750"
  1114. return (
  1115. <div class={`relative size-8 shrink-0 rounded ${props.class ?? ""}`}>
  1116. <div class="size-full rounded overflow-clip">
  1117. <Avatar
  1118. fallback={name()}
  1119. src={props.project.id === opencode ? "https://opencode.ai/favicon.svg" : props.project.icon?.url}
  1120. {...getAvatarColors(props.project.icon?.color)}
  1121. class="size-full rounded"
  1122. style={
  1123. notifications().length > 0 && props.notify
  1124. ? { "-webkit-mask-image": mask, "mask-image": mask }
  1125. : undefined
  1126. }
  1127. />
  1128. </div>
  1129. <Show when={notifications().length > 0 && props.notify}>
  1130. <div
  1131. classList={{
  1132. "absolute top-px right-px size-1.5 rounded-full z-10": true,
  1133. "bg-icon-critical-base": hasError(),
  1134. "bg-text-interactive-base": !hasError(),
  1135. }}
  1136. />
  1137. </Show>
  1138. </div>
  1139. )
  1140. }
  1141. const SessionItem = (props: { session: Session; slug: string; mobile?: boolean; dense?: boolean }): JSX.Element => {
  1142. const notification = useNotification()
  1143. const notifications = createMemo(() => notification.session.unseen(props.session.id))
  1144. const hasError = createMemo(() => notifications().some((n) => n.type === "error"))
  1145. const [sessionStore] = globalSync.child(props.session.directory)
  1146. const hasPermissions = createMemo(() => {
  1147. const permissions = sessionStore.permission?.[props.session.id] ?? []
  1148. if (permissions.length > 0) return true
  1149. const childSessions = sessionStore.session.filter((s) => s.parentID === props.session.id)
  1150. for (const child of childSessions) {
  1151. const childPermissions = sessionStore.permission?.[child.id] ?? []
  1152. if (childPermissions.length > 0) return true
  1153. }
  1154. return false
  1155. })
  1156. const isWorking = createMemo(() => {
  1157. if (hasPermissions()) return false
  1158. const status = sessionStore.session_status[props.session.id]
  1159. return status?.type === "busy" || status?.type === "retry"
  1160. })
  1161. const tint = createMemo(() => {
  1162. const messages = sessionStore.message[props.session.id]
  1163. if (!messages) return undefined
  1164. const user = messages
  1165. .slice()
  1166. .reverse()
  1167. .find((m) => m.role === "user")
  1168. if (!user?.agent) return undefined
  1169. const agent = sessionStore.agent.find((a) => a.name === user.agent)
  1170. return agent?.color
  1171. })
  1172. return (
  1173. <div
  1174. data-session-id={props.session.id}
  1175. class="group/session relative w-full rounded-md cursor-default transition-colors pl-2 pr-3
  1176. hover:bg-surface-raised-base-hover focus-within:bg-surface-raised-base-hover has-[.active]:bg-surface-base-active"
  1177. >
  1178. <A
  1179. href={`${props.slug}/session/${props.session.id}`}
  1180. class={`flex items-center justify-between gap-3 min-w-0 text-left w-full focus:outline-none transition-[padding] group-hover/session:pr-7 group-focus-within/session:pr-7 group-active/session:pr-7 ${props.dense ? "py-0.5" : "py-1"}`}
  1181. onMouseEnter={() => prefetchSession(props.session, "high")}
  1182. onFocus={() => prefetchSession(props.session, "high")}
  1183. >
  1184. <div class="flex items-center gap-1 w-full">
  1185. <div
  1186. class="shrink-0 size-6 flex items-center justify-center"
  1187. style={{ color: tint() ?? "var(--icon-interactive-base)" }}
  1188. >
  1189. <Switch fallback={<Icon name="dash" size="small" class="text-icon-weak" />}>
  1190. <Match when={isWorking()}>
  1191. <Spinner class="size-[15px]" />
  1192. </Match>
  1193. <Match when={hasPermissions()}>
  1194. <div class="size-1.5 rounded-full bg-surface-warning-strong" />
  1195. </Match>
  1196. <Match when={hasError()}>
  1197. <div class="size-1.5 rounded-full bg-text-diff-delete-base" />
  1198. </Match>
  1199. <Match when={notifications().length > 0}>
  1200. <div class="size-1.5 rounded-full bg-text-interactive-base" />
  1201. </Match>
  1202. </Switch>
  1203. </div>
  1204. <Tooltip
  1205. placement="top-start"
  1206. value={props.session.title}
  1207. gutter={0}
  1208. openDelay={3000}
  1209. class="grow-1 min-w-0"
  1210. >
  1211. <InlineEditor
  1212. id={`session:${props.session.id}`}
  1213. value={() => props.session.title}
  1214. onSave={(next) => renameSession(props.session, next)}
  1215. class="text-14-regular text-text-strong grow-1 min-w-0 overflow-hidden text-ellipsis truncate"
  1216. displayClass="text-14-regular text-text-strong grow-1 min-w-0 overflow-hidden text-ellipsis truncate"
  1217. stopPropagation
  1218. />
  1219. </Tooltip>
  1220. <Show when={props.session.summary}>
  1221. {(summary) => (
  1222. <div class="group-hover/session:hidden group-active/session:hidden group-focus-within/session:hidden">
  1223. <DiffChanges changes={summary()} />
  1224. </div>
  1225. )}
  1226. </Show>
  1227. </div>
  1228. </A>
  1229. <div
  1230. class={`hidden group-hover/session:flex group-active/session:flex group-focus-within/session:flex text-text-base gap-1 items-center absolute ${props.dense ? "top-0.5 right-0.5" : "top-1 right-1"}`}
  1231. >
  1232. <TooltipKeybind
  1233. placement={props.mobile ? "bottom" : "right"}
  1234. title="Archive session"
  1235. keybind={command.keybind("session.archive")}
  1236. gutter={8}
  1237. >
  1238. <IconButton icon="archive" variant="ghost" onClick={() => archiveSession(props.session)} />
  1239. </TooltipKeybind>
  1240. </div>
  1241. </div>
  1242. )
  1243. }
  1244. const SessionSkeleton = (props: { count?: number }): JSX.Element => {
  1245. const items = Array.from({ length: props.count ?? 4 }, (_, index) => index)
  1246. return (
  1247. <div class="flex flex-col gap-1">
  1248. <For each={items}>
  1249. {() => <div class="h-8 w-full rounded-md bg-surface-raised-base opacity-60 animate-pulse" />}
  1250. </For>
  1251. </div>
  1252. )
  1253. }
  1254. const ProjectDragOverlay = (): JSX.Element => {
  1255. const project = createMemo(() => layout.projects.list().find((p) => p.worktree === store.activeProject))
  1256. return (
  1257. <Show when={project()}>
  1258. {(p) => (
  1259. <div class="bg-background-base rounded-xl p-1">
  1260. <ProjectIcon project={p()} />
  1261. </div>
  1262. )}
  1263. </Show>
  1264. )
  1265. }
  1266. const WorkspaceDragOverlay = (): JSX.Element => {
  1267. const label = createMemo(() => {
  1268. const project = currentProject()
  1269. if (!project) return
  1270. const directory = store.activeWorkspace
  1271. if (!directory) return
  1272. const [workspaceStore] = globalSync.child(directory)
  1273. const kind = directory === project.worktree ? "local" : "sandbox"
  1274. const name = workspaceLabel(directory, workspaceStore.vcs?.branch)
  1275. return `${kind} : ${name}`
  1276. })
  1277. return (
  1278. <Show when={label()}>
  1279. {(value) => (
  1280. <div class="bg-background-base rounded-md px-2 py-1 text-14-medium text-text-strong">{value()}</div>
  1281. )}
  1282. </Show>
  1283. )
  1284. }
  1285. const SortableWorkspace = (props: { directory: string; project: LocalProject; mobile?: boolean }): JSX.Element => {
  1286. const sortable = createSortable(props.directory)
  1287. const [workspaceStore, setWorkspaceStore] = globalSync.child(props.directory)
  1288. const [menuOpen, setMenuOpen] = createSignal(false)
  1289. const slug = createMemo(() => base64Encode(props.directory))
  1290. const sessions = createMemo(() =>
  1291. workspaceStore.session
  1292. .filter((session) => session.directory === workspaceStore.path.directory)
  1293. .filter((session) => !session.parentID && !session.time?.archived)
  1294. .toSorted(sortSessions),
  1295. )
  1296. const local = createMemo(() => props.directory === props.project.worktree)
  1297. const workspaceValue = createMemo(() => {
  1298. const name = workspaceStore.vcs?.branch ?? getFilename(props.directory)
  1299. return workspaceName(props.directory) ?? name
  1300. })
  1301. const open = createMemo(() => store.workspaceExpanded[props.directory] ?? true)
  1302. const loading = createMemo(() => open() && workspaceStore.status !== "complete" && sessions().length === 0)
  1303. const hasMore = createMemo(() => local() && workspaceStore.sessionTotal > workspaceStore.session.length)
  1304. const loadMore = async () => {
  1305. if (!local()) return
  1306. setWorkspaceStore("limit", (limit) => limit + 5)
  1307. await globalSync.project.loadSessions(props.directory)
  1308. }
  1309. const workspaceEditActive = createMemo(() => editorOpen(`workspace:${props.directory}`))
  1310. const openWrapper = (value: boolean) => {
  1311. setStore("workspaceExpanded", props.directory, value)
  1312. if (value) return
  1313. if (editorOpen(`workspace:${props.directory}`)) closeEditor()
  1314. }
  1315. return (
  1316. // @ts-ignore
  1317. <div use:sortable classList={{ "opacity-30": sortable.isActiveDraggable }}>
  1318. <Collapsible variant="ghost" open={open()} class="shrink-0" onOpenChange={openWrapper}>
  1319. <div class="px-2 py-1">
  1320. <div class="group/workspace relative">
  1321. <div class="flex items-center gap-1">
  1322. <Collapsible.Trigger class="flex items-center justify-between w-full pl-2 pr-16 py-1.5 rounded-md hover:bg-surface-raised-base-hover">
  1323. <div class="flex items-center gap-1 min-w-0 flex-1">
  1324. <div class="flex items-center justify-center shrink-0 size-6">
  1325. <Icon name="branch" size="small" />
  1326. </div>
  1327. <span class="text-14-medium text-text-base shrink-0">{local() ? "local" : "sandbox"} :</span>
  1328. <Show
  1329. when={!local()}
  1330. fallback={
  1331. <span class="text-14-medium text-text-base min-w-0 truncate">
  1332. {workspaceStore.vcs?.branch ?? getFilename(props.directory)}
  1333. </span>
  1334. }
  1335. >
  1336. <InlineEditor
  1337. id={`workspace:${props.directory}`}
  1338. value={workspaceValue}
  1339. onSave={(next) => {
  1340. const trimmed = next.trim()
  1341. if (!trimmed) return
  1342. renameWorkspace(props.directory, trimmed)
  1343. setEditor("value", workspaceValue())
  1344. }}
  1345. class="text-14-medium text-text-base min-w-0 truncate"
  1346. displayClass="text-14-medium text-text-base min-w-0 truncate"
  1347. editing={workspaceEditActive()}
  1348. stopPropagation={false}
  1349. openOnDblClick={false}
  1350. />
  1351. </Show>
  1352. <Icon
  1353. name={open() ? "chevron-down" : "chevron-right"}
  1354. size="small"
  1355. class="shrink-0 text-icon-base opacity-0 transition-opacity group-hover/workspace:opacity-100 group-focus-within/workspace:opacity-100"
  1356. />
  1357. </div>
  1358. </Collapsible.Trigger>
  1359. <div
  1360. class="absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-0.5 transition-opacity"
  1361. classList={{
  1362. "opacity-100 pointer-events-auto": menuOpen(),
  1363. "opacity-0 pointer-events-none": !menuOpen(),
  1364. "group-hover/workspace:opacity-100 group-hover/workspace:pointer-events-auto": true,
  1365. "group-focus-within/workspace:opacity-100 group-focus-within/workspace:pointer-events-auto": true,
  1366. }}
  1367. >
  1368. <DropdownMenu open={menuOpen()} onOpenChange={setMenuOpen}>
  1369. <Tooltip value="More options" placement="top">
  1370. <DropdownMenu.Trigger as={IconButton} icon="dot-grid" variant="ghost" class="size-6 rounded-md" />
  1371. </Tooltip>
  1372. <DropdownMenu.Portal>
  1373. <DropdownMenu.Content>
  1374. <DropdownMenu.Item onSelect={() => navigate(`/${slug()}/session`)}>
  1375. <DropdownMenu.ItemLabel>New session</DropdownMenu.ItemLabel>
  1376. </DropdownMenu.Item>
  1377. <DropdownMenu.Item
  1378. disabled={local()}
  1379. onSelect={() => dialog.show(() => <DialogResetWorkspace directory={props.directory} />)}
  1380. >
  1381. <DropdownMenu.ItemLabel>Reset workspace</DropdownMenu.ItemLabel>
  1382. </DropdownMenu.Item>
  1383. <DropdownMenu.Item
  1384. disabled={local()}
  1385. onSelect={() => dialog.show(() => <DialogDeleteWorkspace directory={props.directory} />)}
  1386. >
  1387. <DropdownMenu.ItemLabel>Delete workspace</DropdownMenu.ItemLabel>
  1388. </DropdownMenu.Item>
  1389. </DropdownMenu.Content>
  1390. </DropdownMenu.Portal>
  1391. </DropdownMenu>
  1392. <TooltipKeybind placement="right" title="New session" keybind={command.keybind("session.new")}>
  1393. <IconButton
  1394. icon="plus-small"
  1395. variant="ghost"
  1396. class="size-6 rounded-md"
  1397. onClick={() => navigate(`/${slug()}/session`)}
  1398. />
  1399. </TooltipKeybind>
  1400. </div>
  1401. </div>
  1402. </div>
  1403. </div>
  1404. <Collapsible.Content>
  1405. <nav class="flex flex-col gap-1 px-2">
  1406. <Button
  1407. as={A}
  1408. href={`${slug()}/session`}
  1409. variant="ghost"
  1410. size="large"
  1411. icon="edit"
  1412. class="hidden _flex w-full text-left justify-start text-text-base rounded-md px-3"
  1413. >
  1414. New session
  1415. </Button>
  1416. <Show when={loading()}>
  1417. <SessionSkeleton />
  1418. </Show>
  1419. <For each={sessions()}>
  1420. {(session) => <SessionItem session={session} slug={slug()} mobile={props.mobile} />}
  1421. </For>
  1422. <Show when={hasMore()}>
  1423. <div class="relative w-full py-1">
  1424. <Button
  1425. variant="ghost"
  1426. class="flex w-full text-left justify-start text-14-regular text-text-weak pl-9 pr-10"
  1427. size="large"
  1428. onClick={(e: MouseEvent) => {
  1429. loadMore()
  1430. ;(e.currentTarget as HTMLButtonElement).blur()
  1431. }}
  1432. >
  1433. Load more
  1434. </Button>
  1435. </div>
  1436. </Show>
  1437. </nav>
  1438. </Collapsible.Content>
  1439. </Collapsible>
  1440. </div>
  1441. )
  1442. }
  1443. const SortableProject = (props: { project: LocalProject; mobile?: boolean }): JSX.Element => {
  1444. const sortable = createSortable(props.project.worktree)
  1445. const selected = createMemo(() => {
  1446. const current = params.dir ? base64Decode(params.dir) : ""
  1447. return props.project.worktree === current || props.project.sandboxes?.includes(current)
  1448. })
  1449. const workspaces = createMemo(() => workspaceIds(props.project).slice(0, 2))
  1450. const workspaceEnabled = createMemo(() => layout.sidebar.workspaces(props.project.worktree)())
  1451. const [open, setOpen] = createSignal(false)
  1452. const label = (directory: string) => {
  1453. const [data] = globalSync.child(directory)
  1454. const kind = directory === props.project.worktree ? "local" : "sandbox"
  1455. const name = workspaceLabel(directory, data.vcs?.branch)
  1456. return `${kind} : ${name}`
  1457. }
  1458. const sessions = (directory: string) => {
  1459. const [data] = globalSync.child(directory)
  1460. return data.session
  1461. .filter((session) => session.directory === data.path.directory)
  1462. .filter((session) => !session.parentID && !session.time?.archived)
  1463. .toSorted(sortSessions)
  1464. .slice(0, 2)
  1465. }
  1466. const projectSessions = () => {
  1467. const [data] = globalSync.child(props.project.worktree)
  1468. return data.session
  1469. .filter((session) => session.directory === data.path.directory)
  1470. .filter((session) => !session.parentID && !session.time?.archived)
  1471. .toSorted(sortSessions)
  1472. .slice(0, 2)
  1473. }
  1474. const trigger = (
  1475. <button
  1476. type="button"
  1477. classList={{
  1478. "flex items-center justify-center size-10 p-1 rounded-lg overflow-hidden transition-colors cursor-default": true,
  1479. "bg-transparent border-2 border-icon-strong-base hover:bg-surface-base-hover": selected(),
  1480. "bg-transparent border border-transparent hover:bg-surface-base-hover hover:border-border-weak-base":
  1481. !selected() && !open(),
  1482. "bg-surface-base-hover border border-border-weak-base": !selected() && open(),
  1483. }}
  1484. onClick={() => navigateToProject(props.project.worktree)}
  1485. >
  1486. <ProjectIcon project={props.project} notify />
  1487. </button>
  1488. )
  1489. return (
  1490. // @ts-ignore
  1491. <div use:sortable classList={{ "opacity-30": sortable.isActiveDraggable }}>
  1492. <HoverCard
  1493. openDelay={0}
  1494. closeDelay={0}
  1495. placement="right-start"
  1496. gutter={6}
  1497. trigger={trigger}
  1498. onOpenChange={setOpen}
  1499. >
  1500. <div class="-m-3 flex flex-col w-72">
  1501. <div class="px-4 pt-2 pb-1 text-14-medium text-text-strong truncate">{displayName(props.project)}</div>
  1502. <div class="px-4 pb-2 text-12-medium text-text-weak">Recent sessions</div>
  1503. <div class="px-2 pb-2 flex flex-col gap-2">
  1504. <Show
  1505. when={workspaceEnabled()}
  1506. fallback={
  1507. <For each={projectSessions()}>
  1508. {(session) => (
  1509. <SessionItem
  1510. session={session}
  1511. slug={base64Encode(props.project.worktree)}
  1512. dense
  1513. mobile={props.mobile}
  1514. />
  1515. )}
  1516. </For>
  1517. }
  1518. >
  1519. <For each={workspaces()}>
  1520. {(directory) => (
  1521. <div class="flex flex-col gap-1">
  1522. <div class="px-2 py-0.5 flex items-center gap-1 min-w-0">
  1523. <div class="shrink-0 size-6 flex items-center justify-center">
  1524. <Icon name="branch" size="small" class="text-icon-base" />
  1525. </div>
  1526. <span class="truncate text-14-medium text-text-base">{label(directory)}</span>
  1527. </div>
  1528. <For each={sessions(directory)}>
  1529. {(session) => (
  1530. <SessionItem session={session} slug={base64Encode(directory)} dense mobile={props.mobile} />
  1531. )}
  1532. </For>
  1533. </div>
  1534. )}
  1535. </For>
  1536. </Show>
  1537. </div>
  1538. <Show when={!selected()}>
  1539. <div class="px-2 py-2 border-t border-border-weak-base">
  1540. <Button
  1541. variant="ghost"
  1542. class="flex w-full text-left justify-start text-text-base px-2 hover:bg-transparent active:bg-transparent"
  1543. onClick={() => {
  1544. layout.sidebar.open()
  1545. navigateToProject(props.project.worktree)
  1546. }}
  1547. >
  1548. View all sessions
  1549. </Button>
  1550. </div>
  1551. </Show>
  1552. </div>
  1553. </HoverCard>
  1554. </div>
  1555. )
  1556. }
  1557. const LocalWorkspace = (props: { project: LocalProject; mobile?: boolean }): JSX.Element => {
  1558. const [workspaceStore, setWorkspaceStore] = globalSync.child(props.project.worktree)
  1559. const slug = createMemo(() => base64Encode(props.project.worktree))
  1560. const sessions = createMemo(() =>
  1561. workspaceStore.session
  1562. .filter((session) => session.directory === workspaceStore.path.directory)
  1563. .filter((session) => !session.parentID && !session.time?.archived)
  1564. .toSorted(sortSessions),
  1565. )
  1566. const loading = createMemo(() => workspaceStore.status !== "complete" && sessions().length === 0)
  1567. const hasMore = createMemo(() => workspaceStore.sessionTotal > workspaceStore.session.length)
  1568. const loadMore = async () => {
  1569. setWorkspaceStore("limit", (limit) => limit + 5)
  1570. await globalSync.project.loadSessions(props.project.worktree)
  1571. }
  1572. return (
  1573. <div
  1574. ref={(el) => {
  1575. if (!props.mobile) scrollContainerRef = el
  1576. }}
  1577. class="size-full flex flex-col py-2 overflow-y-auto no-scrollbar"
  1578. style={{ "overflow-anchor": "none" }}
  1579. >
  1580. <nav class="flex flex-col gap-1 px-2">
  1581. <Show when={loading()}>
  1582. <SessionSkeleton />
  1583. </Show>
  1584. <For each={sessions()}>
  1585. {(session) => <SessionItem session={session} slug={slug()} mobile={props.mobile} />}
  1586. </For>
  1587. <Show when={hasMore()}>
  1588. <div class="relative w-full py-1">
  1589. <Button
  1590. variant="ghost"
  1591. class="flex w-full text-left justify-start text-14-regular text-text-weak pl-9 pr-10"
  1592. size="large"
  1593. onClick={(e: MouseEvent) => {
  1594. loadMore()
  1595. ;(e.currentTarget as HTMLButtonElement).blur()
  1596. }}
  1597. >
  1598. Load more
  1599. </Button>
  1600. </div>
  1601. </Show>
  1602. </nav>
  1603. </div>
  1604. )
  1605. }
  1606. const SidebarContent = (sidebarProps: { mobile?: boolean }) => {
  1607. const expanded = () => sidebarProps.mobile || layout.sidebar.opened()
  1608. const sync = useGlobalSync()
  1609. const project = createMemo(() => currentProject())
  1610. const projectName = createMemo(() => {
  1611. const current = project()
  1612. if (!current) return ""
  1613. return current.name || getFilename(current.worktree)
  1614. })
  1615. const projectId = createMemo(() => project()?.id ?? "")
  1616. const workspaces = createMemo(() => workspaceIds(project()))
  1617. const createWorkspace = async () => {
  1618. const current = project()
  1619. if (!current) return
  1620. const created = await globalSDK.client.worktree
  1621. .create({ directory: current.worktree })
  1622. .then((x) => x.data)
  1623. .catch((err) => {
  1624. showToast({
  1625. title: "Failed to create workspace",
  1626. description: errorMessage(err),
  1627. })
  1628. return undefined
  1629. })
  1630. if (!created?.directory) return
  1631. globalSync.child(created.directory)
  1632. navigate(`/${base64Encode(created.directory)}/session`)
  1633. }
  1634. const homedir = createMemo(() => sync.data.path.home)
  1635. return (
  1636. <div class="flex h-full w-full overflow-hidden">
  1637. <div class="w-16 shrink-0 bg-background-base flex flex-col items-center overflow-hidden">
  1638. <div class="flex-1 min-h-0 w-full">
  1639. <DragDropProvider
  1640. onDragStart={handleDragStart}
  1641. onDragEnd={handleDragEnd}
  1642. onDragOver={handleDragOver}
  1643. collisionDetector={closestCenter}
  1644. >
  1645. <DragDropSensors />
  1646. <ConstrainDragXAxis />
  1647. <div class="h-full w-full flex flex-col items-center gap-3 px-3 py-2 overflow-y-auto no-scrollbar">
  1648. <SortableProvider ids={layout.projects.list().map((p) => p.worktree)}>
  1649. <For each={layout.projects.list()}>
  1650. {(project) => <SortableProject project={project} mobile={sidebarProps.mobile} />}
  1651. </For>
  1652. </SortableProvider>
  1653. <Tooltip
  1654. placement={sidebarProps.mobile ? "bottom" : "right"}
  1655. value={
  1656. <div class="flex items-center gap-2">
  1657. <span>Open project</span>
  1658. <Show when={!sidebarProps.mobile}>
  1659. <span class="text-icon-base text-12-medium">{command.keybind("project.open")}</span>
  1660. </Show>
  1661. </div>
  1662. }
  1663. >
  1664. <IconButton icon="plus" variant="ghost" size="large" onClick={chooseProject} />
  1665. </Tooltip>
  1666. </div>
  1667. <DragOverlay>
  1668. <ProjectDragOverlay />
  1669. </DragOverlay>
  1670. </DragDropProvider>
  1671. </div>
  1672. <div class="shrink-0 w-full pt-3 pb-3 flex flex-col items-center gap-2">
  1673. <Tooltip placement={sidebarProps.mobile ? "bottom" : "right"} value="Settings">
  1674. <IconButton disabled icon="settings-gear" variant="ghost" size="large" />
  1675. </Tooltip>
  1676. <Tooltip placement={sidebarProps.mobile ? "bottom" : "right"} value="Help">
  1677. <IconButton
  1678. icon="help"
  1679. variant="ghost"
  1680. size="large"
  1681. onClick={() => platform.openLink("https://opencode.ai/desktop-feedback")}
  1682. />
  1683. </Tooltip>
  1684. </div>
  1685. </div>
  1686. <Show when={expanded()}>
  1687. <div
  1688. classList={{
  1689. "flex flex-col min-h-0 bg-background-stronger border border-b-0 border-border-weak-base rounded-tl-sm": true,
  1690. "flex-1 min-w-0": sidebarProps.mobile,
  1691. }}
  1692. style={{ width: sidebarProps.mobile ? undefined : `${Math.max(layout.sidebar.width() - 64, 0)}px` }}
  1693. >
  1694. <Show when={project()} keyed>
  1695. {(p) => (
  1696. <>
  1697. <div class="shrink-0 px-2 py-1">
  1698. <div class="group/project flex items-start justify-between gap-2 p-2 pr-1">
  1699. <div class="flex flex-col min-w-0">
  1700. <InlineEditor
  1701. id={`project:${projectId()}`}
  1702. value={projectName}
  1703. onSave={(next) => project() && renameProject(project()!, next)}
  1704. class="text-16-medium text-text-strong truncate"
  1705. displayClass="text-16-medium text-text-strong truncate"
  1706. stopPropagation
  1707. />
  1708. <Tooltip
  1709. placement={sidebarProps.mobile ? "bottom" : "top"}
  1710. gutter={2}
  1711. value={project()?.worktree}
  1712. class="shrink-0"
  1713. contentStyle={{
  1714. "max-width": "640px",
  1715. transform: "translate3d(52px, 0, 0)",
  1716. }}
  1717. >
  1718. <span class="text-12-regular text-text-base truncate">
  1719. {project()?.worktree.replace(homedir(), "~")}
  1720. </span>
  1721. </Tooltip>
  1722. </div>
  1723. <DropdownMenu>
  1724. <DropdownMenu.Trigger
  1725. as={IconButton}
  1726. icon="dot-grid"
  1727. variant="ghost"
  1728. class="shrink-0 size-6 rounded-md opacity-0 group-hover/project:opacity-100 data-[expanded]:opacity-100 data-[expanded]:bg-surface-base-active"
  1729. />
  1730. <DropdownMenu.Portal>
  1731. <DropdownMenu.Content class="mt-1">
  1732. <DropdownMenu.Item onSelect={() => dialog.show(() => <DialogEditProject project={p} />)}>
  1733. <DropdownMenu.ItemLabel>Edit</DropdownMenu.ItemLabel>
  1734. </DropdownMenu.Item>
  1735. <DropdownMenu.Item onSelect={() => layout.sidebar.toggleWorkspaces(p.worktree)}>
  1736. <DropdownMenu.ItemLabel>
  1737. {layout.sidebar.workspaces(p.worktree)() ? "Disable workspaces" : "Enable workspaces"}
  1738. </DropdownMenu.ItemLabel>
  1739. </DropdownMenu.Item>
  1740. <DropdownMenu.Separator />
  1741. <DropdownMenu.Item onSelect={() => closeProject(p.worktree)}>
  1742. <DropdownMenu.ItemLabel>Close</DropdownMenu.ItemLabel>
  1743. </DropdownMenu.Item>
  1744. </DropdownMenu.Content>
  1745. </DropdownMenu.Portal>
  1746. </DropdownMenu>
  1747. </div>
  1748. </div>
  1749. <Show
  1750. when={layout.sidebar.workspaces(p.worktree)()}
  1751. fallback={
  1752. <>
  1753. <div class="py-4 px-3">
  1754. <Button
  1755. size="large"
  1756. icon="plus-small"
  1757. class="w-full"
  1758. onClick={() => {
  1759. navigate(`/${base64Encode(p.worktree)}/session`)
  1760. layout.mobileSidebar.hide()
  1761. }}
  1762. >
  1763. New session
  1764. </Button>
  1765. </div>
  1766. <div class="flex-1 min-h-0">
  1767. <LocalWorkspace project={p} mobile={sidebarProps.mobile} />
  1768. </div>
  1769. </>
  1770. }
  1771. >
  1772. <>
  1773. <div class="py-4 px-3">
  1774. <Button size="large" icon="plus-small" class="w-full" onClick={createWorkspace}>
  1775. New workspace
  1776. </Button>
  1777. </div>
  1778. <div class="relative flex-1 min-h-0">
  1779. <DragDropProvider
  1780. onDragStart={handleWorkspaceDragStart}
  1781. onDragEnd={handleWorkspaceDragEnd}
  1782. onDragOver={handleWorkspaceDragOver}
  1783. collisionDetector={closestCenter}
  1784. >
  1785. <DragDropSensors />
  1786. <ConstrainDragXAxis />
  1787. <div
  1788. ref={(el) => {
  1789. if (!sidebarProps.mobile) scrollContainerRef = el
  1790. }}
  1791. class="size-full flex flex-col py-2 gap-4 overflow-y-auto no-scrollbar"
  1792. style={{ "overflow-anchor": "none" }}
  1793. >
  1794. <SortableProvider ids={workspaces()}>
  1795. <For each={workspaces()}>
  1796. {(directory) => (
  1797. <SortableWorkspace directory={directory} project={p} mobile={sidebarProps.mobile} />
  1798. )}
  1799. </For>
  1800. </SortableProvider>
  1801. </div>
  1802. <DragOverlay>
  1803. <WorkspaceDragOverlay />
  1804. </DragOverlay>
  1805. </DragDropProvider>
  1806. </div>
  1807. </>
  1808. </Show>
  1809. </>
  1810. )}
  1811. </Show>
  1812. <Show when={providers.all().length > 0 && providers.paid().length === 0}>
  1813. <div class="shrink-0 px-2 py-3 border-t border-border-weak-base">
  1814. <div class="rounded-md bg-background-base shadow-xs-border-base">
  1815. <div class="p-3 flex flex-col gap-2">
  1816. <div class="text-12-medium text-text-strong">Getting started</div>
  1817. <div class="text-text-base">OpenCode includes free models so you can start immediately.</div>
  1818. <div class="text-text-base">Connect any provider to use models, inc. Claude, GPT, Gemini etc.</div>
  1819. </div>
  1820. <Button
  1821. class="flex w-full text-left justify-start text-12-medium text-text-strong stroke-[1.5px] rounded-md rounded-t-none shadow-none border-t border-border-weak-base px-3"
  1822. size="large"
  1823. icon="plus"
  1824. onClick={connectProvider}
  1825. >
  1826. Connect provider
  1827. </Button>
  1828. </div>
  1829. </div>
  1830. </Show>
  1831. </div>
  1832. </Show>
  1833. </div>
  1834. )
  1835. }
  1836. return (
  1837. <div class="relative bg-background-base flex-1 min-h-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text">
  1838. <Titlebar />
  1839. <div class="flex-1 min-h-0 flex">
  1840. <div
  1841. classList={{
  1842. "hidden xl:block": true,
  1843. "relative shrink-0": true,
  1844. }}
  1845. style={{ width: layout.sidebar.opened() ? `${Math.max(layout.sidebar.width(), 244)}px` : "64px" }}
  1846. >
  1847. <div class="@container w-full h-full contain-strict">
  1848. <SidebarContent />
  1849. </div>
  1850. <Show when={layout.sidebar.opened()}>
  1851. <ResizeHandle
  1852. direction="horizontal"
  1853. size={layout.sidebar.width()}
  1854. min={244}
  1855. max={window.innerWidth * 0.3 + 64}
  1856. collapseThreshold={244}
  1857. onResize={layout.sidebar.resize}
  1858. onCollapse={layout.sidebar.close}
  1859. />
  1860. </Show>
  1861. </div>
  1862. <div class="xl:hidden">
  1863. <div
  1864. classList={{
  1865. "fixed inset-x-0 top-10 bottom-0 z-40 transition-opacity duration-200": true,
  1866. "opacity-100 pointer-events-auto": layout.mobileSidebar.opened(),
  1867. "opacity-0 pointer-events-none": !layout.mobileSidebar.opened(),
  1868. }}
  1869. onClick={(e) => {
  1870. if (e.target === e.currentTarget) layout.mobileSidebar.hide()
  1871. }}
  1872. />
  1873. <div
  1874. classList={{
  1875. "@container fixed top-10 bottom-0 left-0 z-50 w-72 bg-background-base transition-transform duration-200 ease-out": true,
  1876. "translate-x-0": layout.mobileSidebar.opened(),
  1877. "-translate-x-full": !layout.mobileSidebar.opened(),
  1878. }}
  1879. onClick={(e) => e.stopPropagation()}
  1880. >
  1881. <SidebarContent mobile />
  1882. </div>
  1883. </div>
  1884. <main
  1885. classList={{
  1886. "size-full overflow-x-hidden flex flex-col items-start contain-strict border-t border-border-weak-base": true,
  1887. "xl:border-l xl:rounded-tl-sm": !layout.sidebar.opened(),
  1888. }}
  1889. >
  1890. {props.children}
  1891. </main>
  1892. </div>
  1893. <Toast.Region />
  1894. </div>
  1895. )
  1896. }