index.tsx 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. import {
  2. createContext,
  3. createEffect,
  4. createMemo,
  5. createSignal,
  6. For,
  7. Match,
  8. on,
  9. Show,
  10. Switch,
  11. useContext,
  12. type Component,
  13. } from "solid-js"
  14. import { Dynamic } from "solid-js/web"
  15. import path from "path"
  16. import { useRoute, useRouteData } from "@tui/context/route"
  17. import { useSync } from "@tui/context/sync"
  18. import { SplitBorder } from "@tui/component/border"
  19. import { useTheme } from "@tui/context/theme"
  20. import {
  21. BoxRenderable,
  22. ScrollBoxRenderable,
  23. addDefaultParsers,
  24. MacOSScrollAccel,
  25. type ScrollAcceleration,
  26. } from "@opentui/core"
  27. import { Prompt, type PromptRef } from "@tui/component/prompt"
  28. import type { AssistantMessage, Part, ToolPart, UserMessage, TextPart, ReasoningPart } from "@opencode-ai/sdk/v2"
  29. import { useLocal } from "@tui/context/local"
  30. import { Locale } from "@/util/locale"
  31. import type { Tool } from "@/tool/tool"
  32. import type { ReadTool } from "@/tool/read"
  33. import type { WriteTool } from "@/tool/write"
  34. import { BashTool } from "@/tool/bash"
  35. import type { GlobTool } from "@/tool/glob"
  36. import { TodoWriteTool } from "@/tool/todo"
  37. import type { GrepTool } from "@/tool/grep"
  38. import type { ListTool } from "@/tool/ls"
  39. import type { EditTool } from "@/tool/edit"
  40. import type { PatchTool } from "@/tool/patch"
  41. import type { WebFetchTool } from "@/tool/webfetch"
  42. import type { TaskTool } from "@/tool/task"
  43. import { useKeyboard, useRenderer, useTerminalDimensions, type BoxProps, type JSX } from "@opentui/solid"
  44. import { useSDK } from "@tui/context/sdk"
  45. import { useCommandDialog } from "@tui/component/dialog-command"
  46. import { useKeybind } from "@tui/context/keybind"
  47. import { Header } from "./header"
  48. import { parsePatch } from "diff"
  49. import { useDialog } from "../../ui/dialog"
  50. import { DialogMessage } from "./dialog-message"
  51. import type { PromptInfo } from "../../component/prompt/history"
  52. import { iife } from "@/util/iife"
  53. import { DialogConfirm } from "@tui/ui/dialog-confirm"
  54. import { DialogPrompt } from "@tui/ui/dialog-prompt"
  55. import { DialogTimeline } from "./dialog-timeline"
  56. import { DialogSessionRename } from "../../component/dialog-session-rename"
  57. import { Sidebar } from "./sidebar"
  58. import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
  59. import parsers from "../../../../../../parsers-config.ts"
  60. import { Clipboard } from "../../util/clipboard"
  61. import { Toast, useToast } from "../../ui/toast"
  62. import { useKV } from "../../context/kv.tsx"
  63. import { Editor } from "../../util/editor"
  64. import stripAnsi from "strip-ansi"
  65. import { Footer } from "./footer.tsx"
  66. import { usePromptRef } from "../../context/prompt"
  67. addDefaultParsers(parsers.parsers)
  68. class CustomSpeedScroll implements ScrollAcceleration {
  69. constructor(private speed: number) {}
  70. tick(_now?: number): number {
  71. return this.speed
  72. }
  73. reset(): void {}
  74. }
  75. const context = createContext<{
  76. width: number
  77. conceal: () => boolean
  78. showThinking: () => boolean
  79. showTimestamps: () => boolean
  80. usernameVisible: () => boolean
  81. showDetails: () => boolean
  82. diffWrapMode: () => "word" | "none"
  83. sync: ReturnType<typeof useSync>
  84. }>()
  85. function use() {
  86. const ctx = useContext(context)
  87. if (!ctx) throw new Error("useContext must be used within a Session component")
  88. return ctx
  89. }
  90. export function Session() {
  91. const route = useRouteData("session")
  92. const { navigate } = useRoute()
  93. const sync = useSync()
  94. const kv = useKV()
  95. const { theme } = useTheme()
  96. const promptRef = usePromptRef()
  97. const session = createMemo(() => sync.session.get(route.sessionID)!)
  98. const messages = createMemo(() => sync.data.message[route.sessionID] ?? [])
  99. const permissions = createMemo(() => sync.data.permission[route.sessionID] ?? [])
  100. const pending = createMemo(() => {
  101. return messages().findLast((x) => x.role === "assistant" && !x.time.completed)?.id
  102. })
  103. const lastAssistant = createMemo(() => {
  104. return messages().findLast((x) => x.role === "assistant")
  105. })
  106. const dimensions = useTerminalDimensions()
  107. const [sidebar, setSidebar] = createSignal<"show" | "hide" | "auto">(kv.get("sidebar", "auto"))
  108. const [conceal, setConceal] = createSignal(true)
  109. const [showThinking, setShowThinking] = createSignal(kv.get("thinking_visibility", true))
  110. const [showTimestamps, setShowTimestamps] = createSignal(kv.get("timestamps", "hide") === "show")
  111. const [usernameVisible, setUsernameVisible] = createSignal(kv.get("username_visible", true))
  112. const [showDetails, setShowDetails] = createSignal(kv.get("tool_details_visibility", true))
  113. const [showScrollbar, setShowScrollbar] = createSignal(kv.get("scrollbar_visible", false))
  114. const [diffWrapMode, setDiffWrapMode] = createSignal<"word" | "none">("word")
  115. const wide = createMemo(() => dimensions().width > 120)
  116. const sidebarVisible = createMemo(() => {
  117. if (session()?.parentID) return false
  118. if (sidebar() === "show") return true
  119. if (sidebar() === "auto" && wide()) return true
  120. return false
  121. })
  122. const contentWidth = createMemo(() => dimensions().width - (sidebarVisible() ? 42 : 0) - 4)
  123. const scrollAcceleration = createMemo(() => {
  124. const tui = sync.data.config.tui
  125. if (tui?.scroll_acceleration?.enabled) {
  126. return new MacOSScrollAccel()
  127. }
  128. if (tui?.scroll_speed) {
  129. return new CustomSpeedScroll(tui.scroll_speed)
  130. }
  131. return new CustomSpeedScroll(3)
  132. })
  133. createEffect(async () => {
  134. await sync.session
  135. .sync(route.sessionID)
  136. .then(() => {
  137. if (scroll) scroll.scrollBy(100_000)
  138. })
  139. .catch((e) => {
  140. console.error(e)
  141. toast.show({
  142. message: `Session not found: ${route.sessionID}`,
  143. variant: "error",
  144. })
  145. return navigate({ type: "home" })
  146. })
  147. })
  148. const toast = useToast()
  149. const sdk = useSDK()
  150. // Auto-navigate to whichever session currently needs permission input
  151. createEffect(() => {
  152. const currentSession = session()
  153. if (!currentSession) return
  154. const currentPermissions = permissions()
  155. let targetID = currentPermissions.length > 0 ? currentSession.id : undefined
  156. if (!targetID) {
  157. const child = sync.data.session.find(
  158. (x) => x.parentID === currentSession.id && (sync.data.permission[x.id]?.length ?? 0) > 0,
  159. )
  160. if (child) targetID = child.id
  161. }
  162. if (targetID && targetID !== currentSession.id) {
  163. navigate({
  164. type: "session",
  165. sessionID: targetID,
  166. })
  167. }
  168. })
  169. let scroll: ScrollBoxRenderable
  170. let prompt: PromptRef
  171. const keybind = useKeybind()
  172. useKeyboard((evt) => {
  173. if (dialog.stack.length > 0) return
  174. const first = permissions()[0]
  175. if (first) {
  176. const response = iife(() => {
  177. if (evt.ctrl || evt.meta) return
  178. if (evt.name === "return") return "once"
  179. if (evt.name === "a") return "always"
  180. if (evt.name === "d") return "reject"
  181. if (evt.name === "escape") return "reject"
  182. return
  183. })
  184. if (response) {
  185. sdk.client.permission.respond({
  186. permissionID: first.id,
  187. sessionID: route.sessionID,
  188. response: response,
  189. })
  190. }
  191. }
  192. })
  193. function toBottom() {
  194. setTimeout(() => {
  195. if (scroll) scroll.scrollTo(scroll.scrollHeight)
  196. }, 50)
  197. }
  198. const local = useLocal()
  199. function moveChild(direction: number) {
  200. const parentID = session()?.parentID ?? session()?.id
  201. let children = sync.data.session
  202. .filter((x) => x.parentID === parentID || x.id === parentID)
  203. .toSorted((b, a) => a.id.localeCompare(b.id))
  204. if (children.length === 1) return
  205. let next = children.findIndex((x) => x.id === session()?.id) + direction
  206. if (next >= children.length) next = 0
  207. if (next < 0) next = children.length - 1
  208. if (children[next]) {
  209. navigate({
  210. type: "session",
  211. sessionID: children[next].id,
  212. })
  213. }
  214. }
  215. const command = useCommandDialog()
  216. command.register(() => [
  217. ...(sync.data.config.share !== "disabled"
  218. ? [
  219. {
  220. title: "Share session",
  221. value: "session.share",
  222. suggested: route.type === "session",
  223. keybind: "session_share" as const,
  224. disabled: !!session()?.share?.url,
  225. category: "Session",
  226. onSelect: async (dialog: any) => {
  227. await sdk.client.session
  228. .share({
  229. sessionID: route.sessionID,
  230. })
  231. .then((res) =>
  232. Clipboard.copy(res.data!.share!.url).catch(() =>
  233. toast.show({ message: "Failed to copy URL to clipboard", variant: "error" }),
  234. ),
  235. )
  236. .then(() => toast.show({ message: "Share URL copied to clipboard!", variant: "success" }))
  237. .catch(() => toast.show({ message: "Failed to share session", variant: "error" }))
  238. dialog.clear()
  239. },
  240. },
  241. ]
  242. : []),
  243. {
  244. title: "Rename session",
  245. value: "session.rename",
  246. keybind: "session_rename",
  247. category: "Session",
  248. onSelect: (dialog) => {
  249. dialog.replace(() => <DialogSessionRename session={route.sessionID} />)
  250. },
  251. },
  252. {
  253. title: "Jump to message",
  254. value: "session.timeline",
  255. keybind: "session_timeline",
  256. category: "Session",
  257. onSelect: (dialog) => {
  258. dialog.replace(() => (
  259. <DialogTimeline
  260. onMove={(messageID) => {
  261. const child = scroll.getChildren().find((child) => {
  262. return child.id === messageID
  263. })
  264. if (child) scroll.scrollBy(child.y - scroll.y - 1)
  265. }}
  266. sessionID={route.sessionID}
  267. />
  268. ))
  269. },
  270. },
  271. {
  272. title: "Compact session",
  273. value: "session.compact",
  274. keybind: "session_compact",
  275. category: "Session",
  276. onSelect: (dialog) => {
  277. const selectedModel = local.model.current()
  278. if (!selectedModel) {
  279. toast.show({
  280. variant: "warning",
  281. message: "Connect a provider to summarize this session",
  282. duration: 3000,
  283. })
  284. return
  285. }
  286. sdk.client.session.summarize({
  287. sessionID: route.sessionID,
  288. modelID: selectedModel.modelID,
  289. providerID: selectedModel.providerID,
  290. })
  291. dialog.clear()
  292. },
  293. },
  294. {
  295. title: "Unshare session",
  296. value: "session.unshare",
  297. keybind: "session_unshare",
  298. disabled: !session()?.share?.url,
  299. category: "Session",
  300. onSelect: (dialog) => {
  301. sdk.client.session.unshare({
  302. sessionID: route.sessionID,
  303. })
  304. dialog.clear()
  305. },
  306. },
  307. {
  308. title: "Undo previous message",
  309. value: "session.undo",
  310. keybind: "messages_undo",
  311. category: "Session",
  312. onSelect: async (dialog) => {
  313. const status = sync.data.session_status[route.sessionID]
  314. if (status?.type !== "idle") await sdk.client.session.abort({ sessionID: route.sessionID }).catch(() => {})
  315. const revert = session().revert?.messageID
  316. const message = messages().findLast((x) => (!revert || x.id < revert) && x.role === "user")
  317. if (!message) return
  318. sdk.client.session
  319. .revert({
  320. sessionID: route.sessionID,
  321. messageID: message.id,
  322. })
  323. .then(() => {
  324. toBottom()
  325. })
  326. const parts = sync.data.part[message.id]
  327. prompt.set(
  328. parts.reduce(
  329. (agg, part) => {
  330. if (part.type === "text") {
  331. if (!part.synthetic) agg.input += part.text
  332. }
  333. if (part.type === "file") agg.parts.push(part)
  334. return agg
  335. },
  336. { input: "", parts: [] as PromptInfo["parts"] },
  337. ),
  338. )
  339. dialog.clear()
  340. },
  341. },
  342. {
  343. title: "Redo",
  344. value: "session.redo",
  345. keybind: "messages_redo",
  346. disabled: !session()?.revert?.messageID,
  347. category: "Session",
  348. onSelect: (dialog) => {
  349. dialog.clear()
  350. const messageID = session().revert?.messageID
  351. if (!messageID) return
  352. const message = messages().find((x) => x.role === "user" && x.id > messageID)
  353. if (!message) {
  354. sdk.client.session.unrevert({
  355. sessionID: route.sessionID,
  356. })
  357. prompt.set({ input: "", parts: [] })
  358. return
  359. }
  360. sdk.client.session.revert({
  361. sessionID: route.sessionID,
  362. messageID: message.id,
  363. })
  364. },
  365. },
  366. {
  367. title: sidebarVisible() ? "Hide sidebar" : "Show sidebar",
  368. value: "session.sidebar.toggle",
  369. keybind: "sidebar_toggle",
  370. category: "Session",
  371. onSelect: (dialog) => {
  372. setSidebar((prev) => {
  373. if (prev === "auto") return sidebarVisible() ? "hide" : "show"
  374. if (prev === "show") return "hide"
  375. return "show"
  376. })
  377. if (sidebar() === "show") kv.set("sidebar", "auto")
  378. if (sidebar() === "hide") kv.set("sidebar", "hide")
  379. dialog.clear()
  380. },
  381. },
  382. {
  383. title: usernameVisible() ? "Hide username" : "Show username",
  384. value: "session.username_visible.toggle",
  385. keybind: "username_toggle",
  386. category: "Session",
  387. onSelect: (dialog) => {
  388. setUsernameVisible((prev) => {
  389. const next = !prev
  390. kv.set("username_visible", next)
  391. return next
  392. })
  393. dialog.clear()
  394. },
  395. },
  396. {
  397. title: "Toggle code concealment",
  398. value: "session.toggle.conceal",
  399. keybind: "messages_toggle_conceal" as any,
  400. category: "Session",
  401. onSelect: (dialog) => {
  402. setConceal((prev) => !prev)
  403. dialog.clear()
  404. },
  405. },
  406. {
  407. title: showTimestamps() ? "Hide timestamps" : "Show timestamps",
  408. value: "session.toggle.timestamps",
  409. category: "Session",
  410. onSelect: (dialog) => {
  411. setShowTimestamps((prev) => {
  412. const next = !prev
  413. kv.set("timestamps", next ? "show" : "hide")
  414. return next
  415. })
  416. dialog.clear()
  417. },
  418. },
  419. {
  420. title: showThinking() ? "Hide thinking" : "Show thinking",
  421. value: "session.toggle.thinking",
  422. category: "Session",
  423. onSelect: (dialog) => {
  424. setShowThinking((prev) => {
  425. const next = !prev
  426. kv.set("thinking_visibility", next)
  427. return next
  428. })
  429. dialog.clear()
  430. },
  431. },
  432. {
  433. title: "Toggle diff wrapping",
  434. value: "session.toggle.diffwrap",
  435. category: "Session",
  436. onSelect: (dialog) => {
  437. setDiffWrapMode((prev) => (prev === "word" ? "none" : "word"))
  438. dialog.clear()
  439. },
  440. },
  441. {
  442. title: showDetails() ? "Hide tool details" : "Show tool details",
  443. value: "session.toggle.actions",
  444. keybind: "tool_details",
  445. category: "Session",
  446. onSelect: (dialog) => {
  447. const newValue = !showDetails()
  448. setShowDetails(newValue)
  449. kv.set("tool_details_visibility", newValue)
  450. dialog.clear()
  451. },
  452. },
  453. {
  454. title: "Toggle session scrollbar",
  455. value: "session.toggle.scrollbar",
  456. keybind: "scrollbar_toggle",
  457. category: "Session",
  458. onSelect: (dialog) => {
  459. setShowScrollbar((prev) => {
  460. const next = !prev
  461. kv.set("scrollbar_visible", next)
  462. return next
  463. })
  464. dialog.clear()
  465. },
  466. },
  467. {
  468. title: "Page up",
  469. value: "session.page.up",
  470. keybind: "messages_page_up",
  471. category: "Session",
  472. disabled: true,
  473. onSelect: (dialog) => {
  474. scroll.scrollBy(-scroll.height / 2)
  475. dialog.clear()
  476. },
  477. },
  478. {
  479. title: "Page down",
  480. value: "session.page.down",
  481. keybind: "messages_page_down",
  482. category: "Session",
  483. disabled: true,
  484. onSelect: (dialog) => {
  485. scroll.scrollBy(scroll.height / 2)
  486. dialog.clear()
  487. },
  488. },
  489. {
  490. title: "Half page up",
  491. value: "session.half.page.up",
  492. keybind: "messages_half_page_up",
  493. category: "Session",
  494. disabled: true,
  495. onSelect: (dialog) => {
  496. scroll.scrollBy(-scroll.height / 4)
  497. dialog.clear()
  498. },
  499. },
  500. {
  501. title: "Half page down",
  502. value: "session.half.page.down",
  503. keybind: "messages_half_page_down",
  504. category: "Session",
  505. disabled: true,
  506. onSelect: (dialog) => {
  507. scroll.scrollBy(scroll.height / 4)
  508. dialog.clear()
  509. },
  510. },
  511. {
  512. title: "First message",
  513. value: "session.first",
  514. keybind: "messages_first",
  515. category: "Session",
  516. disabled: true,
  517. onSelect: (dialog) => {
  518. scroll.scrollTo(0)
  519. dialog.clear()
  520. },
  521. },
  522. {
  523. title: "Last message",
  524. value: "session.last",
  525. keybind: "messages_last",
  526. category: "Session",
  527. disabled: true,
  528. onSelect: (dialog) => {
  529. scroll.scrollTo(scroll.scrollHeight)
  530. dialog.clear()
  531. },
  532. },
  533. {
  534. title: "Jump to last user message",
  535. value: "session.messages_last_user",
  536. keybind: "messages_last_user",
  537. category: "Session",
  538. onSelect: () => {
  539. const messages = sync.data.message[route.sessionID]
  540. if (!messages || !messages.length) return
  541. // Find the most recent user message with non-ignored, non-synthetic text parts
  542. for (let i = messages.length - 1; i >= 0; i--) {
  543. const message = messages[i]
  544. if (!message || message.role !== "user") continue
  545. const parts = sync.data.part[message.id]
  546. if (!parts || !Array.isArray(parts)) continue
  547. const hasValidTextPart = parts.some(
  548. (part) => part && part.type === "text" && !part.synthetic && !part.ignored,
  549. )
  550. if (hasValidTextPart) {
  551. const child = scroll.getChildren().find((child) => {
  552. return child.id === message.id
  553. })
  554. if (child) scroll.scrollBy(child.y - scroll.y - 1)
  555. break
  556. }
  557. }
  558. },
  559. },
  560. {
  561. title: "Copy last assistant message",
  562. value: "messages.copy",
  563. keybind: "messages_copy",
  564. category: "Session",
  565. onSelect: (dialog) => {
  566. const lastAssistantMessage = messages().findLast((msg) => msg.role === "assistant")
  567. if (!lastAssistantMessage) {
  568. toast.show({ message: "No assistant messages found", variant: "error" })
  569. dialog.clear()
  570. return
  571. }
  572. const parts = sync.data.part[lastAssistantMessage.id] ?? []
  573. const textParts = parts.filter((part) => part.type === "text")
  574. if (textParts.length === 0) {
  575. toast.show({ message: "No text parts found in last assistant message", variant: "error" })
  576. dialog.clear()
  577. return
  578. }
  579. const text = textParts
  580. .map((part) => part.text)
  581. .join("\n")
  582. .trim()
  583. if (!text) {
  584. toast.show({
  585. message: "No text content found in last assistant message",
  586. variant: "error",
  587. })
  588. dialog.clear()
  589. return
  590. }
  591. const base64 = Buffer.from(text).toString("base64")
  592. const osc52 = `\x1b]52;c;${base64}\x07`
  593. const finalOsc52 = process.env["TMUX"] ? `\x1bPtmux;\x1b${osc52}\x1b\\` : osc52
  594. /* @ts-expect-error */
  595. renderer.writeOut(finalOsc52)
  596. Clipboard.copy(text)
  597. .then(() => toast.show({ message: "Message copied to clipboard!", variant: "success" }))
  598. .catch(() => toast.show({ message: "Failed to copy to clipboard", variant: "error" }))
  599. dialog.clear()
  600. },
  601. },
  602. {
  603. title: "Copy session transcript",
  604. value: "session.copy",
  605. keybind: "session_copy",
  606. category: "Session",
  607. onSelect: async (dialog) => {
  608. try {
  609. // Format session transcript as markdown
  610. const sessionData = session()
  611. const sessionMessages = messages()
  612. let transcript = `# ${sessionData.title}\n\n`
  613. transcript += `**Session ID:** ${sessionData.id}\n`
  614. transcript += `**Created:** ${new Date(sessionData.time.created).toLocaleString()}\n`
  615. transcript += `**Updated:** ${new Date(sessionData.time.updated).toLocaleString()}\n\n`
  616. transcript += `---\n\n`
  617. for (const msg of sessionMessages) {
  618. const parts = sync.data.part[msg.id] ?? []
  619. const role = msg.role === "user" ? "User" : "Assistant"
  620. transcript += `## ${role}\n\n`
  621. for (const part of parts) {
  622. if (part.type === "text" && !part.synthetic) {
  623. transcript += `${part.text}\n\n`
  624. } else if (part.type === "tool") {
  625. transcript += `\`\`\`\nTool: ${part.tool}\n\`\`\`\n\n`
  626. }
  627. }
  628. transcript += `---\n\n`
  629. }
  630. // Copy to clipboard
  631. await Clipboard.copy(transcript)
  632. toast.show({ message: "Session transcript copied to clipboard!", variant: "success" })
  633. } catch (error) {
  634. toast.show({ message: "Failed to copy session transcript", variant: "error" })
  635. }
  636. dialog.clear()
  637. },
  638. },
  639. {
  640. title: "Export session transcript to file",
  641. value: "session.export",
  642. keybind: "session_export",
  643. category: "Session",
  644. onSelect: async (dialog) => {
  645. try {
  646. // Format session transcript as markdown
  647. const sessionData = session()
  648. const sessionMessages = messages()
  649. let transcript = `# ${sessionData.title}\n\n`
  650. transcript += `**Session ID:** ${sessionData.id}\n`
  651. transcript += `**Created:** ${new Date(sessionData.time.created).toLocaleString()}\n`
  652. transcript += `**Updated:** ${new Date(sessionData.time.updated).toLocaleString()}\n\n`
  653. transcript += `---\n\n`
  654. for (const msg of sessionMessages) {
  655. const parts = sync.data.part[msg.id] ?? []
  656. const role = msg.role === "user" ? "User" : "Assistant"
  657. transcript += `## ${role}\n\n`
  658. for (const part of parts) {
  659. if (part.type === "text" && !part.synthetic) {
  660. transcript += `${part.text}\n\n`
  661. } else if (part.type === "tool") {
  662. transcript += `\`\`\`\nTool: ${part.tool}\n\`\`\`\n\n`
  663. }
  664. }
  665. transcript += `---\n\n`
  666. }
  667. // Prompt for optional filename
  668. const customFilename = await DialogPrompt.show(dialog, "Export filename", {
  669. value: `session-${sessionData.id.slice(0, 8)}.md`,
  670. })
  671. // Cancel if user pressed escape
  672. if (customFilename === null) return
  673. // Save to file in current working directory
  674. const exportDir = process.cwd()
  675. const filename = customFilename.trim()
  676. const filepath = path.join(exportDir, filename)
  677. await Bun.write(filepath, transcript)
  678. // Open with EDITOR if available
  679. const result = await Editor.open({ value: transcript, renderer })
  680. if (result !== undefined) {
  681. // User edited the file, save the changes
  682. await Bun.write(filepath, result)
  683. }
  684. toast.show({ message: `Session exported to ${filename}`, variant: "success" })
  685. } catch (error) {
  686. toast.show({ message: "Failed to export session", variant: "error" })
  687. }
  688. dialog.clear()
  689. },
  690. },
  691. {
  692. title: "Next child session",
  693. value: "session.child.next",
  694. keybind: "session_child_cycle",
  695. category: "Session",
  696. disabled: true,
  697. onSelect: (dialog) => {
  698. moveChild(1)
  699. dialog.clear()
  700. },
  701. },
  702. {
  703. title: "Previous child session",
  704. value: "session.child.previous",
  705. keybind: "session_child_cycle_reverse",
  706. category: "Session",
  707. disabled: true,
  708. onSelect: (dialog) => {
  709. moveChild(-1)
  710. dialog.clear()
  711. },
  712. },
  713. ])
  714. const revertInfo = createMemo(() => session()?.revert)
  715. const revertMessageID = createMemo(() => revertInfo()?.messageID)
  716. const revertDiffFiles = createMemo(() => {
  717. const diffText = revertInfo()?.diff ?? ""
  718. if (!diffText) return []
  719. try {
  720. const patches = parsePatch(diffText)
  721. return patches.map((patch) => {
  722. const filename = patch.newFileName || patch.oldFileName || "unknown"
  723. const cleanFilename = filename.replace(/^[ab]\//, "")
  724. return {
  725. filename: cleanFilename,
  726. additions: patch.hunks.reduce(
  727. (sum, hunk) => sum + hunk.lines.filter((line) => line.startsWith("+")).length,
  728. 0,
  729. ),
  730. deletions: patch.hunks.reduce(
  731. (sum, hunk) => sum + hunk.lines.filter((line) => line.startsWith("-")).length,
  732. 0,
  733. ),
  734. }
  735. })
  736. } catch (error) {
  737. return []
  738. }
  739. })
  740. const revertRevertedMessages = createMemo(() => {
  741. const messageID = revertMessageID()
  742. if (!messageID) return []
  743. return messages().filter((x) => x.id >= messageID && x.role === "user")
  744. })
  745. const revert = createMemo(() => {
  746. const info = revertInfo()
  747. if (!info) return
  748. if (!info.messageID) return
  749. return {
  750. messageID: info.messageID,
  751. reverted: revertRevertedMessages(),
  752. diff: info.diff,
  753. diffFiles: revertDiffFiles(),
  754. }
  755. })
  756. const dialog = useDialog()
  757. const renderer = useRenderer()
  758. // snap to bottom when session changes
  759. createEffect(on(() => route.sessionID, toBottom))
  760. return (
  761. <context.Provider
  762. value={{
  763. get width() {
  764. return contentWidth()
  765. },
  766. conceal,
  767. showThinking,
  768. showTimestamps,
  769. usernameVisible,
  770. showDetails,
  771. diffWrapMode,
  772. sync,
  773. }}
  774. >
  775. <box flexDirection="row">
  776. <box flexGrow={1} paddingBottom={1} paddingTop={1} paddingLeft={2} paddingRight={2} gap={1}>
  777. <Show when={session()}>
  778. <Show when={!sidebarVisible()}>
  779. <Header />
  780. </Show>
  781. <scrollbox
  782. ref={(r) => (scroll = r)}
  783. verticalScrollbarOptions={{
  784. paddingLeft: 1,
  785. visible: showScrollbar(),
  786. trackOptions: {
  787. backgroundColor: theme.backgroundElement,
  788. foregroundColor: theme.border,
  789. },
  790. }}
  791. stickyScroll={true}
  792. stickyStart="bottom"
  793. flexGrow={1}
  794. scrollAcceleration={scrollAcceleration()}
  795. >
  796. <For each={messages()}>
  797. {(message, index) => (
  798. <Switch>
  799. <Match when={message.id === revert()?.messageID}>
  800. {(function () {
  801. const command = useCommandDialog()
  802. const [hover, setHover] = createSignal(false)
  803. const dialog = useDialog()
  804. const handleUnrevert = async () => {
  805. const confirmed = await DialogConfirm.show(
  806. dialog,
  807. "Confirm Redo",
  808. "Are you sure you want to restore the reverted messages?",
  809. )
  810. if (confirmed) {
  811. command.trigger("session.redo")
  812. }
  813. }
  814. return (
  815. <box
  816. onMouseOver={() => setHover(true)}
  817. onMouseOut={() => setHover(false)}
  818. onMouseUp={handleUnrevert}
  819. marginTop={1}
  820. flexShrink={0}
  821. border={["left"]}
  822. customBorderChars={SplitBorder.customBorderChars}
  823. borderColor={theme.backgroundPanel}
  824. >
  825. <box
  826. paddingTop={1}
  827. paddingBottom={1}
  828. paddingLeft={2}
  829. backgroundColor={hover() ? theme.backgroundElement : theme.backgroundPanel}
  830. >
  831. <text fg={theme.textMuted}>{revert()!.reverted.length} message reverted</text>
  832. <text fg={theme.textMuted}>
  833. <span style={{ fg: theme.text }}>{keybind.print("messages_redo")}</span> or /redo to
  834. restore
  835. </text>
  836. <Show when={revert()!.diffFiles?.length}>
  837. <box marginTop={1}>
  838. <For each={revert()!.diffFiles}>
  839. {(file) => (
  840. <text fg={theme.text}>
  841. {file.filename}
  842. <Show when={file.additions > 0}>
  843. <span style={{ fg: theme.diffAdded }}> +{file.additions}</span>
  844. </Show>
  845. <Show when={file.deletions > 0}>
  846. <span style={{ fg: theme.diffRemoved }}> -{file.deletions}</span>
  847. </Show>
  848. </text>
  849. )}
  850. </For>
  851. </box>
  852. </Show>
  853. </box>
  854. </box>
  855. )
  856. })()}
  857. </Match>
  858. <Match when={revert()?.messageID && message.id >= revert()!.messageID}>
  859. <></>
  860. </Match>
  861. <Match when={message.role === "user"}>
  862. <UserMessage
  863. index={index()}
  864. onMouseUp={() => {
  865. if (renderer.getSelection()?.getSelectedText()) return
  866. dialog.replace(() => (
  867. <DialogMessage
  868. messageID={message.id}
  869. sessionID={route.sessionID}
  870. setPrompt={(promptInfo) => prompt.set(promptInfo)}
  871. />
  872. ))
  873. }}
  874. message={message as UserMessage}
  875. parts={sync.data.part[message.id] ?? []}
  876. pending={pending()}
  877. />
  878. </Match>
  879. <Match when={message.role === "assistant"}>
  880. <AssistantMessage
  881. last={lastAssistant()?.id === message.id}
  882. message={message as AssistantMessage}
  883. parts={sync.data.part[message.id] ?? []}
  884. />
  885. </Match>
  886. </Switch>
  887. )}
  888. </For>
  889. </scrollbox>
  890. <box flexShrink={0}>
  891. <Prompt
  892. ref={(r) => {
  893. prompt = r
  894. promptRef.set(r)
  895. }}
  896. disabled={permissions().length > 0}
  897. onSubmit={() => {
  898. toBottom()
  899. }}
  900. sessionID={route.sessionID}
  901. />
  902. </box>
  903. <Show when={!sidebarVisible()}>
  904. <Footer />
  905. </Show>
  906. </Show>
  907. <Toast />
  908. </box>
  909. <Show when={sidebarVisible()}>
  910. <Sidebar sessionID={route.sessionID} />
  911. </Show>
  912. </box>
  913. </context.Provider>
  914. )
  915. }
  916. const MIME_BADGE: Record<string, string> = {
  917. "text/plain": "txt",
  918. "image/png": "img",
  919. "image/jpeg": "img",
  920. "image/gif": "img",
  921. "image/webp": "img",
  922. "application/pdf": "pdf",
  923. "application/x-directory": "dir",
  924. }
  925. function UserMessage(props: {
  926. message: UserMessage
  927. parts: Part[]
  928. onMouseUp: () => void
  929. index: number
  930. pending?: string
  931. }) {
  932. const ctx = use()
  933. const local = useLocal()
  934. const text = createMemo(() => props.parts.flatMap((x) => (x.type === "text" && !x.synthetic ? [x] : []))[0])
  935. const files = createMemo(() => props.parts.flatMap((x) => (x.type === "file" ? [x] : [])))
  936. const sync = useSync()
  937. const { theme } = useTheme()
  938. const [hover, setHover] = createSignal(false)
  939. const queued = createMemo(() => props.pending && props.message.id > props.pending)
  940. const color = createMemo(() => (queued() ? theme.accent : local.agent.color(props.message.agent)))
  941. const compaction = createMemo(() => props.parts.find((x) => x.type === "compaction"))
  942. return (
  943. <>
  944. <Show when={text()}>
  945. <box
  946. id={props.message.id}
  947. border={["left"]}
  948. borderColor={color()}
  949. customBorderChars={SplitBorder.customBorderChars}
  950. marginTop={props.index === 0 ? 0 : 1}
  951. >
  952. <box
  953. onMouseOver={() => {
  954. setHover(true)
  955. }}
  956. onMouseOut={() => {
  957. setHover(false)
  958. }}
  959. onMouseUp={props.onMouseUp}
  960. paddingTop={1}
  961. paddingBottom={1}
  962. paddingLeft={2}
  963. backgroundColor={hover() ? theme.backgroundElement : theme.backgroundPanel}
  964. flexShrink={0}
  965. >
  966. <text fg={theme.text}>{text()?.text}</text>
  967. <Show when={files().length}>
  968. <box flexDirection="row" paddingBottom={1} paddingTop={1} gap={1} flexWrap="wrap">
  969. <For each={files()}>
  970. {(file) => {
  971. const bg = createMemo(() => {
  972. if (file.mime.startsWith("image/")) return theme.accent
  973. if (file.mime === "application/pdf") return theme.primary
  974. return theme.secondary
  975. })
  976. return (
  977. <text fg={theme.text}>
  978. <span style={{ bg: bg(), fg: theme.background }}> {MIME_BADGE[file.mime] ?? file.mime} </span>
  979. <span style={{ bg: theme.backgroundElement, fg: theme.textMuted }}> {file.filename} </span>
  980. </text>
  981. )
  982. }}
  983. </For>
  984. </box>
  985. </Show>
  986. <text fg={theme.textMuted}>
  987. {ctx.usernameVisible() ? `${sync.data.config.username ?? "You "}` : "You "}
  988. <Show
  989. when={queued()}
  990. fallback={
  991. <Show when={ctx.showTimestamps()}>
  992. <span style={{ fg: theme.textMuted }}>
  993. {ctx.usernameVisible() ? " · " : " "}
  994. {Locale.todayTimeOrDateTime(props.message.time.created)}
  995. </span>
  996. </Show>
  997. }
  998. >
  999. <span> </span>
  1000. <span style={{ bg: theme.accent, fg: theme.backgroundPanel, bold: true }}> QUEUED </span>
  1001. </Show>
  1002. </text>
  1003. </box>
  1004. </box>
  1005. </Show>
  1006. <Show when={compaction()}>
  1007. <box
  1008. marginTop={1}
  1009. border={["top"]}
  1010. title=" Compaction "
  1011. titleAlignment="center"
  1012. borderColor={theme.borderActive}
  1013. />
  1014. </Show>
  1015. </>
  1016. )
  1017. }
  1018. function AssistantMessage(props: { message: AssistantMessage; parts: Part[]; last: boolean }) {
  1019. const local = useLocal()
  1020. const { theme } = useTheme()
  1021. const sync = useSync()
  1022. const messages = createMemo(() => sync.data.message[props.message.sessionID] ?? [])
  1023. const final = createMemo(() => {
  1024. return props.message.finish && !["tool-calls", "unknown"].includes(props.message.finish)
  1025. })
  1026. const duration = createMemo(() => {
  1027. if (!final()) return 0
  1028. if (!props.message.time.completed) return 0
  1029. const user = messages().find((x) => x.role === "user" && x.id === props.message.parentID)
  1030. if (!user || !user.time) return 0
  1031. return props.message.time.completed - user.time.created
  1032. })
  1033. return (
  1034. <>
  1035. <For each={props.parts}>
  1036. {(part, index) => {
  1037. const component = createMemo(() => PART_MAPPING[part.type as keyof typeof PART_MAPPING])
  1038. return (
  1039. <Show when={component()}>
  1040. <Dynamic
  1041. last={index() === props.parts.length - 1}
  1042. component={component()}
  1043. part={part as any}
  1044. message={props.message}
  1045. />
  1046. </Show>
  1047. )
  1048. }}
  1049. </For>
  1050. <Show when={props.message.error}>
  1051. <box
  1052. border={["left"]}
  1053. paddingTop={1}
  1054. paddingBottom={1}
  1055. paddingLeft={2}
  1056. marginTop={1}
  1057. backgroundColor={theme.backgroundPanel}
  1058. customBorderChars={SplitBorder.customBorderChars}
  1059. borderColor={theme.error}
  1060. >
  1061. <text fg={theme.textMuted}>{props.message.error?.data.message}</text>
  1062. </box>
  1063. </Show>
  1064. <Switch>
  1065. <Match when={props.last || final()}>
  1066. <box paddingLeft={3}>
  1067. <text marginTop={1}>
  1068. <span style={{ fg: local.agent.color(props.message.mode) }}>▣ </span>{" "}
  1069. <span style={{ fg: theme.text }}>{Locale.titlecase(props.message.mode)}</span>
  1070. <span style={{ fg: theme.textMuted }}> · {props.message.modelID}</span>
  1071. <Show when={duration()}>
  1072. <span style={{ fg: theme.textMuted }}> · {Locale.duration(duration())}</span>
  1073. </Show>
  1074. </text>
  1075. </box>
  1076. </Match>
  1077. </Switch>
  1078. </>
  1079. )
  1080. }
  1081. const PART_MAPPING = {
  1082. text: TextPart,
  1083. tool: ToolPart,
  1084. reasoning: ReasoningPart,
  1085. }
  1086. function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: AssistantMessage }) {
  1087. const { theme, subtleSyntax } = useTheme()
  1088. const ctx = use()
  1089. const content = createMemo(() => {
  1090. // Filter out redacted reasoning chunks from OpenRouter
  1091. // OpenRouter sends encrypted reasoning data that appears as [REDACTED]
  1092. return props.part.text.replace("[REDACTED]", "").trim()
  1093. })
  1094. return (
  1095. <Show when={content() && ctx.showThinking()}>
  1096. <box
  1097. id={"text-" + props.part.id}
  1098. paddingLeft={2}
  1099. marginTop={1}
  1100. flexDirection="column"
  1101. border={["left"]}
  1102. customBorderChars={SplitBorder.customBorderChars}
  1103. borderColor={theme.backgroundElement}
  1104. >
  1105. <code
  1106. filetype="markdown"
  1107. drawUnstyledText={false}
  1108. streaming={true}
  1109. syntaxStyle={subtleSyntax()}
  1110. content={"_Thinking:_ " + content()}
  1111. conceal={ctx.conceal()}
  1112. fg={theme.textMuted}
  1113. />
  1114. </box>
  1115. </Show>
  1116. )
  1117. }
  1118. function TextPart(props: { last: boolean; part: TextPart; message: AssistantMessage }) {
  1119. const ctx = use()
  1120. const { theme, syntax } = useTheme()
  1121. return (
  1122. <Show when={props.part.text.trim()}>
  1123. <box id={"text-" + props.part.id} paddingLeft={3} marginTop={1} flexShrink={0}>
  1124. <code
  1125. filetype="markdown"
  1126. drawUnstyledText={false}
  1127. streaming={true}
  1128. syntaxStyle={syntax()}
  1129. content={props.part.text.trim()}
  1130. conceal={ctx.conceal()}
  1131. fg={theme.text}
  1132. />
  1133. </box>
  1134. </Show>
  1135. )
  1136. }
  1137. // Pending messages moved to individual tool pending functions
  1138. function ToolPart(props: { last: boolean; part: ToolPart; message: AssistantMessage }) {
  1139. const { theme } = useTheme()
  1140. const { showDetails } = use()
  1141. const sync = useSync()
  1142. const [margin, setMargin] = createSignal(0)
  1143. const component = createMemo(() => {
  1144. // Hide tool if showDetails is false and tool completed successfully
  1145. // But always show if there's an error or permission is required
  1146. const shouldHide =
  1147. !showDetails() &&
  1148. props.part.state.status === "completed" &&
  1149. !sync.data.permission[props.message.sessionID]?.some((x) => x.callID === props.part.callID)
  1150. if (shouldHide) {
  1151. return undefined
  1152. }
  1153. const render = ToolRegistry.render(props.part.tool) ?? GenericTool
  1154. const metadata = props.part.state.status === "pending" ? {} : (props.part.state.metadata ?? {})
  1155. const input = props.part.state.input ?? {}
  1156. const container = ToolRegistry.container(props.part.tool)
  1157. const permissions = sync.data.permission[props.message.sessionID] ?? []
  1158. const permissionIndex = permissions.findIndex((x) => x.callID === props.part.callID)
  1159. const permission = permissions[permissionIndex]
  1160. const style: BoxProps =
  1161. container === "block" || permission
  1162. ? {
  1163. border: permissionIndex === 0 ? (["left", "right"] as const) : (["left"] as const),
  1164. paddingTop: 1,
  1165. paddingBottom: 1,
  1166. paddingLeft: 2,
  1167. marginTop: 1,
  1168. gap: 1,
  1169. backgroundColor: theme.backgroundPanel,
  1170. customBorderChars: SplitBorder.customBorderChars,
  1171. borderColor: permissionIndex === 0 ? theme.warning : theme.background,
  1172. }
  1173. : {
  1174. paddingLeft: 3,
  1175. }
  1176. return (
  1177. <box
  1178. marginTop={margin()}
  1179. {...style}
  1180. renderBefore={function () {
  1181. const el = this as BoxRenderable
  1182. const parent = el.parent
  1183. if (!parent) {
  1184. return
  1185. }
  1186. if (el.height > 1) {
  1187. setMargin(1)
  1188. return
  1189. }
  1190. const children = parent.getChildren()
  1191. const index = children.indexOf(el)
  1192. const previous = children[index - 1]
  1193. if (!previous) {
  1194. setMargin(0)
  1195. return
  1196. }
  1197. if (previous.height > 1 || previous.id.startsWith("text-")) {
  1198. setMargin(1)
  1199. return
  1200. }
  1201. }}
  1202. >
  1203. <Dynamic
  1204. component={render}
  1205. input={input}
  1206. tool={props.part.tool}
  1207. metadata={metadata}
  1208. permission={permission?.metadata ?? {}}
  1209. output={props.part.state.status === "completed" ? props.part.state.output : undefined}
  1210. />
  1211. {props.part.state.status === "error" && (
  1212. <box paddingLeft={2}>
  1213. <text fg={theme.error}>{props.part.state.error.replace("Error: ", "")}</text>
  1214. </box>
  1215. )}
  1216. {permission && (
  1217. <box gap={1}>
  1218. <text fg={theme.text}>Permission required to run this tool:</text>
  1219. <box flexDirection="row" gap={2}>
  1220. <text fg={theme.text}>
  1221. <b>enter</b>
  1222. <span style={{ fg: theme.textMuted }}> accept</span>
  1223. </text>
  1224. <text fg={theme.text}>
  1225. <b>a</b>
  1226. <span style={{ fg: theme.textMuted }}> accept always</span>
  1227. </text>
  1228. <text fg={theme.text}>
  1229. <b>d</b>
  1230. <span style={{ fg: theme.textMuted }}> deny</span>
  1231. </text>
  1232. </box>
  1233. </box>
  1234. )}
  1235. </box>
  1236. )
  1237. })
  1238. return <Show when={component()}>{component()}</Show>
  1239. }
  1240. type ToolProps<T extends Tool.Info> = {
  1241. input: Partial<Tool.InferParameters<T>>
  1242. metadata: Partial<Tool.InferMetadata<T>>
  1243. permission: Record<string, any>
  1244. tool: string
  1245. output?: string
  1246. }
  1247. function GenericTool(props: ToolProps<any>) {
  1248. return (
  1249. <ToolTitle icon="⚙" fallback="Writing command..." when={true}>
  1250. {props.tool} {input(props.input)}
  1251. </ToolTitle>
  1252. )
  1253. }
  1254. type ToolRegistration<T extends Tool.Info = any> = {
  1255. name: string
  1256. container: "inline" | "block"
  1257. render?: Component<ToolProps<T>>
  1258. }
  1259. const ToolRegistry = (() => {
  1260. const state: Record<string, ToolRegistration> = {}
  1261. function register<T extends Tool.Info>(input: ToolRegistration<T>) {
  1262. state[input.name] = input
  1263. return input
  1264. }
  1265. return {
  1266. register,
  1267. container(name: string) {
  1268. return state[name]?.container
  1269. },
  1270. render(name: string) {
  1271. return state[name]?.render
  1272. },
  1273. }
  1274. })()
  1275. function ToolTitle(props: { fallback: string; when: any; icon: string; children: JSX.Element }) {
  1276. const { theme } = useTheme()
  1277. return (
  1278. <text paddingLeft={3} fg={props.when ? theme.textMuted : theme.text}>
  1279. <Show fallback={<>~ {props.fallback}</>} when={props.when}>
  1280. <span style={{ bold: true }}>{props.icon}</span> {props.children}
  1281. </Show>
  1282. </text>
  1283. )
  1284. }
  1285. ToolRegistry.register<typeof BashTool>({
  1286. name: "bash",
  1287. container: "block",
  1288. render(props) {
  1289. const output = createMemo(() => stripAnsi(props.metadata.output?.trim() ?? ""))
  1290. const { theme } = useTheme()
  1291. return (
  1292. <>
  1293. <ToolTitle icon="#" fallback="Writing command..." when={props.input.command}>
  1294. {props.input.description || "Shell"}
  1295. </ToolTitle>
  1296. <Show when={props.input.command}>
  1297. <text fg={theme.text}>$ {props.input.command}</text>
  1298. </Show>
  1299. <Show when={output()}>
  1300. <box>
  1301. <text fg={theme.text}>{output()}</text>
  1302. </box>
  1303. </Show>
  1304. </>
  1305. )
  1306. },
  1307. })
  1308. ToolRegistry.register<typeof ReadTool>({
  1309. name: "read",
  1310. container: "inline",
  1311. render(props) {
  1312. return (
  1313. <>
  1314. <ToolTitle icon="→" fallback="Reading file..." when={props.input.filePath}>
  1315. Read {normalizePath(props.input.filePath!)} {input(props.input, ["filePath"])}
  1316. </ToolTitle>
  1317. </>
  1318. )
  1319. },
  1320. })
  1321. ToolRegistry.register<typeof WriteTool>({
  1322. name: "write",
  1323. container: "block",
  1324. render(props) {
  1325. const { theme, syntax } = useTheme()
  1326. const code = createMemo(() => {
  1327. if (!props.input.content) return ""
  1328. return props.input.content
  1329. })
  1330. const diagnostics = createMemo(() => props.metadata.diagnostics?.[props.input.filePath ?? ""] ?? [])
  1331. return (
  1332. <>
  1333. <ToolTitle icon="←" fallback="Preparing write..." when={props.input.filePath}>
  1334. Wrote {props.input.filePath}
  1335. </ToolTitle>
  1336. <line_number fg={theme.textMuted} minWidth={3} paddingRight={1}>
  1337. <code
  1338. conceal={false}
  1339. fg={theme.text}
  1340. filetype={filetype(props.input.filePath!)}
  1341. syntaxStyle={syntax()}
  1342. content={code()}
  1343. />
  1344. </line_number>
  1345. <Show when={diagnostics().length}>
  1346. <For each={diagnostics()}>
  1347. {(diagnostic) => (
  1348. <text fg={theme.error}>
  1349. Error [{diagnostic.range.start.line}:{diagnostic.range.start.character}]: {diagnostic.message}
  1350. </text>
  1351. )}
  1352. </For>
  1353. </Show>
  1354. </>
  1355. )
  1356. },
  1357. })
  1358. ToolRegistry.register<typeof GlobTool>({
  1359. name: "glob",
  1360. container: "inline",
  1361. render(props) {
  1362. return (
  1363. <>
  1364. <ToolTitle icon="✱" fallback="Finding files..." when={props.input.pattern}>
  1365. Glob "{props.input.pattern}" <Show when={props.input.path}>in {normalizePath(props.input.path)} </Show>
  1366. <Show when={props.metadata.count}>({props.metadata.count} matches)</Show>
  1367. </ToolTitle>
  1368. </>
  1369. )
  1370. },
  1371. })
  1372. ToolRegistry.register<typeof GrepTool>({
  1373. name: "grep",
  1374. container: "inline",
  1375. render(props) {
  1376. return (
  1377. <ToolTitle icon="✱" fallback="Searching content..." when={props.input.pattern}>
  1378. Grep "{props.input.pattern}" <Show when={props.input.path}>in {normalizePath(props.input.path)} </Show>
  1379. <Show when={props.metadata.matches}>({props.metadata.matches} matches)</Show>
  1380. </ToolTitle>
  1381. )
  1382. },
  1383. })
  1384. ToolRegistry.register<typeof ListTool>({
  1385. name: "list",
  1386. container: "inline",
  1387. render(props) {
  1388. const dir = createMemo(() => {
  1389. if (props.input.path) {
  1390. return normalizePath(props.input.path)
  1391. }
  1392. return ""
  1393. })
  1394. return (
  1395. <>
  1396. <ToolTitle icon="→" fallback="Listing directory..." when={props.input.path !== undefined}>
  1397. List {dir()}
  1398. </ToolTitle>
  1399. </>
  1400. )
  1401. },
  1402. })
  1403. ToolRegistry.register<typeof TaskTool>({
  1404. name: "task",
  1405. container: "block",
  1406. render(props) {
  1407. const { theme } = useTheme()
  1408. const keybind = useKeybind()
  1409. return (
  1410. <>
  1411. <ToolTitle icon="◉" fallback="Delegating..." when={props.input.subagent_type ?? props.input.description}>
  1412. {Locale.titlecase(props.input.subagent_type ?? "unknown")} Task "{props.input.description}"
  1413. </ToolTitle>
  1414. <Show when={props.metadata.summary?.length}>
  1415. <box>
  1416. <For each={props.metadata.summary ?? []}>
  1417. {(task, index) => {
  1418. const summary = props.metadata.summary ?? []
  1419. return (
  1420. <text style={{ fg: task.state.status === "error" ? theme.error : theme.textMuted }}>
  1421. {index() === summary.length - 1 ? "└" : "├"} {Locale.titlecase(task.tool)}{" "}
  1422. {task.state.status === "completed" ? task.state.title : ""}
  1423. </text>
  1424. )
  1425. }}
  1426. </For>
  1427. </box>
  1428. </Show>
  1429. <text fg={theme.text}>
  1430. {keybind.print("session_child_cycle")}, {keybind.print("session_child_cycle_reverse")}
  1431. <span style={{ fg: theme.textMuted }}> to navigate between subagent sessions</span>
  1432. </text>
  1433. </>
  1434. )
  1435. },
  1436. })
  1437. ToolRegistry.register<typeof WebFetchTool>({
  1438. name: "webfetch",
  1439. container: "inline",
  1440. render(props) {
  1441. return (
  1442. <ToolTitle icon="%" fallback="Fetching from the web..." when={(props.input as any).url}>
  1443. WebFetch {(props.input as any).url}
  1444. </ToolTitle>
  1445. )
  1446. },
  1447. })
  1448. ToolRegistry.register({
  1449. name: "codesearch",
  1450. container: "inline",
  1451. render(props: ToolProps<any>) {
  1452. const input = props.input as any
  1453. const metadata = props.metadata as any
  1454. return (
  1455. <ToolTitle icon="◇" fallback="Searching code..." when={input.query}>
  1456. Exa Code Search "{input.query}" <Show when={metadata.results}>({metadata.results} results)</Show>
  1457. </ToolTitle>
  1458. )
  1459. },
  1460. })
  1461. ToolRegistry.register({
  1462. name: "websearch",
  1463. container: "inline",
  1464. render(props: ToolProps<any>) {
  1465. const input = props.input as any
  1466. const metadata = props.metadata as any
  1467. return (
  1468. <ToolTitle icon="◈" fallback="Searching web..." when={input.query}>
  1469. Exa Web Search "{input.query}" <Show when={metadata.numResults}>({metadata.numResults} results)</Show>
  1470. </ToolTitle>
  1471. )
  1472. },
  1473. })
  1474. ToolRegistry.register<typeof EditTool>({
  1475. name: "edit",
  1476. container: "block",
  1477. render(props) {
  1478. const ctx = use()
  1479. const { theme, syntax } = useTheme()
  1480. const view = createMemo(() => {
  1481. const diffStyle = ctx.sync.data.config.tui?.diff_style
  1482. if (diffStyle === "stacked") return "unified"
  1483. // Default to "auto" behavior
  1484. return ctx.width > 120 ? "split" : "unified"
  1485. })
  1486. const ft = createMemo(() => filetype(props.input.filePath))
  1487. const diffContent = createMemo(() => props.metadata.diff ?? props.permission["diff"])
  1488. const diagnostics = createMemo(() => {
  1489. const arr = props.metadata.diagnostics?.[props.input.filePath ?? ""] ?? []
  1490. return arr.filter((x) => x.severity === 1).slice(0, 3)
  1491. })
  1492. return (
  1493. <>
  1494. <ToolTitle icon="←" fallback="Preparing edit..." when={props.input.filePath}>
  1495. Edit {normalizePath(props.input.filePath!)}{" "}
  1496. {input({
  1497. replaceAll: props.input.replaceAll,
  1498. })}
  1499. </ToolTitle>
  1500. <Show when={diffContent()}>
  1501. <box paddingLeft={1}>
  1502. <diff
  1503. diff={diffContent()}
  1504. view={view()}
  1505. filetype={ft()}
  1506. syntaxStyle={syntax()}
  1507. showLineNumbers={true}
  1508. width="100%"
  1509. wrapMode={ctx.diffWrapMode()}
  1510. fg={theme.text}
  1511. addedBg={theme.diffAddedBg}
  1512. removedBg={theme.diffRemovedBg}
  1513. contextBg={theme.diffContextBg}
  1514. addedSignColor={theme.diffHighlightAdded}
  1515. removedSignColor={theme.diffHighlightRemoved}
  1516. lineNumberFg={theme.diffLineNumber}
  1517. lineNumberBg={theme.diffContextBg}
  1518. addedLineNumberBg={theme.diffAddedLineNumberBg}
  1519. removedLineNumberBg={theme.diffRemovedLineNumberBg}
  1520. />
  1521. </box>
  1522. </Show>
  1523. <Show when={diagnostics().length}>
  1524. <box>
  1525. <For each={diagnostics()}>
  1526. {(diagnostic) => (
  1527. <text fg={theme.error}>
  1528. Error [{diagnostic.range.start.line + 1}:{diagnostic.range.start.character + 1}] {diagnostic.message}
  1529. </text>
  1530. )}
  1531. </For>
  1532. </box>
  1533. </Show>
  1534. </>
  1535. )
  1536. },
  1537. })
  1538. ToolRegistry.register<typeof PatchTool>({
  1539. name: "patch",
  1540. container: "block",
  1541. render(props) {
  1542. const { theme } = useTheme()
  1543. return (
  1544. <>
  1545. <ToolTitle icon="%" fallback="Preparing patch..." when={true}>
  1546. Patch
  1547. </ToolTitle>
  1548. <Show when={props.output}>
  1549. <box>
  1550. <text fg={theme.text}>{props.output?.trim()}</text>
  1551. </box>
  1552. </Show>
  1553. </>
  1554. )
  1555. },
  1556. })
  1557. ToolRegistry.register<typeof TodoWriteTool>({
  1558. name: "todowrite",
  1559. container: "block",
  1560. render(props) {
  1561. const { theme } = useTheme()
  1562. return (
  1563. <>
  1564. <Show when={!props.input.todos?.length}>
  1565. <ToolTitle icon="⚙" fallback="Updating todos..." when={true}>
  1566. Updating todos...
  1567. </ToolTitle>
  1568. </Show>
  1569. <Show when={props.metadata.todos?.length}>
  1570. <box>
  1571. <For each={props.input.todos ?? []}>
  1572. {(todo) => (
  1573. <text style={{ fg: todo.status === "in_progress" ? theme.success : theme.textMuted }}>
  1574. [{todo.status === "completed" ? "✓" : " "}] {todo.content}
  1575. </text>
  1576. )}
  1577. </For>
  1578. </box>
  1579. </Show>
  1580. </>
  1581. )
  1582. },
  1583. })
  1584. function normalizePath(input?: string) {
  1585. if (!input) return ""
  1586. if (path.isAbsolute(input)) {
  1587. return path.relative(process.cwd(), input) || "."
  1588. }
  1589. return input
  1590. }
  1591. function input(input: Record<string, any>, omit?: string[]): string {
  1592. const primitives = Object.entries(input).filter(([key, value]) => {
  1593. if (omit?.includes(key)) return false
  1594. return typeof value === "string" || typeof value === "number" || typeof value === "boolean"
  1595. })
  1596. if (primitives.length === 0) return ""
  1597. return `[${primitives.map(([key, value]) => `${key}=${value}`).join(", ")}]`
  1598. }
  1599. function filetype(input?: string) {
  1600. if (!input) return "none"
  1601. const ext = path.extname(input)
  1602. const language = LANGUAGE_EXTENSIONS[ext]
  1603. if (["typescriptreact", "javascriptreact", "javascript"].includes(language)) return "typescript"
  1604. return language
  1605. }