Repository navigation
Expand file tree
/
Copy pathindex.tsx
More file actions
3628 lines (3501 loc) · 128 KB
/
Copy pathindex.tsx
File metadata and controls
3628 lines (3501 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
batch,
createEffect,
createMemo,
createSignal,
For,
Index,
Match,
on,
onCleanup,
Show,
Switch,
type Accessor,
} from "solid-js"
import path from "node:path"
import { EOL, tmpdir } from "node:os"
import { mkdir, writeFile } from "node:fs/promises"
import { useRoute, useRouteData } from "../../context/route"
import { createStore } from "solid-js/store"
import { useData } from "../../context/data"
import { SplitBorder } from "../../ui/border"
import { useTuiTerminalEnvironment } from "../../context/runtime"
import { Spinner, SPINNER_FRAMES } from "../../component/spinner"
import { PatchDiff } from "../../component/patch-diff"
import { useTheme, useThemes } from "../../context/theme"
import {
BoxRenderable,
ScrollBoxRenderable,
addDefaultParsers,
TextAttributes,
RGBA,
MouseEvent,
type Renderable,
} from "@opentui/core"
import { Prompt, type PromptRef } from "../../component/prompt"
import type {
SessionMessageInfo,
SessionMessageAssistant,
SessionMessageAssistantReasoning,
SessionMessageAssistantText,
SessionMessageAssistantTool,
SessionMessageUser,
SessionInfo,
ModelInfo,
} from "@opencode/client"
import { useLocal } from "../../context/local"
import { Locale } from "../../util/locale"
import { FilePath } from "../../ui/file-path"
import {
canonicalToolName,
executeCalls,
executeCallSummary,
finiteNumber,
primitiveInputSummary,
toolDisplayContent,
toolDisplayMetadata,
type ExecuteCall,
} from "../../util/tool-display"
import { DialogExecute } from "./dialog-execute"
import { RetryProvider } from "../../component/retry-provider"
import { useRenderer, useTerminalDimensions, type JSX } from "@opentui/solid"
import { useClient } from "../../context/client"
import { useEditorContext } from "../../context/editor"
import { useDialog } from "../../ui/dialog"
import { DialogSelect } from "../../ui/dialog-select"
import { DialogSessionRename } from "../../component/dialog-session-rename"
import { DialogImagePreview } from "../../component/dialog-image-preview"
import { statusLabel } from "../../component/dialog-workspace-file-changes"
import { DialogMessage } from "./dialog-message"
import { DialogFork } from "./dialog-fork"
import { DialogTimeline } from "./dialog-timeline"
import { Composer } from "./composer"
import { filetype } from "../../util/filetype"
import parsers from "../../parsers-config"
import { errorMessage } from "../../util/error"
import { useToast } from "../../ui/toast"
import stripAnsi from "strip-ansi"
import { usePromptRef } from "../../context/prompt"
import { projectedPromptInput } from "../../prompt/codec"
import { appendPrompt } from "../../prompt/history"
import { deduplicateVisibleImages } from "../../prompt/attachment"
import { useEpilogue } from "../../context/epilogue"
import { normalizePath } from "../../util/path"
import { PermissionPrompt } from "./permission"
import { FormPrompt } from "./form"
import { DialogExportOptions } from "../../ui/dialog-export-options"
import { DialogExportResult } from "../../ui/dialog-export-result"
import { sessionEpilogue } from "../../util/presentation"
import { useConfig } from "../../config"
import { useClipboard } from "../../context/clipboard"
import { nextThinkingMode, type ThinkingMode } from "../../context/thinking"
import { getScrollAcceleration } from "../../util/scroll"
import { collapseShellOutput, collapseToolOutput } from "../../util/collapse-tool-output"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { usePathFormatter } from "../../context/path-format"
import { useLocation } from "../../context/location"
import { Slot } from "../../plugin/render"
import { usePlugin } from "../../plugin/context"
import {
cacheReuseDrop,
completeGroupBoundary,
createSessionRows,
legacyTurns,
messageBoundaryIDs,
resolvePart,
sessionRowID,
turnDuration,
turnTokensPerSecond,
type CacheUsage,
type PartRef,
type SessionRow,
} from "./rows"
import { switchLabel } from "../../util/model"
import { findMessageBoundary, messageNavigationSlack } from "./message-navigation"
import { stringWidth } from "../../util/string-width"
import { useArgs } from "../../context/args"
import { withTimestampedFallback } from "@opencode/util/session-title-fallback"
import { useSessionTabs, type ScrollAnchor } from "../../context/session-tabs"
import { createSingleFlight } from "../../util/single-flight"
import { createDelayedPresence } from "../../util/delayed-presence"
import { SessionLocationMissing } from "./location-missing"
import { isRecord } from "../../util/record"
import { createHistoryPrepend } from "./history"
import { context, use, type PendingAction } from "./render-context"
import { INLINE_TOOL_ICON_WIDTH, InlineToolRow, ReasoningPart, TextPart, toolDisplay } from "./message-parts"
import { defaultVerbosity, type GroupKind, type SessionEntry } from "./grouping/session"
import { SessionGroupView } from "./group-view"
import { useEntryAnchor } from "./anchor-view"
import { containsAnchor, createTimelineAnchors, groupID } from "./anchors"
import { rowsAfter, rowsBefore, rowWeight } from "./mount-budget"
export { InlineToolRow } from "./message-parts"
export { toolDisplay } from "./message-parts"
addDefaultParsers(parsers.parsers)
// Exclude temporary bottom space when measuring the real transcript height.
const NAVIGATION_SLACK_ID = "session-navigation-slack"
const BACKGROUND_TOOL_HINT_DELAY = 3_000
// Budgets count rendered entries (see mount-budget.ts); a collapsed group costs one.
// The tail comfortably overfills a tall viewport; older rows mount as the reader approaches them.
const TRANSCRIPT_TAIL_ROWS = 40
const TRANSCRIPT_BACKFILL_CHUNK = 60
export function Session(props: {
scrollRef?: (scroll: ScrollBoxRenderable | undefined) => void
verticalTabsWidth: number
promptMuted?: boolean
sidebarVisible: boolean
onToggleSidebar: () => void
terminals?: boolean
visibleTerminalID?: string
onTerminalPicker?: (show: (() => void) | undefined) => void
width?: number
}) {
const setEpilogue = useEpilogue()
const clipboard = useClipboard()
const writeExport = async (file: string, content: string) => {
await mkdir(path.dirname(file), { recursive: true })
await writeFile(file, content)
}
const route = useRouteData("session")
const sessionID = route.sessionID
const { navigate } = useRoute()
const data = useData()
const local = useLocal()
const args = useArgs()
const configState = useConfig()
const config = configState.data
const theme = useTheme()
const promptRef = usePromptRef()
const session = createMemo(() => data.session.get(route.sessionID))
const messages = () => data.session.message.list(route.sessionID)
const messageIndexes = createMemo(() => new Map(messages().map((message, index) => [message.id, index])))
const legacy = createMemo(() => legacyTurns(messages()))
const messagesBeforeRevert = () => {
const messageID = session()?.revert?.messageID
if (!messageID) return messages()
const index = messages().findIndex((message) => message.id === messageID)
return index === -1 ? messages() : messages().slice(0, index)
}
const messagesFromRevert = () => {
const messageID = session()?.revert?.messageID
if (!messageID) return []
const index = messages().findIndex((message) => message.id === messageID)
return index === -1 ? [] : messages().slice(index)
}
const currentLocation = useLocation()
const location = createMemo(() => session()?.location ?? currentLocation.ref)
createEffect(() => currentLocation.set(location()))
createEffect(() => {
const title = Locale.truncate(session()?.title ?? "", 50)
setEpilogue(sessionEpilogue({ title, sessionID: session()?.id }))
})
onCleanup(() => setEpilogue())
const descendantSessionIDs = createMemo(() => {
if (session()?.parentID) return []
return data.session.family(route.sessionID).filter((id) => id !== route.sessionID)
})
const permissions = createMemo(() => {
if (session()?.parentID) return []
return [route.sessionID, ...descendantSessionIDs()].flatMap(
(sessionID) => data.session.permission.list(sessionID) ?? [],
)
})
const promptedPermissions = createMemo(() => (local.permission.mode === "autoaccept" ? [] : permissions()))
const forms = createMemo(() => {
const global = data.session.form.list("global", location()) ?? []
if (session()?.parentID) return global
return [route.sessionID, ...descendantSessionIDs()]
.flatMap((sessionID) => data.session.form.list(sessionID) ?? [])
.concat(global)
})
const pendingUsers = createMemo(() =>
data.session.pending.list(route.sessionID).flatMap((item) => (item.type === "user" ? [item] : [])),
)
const pendingDeliveries = createMemo(() => new Map(pendingUsers().map((item) => [item.id, item.delivery])))
const queuedPrompts = createMemo(() =>
pendingUsers().flatMap((item) =>
item.delivery === "queue" ? [{ id: item.id, text: item.payload.text, payload: item.payload }] : [],
),
)
const [composer, setComposer] = createStore({
open: false,
tab: undefined as string | undefined,
})
props.onTerminalPicker?.(() => setComposer({ open: true, tab: "terminals" }))
onCleanup(() => props.onTerminalPicker?.(undefined))
createEffect(() => {
if (props.promptMuted && composer.open) setComposer("open", false)
})
const disabled = createMemo(() => promptedPermissions().length > 0 || forms().length > 0)
const dimensions = useTerminalDimensions()
const thinkingMode = createMemo<ThinkingMode>(() => config.session?.thinking ?? "hide")
const showScrollbar = createMemo(() => config.session?.scrollbar ?? false)
const markdownMode = createMemo(() => config.session?.markdown ?? "rendered")
const diffWrapMode = createMemo(() => config.diffs?.wrap ?? "word")
const groupExploration = createMemo(() => config.session?.grouping !== "none")
const verbosity = createMemo(() => config.session?.verbosity ?? defaultVerbosity)
// High opens exploration and instruction summaries by default; everything else starts collapsed.
const groupExpanded = (groupID: string, kind: GroupKind) =>
sessionTabs.groupExpanded(sessionID, groupID) ??
(verbosity() === "high" && (kind === "exploration" || kind === "instructions"))
const groupedKind = (kind: GroupKind) =>
kind === "reasoning" ? thinkingMode() === "hide" : kind === "exploration" ? groupExploration() : true
Keymap.createLayer(() => ({
priority: 10,
enabled: () => props.sidebarVisible && dimensions().width - props.verticalTabsWidth <= 120 && !disabled(),
commands: [{ bind: "escape,ctrl+c", title: "Close sidebar", group: "Session", run: props.onToggleSidebar }],
}))
const contentWidth = createMemo(() => (props.width ?? dimensions().width - props.verticalTabsWidth) - 4)
const models = createMemo(() => data.location.model.list(location()) ?? [])
const scrollAcceleration = createMemo(() => getScrollAcceleration(config))
const toast = useToast()
const client = useClient()
const autoApproved = new Set<string>()
createEffect(() => {
if (local.permission.mode !== "autoaccept") return
permissions().forEach((request) => {
if (autoApproved.has(request.id)) return
autoApproved.add(request.id)
void data.session.permission
.reply({
sessionID: request.sessionID,
decision: "once",
requestID: request.id,
})
.catch((error) => {
autoApproved.delete(request.id)
toast.error(error)
})
})
})
const editor = useEditorContext()
const [rowsSynced, setRowsSynced] = createSignal(false)
const rows = createSessionRows(
() => route.sessionID,
(id) => {
if (id === sessionID) setRowsSynced(true)
},
)
const boundaries = createMemo(() => messageBoundaryIDs(rows, messages()))
const anchors = createTimelineAnchors()
const [navigationMessage, setNavigationMessage] = createSignal<string>()
const [navigationSlack, setNavigationSlack] = createSignal(0)
const [firstJump, setFirstJump] = createSignal<() => void>()
const [synced, setSynced] = createSignal(false)
const sessionTabs = useSessionTabs()
const [awayFromBottom, setAwayFromBottom] = createSignal(false)
const [latestHovered, setLatestHovered] = createSignal(false)
let ensureAllRowsPending: (() => void)[] | undefined
createEffect(() => {
if (!awayFromBottom()) setLatestHovered(false)
})
const clearMessageNavigation = () => {
ensureAllRowsPending?.splice(0)
prependHistory.cancel()
firstJump()?.()
setFirstJump(undefined)
setNavigationSlack(0)
setNavigationMessage(undefined)
}
createEffect(
on(
() => [dimensions().width, dimensions().height, props.verticalTabsWidth] as const,
(_, previous) => {
if (!previous) return
clearMessageNavigation()
if (scroll && !scroll.isDestroyed) updateAwayFromBottom()
},
),
)
createEffect(
on([descendantSessionIDs, () => client.connection.status()], ([sessionIDs, status]) => {
if (status !== "connected") return
void Promise.allSettled(
sessionIDs.flatMap((sessionID) => [data.session.permission.sync(sessionID), data.session.form.sync(sessionID)]),
)
}),
)
createEffect(() => {
if (client.connection.status() !== "connected") return
setSynced(false)
const sessionID = route.sessionID
void (async () => {
await Promise.all([
data.session.sync(sessionID, { children: true }),
data.session.permission.sync(sessionID).catch(() => undefined),
data.session.form.sync(sessionID).catch(() => undefined),
])
const info = data.session.get(sessionID)
if (!info) {
toast.show({
message: `Session not found: ${sessionID}`,
variant: "error",
duration: 5000,
})
sessionTabs.enabled() ? sessionTabs.close(sessionID) : navigate({ type: "home" })
return
}
editor.reconnect(info.location.directory)
setSynced(true)
})().catch((error) => {
if (route.sessionID !== sessionID) return
toast.show({
message: errorMessage(error),
variant: "error",
duration: 5000,
})
sessionTabs.enabled() ? sessionTabs.close(sessionID) : navigate({ type: "home" })
})
})
let seeded = false
let sent = false
let restored = false
let scroll: ScrollBoxRenderable
createEffect(() => {
if (restored || !synced() || !rowsSynced() || !scroll || scroll.isDestroyed) return
restored = true
// Initial synchronization can finish after the reader has already navigated.
if (!isAwayFromBottom()) restoreScrollPosition()
})
let awayTimer: ReturnType<typeof setTimeout> | undefined
onCleanup(() => {
if (awayTimer) clearTimeout(awayTimer)
props.scrollRef?.(undefined)
prependHistory.cancel()
firstJump()?.()
if (!scroll || scroll.isDestroyed) return
scroll.verticalScrollBar.off("change", updateAwayFromBottom)
scroll.content.off("resize", holdAnchor)
saveScrollAnchor(true)
})
const [prompt, setPrompt] = createSignal<PromptRef>()
const bind = (r: PromptRef | undefined) => {
setPrompt(r)
promptRef.set(r)
if (seeded || !route.prompt || !r) return
seeded = true
r.set(route.prompt)
}
/** Runs after layout has settled (two frames), unless the transcript was torn down. */
const afterLayout = (continuation: () => void) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (!scroll || scroll.isDestroyed) return
continuation()
})
})
}
// Keeps a toggled disclosure's header on its viewport row. The content resize fires inside the
// layout pass, before rows take their screen positions, so the correction lands in the same frame.
// Renderable positions are still stale at that point; read the computed layout instead.
let held: { node: Renderable; top: number } | undefined
const layoutTop = (node: Renderable): number =>
node === scroll.content || !node.parent ? 0 : node.getLayoutNode().getComputedTop() + layoutTop(node.parent)
const holdAnchor = () => {
if (held && !held.node.isDestroyed) scroll.scrollTo(layoutTop(held.node) - held.top)
}
// Tail-first transcript mounting: only the newest rows mount when the session opens. Older rows
// mount on demand near the top, keeping inactive tabs cheap to tear down. While the reader stays
// at the bottom the hidden span follows appends; leaving the bottom pins it to preserve the viewport.
const [hiddenRows, setHiddenRows] = createSignal<number>()
const [visibleRowsEnd, setVisibleRowsEnd] = createSignal<number>()
const weights = createMemo(() =>
rows.map((row) =>
rowWeight(row, {
expanded: groupExpanded,
grouped: groupedKind,
}),
),
)
const hidden = createMemo(() =>
Math.min(hiddenRows() ?? Infinity, rowsBefore(weights(), rows.length, TRANSCRIPT_TAIL_ROWS)),
)
const visibleEnd = createMemo(() => Math.max(hidden(), Math.min(visibleRowsEnd() ?? rows.length, rows.length)))
const visibleRows = createMemo(() => rows.slice(hidden(), visibleEnd()))
const prependHistory = createHistoryPrepend({
sessionID: () => route.sessionID,
more: (id) => data.session.message.more(id),
loadMore: async (id) => {
await data.session.message.loadMore(id)
await completeGroupBoundary({
rows,
messages: () => data.session.message.list(id).length,
more: () => data.session.message.more(id),
loadMore: () => data.session.message.loadMore(id),
active: () => route.sessionID === id,
})
},
height: () => scroll.scrollHeight,
afterLayout,
active: (id) => route.sessionID === id && Boolean(scroll && !scroll.isDestroyed),
scrollBy: (amount) => {
scroll.scrollBy(amount)
updateAwayFromBottom()
},
})
let revealingOlderRows = false
const revealOlderRows = (scrollBy = 0) => {
const current = hidden()
if (revealingOlderRows || !scroll || scroll.isDestroyed || scroll.scrollTop > scroll.viewport.height) return false
if (current === 0) return prependHistory(scrollBy)
revealingOlderRows = true
const before = scroll.scrollHeight
scroll.stickyScroll = false
setHiddenRows(rowsBefore(weights(), current, TRANSCRIPT_BACKFILL_CHUNK))
afterLayout(() => {
scroll.scrollBy(scroll.scrollHeight - before + scrollBy)
scroll.stickyScroll = !navigationMessage()
revealingOlderRows = false
})
return true
}
let revealingNewerRows = false
const revealNewerRows = (scrollBy = 0) => {
const current = visibleEnd()
if (
revealingNewerRows ||
current === rows.length ||
!scroll ||
scroll.isDestroyed ||
scroll.scrollTop + scroll.viewport.height < scroll.scrollHeight - scroll.viewport.height
)
return false
revealingNewerRows = true
const next = rowsAfter(weights(), current, TRANSCRIPT_BACKFILL_CHUNK)
setVisibleRowsEnd(next === rows.length ? undefined : next)
afterLayout(() => {
revealingNewerRows = false
scroll.scrollBy(scrollBy)
updateAwayFromBottom()
})
return true
}
/** Message navigation needs the full transcript mounted before walking or jumping. */
const ensureAllRows = (continuation: () => void) => {
if (firstJump()) clearMessageNavigation()
if (!ensureAllRowsPending && hidden() === 0 && visibleEnd() === rows.length) return continuation()
if (ensureAllRowsPending) {
ensureAllRowsPending.push(continuation)
return
}
const pending = [continuation]
ensureAllRowsPending = pending
setHiddenRows(0)
setVisibleRowsEnd(undefined)
afterLayout(() => {
if (ensureAllRowsPending === pending) ensureAllRowsPending = undefined
pending.forEach((continuation) => continuation())
updateAwayFromBottom()
})
}
function isAwayFromBottom() {
if (
revealingOlderRows ||
revealingNewerRows ||
ensureAllRowsPending ||
navigationMessage() ||
navigationSlack() ||
firstJump()
)
return true
if (visibleEnd() < rows.length) return true
return scroll.scrollTop < Math.max(0, scroll.scrollHeight - scroll.viewport.height)
}
function updateAwayFromBottom() {
const preserveWindow = revealingOlderRows || revealingNewerRows || !!ensureAllRowsPending || !!firstJump()
if (isAwayFromBottom()) setHiddenRows((current) => current ?? hidden())
if (awayTimer) clearTimeout(awayTimer)
awayTimer = setTimeout(() => {
awayTimer = undefined
if (!scroll || scroll.isDestroyed) return
const away = preserveWindow || isAwayFromBottom()
setAwayFromBottom(away)
if (!away) {
if (!renderer.getSelection()) setHiddenRows(undefined)
scroll.stickyScroll = true
}
saveScrollAnchor()
})
}
function saveScrollAnchor(unmounting = false) {
// Initial layout must not overwrite the saved position before synchronization restores it.
if (!restored) return
const mounted = anchors.list()
// Solid disposes child registrations before the route's cleanup. Keep the
// last scroll-event anchor once those children have gone away.
if (unmounting && !mounted.length) return
if (!isAwayFromBottom()) {
sessionTabs.setScrollAnchor(sessionID, undefined)
return
}
let first: ScrollAnchor | undefined
let anchor: ScrollAnchor | undefined
for (const child of mounted) {
const item = {
target: child.target,
screenY: child.node.y - scroll.viewport.y,
}
first ??= item
const inset =
item.target.type === "group" ||
data.session.message.get(sessionID, item.target.ref.messageID)?.type === "assistant"
? 1
: 0
if (item.screenY <= inset && (!anchor || item.screenY > anchor.screenY)) anchor = item
}
anchor ??= first
if (anchor) sessionTabs.setScrollAnchor(sessionID, anchor)
else sessionTabs.setScrollAnchor(sessionID, undefined)
}
function restoreScrollPosition() {
const anchor = sessionTabs.scrollAnchor(sessionID)
const index = anchor ? rows.findIndex((row) => containsAnchor(row, anchor.target)) : -1
if (!anchor || index === -1) {
scroll.scrollTo(scroll.scrollHeight)
setAwayFromBottom(false)
return
}
setHiddenRows(rowsBefore(weights(), index, TRANSCRIPT_BACKFILL_CHUNK))
const end = rowsAfter(weights(), index, TRANSCRIPT_BACKFILL_CHUNK)
setVisibleRowsEnd(end === rows.length ? undefined : end)
scroll.stickyScroll = false
const restore = () =>
afterLayout(() => {
const boundary = anchors.get(anchor.target)
if (!boundary) {
sessionTabs.setScrollAnchor(sessionID, undefined)
scroll.stickyScroll = true
scroll.scrollTo(scroll.scrollHeight)
setAwayFromBottom(false)
return
}
const contentY = scroll.scrollTop + boundary.node.y - scroll.viewport.y
const target = contentY - anchor.screenY
const maximum = Math.max(0, scroll.scrollHeight - scroll.viewport.height)
if (target > maximum && visibleEnd() < rows.length) {
const next = rowsAfter(weights(), visibleEnd(), TRANSCRIPT_BACKFILL_CHUNK)
setVisibleRowsEnd(next === rows.length ? undefined : next)
restore()
return
}
if (target > maximum) {
setNavigationSlack(
messageNavigationSlack({
top: target,
viewportHeight: scroll.viewport.height,
scrollHeight: scroll.scrollHeight,
currentSlack: scroll.getRenderable(NAVIGATION_SLACK_ID)?.height ?? 0,
}),
)
restore()
return
}
scroll.scrollTo(target)
updateAwayFromBottom()
})
restore()
}
createEffect(() => {
const current = prompt()
if (sent || !current || !synced() || !local.model.ready || !local.model.catalogReady) return
if (!local.agent.current() || !local.model.current()) return
if (!args.prompt || route.prompt?.text !== args.prompt || current.current.text !== args.prompt) return
sent = true
current.submit()
})
const dialog = useDialog()
const renderer = useRenderer()
const runPendingAction = createSingleFlight<string>()
const mutatePending = async (action: PendingAction, inboxID: string, failureLabel?: string) => {
const result = await runPendingAction(inboxID, async () => {
const request =
action === "steer"
? client.api.session.inbox.update({ sessionID: route.sessionID, inboxID, delivery: "steer" })
: action === "queue"
? client.api.session.inbox.update({ sessionID: route.sessionID, inboxID, delivery: "queue" })
: client.api.session.inbox.cancel({ sessionID: route.sessionID, inboxID })
const error = await request.then(
() => undefined,
(error) => error,
)
if (!error) return true
const label = failureLabel ?? (action === "cancel" ? "delete" : action)
toast.show({ title: `Failed to ${label} pending prompt`, message: errorMessage(error), variant: "error" })
return false
})
return result ?? false
}
const openQueuedPrompts = () =>
dialog.replace(() => (
<DialogSelect
title="Queued prompts"
options={queuedPrompts().map((prompt, index) => ({
title: prompt.text,
value: prompt.id,
footer: `${index + 1} of ${queuedPrompts().length}`,
}))}
onSelect={(option) => {
void mutatePending("steer", option.value).then((steered) => {
if (steered) dialog.clear()
})
}}
actions={[
{
command: "queued_prompt.delete",
title: "delete",
onTrigger: (option) => {
const last = queuedPrompts().length === 1
void mutatePending("cancel", option.value).then((cancelled) => {
if (cancelled && last) dialog.clear()
})
},
},
{
command: "queued_prompt.undo",
title: "undo",
onTrigger: (option) => {
const target = prompt()
const queued = queuedPrompts().find((item) => item.id === option.value)
if (!target || !queued) return
if (target.mode === "shell" && target.current.text) {
toast.show({ message: "Leave shell mode before undoing a queued prompt", variant: "error" })
return
}
void mutatePending("cancel", queued.id, "undo").then((undone) => {
if (!undone) return
target.setMode("normal")
target.set(appendPrompt(target.current, { ...projectedPromptInput(queued.payload), pasted: [] }))
dialog.clear()
target.focus()
})
},
},
]}
footerHints={[{ title: "steer", label: "enter" }]}
/>
))
const unavailable = (feature: string) => {
toast.show({ message: `${feature} is not implemented for V2 sessions yet`, variant: "error", duration: 5000 })
dialog.clear()
}
const alignMessage = (messageID: string, top: number) => {
scroll.stickyScroll = false
setNavigationMessage(messageID)
updateAwayFromBottom()
setNavigationSlack(
messageNavigationSlack({
top,
viewportHeight: scroll.viewport.height,
scrollHeight: scroll.scrollHeight,
currentSlack: scroll.getRenderable(NAVIGATION_SLACK_ID)?.height ?? 0,
}),
)
afterLayout(() => {
if (navigationMessage() !== messageID) return
scroll.scrollTo(top)
})
}
const scrollToMessage = (direction: "next" | "prev", dialog: ReturnType<typeof useDialog>, userOnly = false) =>
ensureAllRows(() => {
const target = findMessageBoundary({
direction,
children: anchors.messagePositions(),
messages: messages(),
scrollTop: scroll.scrollTop,
viewportY: scroll.viewport.y,
currentID: navigationMessage(),
userOnly,
})
if (target) {
jumpToMessage(target.id)
dialog.clear()
return
}
if (direction === "prev" && data.session.message.more(route.sessionID)) {
prependHistory(0, () => scrollToMessage(direction, dialog, userOnly))
return
}
dialog.clear()
})
const jumpToMessage = (messageID: string) =>
ensureAllRows(() => {
const child = anchors.forMessage(messageID)
if (!child) return
const y = scroll.scrollTop + child.node.y - scroll.viewport.y
const message = data.session.message.get(route.sessionID, messageID)
alignMessage(messageID, Math.max(0, y - (message?.type === "assistant" ? 1 : 0)))
})
function toBottom() {
clearMessageNavigation()
ensureAllRowsPending = undefined
if (awayTimer) clearTimeout(awayTimer)
awayTimer = undefined
setAwayFromBottom(false)
sessionTabs.setScrollAnchor(route.sessionID, undefined)
setHiddenRows(undefined)
setVisibleRowsEnd(undefined)
setTimeout(() => {
if (!scroll || scroll.isDestroyed) return
scroll.stickyScroll = true
scroll.scrollTo(scroll.scrollHeight)
}, 50)
}
function moveTranscript(delta: number) {
clearMessageNavigation()
if (delta < 0 && revealOlderRows(delta)) {
dialog.clear()
return
}
if (delta > 0 && revealNewerRows(delta)) {
dialog.clear()
return
}
scroll.scrollBy(delta)
updateAwayFromBottom()
dialog.clear()
}
const globalCommands = [
{
id: "session.page.up",
title: "Page up",
group: "Session",
palette: undefined,
run: () => moveTranscript(-scroll.height / 2),
},
{
id: "session.page.down",
title: "Page down",
group: "Session",
palette: undefined,
run: () => moveTranscript(scroll.height / 2),
},
{
id: "session.line.up",
title: "Line up",
group: "Session",
palette: undefined,
run: () => moveTranscript(-1),
},
{
id: "session.line.down",
title: "Line down",
group: "Session",
palette: undefined,
run: () => moveTranscript(1),
},
{
id: "session.half.page.up",
title: "Half page up",
group: "Session",
palette: undefined,
run: () => moveTranscript(-scroll.height / 4),
},
{
id: "session.half.page.down",
title: "Half page down",
group: "Session",
palette: undefined,
run: () => moveTranscript(scroll.height / 4),
},
]
const baseAndUnfocusedCommands = [
{
id: "session.first",
title: "First message",
group: "Session",
palette: undefined,
run: () => {
if (firstJump()) return
clearMessageNavigation()
const request = new AbortController()
const cancel = () => request.abort()
setFirstJump(() => cancel)
const start = () => {
if (firstJump() !== cancel || scroll.isDestroyed) return
if (revealingOlderRows || revealingNewerRows || ensureAllRowsPending) return afterLayout(start)
const previous = { start: hiddenRows(), end: visibleRowsEnd() }
const restore = () => {
cancel()
batch(() => {
setHiddenRows(previous.start)
setVisibleRowsEnd(previous.end)
})
}
const commit = () => {
if (firstJump() !== restore || scroll.isDestroyed) return
scroll.stickyScroll = false
batch(() => {
setHiddenRows(0)
setVisibleRowsEnd(TRANSCRIPT_BACKFILL_CHUNK)
setFirstJump(() => cancel)
})
}
// Pin both ends until the head budget commits in the same batch as history.
batch(() => {
setFirstJump(() => restore)
setHiddenRows(hidden())
setVisibleRowsEnd(visibleEnd())
})
void data.session.message
.loadMore(route.sessionID, {
all: true,
signal: request.signal,
beforePublish: commit,
})
.then(
() => {
commit()
if (firstJump() !== cancel || scroll.isDestroyed) return
if (rows.length <= TRANSCRIPT_BACKFILL_CHUNK) setVisibleRowsEnd(undefined)
scroll.scrollTo(0)
afterLayout(() => {
if (firstJump() !== cancel) return
scroll.scrollTo(0)
setFirstJump(undefined)
updateAwayFromBottom()
})
},
(error) => {
if (firstJump() !== restore || scroll.isDestroyed) return
clearMessageNavigation()
toast.error(error)
updateAwayFromBottom()
},
)
}
prependHistory.after(start)
dialog.clear()
},
},
{
id: "session.last",
title: "Last message",
group: "Session",
palette: undefined,
run: () => {
toBottom()
dialog.clear()
},
},
]
const baseCommands = createMemo(() => [
{
title: "Share session",
id: "session.share",
suggested: route.type === "session",
group: "Session",
slash: { name: "share" },
run: () => unavailable("Sharing"),
},
{
title: "Rename session",
id: "session.rename",
group: "Session",
slash: { name: "rename", arguments: true as const },
run: (input?: string) => {
if (input === undefined) return DialogSessionRename.show(dialog, route.sessionID, session()?.title)
const title = input.trim()
void (
title
? client.api.session.update({ sessionID: route.sessionID, title })
: data.session.title.generate(route.sessionID)
).catch((error) => toast.error(error))
},
},
{
title: "Jump to message",
id: "session.timeline",
group: "Session",
slash: { name: "timeline" },
run: () => {
dialog.replace(() => (
<DialogTimeline
sessionID={route.sessionID}
onMove={jumpToMessage}
setPrompt={(value) => promptRef.current?.set(value)}
/>
))
},
},
{
title: "Fork session",
id: "session.fork",
group: "Session",
slash: { name: "fork" },
run: () => {
dialog.replace(() => (
<DialogFork
sessionID={route.sessionID}
onMove={(messageID) => {
if (!messageID) return
jumpToMessage(messageID)
}}
/>
))
},
},
{
title: "Compact session",
id: "session.compact",
group: "Session",
slash: {
name: "compact",
},
run: () => {
const selection = local.model.current()
void data.session
.compact({
sessionID: route.sessionID,
model: selection
? {
providerID: selection.providerID,
id: selection.modelID,
variant: local.model.variant.current(),
}
: undefined,
})
.catch((error) => toast.show({ message: errorMessage(error), variant: "error" }))
dialog.clear()
},
},
{
title: "Undo previous message",
id: "session.undo",
group: "Session",
slash: { name: "undo" },
run: () => {
const message = messagesBeforeRevert().findLast(
(message): message is SessionMessageUser => message.type === "user" && !!message.text.trim(),
)
if (!message) {
toast.show({ message: "Nothing to undo", variant: "error", duration: 3000 })
dialog.clear()
return