Documentation
¶
Overview ¶
Package components provides UI components for the repl terminal interface.
Index ¶
- Constants
- Variables
- func BashToolRenderer(tool store.ToolPart) trail.Node
- func DefaultToolRenderer(tool store.ToolPart) trail.Node
- func DownloadToolRenderer(tool store.ToolPart) trail.Node
- func EditToolRenderer(tool store.ToolPart) trail.Node
- func FormatTurnSummary(rec api.TurnCompletedRecord, entryID string, at time.Time) string
- func GlobToolRenderer(tool store.ToolPart) trail.Node
- func GrepToolRenderer(tool store.ToolPart) trail.Node
- func InvokeAgentToolRenderer(tool store.ToolPart) trail.Node
- func IsStandardModelAlias(alias string) bool
- func LogoLines() ([]string, []color.Color)
- func LsRenderer(tool store.ToolPart) trail.Node
- func LsToolRenderer(tool store.ToolPart) trail.Node
- func ManageAgentsToolRenderer(tool store.ToolPart) trail.Node
- func NormalizeVersion(version string) string
- func OpenWarnings()
- func PlanToolRenderer(tool store.ToolPart) trail.Node
- func ProviderDisplayName(name, displayName string) string
- func QuestionToolRenderer(tool store.ToolPart) trail.Node
- func RemoveToolRenderer(tool store.ToolPart) trail.Node
- func ShortenHomePath(path string) string
- func SpinnerStats(startedAt time.Time, input, output int64, now time.Time) string
- func SubagentColor(scheme *theme.Scheme, agentName string) color.Color
- func SubagentModelBadge(scheme *theme.Scheme, sub api.Session) trail.Node
- func TasksToolRenderer(tool store.ToolPart) trail.Node
- func TodosToolRenderer(tool store.ToolPart) trail.Node
- func ToolSearchToolRenderer(tool store.ToolPart) trail.Node
- func ViewToolRenderer(tool store.ToolPart) trail.Node
- func WebFetchToolRenderer(tool store.ToolPart) trail.Node
- func WebSearchToolRenderer(tool store.ToolPart) trail.Node
- func WriteToolRenderer(tool store.ToolPart) trail.Node
- type AlignedRow
- type BashToolWidgetProps
- type ComposerProps
- type ConfirmAction
- type DiffProps
- type DownloadToolWidgetProps
- type DraftEdit
- type EditToolWidgetProps
- type GlobToolWidgetProps
- type GrepToolWidgetProps
- type HeaderProps
- type HistoryEntry
- type InputAction
- type InvokeAgentToolWidgetProps
- type LoadRuleToolWidgetProps
- type LoadSkillToolWidgetProps
- type LsToolWidgetProps
- type ManageAgentsToolWidgetProps
- type MessageProps
- type MessageTextProps
- type MessageThoughtProps
- type MessageToolProps
- type ModelAliasEditorProps
- type ModelSwitchPromptProps
- type OnboardingWizardProps
- type PermissionConfigEditorProps
- type PermissionPromptProps
- type PickerProps
- type PlanReviewPromptProps
- type PromptHistory
- type ProviderReauthPromptProps
- type QuestionPromptProps
- type RemoveToolWidgetProps
- type SandboxConfigEditorProps
- type SandboxPolicyKnob
- type SlotComponent
- type SpinnerProps
- type StandardModelAlias
- type StreamingHintProps
- type TasksToolWidgetProps
- type TodosToolWidgetProps
- type ToolDefaultWidgetProps
- type ToolRenderer
- type ToolSearchToolWidgetProps
- type TrustDecision
- type TrustPromptProps
- type ViewToolWidgetProps
- type WebFetchToolWidgetProps
- type WebSearchToolWidgetProps
- type WriteToolWidgetProps
Constants ¶
const BashModeHint = "activated bash mode · esc to cancel"
BashModeHint is the status line hint shown when interactive bash mode is active.
const HistoryModeHint = "prompt history · enter to send · esc to cancel"
HistoryModeHint is the status line hint shown while browsing prompt history.
Variables ¶
var ActiveStream = trail.SimpleFC("ActiveStream", func() trail.Node { scheme := theme.UseTheme() msgsPtr := store.UseStream(func(s store.StreamState) *[]store.Message { return s.Messages }) streaming := store.UseStream(func(s store.StreamState) bool { return s.Streaming }) waitingPerm := store.UseStream(func(s store.StreamState) bool { return s.WaitingPermission || s.WaitingQuestion || s.WaitingPlanReview }) status := store.UseStream(func(s store.StreamState) api.SessionStatus { return s.Status }) delegated := store.UseStream(func(s store.StreamState) bool { return s.Delegated }) pendingCmd := store.UseStream(func(s store.StreamState) string { return s.PendingCommand }) todosPtr := store.UseStream(func(s store.StreamState) *[]api.TodoItem { return s.Todos }) turn := store.UseStream(func(s store.StreamState) turnStats { return turnStats{StartedAt: s.TurnStartedAt, BaseInput: s.BaseInput, BaseOutput: s.BaseOutput, CallInput: s.CallInput, CallOutput: s.CallOutput} }) totals := store.UseUsageTotals() runningSubs := store.UseRunningDelegatedSubagents() var msgs []store.Message if msgsPtr != nil { msgs = *msgsPtr } var todos []api.TodoItem if todosPtr != nil { todos = *todosPtr } hasIncomplete := hasIncompleteTodos(todos) if !streaming && len(msgs) == 0 && pendingCmd == "" && !hasIncomplete { return nil } var children []trail.Node if streaming && !waitingPerm { children = append(children, StreamingHint(StreamingHintProps{Delegated: delegated})) } for _, msg := range msgs { children = append(children, Message(MessageProps{Message: msg})) } if pendingCmd != "" { bashColor := scheme.Color.Mode.Bash primaryColor := scheme.Color.Text.Primary children = append(children, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). MarginBottom(1), }, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).Foreground(bashColor).WhiteSpace(style.WhiteSpaceNoWrap).Flex(0, 0), }, trail.Text("! ")), trail.Span(trail.SpanProps{ Style: style.S().Foreground(primaryColor), }, trail.Text(pendingCmd)), )) } activeText := activeTodoText(todos) if streaming && !waitingPerm { var spinnerText string if delegated { spinnerText = delegatedSpinnerText(runningSubs, activeText) } spinnerBlock := []trail.Node{ Spinner(SpinnerProps{Text: spinnerText, Status: status, ActiveText: activeText, StartedAt: turn.StartedAt, Input: turn.input(totals), Output: turn.output(totals)}), } if hasIncomplete { for i, item := range todos { prefix := " " if i == 0 { prefix = " ⎿ " } spinnerBlock = append(spinnerBlock, renderChecklistRow(item, prefix, scheme)) } } children = append(children, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). MarginBottom(1), }, spinnerBlock...)) } else if hasIncomplete { var done, inProgress, pending int for _, item := range todos { switch item.Status { case "completed": done++ case "in_progress": inProgress++ case "pending": pending++ } } headerText := fmt.Sprintf("%d todos (%d done, %d in progress, %d pending)", len(todos), done, inProgress, pending) headerNode := trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(headerText))) checklistBlock := []trail.Node{headerNode} for i, item := range todos { prefix := " " if i == 0 { prefix = " ⎿ " } checklistBlock = append(checklistBlock, renderChecklistRow(item, prefix, scheme)) } children = append(children, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). MarginBottom(1), }, checklistBlock...)) } return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)). MinWidth(style.Cells(0)), }, children...) })
ActiveStream renders the in-flight conversation messages, animated spinner, and pinned task checklist for the current active LLM turn.
var AssistantMessage = trail.FC("AssistantMessage", func(props MessageProps) trail.Node {
return messageBody(props.Message)
})
var BashCommand = trail.FC("BashCommand", func(record api.CommandRecord) trail.Node { scheme := theme.UseTheme() bashColor := scheme.Color.Mode.Bash primaryColor := scheme.Color.Text.Primary secondaryColor := scheme.Color.Text.Secondary errorColor := scheme.Color.Text.Error headerChildren := []trail.Node{ trail.Span(trail.SpanProps{ Style: style.S().Bold(true).Foreground(bashColor).WhiteSpace(style.WhiteSpaceNoWrap).Flex(0, 0), }, trail.Text("! ")), trail.Span(trail.SpanProps{ Style: style.S().WhiteSpace(style.WhiteSpacePreWrap).OverflowWrap(style.OverflowWrapAnywhere), }, components.HighlightShellSpans(record.Command, scheme, primaryColor)...), } if record.ExitCode != 0 { headerChildren = append(headerChildren, trail.Span(trail.SpanProps{ Style: style.S().Foreground(errorColor).WhiteSpace(style.WhiteSpacePre), }, trail.Text(fmt.Sprintf(" (exit %d)", record.ExitCode)))) } row1 := trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow).Width(style.Percent(100)), }, headerChildren...) outText := record.Output if strings.TrimSpace(outText) == "" { outText = "(no output)" } row2 := trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow).Width(style.Percent(100)), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(secondaryColor).WhiteSpace(style.WhiteSpacePre).Flex(0, 0), }, trail.Text(" ⎿ ")), trail.Span(trail.SpanProps{ Style: style.S().Foreground(secondaryColor).WhiteSpace(style.WhiteSpacePreWrap).OverflowWrap(style.OverflowWrapAnywhere).Flex(1, 1).MinWidth(style.Cells(0)), }, trail.Text(outText)), ) return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Cells(0)). MarginBottom(1), }, row1, row2) })
BashCommand renders a completed direct user shell command (!) from the timeline.
var BashToolWidget = trail.FC("BashToolWidget", func(props BashToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.BashInput](tool.Call) output := parseToolOutput[api.BashOutput](tool.Response) failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) || output.ExitCode != 0 || output.Status == "failed" status := tool.Status if output.TaskID != "" && (output.Status == "running" || tool.Status == store.ToolRunning) { status = store.ToolRunning } else if failed { status = store.ToolFailed } verb := "Running" if status == store.ToolSucceeded || status == store.ToolFailed { verb = "Ran" } desc := strings.TrimSpace(strings.ReplaceAll(input.Description, "\n", " ")) hasTarget := desc != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { descSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(desc)) headerNodes = append(headerNodes, descSpan) } if output.TaskID != "" && (output.Status == "running" || tool.Status == store.ToolRunning) { if suffixNode := renderSuffixSpan(fmt.Sprintf(" (background: %s)", output.TaskID), scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } } else if tool.Response != nil { durStr := "" if output.DurationMs > 0 { durStr = formatDuration(output.DurationMs) } if output.ExitCode != 0 { secStyle := style.S().Flex(0, 0).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) errStyle := style.S().Flex(0, 0).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Error) headerNodes = append(headerNodes, trail.Span(trail.SpanProps{Style: secStyle}, trail.Text(" (")), trail.Span(trail.SpanProps{Style: errStyle}, trail.Text(fmt.Sprintf("exit %d", output.ExitCode))), ) if durStr != "" { headerNodes = append(headerNodes, trail.Span(trail.SpanProps{Style: secStyle}, trail.Text(", "+durStr)), ) } headerNodes = append(headerNodes, trail.Span(trail.SpanProps{Style: secStyle}, trail.Text(")")), ) } else if durStr != "" { if suffixNode := renderSuffixSpan(" ("+durStr+")", scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } } } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } cmd := strings.TrimSpace(strings.ReplaceAll(input.Command, "\n", " ")) var cmdSubline *toolSubline if cmd != "" { line2Nodes := []trail.Node{ trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, icon.FontAwesomeTerminal, trail.Text(" ")), trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, components.HighlightShellSpans(cmd, scheme, scheme.Color.Text.Secondary)...), } if input.Dir != "" && input.Dir != "." { line2Nodes = append(line2Nodes, trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, trail.Text(" (in "+input.Dir+")"))) } cmdSubline = &toolSubline{ prefixColor: scheme.Color.Text.Secondary, nodes: line2Nodes, } } return wrapToolWidget(tool, scheme, headerNodes, cmdSubline) })
var CommandOutput = trail.FC("CommandOutput", func(props store.CommandData) trail.Node { scheme := theme.UseTheme() promptStyle := style.S().FlexDirection(style.FlexRow).Foreground(scheme.Color.Text.Primary) outStyle := style.S().FlexDirection(style.FlexRow).Foreground(scheme.Color.Text.Secondary) return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, trail.Box(trail.BoxProps{Style: promptStyle}, trail.Span(trail.SpanProps{Style: style.S().Bold(true)}, trail.Text("> ")), trail.Span(trail.SpanProps{}, trail.Text(props.Command)), ), trail.Box(trail.BoxProps{Style: outStyle}, trail.Span(trail.SpanProps{Style: style.S().WhiteSpace(style.WhiteSpacePre)}, trail.Text(" ⎿ ")), trail.Span(trail.SpanProps{}, trail.Text(props.Output)), ), ) })
CommandOutput is a trail functional component rendering a slash command execution and output.
var Composer = trail.FC("Composer", func(props ComposerProps) trail.Node { hide := store.UseHideComposer() ctrlCPending := store.UseApp(func(s store.AppState) bool { return s.CtrlCPending }) scheme := theme.UseTheme() winSize := trail.UseWindowSize() draft, setDraft := kitex.UseState(DraftEdit{}) attachments, setAttachments := kitex.UseState([]api.Attachment(nil)) bashMode, setBashMode := kitex.UseState(false) history := usePromptHistory() nextImageNum := kitex.UseRef(1) attachmentsRef := kitex.UseRef[[]api.Attachment](nil) attachmentsRef.Current = attachments() disabled := props.Disabled || hide browsing := history.Browsing() auto := uicomponents.UseAutocomplete(uicomponents.AutocompleteOptions{ Engine: props.Autocomplete, Value: draft().Value, Cursor: draft().Cursor, Disabled: disabled || bashMode() || browsing, }) inputRef := kitex.UseRef[dom.Element](nil) trail.UseFocus(inputRef, trail.FocusOptions{ AutoFocus: true, IsActive: !disabled, }) kitex.UseEffect(func() { if inputRef.Current != nil { if !disabled { inputRef.Current.Focus() } else { inputRef.Current.Blur() } } }, []any{disabled}) recordCandidate := func(idx int) []api.Attachment { currentAtts := attachments() if idx < 0 || idx >= len(auto.Result.Candidates) { return currentAtts } newAtt, ok := candidateAttachment(auto.Result.Candidates[idx]) if !ok { return currentAtts } next := slices.Clone(currentAtts) if attIdx := slices.IndexFunc(next, func(a api.Attachment) bool { return a.Ref == newAtt.Ref }); attIdx >= 0 { next[attIdx] = newAtt } else { next = append(next, newAtt) } setAttachments(next) return next } readDraft := func() DraftEdit { if input, ok := inputRef.Current.(*element.TextAreaElement); ok { return DraftEdit{Value: input.TextContent(), Cursor: input.Buffer().ByteOffset()} } return draft() } navValue := kitex.UseRef("") syncDraft := func() { next := readDraft() if history.Browsing() && next.Value != navValue.Current { history.Exit(HistoryEntry{Text: next.Value, Attachments: slices.Clone(attachments())}) } if next != draft() { setDraft(next) } } replaceDraft := func(next DraftEdit) { if input, ok := inputRef.Current.(*element.TextAreaElement); ok { input.SetValue(next.Value) input.SetSelectionRange(next.Cursor, next.Cursor) } navValue.Current = next.Value setDraft(next) } recall := func(entry HistoryEntry) { setAttachments(slices.Clone(entry.Attachments)) value := entry.Text if strings.HasPrefix(value, "!") { if !bashMode() { setBashMode(true) } stripped := strings.TrimPrefix(value, "!") replaceDraft(DraftEdit{Value: stripped, Cursor: len(stripped)}) return } if bashMode() { setBashMode(false) } replaceDraft(DraftEdit{Value: value, Cursor: len(value)}) } kitex.UseLayoutEffect(func() { if ctrlCPending { replaceDraft(DraftEdit{}) setAttachments(nil) if bashMode() { setBashMode(false) store.SetHint(store.DefaultHint) } if history.Browsing() { history.Exit(HistoryEntry{}) } } }, []any{ctrlCPending}) wasBrowsing := kitex.UseRef(false) kitex.UseEffect(func() { prev := wasBrowsing.Current wasBrowsing.Current = browsing switch { case bashMode(): store.SetHint(BashModeHint) case browsing: store.SetHint(HistoryModeHint) case prev: store.SetHint(store.DefaultHint) } }, []any{browsing, bashMode()}) handleKeyDown := func(e event.Event) { ke, ok := e.(*event.KeyEvent) if !ok || disabled { return } kitex.PostMacro(syncDraft) current := readDraft() isCurrent := current.Value == auto.Result.Input && current.Cursor == auto.Result.Cursor if !bashMode() && current.Value == "" && (ke.Text == "!" || ke.MatchString("!")) { e.PreventDefault() e.StopPropagation() setBashMode(true) store.SetHint(BashModeHint) return } switch { case ke.MatchString("ctrl+y"): waiting := store.GetWaitingSubagents() if len(waiting) > 0 && len(waiting[0].PendingPermissions) > 0 { e.PreventDefault() e.StopPropagation() store.DecideSubagentPermission(waiting[0].ID, waiting[0].PendingPermissions[0], api.PermissionDecision{Kind: api.DecisionAllowOnce}) return } case ke.MatchString("ctrl+g"): waiting := store.GetWaitingSubagents() if len(waiting) > 0 { e.PreventDefault() e.StopPropagation() store.OpenSubagent(waiting[0].ID) return } case ke.MatchString("shift+tab"): e.PreventDefault() e.StopPropagation() if props.OnCycleMode != nil { props.OnCycleMode() } else { store.CycleMode() } case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() if bashMode() { setBashMode(false) store.SetHint(store.DefaultHint) return } if browsing { recall(history.Cancel()) return } if auto.Dismiss() { return } if props.OnCancel != nil { props.OnCancel() } case ke.MatchString("backspace"): if bashMode() && current.Value == "" { e.PreventDefault() e.StopPropagation() setBashMode(false) store.SetHint(store.DefaultHint) return } case ke.MatchString("tab"): if isCurrent && auto.IsOpen { e.PreventDefault() e.StopPropagation() if !auto.IsLoading && auto.Error == nil && len(auto.Result.Candidates) > 0 { candIdx := auto.Selected if edit, err := auto.Accept(); err == nil { recordCandidate(candIdx) replaceDraft(edit) } } } case ke.MatchString("up", "ctrl+p"): if !browsing && isCurrent && auto.Up() { e.PreventDefault() e.StopPropagation() return } if txa, ok := inputRef.Current.(*element.TextAreaElement); ok { if txa.CursorState().Y > 0 { return } } e.PreventDefault() e.StopPropagation() valToPass := current.Value if bashMode() && current.Value != "" { valToPass = "!" + current.Value } entryToPass := HistoryEntry{ Text: valToPass, Attachments: slices.Clone(attachments()), } if prevEntry, ok := history.Up(entryToPass); ok { recall(prevEntry) } case ke.MatchString("down", "ctrl+n"): if !browsing && isCurrent && auto.Down() { e.PreventDefault() e.StopPropagation() return } if txa, ok := inputRef.Current.(*element.TextAreaElement); ok { lineCount := strings.Count(txa.TextContent(), "\n") + 1 if txa.CursorState().Y < lineCount-1 { return } } e.PreventDefault() e.StopPropagation() if nextEntry, ok := history.Down(); ok { recall(nextEntry) } case ke.MatchString("shift+enter", "alt+enter"): e.PreventDefault() e.StopPropagation() start, end := current.Cursor, current.Cursor if input, ok := inputRef.Current.(*element.TextAreaElement); ok && input.SelectedText() != "" { start, end = input.SelectionRange() } replaceDraft(DraftEdit{ Value: current.Value[:start] + "\n" + current.Value[end:], Cursor: start + 1, }) case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() if bashMode() { text := strings.TrimSpace(current.Value) replaceDraft(DraftEdit{}) setAttachments(nil) setBashMode(false) store.SetHint(store.DefaultHint) if text != "" { history.Add(HistoryEntry{Text: "!" + text}) if props.OnSubmit != nil { props.OnSubmit("!"+text, nil) } } return } activeAtts := attachments() if isCurrent && auto.IsOpen && !auto.IsLoading && auto.Error == nil && len(auto.Result.Candidates) > 0 { if !selectionMatchesQuery(auto) { candIdx := auto.Selected if edit, err := auto.Accept(); err == nil { recordCandidate(candIdx) replaceDraft(edit) } return } activeAtts = recordCandidate(auto.Selected) } text := strings.TrimSpace(current.Value) reconciled := mentions.Resolve(text, activeAtts, nil) replaceDraft(DraftEdit{}) setAttachments(nil) if text != "" { history.Add(HistoryEntry{Text: text, Attachments: reconciled}) if props.OnSubmit != nil { props.OnSubmit(text, reconciled) } } } } handlePaste := func(e event.Event) { ce, ok := e.(*event.ClipboardEvent) if !ok || disabled || bashMode() || len(ce.Items) == 0 { return } candidates := clipboard.ResolvePastedImages(ce.Items, ce.Text()) if len(candidates) == 0 { return } e.PreventDefault() e.StopPropagation() var valid []clipboard.ImageCandidate for _, cand := range candidates { if cand.TooLarge > 0 { store.AppendNotice(fmt.Sprintf("Clipboard image (%s) exceeds the %s limit.", format.Bytes(cand.TooLarge), format.Bytes(clipboard.MaxImageBytes))) continue } valid = append(valid, cand) } if len(valid) == 0 { return } if modelID, supported := store.ActiveModelSupports("image"); !supported { store.AppendNotice(fmt.Sprintf("Model %s does not support image input; clipboard image was not attached.", modelID)) return } nextAtts := slices.Clone(attachmentsRef.Current) var refs strings.Builder for _, cand := range valid { imgIdx := nextImageNum.Current nextImageNum.Current++ ref := fmt.Sprintf("[Image #%d]", imgIdx) displayName := cand.DisplayName if displayName == "" { displayName = fmt.Sprintf("image-%d%s", imgIdx, clipboard.ExtForImageMIME(cand.MIMEType)) } nextAtts = append(nextAtts, store.StageClipboardMedia(ref, cand.Data, cand.MIMEType, displayName)) refs.WriteString(ref) refs.WriteByte(' ') } attachmentsRef.Current = nextAtts setAttachments(nextAtts) live := readDraft() start, end := live.Cursor, live.Cursor if input, ok := inputRef.Current.(*element.TextAreaElement); ok && input.SelectedText() != "" { start, end = input.SelectionRange() } insert := refs.String() replaceDraft(DraftEdit{ Value: live.Value[:start] + insert + live.Value[end:], Cursor: start + len(insert), }) } keyHandler := kitex.UseRef[event.Listener](nil) keyHandler.Current = handleKeyDown pasteHandler := kitex.UseRef[event.Listener](nil) pasteHandler.Current = handlePaste kitex.UseEffectCleanup(func() func() { if input := inputRef.Current; input != nil { selection := input.AddEventListener(event.EventSelectionChange, func(event.Event) { syncDraft() }) keys := input.AddEventListener(event.EventKeyDown, func(e event.Event) { keyHandler.Current(e) }, event.Capture()) paste := input.AddEventListener(event.EventPaste, func(e event.Event) { pasteHandler.Current(e) }, event.Capture()) mouse := input.AddEventListener(event.EventMouseDown, func(event.Event) { kitex.PostMacro(syncDraft) }) drag := input.AddEventListener(event.EventDrag, func(event.Event) { kitex.PostMacro(syncDraft) }) return func() { selection.Cancel() keys.Cancel() paste.Cancel() mouse.Cancel() drag.Cancel() } } return nil }, []any{}) borderCol := scheme.Color.Border.Focus if disabled { borderCol = scheme.Color.Border.Default } border := style.SingleBorder().Top(true).Bottom(!browsing).Left(false).Right(false).Color(borderCol) composerStyle := style.S(). Border(border). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignStart). Width(style.Percent(100)) promptStyle := style.S().Bold(true).Margin(0, 1, 0, 0) promptIndicator := ">" if bashMode() { promptIndicator = "!" promptStyle = promptStyle.Foreground(scheme.Color.Mode.Bash) } else { promptStyle = promptStyle.Foreground(scheme.Color.Icon.Primary) } outerStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)) if hide { outerStyle = outerStyle.Display(style.DisplayNone) } var stagedMediaPills []api.Attachment draftVal := draft().Value for _, att := range attachments() { if att.Kind == api.AttachmentMedia && att.Ref != "" && strings.Contains(draftVal, att.Ref) { stagedMediaPills = append(stagedMediaPills, att) } } return trail.Box(trail.BoxProps{ Style: outerStyle, }, trail.Box(trail.BoxProps{ Style: composerStyle, }, trail.Span(trail.SpanProps{ Style: promptStyle, }, trail.Text(promptIndicator)), kitex.TextArea(kitex.TextAreaProps{ Ref: inputRef, Value: draft().Value, Disabled: disabled, Style: style.S(). Flex(1). Width(style.Percent(100)). Height(style.Content). MinHeight(style.Cells(1)). Scrollbar(style.Scrollbar{Y: style.Some(false)}), OnChange: func(event.Event) { syncDraft() }, }), ), kitex.If(len(stagedMediaPills) > 0, func() trail.Node { var pillNodes []trail.Node for _, att := range stagedMediaPills { label := strings.Trim(att.Ref, "[]") if att.Media != nil && att.Media.ByteSize > 0 { label = fmt.Sprintf("%s · %s", label, format.Bytes(att.Media.ByteSize)) } name := "image.png" if att.Media != nil && att.Media.DisplayName != "" { name = att.Media.DisplayName } pillNodes = append(pillNodes, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignCenter). Background(scheme.Color.Surface.Elevated). PaddingHorizontal(1). Gap(1), }, icon.FileIcon(icon.FileIconProps{Path: name}), trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Primary).Bold(true), }, trail.Text(label)), )) } return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). FlexWrap(style.FlexWrapOn). Gap(1). MarginTop(0), }, pillNodes...) }), kitex.If(browsing, func() trail.Node { label := fmt.Sprintf(" history (%d/%d) ", history.HistoryIdx+1, len(history.History)) width := winSize.Width if width <= 0 { width = 40 } side := max(1, (width-len(label))/2) rule := strings.Repeat("─", side) + label + strings.Repeat("─", side) return trail.Box(trail.BoxProps{ Style: style.S().Width(style.Percent(100)), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(borderCol).WhiteSpace(style.WhiteSpacePre), }, trail.Text(rule))) }), uicomponents.Autocomplete(uicomponents.AutocompleteProps{ State: auto, Views: props.CompletionViews, Bindings: composerAutocompleteBindings, }), ) })
Composer is a trail functional component managing multi-line user prompt drafting, autocomplete, prompt history navigation, and mode cycling.
var ContextUsage = trail.FC("ContextUsage", func(props store.ContextUsageData) trail.Node { scheme := theme.UseTheme() ctx := props.Context staticTokens := ctx.Breakdown.SystemPrompt + ctx.Breakdown.ContextFiles + ctx.Breakdown.SystemTools + ctx.Breakdown.CustomTools + ctx.Breakdown.MCPTools + ctx.Breakdown.Skills + ctx.Breakdown.Rules + ctx.Breakdown.Subagents convTokens := ctx.Breakdown.Summary + ctx.Breakdown.UserMessages + ctx.Breakdown.AgentResponses + ctx.Breakdown.ToolCalls reserveTokens := ctx.ReserveTokens freeTokens := ctx.FreeTokens const totalCells = 200 const gridCols = 20 const gridRows = 10 var staticCells, convCells, reserveCells, freeCells int if ctx.MaxTokens > 0 { staticCells = int(float64(staticTokens)/float64(ctx.MaxTokens)*float64(totalCells) + 0.5) convCells = int(float64(convTokens)/float64(ctx.MaxTokens)*float64(totalCells) + 0.5) reserveCells = int(float64(reserveTokens)/float64(ctx.MaxTokens)*float64(totalCells) + 0.5) if staticTokens > 0 && staticCells == 0 { staticCells = 1 } if convTokens > 0 && convCells == 0 { convCells = 1 } if reserveTokens > 0 && reserveCells == 0 { reserveCells = 1 } if staticCells > totalCells { staticCells = totalCells } if staticCells+convCells > totalCells { convCells = totalCells - staticCells } if staticCells+convCells+reserveCells > totalCells { reserveCells = totalCells - staticCells - convCells } freeCells = max(totalCells-staticCells-convCells-reserveCells, 0) } type cellInfo struct { glyph string col color.Color } cells := make([]cellInfo, totalCells) for i := range totalCells { if i < staticCells { cells[i] = cellInfo{glyph: "⛁", col: scheme.Color.Agent.Thinking} } else if i < staticCells+convCells { cells[i] = cellInfo{glyph: "◉", col: scheme.Color.Agent.Generating} } else if i < staticCells+convCells+freeCells { cells[i] = cellInfo{glyph: "⛶", col: scheme.Color.Text.Secondary} } else { cells[i] = cellInfo{glyph: "⛝", col: scheme.Color.Text.Warning} } } gridRowNodes := make([]trail.Node, gridRows) for r := range gridRows { start := r * gridCols end := start + gridCols var spans []trail.Node var currentRun strings.Builder var currentColor color.Color for i := start; i < end; i++ { c := cells[i] if currentColor == nil { currentColor = c.col } if c.col != currentColor { spans = append(spans, trail.Span(trail.SpanProps{ Style: style.S().Foreground(currentColor).WhiteSpace(style.WhiteSpacePre), }, trail.Text(currentRun.String()))) currentRun.Reset() currentColor = c.col } if i > start { currentRun.WriteString(" ") } currentRun.WriteString(c.glyph) } if currentRun.Len() > 0 { spans = append(spans, trail.Span(trail.SpanProps{ Style: style.S().Foreground(currentColor).WhiteSpace(style.WhiteSpacePre), }, trail.Text(currentRun.String()))) } gridRowNodes[r] = trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow), }, spans...) } gridBox := trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). MarginRight(3), }, gridRowNodes...) modelName := cmp.Or(strings.TrimSpace(props.ModelName), "default") totalPct := 0.0 if ctx.MaxTokens > 0 { totalPct = float64(ctx.UsedTokens) / float64(ctx.MaxTokens) * 100.0 } modelHeader := fmt.Sprintf("%s · %s/%s (%.1f%%)", modelName, format.Tokens(ctx.UsedTokens), format.Tokens(ctx.MaxTokens), totalPct) categoryHeader := "Token usage by category" if ctx.InputTokens == 0 { categoryHeader = "Estimated usage by category (awaiting generation)" } items := []categoryItem{ {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "System prompt", ctx.Breakdown.SystemPrompt}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "Context files", ctx.Breakdown.ContextFiles}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "System tools", ctx.Breakdown.SystemTools}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "Custom tools", ctx.Breakdown.CustomTools}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "MCP tools", ctx.Breakdown.MCPTools}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "Skills", ctx.Breakdown.Skills}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "Rules", ctx.Breakdown.Rules}, {"⛁", func(s *theme.Scheme) color.Color { return s.Color.Agent.Thinking }, "Subagents", ctx.Breakdown.Subagents}, {"◉", func(s *theme.Scheme) color.Color { return s.Color.Agent.Generating }, "Compacted summary", ctx.Breakdown.Summary}, {"◉", func(s *theme.Scheme) color.Color { return s.Color.Agent.Generating }, "User messages", ctx.Breakdown.UserMessages}, {"◉", func(s *theme.Scheme) color.Color { return s.Color.Agent.Generating }, "Agent responses", ctx.Breakdown.AgentResponses}, {"◉", func(s *theme.Scheme) color.Color { return s.Color.Agent.Generating }, "Tool calls", ctx.Breakdown.ToolCalls}, {"⛶", func(s *theme.Scheme) color.Color { return s.Color.Text.Secondary }, "Free space", freeTokens}, {"⛝", func(s *theme.Scheme) color.Color { return s.Color.Text.Warning }, "Autocompact buffer", reserveTokens}, } infoNodes := make([]trail.Node, 0, len(items)+2) infoNodes = append(infoNodes, trail.Box(trail.BoxProps{Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).Foreground(scheme.Color.Text.Primary), }, trail.Text(modelHeader)), ), trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow).MarginTop(1), }, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).Foreground(scheme.Color.Text.Primary), }, trail.Text(categoryHeader)), ), ) for _, item := range items { if item.count <= 0 { continue } pct := 0.0 if ctx.MaxTokens > 0 { pct = float64(item.count) / float64(ctx.MaxTokens) * 100.0 } rowText := fmt.Sprintf("%s: %s tokens (%.1f%%)", item.label, format.Tokens(item.count), pct) infoNodes = append(infoNodes, trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(item.color(scheme)).WhiteSpace(style.WhiteSpacePre), }, trail.Text(item.glyph+" ")), trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(rowText)), )) } infoBox := trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn), }, infoNodes...) promptStyle := style.S().FlexDirection(style.FlexRow).Foreground(scheme.Color.Text.Primary) outStyle := style.S().FlexDirection(style.FlexRow).Foreground(scheme.Color.Text.Secondary) return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, trail.Box(trail.BoxProps{Style: promptStyle}, trail.Span(trail.SpanProps{Style: style.S().Bold(true)}, trail.Text("> ")), trail.Span(trail.SpanProps{}, trail.Text("/context")), ), trail.Box(trail.BoxProps{Style: outStyle}, trail.Span(trail.SpanProps{Style: style.S().WhiteSpace(style.WhiteSpacePre)}, trail.Text(" ⎿ ")), trail.Span(trail.SpanProps{Style: style.S().Bold(true)}, trail.Text("Context Usage")), ), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). MarginLeft(5), }, gridBox, infoBox), ) })
ContextUsage is a trail functional component rendering a visual token usage grid and category breakdown table for /context.
var DaemonAlert = trail.SimpleFC("DaemonAlert", func() trail.Node { if store.UseHasActiveSlot() { return nil } status := store.UseDaemonStatus() if status == "" || status == store.DaemonConnected { return nil } scheme := theme.UseTheme() var borderColor color.Color var line1Text string var line1Color color.Color var line2Text string switch status { case store.DaemonDisconnected: borderColor = scheme.Color.Border.Error line1Text = "⚠ Brain Daemon is offline" line1Color = scheme.Color.Text.Error line2Text = "Waiting to reconnect automatically, or run /daemon restart" case store.DaemonRestarting: borderColor = scheme.Color.Border.Warning line1Text = "↻ Restarting Brain Daemon..." line1Color = scheme.Color.Text.Warning line2Text = "Spawning background process and syncing session state" default: return nil } border := style.SingleBorder().Top(false).Bottom(false).Right(false).Left(true).Color(borderColor) containerStyle := style.S(). Border(border). PaddingLeft(1). MarginBottom(1). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)) headerStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). WhiteSpace(style.WhiteSpaceNoWrap) return trail.Box(trail.BoxProps{ Style: containerStyle, }, trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(line1Color), }, trail.Text(line1Text)), ), trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(line2Text)), ), ) })
DaemonAlert renders a non-blocking alert banner above the composer when the background Brain Daemon is disconnected or restarting.
var DefaultPickerBindings = []components.KeyBinding{
{Key: "↑/↓", Label: "Navigate"},
{Key: "enter", Label: "Confirm"},
{Key: "esc", Label: "Cancel"},
}
DefaultPickerBindings defines the default keyboard shortcuts displayed on the picker.
var DefaultStatusLine = trail.SimpleFC("DefaultStatusLine", func() trail.Node { scheme := theme.UseTheme() width := trail.UseWindowSize().Width cfg := store.UseStatusLine() ctrlCPending := store.UseApp(func(s store.AppState) bool { return s.CtrlCPending }) hint := store.UseApp(func(s store.AppState) string { return s.Hint }) hasSlot := store.UseHasActiveSlot() mode := store.UseMode() ctx := store.UseContext() usage := store.UseUsageTotals() quota := store.UseQuota() billed := store.UseSession(func(s store.SessionState) bool { return s.ModelQuotaBilled }) quotaNow := useQuotaClock() ready := store.UseSession(func(s store.SessionState) bool { return s.Ready }) model := store.UseSession(store.SessionState.ModelLabels) effort := store.UseSession(func(s store.SessionState) string { return s.Thinking }) warningCount := len(store.UseWarnings()) switch { case ctrlCPending: hint = store.CtrlCHint case hasSlot: hint = "" } secondary := scheme.Color.Text.Secondary fields := map[store.StatusLineSegmentID]statusField{ store.StatusLineHint: {full: hint, color: secondary}, store.StatusLineCost: statusCost(usage, quota, billed, quotaNow, scheme), store.StatusLineWarnings: statusWarningCount(warningCount, scheme), } if mode != "" { text := "[" + strings.ReplaceAll(string(mode), "_", " ") + "]" short := text if mode == api.ModeAcceptEdits { short = "[edits]" } fields[store.StatusLineMode] = statusField{full: text, compact: short, color: modeColor(scheme, mode), bold: true} } if ready { fields[store.StatusLineContext] = statusContext(ctx, scheme) fields[store.StatusLineModel] = statusField{full: model.Full, compact: model.Compact, color: secondary} effort = strings.Join(strings.Fields(effort), " ") if effort == "" || effort == store.ThinkingProviderDefault { effort = "default effort" } fields[store.StatusLineEffort] = statusField{full: effort, color: secondary} } if usage.Calls > 0 { text := fmt.Sprintf("↑%s ↓%s", format.Tokens(int(usage.InputTokens)), format.Tokens(int(usage.OutputTokens))) fields[store.StatusLineTokens] = statusField{full: "Tokens " + text, compact: text, color: secondary} } rows := make([]trail.Node, 0, len(cfg.Rows)) for i, row := range cfg.Rows { if node := renderStatusRow(width, i, cfg.Compact, row, fields, !hasSlot); node != nil { rows = append(rows, node) } } if len(rows) == 0 { return nil } return trail.Box(trail.BoxProps{Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexColumn).Width(style.Percent(100))}, rows...) })
var DiffView = trail.FC("DiffView", func(props DiffProps) trail.Node { diffText := strings.TrimSpace(props.Text) if diffText == "" { return nil } rows, extractedPath := parseUnifiedDiff(props.Text) if len(rows) == 0 { return nil } targetPath := props.Path if targetPath == "" { targetPath = extractedPath } var lexer chroma.Lexer if props.Lang != "" { lexer = lexers.Get(props.Lang) } if lexer == nil && targetPath != "" { lexer = lexers.Match(targetPath) } if lexer == nil { lexer = lexers.Fallback } lexer = chroma.Coalesce(lexer) scheme := theme.UseTheme() redBg := scheme.Color.Diff.RemovedBg greenBg := scheme.Color.Diff.AddedBg cyanBg := scheme.Color.Diff.HunkBg var gutterSpans []trail.Node var sepSpans []trail.Node var codeSpans []trail.Node for _, row := range rows { var bg color.Color if row.IsHeader { bg = cyanBg } else if row.Op == diff.OpDelete { bg = redBg } else if row.Op == diff.OpInsert { bg = greenBg } var gutterText string if row.IsHeader { gutterText = fmt.Sprintf("%12s\n", "") } else { numAStr := "" if row.NumA > 0 { numAStr = strconv.Itoa(row.NumA) } numBStr := "" if row.NumB > 0 { numBStr = strconv.Itoa(row.NumB) } sign := " " switch row.Op { case diff.OpDelete: sign = "-" case diff.OpInsert: sign = "+" } gutterText = fmt.Sprintf("%5s%5s %s\n", numAStr, numBStr, sign) } gutterStyle := style.S(). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Muted) if bg != nil { gutterStyle = gutterStyle.Background(bg) } gutterSpans = append(gutterSpans, trail.Span(trail.SpanProps{ Style: gutterStyle, }, trail.Text(gutterText))) sepStyle := style.S(). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Border.Default) if bg != nil { sepStyle = sepStyle.Background(bg) } sepSpans = append(sepSpans, trail.Span(trail.SpanProps{ Style: sepStyle, }, trail.Text("│\n"))) if row.IsHeader { headerStyle := style.S(). Bold(true). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Diff.HunkText) if bg != nil { headerStyle = headerStyle.Background(bg) } codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: headerStyle, }, trail.Text(row.HeaderText))) if bg != nil { if paddingLength := 500 - len(row.HeaderText); paddingLength > 0 { codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: style.S(). Background(bg). WhiteSpace(style.WhiteSpacePre), }, trail.Text(strings.Repeat(" ", paddingLength)), )) } } nlStyle := style.S().WhiteSpace(style.WhiteSpacePre) if bg != nil { nlStyle = nlStyle.Background(bg) } codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: nlStyle, }, trail.Text("\n"))) } else { codeLine := strings.ReplaceAll(row.Text, "\t", " ") iterator, err := lexer.Tokenise(nil, codeLine) if err != nil { fallbackStyle := style.S(). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary) if bg != nil { fallbackStyle = fallbackStyle.Background(bg) } codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: fallbackStyle, }, trail.Text(codeLine))) } else { for tok := iterator(); tok != chroma.EOF; tok = iterator() { tokStyle := uicomponents.ResolveTokenStyle(scheme, tok.Type) if bg != nil { tokStyle = tokStyle.Background(bg) } codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: tokStyle, }, trail.Text(tok.Value))) } } if bg != nil { if paddingLength := 500 - len(codeLine); paddingLength > 0 { codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: style.S(). Background(bg). WhiteSpace(style.WhiteSpacePre), }, trail.Text(strings.Repeat(" ", paddingLength)), )) } } nlStyle := style.S().WhiteSpace(style.WhiteSpacePre) if bg != nil { nlStyle = nlStyle.Background(bg) } codeSpans = append(codeSpans, trail.Span(trail.SpanProps{ Style: nlStyle, }, trail.Text("\n"))) } } gutterBox := trail.Box(trail.BoxProps{ Style: style.S(). Width(style.Cells(12)). MinWidth(style.Cells(12)). MaxWidth(style.Cells(12)). Flex(0, 0), }, gutterSpans...) sepBox := trail.Box(trail.BoxProps{ Style: style.S(). Width(style.Cells(1)). MinWidth(style.Cells(1)). MaxWidth(style.Cells(1)). Flex(0, 0), }, sepSpans...) codeBox := trail.Box(trail.BoxProps{ Style: style.S(). Flex(1, 1). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden), }, codeSpans...) return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). MinWidth(style.Cells(0)). Merge(props.Style), }, gutterBox, sepBox, codeBox) })
DiffView is a trail functional component rendering unified diff lines with syntax highlighting and theme-aware colors in a 3-column layout (gutter, separator, code).
var DownloadToolWidget = trail.FC("DownloadToolWidget", func(props DownloadToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.DownloadInput](tool.Call) output := parseToolOutput[api.DownloadOutput](tool.Response) path := input.Path if output.Path != "" { path = output.Path } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) || output.StatusCode >= 400 verb := "Downloading" if tool.Status == store.ToolSucceeded || failed { verb = "Downloaded" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := path != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { headerNodes = append(headerNodes, renderPathNodes(path, false, scheme)...) } var suffix string if tool.Response != nil && !tool.Response.IsError && output.BytesWritten > 0 { suffix = fmt.Sprintf(" (%s)", formatBytes(int64(output.BytesWritten))) } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var EditToolWidget = trail.FC("EditToolWidget", func(props EditToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.EditInput](tool.Call) output := parseToolOutput[api.EditOutput](tool.Response) path := input.Path if output.Path != "" { path = output.Path } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Editing" if tool.Status == store.ToolSucceeded || failed { verb = "Edited" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := path != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { headerNodes = append(headerNodes, renderPathNodes(path, false, scheme)...) } if tool.Response != nil && !tool.Response.IsError { headerNodes = append(headerNodes, renderDiffStatNodes(output.Additions, output.Deletions, output.Replacements, scheme)...) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var ErrorBanner = trail.FC("ErrorBanner", func(props store.ErrorData) trail.Node { scheme := theme.UseTheme() title := props.Title if title == "" { title = "error" } badgeStyle := style.S().Bold(true).Foreground(scheme.Color.Text.Error) msgStyle := style.S().Foreground(scheme.Color.Text.Error) return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow).MarginBottom(1), }, trail.Span(trail.SpanProps{Style: badgeStyle}, trail.Text(title+": ")), trail.Span(trail.SpanProps{Style: msgStyle}, trail.Text(props.Message)), ) })
ErrorBanner is a trail functional component rendering a styled error notification.
var GlobToolWidget = trail.FC("GlobToolWidget", func(props GlobToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.GlobInput](tool.Call) output := parseToolOutput[api.GlobOutput](tool.Response) failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Matching" if tool.Status == store.ToolSucceeded || failed { verb = "Matched" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := input.Pattern != "" || (input.Path != "" && input.Path != ".") leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if input.Pattern != "" { patternSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(input.Pattern)) headerNodes = append(headerNodes, patternSpan) } if input.Path != "" && input.Path != "." { inSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, trail.Text(" in ")) headerNodes = append(headerNodes, inSpan) headerNodes = append(headerNodes, renderPathNodes(input.Path, true, scheme)...) } var suffix string if tool.Response != nil && !tool.Response.IsError { n := len(output.Matches) fileStr := fmt.Sprintf("%d files", n) if n == 1 { fileStr = "1 file" } if output.Truncated { fileStr += ", truncated" } suffix = " (" + fileStr + ")" } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var GrepToolWidget = trail.FC("GrepToolWidget", func(props GrepToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.GrepInput](tool.Call) output := parseToolOutput[api.GrepOutput](tool.Response) failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Searching" if tool.Status == store.ToolSucceeded || failed { verb = "Searched" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := input.Pattern != "" || input.Include != "" || (input.Path != "" && input.Path != ".") leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if input.Pattern != "" { quotedPattern := fmt.Sprintf("%q", input.Pattern) patternSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(quotedPattern)) headerNodes = append(headerNodes, patternSpan) } if input.Include != "" { includeSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, trail.Text(" ("+input.Include+")")) headerNodes = append(headerNodes, includeSpan) } if input.Path != "" && input.Path != "." { inSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, trail.Text(" in ")) headerNodes = append(headerNodes, inSpan) headerNodes = append(headerNodes, renderPathNodes(input.Path, true, scheme)...) } var suffix string if tool.Response != nil && !tool.Response.IsError { n := len(output.Matches) matchStr := fmt.Sprintf("%d matches", n) if n == 1 { matchStr = "1 match" } if output.Truncated { matchStr += ", truncated" } suffix = " (" + matchStr + ")" } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var Header = trail.FC("Header", func(props HeaderProps) trail.Node { scheme := theme.UseTheme() titleStyle := style.S().Bold(true).Foreground(scheme.Color.Agent.Brand) metaStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) dimStyle := style.S().Foreground(scheme.Color.Text.Secondary) version := NormalizeVersion(props.Version) model := cmp.Or(strings.TrimSpace(props.Model), "default") thinking := strings.TrimSpace(props.Thinking) if thinking == "" || thinking == store.ThinkingProviderDefault { thinking = "default" } modelThinking := fmt.Sprintf("%s with %s effort", model, thinking) if strings.HasPrefix(thinking, "budget ") || strings.HasPrefix(thinking, "thinking ") { modelThinking = fmt.Sprintf("%s · %s", model, thinking) } workspace := ShortenHomePath(props.Workspace) sandboxLabel, sandboxStyle := sandboxBannerSuffix(scheme, props.SandboxMode) line3 := []trail.Node{ trail.Span(trail.SpanProps{Style: dimStyle}, trail.Text(workspace)), } if props.Branch != "" { branch, _ := strutils.TruncateLine(props.Branch, 40, "…") line3 = append(line3, trail.Span(trail.SpanProps{Style: metaStyle}, trail.Text(" · "+branch))) } if sandboxLabel != "" { line3 = append(line3, trail.Span(trail.SpanProps{Style: sandboxStyle}, trail.Text(sandboxLabel))) } mascot := mascotMark(mascotReady) if props.AnimateMascot { mascot = animatedMascot(mascotIdleWait) } bannerContent := []trail.Node{ mascot, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn), }, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: titleStyle, }, trail.Text("TaskSmith")), trail.Span(trail.SpanProps{ Style: metaStyle, }, trail.Text(" "+version)), ), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: metaStyle, }, trail.Text(modelThinking)), ), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow), }, line3...), ), } if len(props.Warnings) == 0 { return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). MarginTop(1). MarginBottom(1), }, bannerContent...) } warningStyle := style.S(). Foreground(scheme.Color.Text.Warning). WhiteSpace(style.WhiteSpacePre) warningNodes := make([]trail.Node, 0, len(props.Warnings)) for _, w := range props.Warnings { warningNodes = append(warningNodes, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: warningStyle, }, icon.Warning, trail.Text(" "+w)), )) } return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). MarginTop(1). MarginBottom(1), }, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow), }, bannerContent...), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). MarginTop(1), }, warningNodes...), ) })
Header is a trail functional component rendering the startup banner: Left: 3-line terminal mascot Right: 3 session info lines: 1. TaskSmith <version> 2. <model> with <thinking> effort 3. <ShortenHomePath(workspace)> Below (optional): workspace warnings
var InvokeAgentToolWidget = trail.FC("InvokeAgentToolWidget", func(props InvokeAgentToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool status := tool.Status input := parseToolInput[api.InvokeAgentInput](tool.Call) output := parseToolOutput[api.InvokeAgentOutput](tool.Response) isFailed := status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) || output.Status == "failed" if isFailed { status = store.ToolFailed } isDone := status == store.ToolSucceeded || status == store.ToolFailed verb := "Spawning" if isDone { verb = "Spawned" } agentName := input.Agent if agentName == "" && output.Agent != "" { agentName = output.Agent } agentColor := SubagentColor(scheme, agentName) title := input.Title if title == "" && output.Title != "" { title = output.Title } leading := toolHeaderLeading(status, verb, true, scheme) headerNodes := append([]trail.Node{}, leading...) headerNodes = append(headerNodes, trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Bold(true). Foreground(agentColor), }, trail.Text("@"+agentName))) if badge := subagentModelBadge(scheme, output.ModelLabel, output.Model); badge != nil { headerNodes = append(headerNodes, badge) } if title != "" { headerNodes = append(headerNodes, trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(" "+title))) } var suffix string isWorktree := input.Workspace == "worktree" if output.SessionID != "" && isWorktree { suffix = fmt.Sprintf(" (%s, worktree)", output.SessionID) } else if output.SessionID != "" { suffix = fmt.Sprintf(" (%s)", output.SessionID) } else if isWorktree { suffix = " (worktree)" } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var LoadRuleToolWidget = trail.FC("LoadRuleToolWidget", func(props LoadRuleToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.LoadRuleInput](tool.Call) output := parseToolOutput[api.LoadRuleOutput](tool.Response) name := strings.TrimSpace(input.Rule) if tool.Response != nil && !tool.Response.IsError && strings.TrimSpace(output.Rule) != "" { name = strings.TrimSpace(output.Rule) } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) status := tool.Status verb := "Loading Rule" if failed { status = store.ToolFailed verb = "Failed to load Rule" } else if status == store.ToolSucceeded { verb = "Loaded Rule" } headerNodes := toolHeaderLeading(status, verb, name != "", scheme) if name != "" { headerNodes = append(headerNodes, trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). WhiteSpace(style.WhiteSpaceNoWrap). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Primary), }, trail.Text(name))) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil && !failed { headerNodes = append(headerNodes, stateSuffix) } var warnSubline *toolSubline if !failed && output.Truncated { warnSubline = &toolSubline{ prefixColor: scheme.Color.Text.Warning, nodes: []trail.Node{ trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). WhiteSpace(style.WhiteSpacePre). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Warning), }, trail.Text("⚠ Rule exceeds size limit (500 lines / 32 KB) and was truncated")), }, } } return wrapToolWidget(tool, scheme, headerNodes, warnSubline) })
var LoadSkillToolWidget = trail.FC("LoadSkillToolWidget", func(props LoadSkillToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.LoadSkillInput](tool.Call) output := parseToolOutput[api.LoadSkillOutput](tool.Response) name := strings.TrimSpace(input.Skill) if tool.Response != nil && !tool.Response.IsError && strings.TrimSpace(output.Skill) != "" { name = strings.TrimSpace(output.Skill) } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) status := tool.Status verb := "Loading Skill" if failed { status = store.ToolFailed verb = "Failed to load Skill" } else if status == store.ToolSucceeded { verb = "Loaded Skill" } headerNodes := toolHeaderLeading(status, verb, name != "", scheme) if name != "" { headerNodes = append(headerNodes, trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). WhiteSpace(style.WhiteSpaceNoWrap). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Primary), }, trail.Text(name))) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil && !failed { headerNodes = append(headerNodes, stateSuffix) } var warnSubline *toolSubline if !failed && output.Truncated { warnSubline = &toolSubline{ prefixColor: scheme.Color.Text.Warning, nodes: []trail.Node{ trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). WhiteSpace(style.WhiteSpacePre). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Warning), }, trail.Text("⚠ Skill exceeds size limit (500 lines / 32 KB) and was truncated")), }, } } return wrapToolWidget(tool, scheme, headerNodes, warnSubline) })
var LsToolWidget = trail.FC("LsToolWidget", func(props LsToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.LsInput](tool.Call) output := parseToolOutput[api.LsOutput](tool.Response) path := input.Path if output.Path != "" { path = output.Path } if strings.TrimSpace(path) == "" { path = "." } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Listing" if tool.Status == store.ToolSucceeded || failed { verb = "Listed" } status := tool.Status if failed { status = store.ToolFailed } leading := toolHeaderLeading(status, verb, true, scheme) headerNodes := append([]trail.Node{}, leading...) headerNodes = append(headerNodes, renderPathNodes(path, true, scheme)...) var suffix string if tool.Response != nil && !tool.Response.IsError { n := len(output.Entries) entryStr := fmt.Sprintf("%d entries", n) if n == 1 { entryStr = "1 entry" } parts := []string{entryStr} if input.Recursive { parts = append(parts, "recursive") } if output.Truncated { parts = append(parts, "truncated") } suffix = " (" + strings.Join(parts, ", ") + ")" } else if input.Recursive { suffix = " (recursive)" } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var ManageAgentsToolWidget = trail.FC("ManageAgentsToolWidget", func(props ManageAgentsToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool status := tool.Status input := parseToolInput[api.ManageAgentsInput](tool.Call) output := parseToolOutput[api.ManageAgentsOutput](tool.Response) if status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) { status = store.ToolFailed } isDone := status == store.ToolSucceeded || status == store.ToolFailed var verb string var target string var suffix string switch input.Action { case "list": verb = "Listing agents" if isDone { verb = "Listed agents" } if tool.Response != nil && !tool.Response.IsError { n := len(output.Agents) if n == 1 { suffix = " (1 agent)" } else { suffix = fmt.Sprintf(" (%d agents)", n) } } case "models": if q := strings.TrimSpace(input.Query); q != "" { verb = "Searching models" if isDone { verb = "Searched models" } target = fmt.Sprintf("%q", q) } else { verb = "Listing models" if isDone { verb = "Listed models" } } if tool.Response != nil && !tool.Response.IsError { n := len(output.Models) if n == 1 { suffix = " (1 model)" } else { suffix = fmt.Sprintf(" (%d models)", n) } } case "status": verb = "Checking agent" if isDone { verb = "Checked agent" } target = input.SessionID if tool.Response != nil && !tool.Response.IsError && output.Status != "" { suffix = fmt.Sprintf(" (%s)", output.Status) } case "send": verb = "Messaging agent" if isDone { verb = "Messaged agent" } target = input.SessionID if tool.Response != nil && !tool.Response.IsError && output.Status != "" { suffix = fmt.Sprintf(" (%s)", output.Status) } case "kill": verb = "Killing agent" if isDone { verb = "Killed agent" } target = input.SessionID if tool.Response != nil && !tool.Response.IsError && output.Status != "" { suffix = fmt.Sprintf(" (%s)", output.Status) } default: verb = "Managing agents" if isDone { verb = "Managed agents" } target = input.SessionID } hasTarget := target != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { targetSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(target)) headerNodes = append(headerNodes, targetSpan) } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var Message = trail.FC("Message", func(props MessageProps) trail.Node { switch props.Message.Role { case api.RoleUser: return UserMessage(props) case api.RoleAssistant: return AssistantMessage(props) case api.RoleSystem: return SystemMessage(props) case api.RoleTool: return messageBody(props.Message) default: return messageError(fmt.Sprintf("Unable to render message: unsupported role %q", props.Message.Role)) } })
var MessageText = trail.FC("MessageText", func(props MessageTextProps) trail.Node { return uicomponents.Markdown(uicomponents.MarkdownProps{Source: props.Text}) })
var MessageThought = trail.FC("MessageThought", func(props MessageThoughtProps) trail.Node { scheme := theme.UseTheme() text := strings.TrimSpace(props.Text) if text == "" { return nil } line, _, multiline := strings.Cut(text, "\n") line = strings.TrimSpace(line) if multiline { line = strings.TrimRight(line, ". ") + "..." } prefix := "● Thought (" if props.Streaming { prefix = "○ Thinking (" } rowStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden) labelStyle := style.S().WhiteSpace(style.WhiteSpaceNoWrap).Flex(0, 0).Foreground(scheme.Color.Text.Secondary) detailsStyle := style.S(). WhiteSpace(style.WhiteSpaceNoWrap). Flex(0, 1). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Secondary) return trail.Box(trail.BoxProps{Style: rowStyle}, trail.Span(trail.SpanProps{Style: labelStyle}, trail.Text(prefix)), trail.Span(trail.SpanProps{Style: detailsStyle}, trail.Text(line)), trail.Span(trail.SpanProps{Style: labelStyle}, trail.Text(")")), ) })
var MessageTool = trail.FC("MessageTool", func(props MessageToolProps) trail.Node { var name string if props.Tool.Call != nil { name = props.Tool.Call.Name } if name == "" && props.Tool.Response != nil { name = props.Tool.Response.Name } switch name { case "view": return ViewToolRenderer(props.Tool) case "ls": return LsToolRenderer(props.Tool) case "glob": return GlobToolRenderer(props.Tool) case "grep": return GrepToolRenderer(props.Tool) case "load_skill": return LoadSkillToolWidget(LoadSkillToolWidgetProps(props)) case "load_rule": return LoadRuleToolWidget(LoadRuleToolWidgetProps(props)) case "write": return WriteToolRenderer(props.Tool) case "edit": return EditToolRenderer(props.Tool) case "remove": return RemoveToolRenderer(props.Tool) case "bash": return BashToolRenderer(props.Tool) case "web_fetch": return WebFetchToolRenderer(props.Tool) case "web_search": return WebSearchToolRenderer(props.Tool) case "download": return DownloadToolRenderer(props.Tool) case "tasks": return TasksToolRenderer(props.Tool) case "invoke_agent": return InvokeAgentToolRenderer(props.Tool) case "manage_agents": return ManageAgentsToolRenderer(props.Tool) case "todos": return TodosToolRenderer(props.Tool) case "ask_question": return QuestionToolRenderer(props.Tool) case "enter_plan_mode", "exit_plan_mode": return PlanToolRenderer(props.Tool) case "tool_search": return ToolSearchToolRenderer(props.Tool) default: return DefaultToolRenderer(props.Tool) } })
var ModelAliasEditor = trail.FC("ModelAliasEditor", func(props ModelAliasEditorProps) trail.Node { scheme := theme.UseTheme() staged, setStaged := kitex.UseState(aliasEditorStaged{toggles: map[string]bool{}}) cursor, setCursor := kitex.UseState(0) inputRef := kitex.UseRef[dom.Element](nil) trail.UseFocus(inputRef, trail.FocusOptions{AutoFocus: true, IsActive: staged().inputOpen}) byAlias := make(map[string]api.AliasAssignment, len(props.Assignments)) for _, a := range props.Assignments { byAlias[a.Alias] = a } defaultHere := strings.TrimSpace(props.DefaultModel) != "" && props.DefaultModel == props.ModelID ownerHere := func(a api.AliasAssignment) bool { if a.Provider == props.Provider && a.Model == props.ModelID { return true } return slices.Contains(a.Duplicates, props.Provider+"/"+props.ModelID) } duplicateText := func(a api.AliasAssignment) string { if !a.Duplicate { return "" } target := props.Provider + "/" + props.ModelID var others []string if primary := a.Provider + "/" + a.Model; a.Provider != "" && primary != target { others = append(others, primary) } for _, d := range a.Duplicates { if d != target { others = append(others, d) } } if len(others) == 0 { return "" } return "⚠ duplicate on " + strings.Join(others, ", ") } buildRows := func(st aliasEditorStaged) []aliasEditorRow { rows := make([]aliasEditorRow, 0, len(StandardModelAliases)+4) for _, std := range StandardModelAliases { row := aliasEditorRow{alias: std.Name, kind: "standard", role: std.Role} a, assigned := byAlias[std.Name] if std.Name == "default" { owned := defaultHere checked := owned if touched, ok := st.toggles["default"]; ok { checked = touched } row.checked = checked hasDefaultOwner := strings.TrimSpace(a.Provider) != "" switch { case a.WorkspaceDefault: row.state = "⚠ WORKSPACE.md overrides @default" row.warn = true case owned && hasDefaultOwner && (a.Provider != props.Provider || a.Model != props.ModelID): row.state = "⚠ " + a.Provider + "/" + a.Model + " wins @default — saving moves it here" row.warn = true case owned: row.state = "assigned to this model" case !hasDefaultOwner: row.state = "unassigned" case checked: row.state = "moves from " + a.Provider + "/" + a.Model default: row.state = "currently " + a.Provider + "/" + a.Model } if dup := duplicateText(a); dup != "" && !a.WorkspaceDefault { if checked { dup += " — saving assigns only here" } row.state = dup row.warn = true } rows = append(rows, row) continue } owned := assigned && ownerHere(a) checked := owned if touched, ok := st.toggles[std.Name]; ok { checked = touched } row.checked = checked switch { case a.WorkspaceDefault: row.state = "⚠ WORKSPACE.md overrides @" + std.Name row.warn = true case owned && !a.Duplicate: row.state = "assigned to this model" case !assigned: row.state = "unassigned" case checked: row.state = "moves from " + a.Provider + "/" + a.Model default: row.state = "currently " + a.Provider + "/" + a.Model } if dup := duplicateText(a); dup != "" && !a.WorkspaceDefault { if checked { dup += " — saving assigns only here" } row.state = dup row.warn = true } rows = append(rows, row) } seen := map[string]bool{} for _, a := range props.Assignments { if IsStandardModelAlias(a.Alias) || !ownerHere(a) || seen[a.Alias] { continue } seen[a.Alias] = true checked := true if touched, ok := st.toggles[a.Alias]; ok { checked = touched } row := aliasEditorRow{alias: a.Alias, kind: "custom", checked: checked, state: "assigned to this model"} if a.WorkspaceDefault { row.state = "⚠ WORKSPACE.md overrides @" + a.Alias row.warn = true } else if dup := duplicateText(a); dup != "" { if checked { dup += " — saving assigns only here" } row.state = dup row.warn = true } rows = append(rows, row) } for _, name := range st.added { if seen[name] { continue } seen[name] = true row := aliasEditorRow{alias: name, kind: "custom", checked: true, state: "new alias"} if a, ok := byAlias[name]; ok && a.Provider != "" { checked := true if touched, okT := st.toggles[name]; okT { checked = touched } row.checked = checked switch { case a.WorkspaceDefault: row.state = "⚠ WORKSPACE.md overrides @" + name row.warn = true case checked: row.state = "moves from " + a.Provider + "/" + a.Model default: row.state = "currently " + a.Provider + "/" + a.Model } if dup := duplicateText(a); dup != "" && !a.WorkspaceDefault { if checked { dup += " — saving assigns only here" } row.state = dup row.warn = true } } rows = append(rows, row) } return rows } rows := buildRows(staged()) cur := min(cursor(), max(0, len(rows)-1)) toggle := func(idx int) { if idx < 0 || idx >= len(rows) || props.Saving { return } row := rows[idx] next := aliasEditorStaged{ toggles: map[string]bool{}, added: slices.Clone(staged().added), inputOpen: false, } maps.Copy(next.toggles, staged().toggles) next.toggles[row.alias] = !row.checked setStaged(next) } submit := func() { if props.Saving || props.OnSave == nil { return } var aliases []string defaultWanted := false for _, row := range buildRows(staged()) { if !row.checked { continue } if row.alias == "default" { defaultWanted = true continue } aliases = append(aliases, row.alias) } props.OnSave(api.AssignModelAliasesRequest{ Provider: props.Provider, Model: props.ModelID, Aliases: aliases, DefaultHere: defaultWanted, }) } trail.UseInput(func(inputChar string, k event.KeyEvent) { st := staged() if st.inputOpen { switch { case k.MatchString("enter"): name := strings.TrimPrefix(strings.TrimSpace(st.inputVal), "@") next := aliasEditorStaged{toggles: map[string]bool{}, notice: ""} maps.Copy(next.toggles, st.toggles) current := byAlias[name] onThisModel := ownerHere(current) switch { case !customAliasPattern.MatchString(name): next.notice = "Custom aliases must be lowercase letters, digits, '-' or '_'." case slices.Contains(st.added, name) || onThisModel: next.toggles[name] = true case IsStandardModelAlias(name): next.notice = "@" + name + " is a standard alias — toggle it above instead." case current.Provider != "": if !slices.Contains(st.added, name) { next.added = append(slices.Clone(st.added), name) } next.toggles[name] = true default: next.added = append(slices.Clone(st.added), name) next.toggles[name] = true } setStaged(next) case k.MatchString("esc", "escape"): next := st next.inputOpen = false next.inputVal = "" setStaged(next) } return } switch { case k.MatchString("esc", "escape"): if props.OnCancel != nil { props.OnCancel() } case k.MatchString("space") || inputChar == " ": toggle(cur) case k.MatchString("n") && !props.Saving: setStaged(aliasEditorStaged{ toggles: staged().toggles, added: staged().added, inputOpen: true, inputVal: "", }) case k.MatchString("up", "ctrl+p", "k"): setCursor(max(0, cur-1)) case k.MatchString("down", "ctrl+n", "j"): setCursor(min(len(rows)-1, cur+1)) case k.MatchString("enter"): submit() } }) border := style.SingleBorder().Top(true).Bottom(true).Left(false).Right(false).Color(scheme.Color.Border.Default) titleStyle := style.S().Bold(true).Foreground(scheme.Color.Text.Primary) muted := style.S().Foreground(scheme.Color.Text.Muted) var body []trail.Node badge := style.S().Bold(true).Foreground(scheme.Color.Text.Success) if strings.EqualFold(props.Scope, "Workspace") { badge = style.S().Bold(true).Foreground(scheme.Color.Text.Info) } body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text("Model aliases · "+props.Provider+"/"+props.ModelName)), trail.Span(trail.SpanProps{Style: badge}, trail.Text(" ["+props.Scope+"]")), )) if props.ManifestPath != "" { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: muted}, trail.Text(props.ManifestPath)))) } if props.Loading { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: muted}, trail.Text("Loading alias assignments…")))) } else { body = append(body, aliasChecklistSection(scheme, "Standard aliases", rows, "standard", cur)) body = append(body, aliasChecklistSection(scheme, "Custom aliases", rows, "custom", cur)) if !staged().inputOpen { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow).Margin(0, 0, 0, 2)}, trail.Span(trail.SpanProps{Style: muted}, trail.Text("n Add custom alias…")))) } else { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: titleStyle.WhiteSpace(style.WhiteSpacePre)}, trail.Text(" @")), kitex.Input(kitex.InputProps{ Ref: inputRef, Value: staged().inputVal, Style: style.S().Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { next := staged() next.inputVal = ie.Value setStaged(next) } }, }), )) } } if notice := staged().notice; notice != "" { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: style.S().Foreground(scheme.Color.Text.Warning)}, trail.Text(notice)))) } if props.ErrorMessage != "" { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: style.S().Foreground(scheme.Color.Text.Error)}, trail.Text(props.ErrorMessage)))) } if props.Saving { body = append(body, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow)}, trail.Span(trail.SpanProps{Style: muted}, trail.Text("Saving…")))) } body = append(body, uicomponents.KeyboardHint(uicomponents.KeyboardHintProps{ Bindings: []uicomponents.KeyBinding{ {Key: "↑/↓", Label: "Select"}, {Key: "space", Label: "Toggle"}, {Key: "n", Label: "Add custom"}, {Key: "enter", Label: "Save"}, {Key: "esc", Label: "Cancel"}, }, })) return trail.Box(trail.BoxProps{ Style: style.S().Border(border).Width(style.Percent(100)).FlexDirection(style.FlexColumn).Padding(0, 0, 0, 1), }, body...) })
ModelAliasEditor renders the inline alias checklist card shared by /model and /providers. Space toggles a row, n adds a custom alias, Enter saves the staged set to the owning manifest, Esc cancels.
var ModelSwitchPrompt = trail.FC("ModelSwitchPrompt", func(props ModelSwitchPromptProps) trail.Node { scheme := theme.UseTheme() missing := strings.Join(props.Request.MissingModalities, ", ") if missing == "" { missing = "media" } header := trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Warning).WhiteSpace(style.WhiteSpacePreWrap), }, trail.Text(fmt.Sprintf("%s does not support %s used in this session; those attachments will be omitted on future turns.", props.Request.Model, missing))), ) options := []uicomponents.Option{ { Value: "force", Label: "Switch anyway", Description: "Omit unsupported attachments on future turns", }, { Value: "cancel", Label: "Cancel", Description: "Keep the current model", }, } return Picker(PickerProps{ Title: "Switch model?", Header: header, Bindings: []uicomponents.KeyBinding{ {Key: "↑/↓", Label: "navigate"}, {Key: "enter", Label: "select"}, {Key: "esc", Label: "cancel"}, }, Options: options, OnSelect: func(opt uicomponents.Option) { if opt.Value == "force" { if props.OnForce != nil { props.OnForce() } return } if props.OnCancel != nil { props.OnCancel() } }, OnCancel: props.OnCancel, }) })
ModelSwitchPrompt asks the user whether to proceed with a model switch that omits incompatible attachments on future turns or keep the current model.
var Notice = trail.FC("Notice", func(props store.NoticeData) trail.Node { scheme := theme.UseTheme() s := style.S().FlexDirection(style.FlexRow).MarginBottom(1).Foreground(scheme.Color.Text.Secondary) if props.Severity == store.NoticeSeverityWarning { s = s.PaddingLeft(1).BorderLeft(true, style.SingleBorder(), scheme.Color.Border.Warning).Foreground(scheme.Color.Text.Warning) } return trail.Box(trail.BoxProps{Style: s}, trail.Span(trail.SpanProps{}, trail.Text(props.Text)), ) })
Notice is a trail functional component rendering a dim informational notice line.
var OnboardingWizard = trail.FC("OnboardingWizard", func(props OnboardingWizardProps) trail.Node { _ = store.UseOnboarding(func(s store.OnboardingState) int { return s.Revision }) step := store.UseOnboarding(func(s store.OnboardingState) store.OnboardingStep { return s.Step }) active := store.UseOnboarding(func(s store.OnboardingState) bool { return s.Active }) state := store.GetOnboarding() scheme := theme.UseTheme() if !active { return nil } frame := renderWizardHeader(state.Workspace, step, scheme) var content trail.Node switch step { case store.StepTrust: content = renderTrustStep(props, state) case store.StepProviderSrc: content = renderProviderSrcStep(props) case store.StepProviderPick: content = renderProviderPickStep(props, state) case store.StepCredentials: content = renderCredentialsStep(props, state) case store.StepMode: content = renderModeStep(props) case store.StepTools: content = renderToolsStep(props, state) case store.StepReview: content = renderReviewStep(props, state, scheme) default: content = nil } return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).Width(style.Percent(100)), }, frame, content, ) })
OnboardingWizard renders the multi-step onboarding/setup wizard matching §4.
var PermissionConfigEditor = trail.FC("PermissionConfigEditor", func(props PermissionConfigEditorProps) trail.Node { scheme := theme.UseTheme() step, setStep := kitex.UseState(stepScope) scopeIndex, setScopeIndex := kitex.UseState(0) activeEffect, setActiveEffect := kitex.UseState(api.EffectAllow) ruleCursor, setRuleCursor := kitex.UseState(0) isEdit, setIsEdit := kitex.UseState(false) editTarget, setEditTarget := kitex.UseState("") inputText, setInputText := kitex.UseState("") localError, setLocalError := kitex.UseState("") inputRef := kitex.UseRef[dom.Element](nil) trail.UseFocus(inputRef, trail.FocusOptions{ AutoFocus: true, IsActive: step() == stepInput, }) activeScope := api.ScopeProject scopeTitle := "Project" if scopeIndex() == 1 { activeScope = api.ScopeGlobal scopeTitle = "Global" } scopePerms := props.Permissions.Project if activeScope == api.ScopeGlobal { scopePerms = props.Permissions.Global } rules := scopePerms.Allow if activeEffect() == api.EffectDeny { rules = scopePerms.Deny } curRule := ruleCursor() if curRule >= len(rules) { curRule = len(rules) - 1 } if curRule < 0 { curRule = 0 } trail.UseInput(func(input string, k event.KeyEvent) { if step() == stepInput { return } switch step() { case stepScope: switch { case k.MatchString("up", "k", "ctrl+p"): if scopeIndex() > 0 { setScopeIndex(0) } case k.MatchString("down", "j", "ctrl+n"): if scopeIndex() < 1 { setScopeIndex(1) } case k.MatchString("enter"): setStep(stepRules) setRuleCursor(0) if props.OnClearError != nil { props.OnClearError() } case k.MatchString("esc", "escape"): if props.OnClose != nil { props.OnClose() } } case stepRules: switch { case k.MatchString("tab", "right", "l"): if activeEffect() == api.EffectAllow { setActiveEffect(api.EffectDeny) } else { setActiveEffect(api.EffectAllow) } setRuleCursor(0) if props.OnClearError != nil { props.OnClearError() } case k.MatchString("left", "h"): if activeEffect() == api.EffectDeny { setActiveEffect(api.EffectAllow) } else { setActiveEffect(api.EffectDeny) } setRuleCursor(0) if props.OnClearError != nil { props.OnClearError() } case k.MatchString("up", "k", "ctrl+p"): if curRule > 0 { setRuleCursor(curRule - 1) } case k.MatchString("down", "j", "ctrl+n"): if curRule < len(rules)-1 { setRuleCursor(curRule + 1) } case input == "a" || input == "A" || k.MatchString("a"): setIsEdit(false) setEditTarget("") setInputText("") setLocalError("") if props.OnClearError != nil { props.OnClearError() } setStep(stepInput) case input == "e" || input == "E" || k.MatchString("e"): if len(rules) > 0 { setIsEdit(true) setEditTarget(rules[curRule]) setInputText(rules[curRule]) setLocalError("") if props.OnClearError != nil { props.OnClearError() } setStep(stepInput) } case input == "d" || input == "D" || k.MatchString("d", "backspace", "delete"): if len(rules) > 0 && props.OnRemoveRule != nil { props.OnRemoveRule(activeScope, activeEffect(), rules[curRule]) } case k.MatchString("esc", "escape"): setStep(stepScope) if props.OnClearError != nil { props.OnClearError() } } } }) border := style.SingleBorder().Top(true).Bottom(false).Left(false).Right(false).Color(scheme.Color.Border.Default) titleStyle := style.S().Bold(true).Foreground(scheme.Color.Agent.Permission) primaryStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Primary) secondaryStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) hintStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Muted) errorStyle := style.S().Foreground(scheme.Color.Text.Error) activeTabStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Primary) inactiveTabStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) var children []trail.Node switch step() { case stepScope: children = append(children, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text("Permission Config Editor")), trail.Newline(1), trail.Span(trail.SpanProps{Style: secondaryStyle}, trail.Text("Select a config scope to edit:")), trail.Newline(1), ) scopeItems := []struct { name string desc string }{ {name: "Project", desc: "Rules that apply only to this project (highest priority)"}, {name: "Global", desc: "Rules that apply across all projects"}, } for i, item := range scopeItems { prefix := " " itemStyle := secondaryStyle if i == scopeIndex() { prefix = "❯ " itemStyle = primaryStyle } children = append(children, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: itemStyle}, trail.Text(prefix+item.name)), )) } children = append(children, trail.Newline(1), trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: hintStyle}, trail.Text(" "+scopeItems[scopeIndex()].desc)), ), components.KeyboardHint(components.KeyboardHintProps{ Bindings: []components.KeyBinding{ {Key: "↑/↓", Label: "Navigate"}, {Key: "enter", Label: "Select"}, {Key: "esc", Label: "Close"}, }, }), ) case stepRules: children = append(children, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text(fmt.Sprintf("Permissions — %s", scopeTitle))), ) var allowTab, denyTab style.Style if activeEffect() == api.EffectAllow { allowTab = activeTabStyle denyTab = inactiveTabStyle } else { allowTab = inactiveTabStyle denyTab = activeTabStyle } children = append(children, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: allowTab}, trail.Text(fmt.Sprintf("allowlist (%d)", len(scopePerms.Allow)))), trail.Span(trail.SpanProps{Style: inactiveTabStyle}, trail.Text(" ")), trail.Span(trail.SpanProps{Style: denyTab}, trail.Text(fmt.Sprintf("denylist (%d)", len(scopePerms.Deny)))), ), trail.Newline(1), ) if len(rules) == 0 { emptyText := "No allowlist rules." if activeEffect() == api.EffectDeny { emptyText = "No denylist rules." } children = append(children, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: secondaryStyle}, trail.Text(emptyText)), )) } else { for i, r := range rules { prefix := " " rStyle := secondaryStyle if i == curRule { prefix = "❯ " rStyle = primaryStyle } children = append(children, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: rStyle}, trail.Text(prefix+r)), )) } } if props.ErrorMessage != "" { children = append(children, trail.Newline(1), trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: errorStyle}, trail.Text(props.ErrorMessage)), ), ) } children = append(children, components.KeyboardHint(components.KeyboardHintProps{ Bindings: []components.KeyBinding{ {Key: "↑/↓", Label: "Navigate"}, {Key: "←/→", Label: "Switch View"}, {Key: "a", Label: "Add rule"}, {Key: "e", Label: "Edit rule"}, {Key: "d/⌫", Label: "Delete rule"}, {Key: "esc", Label: "Back"}, }, }), ) case stepInput: listName := "allowlist" if activeEffect() == api.EffectDeny { listName = "denylist" } inputTitle := fmt.Sprintf("Add Rule — %s — %s", scopeTitle, listName) if isEdit() { inputTitle = fmt.Sprintf("Edit Rule — %s — %s", scopeTitle, listName) } children = append(children, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text(inputTitle)), trail.Newline(1), trail.Span(trail.SpanProps{Style: secondaryStyle}, trail.Text("Enter a permission rule:")), trail.Newline(1), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignCenter). Width(style.Percent(100)), }, trail.Span(trail.SpanProps{Style: primaryStyle}, trail.Text("❯ ")), kitex.Input(kitex.InputProps{ Ref: inputRef, Value: inputText(), Style: style.S().Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { setInputText(ie.Value) if localError() != "" { setLocalError("") } } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { switch { case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() rule := strings.TrimSpace(inputText()) if rule == "" { setLocalError("Rule must not be empty") return } if !strings.Contains(rule, "(") || !strings.HasSuffix(rule, ")") { setLocalError("Invalid rule format: expected tool(pattern)") return } setLocalError("") if isEdit() { if props.OnEditRule != nil && rule != editTarget() { props.OnEditRule(activeScope, activeEffect(), editTarget(), rule) } } else { if props.OnAddRule != nil { props.OnAddRule(activeScope, activeEffect(), rule) } } setStep(stepRules) case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() setLocalError("") if props.OnClearError != nil { props.OnClearError() } setStep(stepRules) } } }, }), ), ) errText := localError() if errText == "" && props.ErrorMessage != "" { errText = props.ErrorMessage } if errText != "" { children = append(children, trail.Newline(1), trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: errorStyle}, trail.Text(errText)), ), ) } children = append(children, trail.Newline(1), trail.Span(trail.SpanProps{Style: hintStyle}, trail.Text("Format: tool(pattern)")), components.KeyboardHint(components.KeyboardHintProps{ Bindings: []components.KeyBinding{ {Key: "enter", Label: "Save"}, {Key: "esc", Label: "Cancel"}, }, }), ) } return trail.Box(trail.BoxProps{ Style: style.S(). Border(border). Width(style.Percent(100)). FlexDirection(style.FlexColumn), }, children...) })
PermissionConfigEditor is a 3-screen interactive permission rule configuration manager.
var PermissionPrompt = trail.FC("PermissionPrompt", func(props PermissionPromptProps) trail.Node { scheme := theme.UseTheme() scope, setScope := kitex.UseState(api.ScopeSession) feedbackMode, setFeedbackMode := kitex.UseState(false) feedbackText, setFeedbackText := kitex.UseState("") feedbackInputRef := kitex.UseRef[dom.Element](nil) trail.UseFocus(feedbackInputRef, trail.FocusOptions{ AutoFocus: true, IsActive: feedbackMode(), }) patterns := props.Request.GrantPatterns if len(patterns) == 0 { if props.Request.ToolName != "" { patterns = []string{props.Request.ToolName + "(*)"} } else { patterns = []string{"*(*)"} } } totalRows := len(patterns) + 2 if props.OnAcceptEdits != nil { totalRows++ } cursor := components.UseCursor(totalRows, 0) submitDecision := func(dec api.PermissionDecision) { if props.OnDecision != nil { props.OnDecision(props.Request, dec) } } trail.UseInput(func(input string, k event.KeyEvent) { if feedbackMode() { return } switch { case k.MatchString("tab"): switch scope() { case api.ScopeSession: setScope(api.ScopeProject) case api.ScopeProject: setScope(api.ScopeGlobal) default: setScope(api.ScopeSession) } case input == "a" || input == "A" || k.MatchString("a"): pat := patterns[0] if cursor.Index >= 1 && cursor.Index <= len(patterns) { pat = patterns[cursor.Index-1] } submitDecision(api.PermissionDecision{ Kind: api.DecisionAllowSession, GrantPattern: pat, Scope: scope(), }) case input == "r" || input == "R" || k.MatchString("r"): setFeedbackMode(true) setFeedbackText("") cursor.Set(totalRows - 1) } }) border := style.RoundedBorder().Color(scheme.Color.Border.Default) titleStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Agent.Permission) toolStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Primary) dotStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) targetStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) unselectedStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) scopeStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Agent.Permission) menuItems := make([]components.ActionMenuItem, 0, totalRows) menuItems = append(menuItems, components.ActionMenuItem{ ID: "allow_once", Label: "Yes, allow once", Shortcut: "y", }) scopeTag := fmt.Sprintf("[%s]", scope()) for _, pat := range patterns { menuItems = append(menuItems, components.ActionMenuItem{ ID: "allow_scope:" + pat, Label: "Always allow " + compactSingleLine(pat, 60), Badge: scopeTag, BadgeStyle: &scopeStyle, }) } if props.OnAcceptEdits != nil { menuItems = append(menuItems, components.ActionMenuItem{ ID: "accept_edits", Label: "Yes, and switch to accept_edits", Shortcut: "e", }) } menuItems = append(menuItems, components.ActionMenuItem{ ID: "deny", Label: "No, deny", Shortcut: "n", }) perm := props.Request var boxChildren []trail.Node boxChildren = append(boxChildren, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text("Permission required")))) if perm.Unsandboxed { badgeStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Error) boxChildren = append(boxChildren, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{Style: badgeStyle}, trail.Text("⚠ UNSANDBOXED — runs directly on the host, outside the OS sandbox")))) } targetText := strings.TrimSpace(perm.Target) if targetText == "" { targetText = strings.TrimSpace(perm.Summary) } targetText = compactSingleLine(targetText, 80) var subtitleNodes []trail.Node if perm.ToolName != "" && targetText != "" { target := trail.Span(trail.SpanProps{Style: targetStyle}, trail.Text(targetText)) if perm.ToolName == "bash" { target = trail.Span(trail.SpanProps{Style: style.S().WhiteSpace(style.WhiteSpacePreWrap)}, components.HighlightShellSpans(targetText, scheme, scheme.Color.Text.Primary)...) } subtitleNodes = append(subtitleNodes, trail.Span(trail.SpanProps{Style: toolStyle}, trail.Text(perm.ToolName)), trail.Span(trail.SpanProps{Style: dotStyle}, trail.Text(" · ")), target, ) } else if targetText != "" { subtitleNodes = append(subtitleNodes, trail.Span(trail.SpanProps{Style: targetStyle}, trail.Text(targetText)), ) } else if perm.ToolName != "" { subtitleNodes = append(subtitleNodes, trail.Span(trail.SpanProps{Style: toolStyle}, trail.Text(perm.ToolName)), ) } if len(subtitleNodes) > 0 { boxChildren = append(boxChildren, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, subtitleNodes...)) } if perm.Diff != "" { boxChildren = append(boxChildren, trail.Newline(1), DiffView(DiffProps{ Text: strings.TrimRight(perm.Diff, "\n"), Path: perm.Target, })) } boxChildren = append(boxChildren, trail.Newline(1), components.ActionMenu(components.ActionMenuProps{ Items: menuItems, Selected: &cursor.Index, Disabled: feedbackMode(), UnselectedStyle: &unselectedStyle, OnChange: cursor.Set, OnSelect: func(index int, item components.ActionMenuItem) { switch item.ID { case "allow_once": submitDecision(api.PermissionDecision{Kind: api.DecisionAllowOnce}) case "accept_edits": props.OnAcceptEdits(props.Request) case "deny": submitDecision(api.PermissionDecision{Kind: api.DecisionReject}) default: submitDecision(api.PermissionDecision{ Kind: api.DecisionAllowSession, GrantPattern: patterns[index-1], Scope: scope(), }) } }, })) if feedbackMode() { feedbackPromptStyle := style.S().Bold(true).Foreground(scheme.Color.Agent.Permission) boxChildren = append(boxChildren, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignCenter). MarginTop(1). Width(style.Percent(100)), }, trail.Span(trail.SpanProps{ Style: feedbackPromptStyle, }, trail.Text("Feedback: ")), kitex.Input(kitex.InputProps{ Ref: feedbackInputRef, Value: feedbackText(), Style: style.S().Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { setFeedbackText(ie.Value) } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { switch { case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() submitDecision(api.PermissionDecision{ Kind: api.DecisionReject, Feedback: feedbackText(), }) case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() setFeedbackMode(false) } } }, }), )) } if !feedbackMode() { bindings := []components.KeyBinding{ {Key: "↑/↓", Label: "Navigate"}, {Key: "tab", Label: "Scope"}, {Key: "enter", Label: "Confirm"}, {Key: "r", Label: "Feedback"}, } if props.OnAcceptEdits != nil { bindings = append(bindings, components.KeyBinding{Key: "e", Label: "Accept edits"}) } boxChildren = append(boxChildren, components.KeyboardHint(components.KeyboardHintProps{Bindings: bindings})) } else { boxChildren = append(boxChildren, components.KeyboardHint(components.KeyboardHintProps{ Bindings: []components.KeyBinding{ {Key: "enter", Label: "Submit"}, {Key: "esc", Label: "Cancel"}, }, })) } return trail.Box(trail.BoxProps{ Style: style.S(). Border(border). Padding(0, 1). Width(style.Percent(100)). FlexDirection(style.FlexColumn), }, boxChildren...) })
PermissionPrompt is a trail functional component rendering a tool authorization request.
var Picker = trail.FC("Picker", func(props PickerProps) trail.Node { scheme := theme.UseTheme() winSize := trail.UseWindowSize() filter, setFilter := kitex.UseState("") modal, setModal := kitex.UseState(pickerModalState{mode: pickerModeBrowse}) notice, setNotice := kitex.UseState("") filterInputRef := kitex.UseRef[dom.Element](nil) actionInputRef := kitex.UseRef[dom.Element](nil) kitex.UseEffect(func() { if props.OnOpen != nil { props.OnOpen() } }, []any{}) st := modal() trail.UseFocus(filterInputRef, trail.FocusOptions{ AutoFocus: true, IsActive: props.Filterable && st.mode == pickerModeBrowse, }) trail.UseFocus(actionInputRef, trail.FocusOptions{ AutoFocus: true, IsActive: st.mode == pickerModeInput, }) filtered := kitex.UseMemo(func() []components.Option { return filterOptions(props.Options, filter()) }, []any{props.Options, filter()}) cursor := components.UseCursor(len(filtered), initialCursor(props.Options)) cur := cursor.Index handleBrowseKey := func(ke event.KeyEvent) bool { if notice() != "" { setNotice("") } if props.FilterSafeKeys && props.Filterable && isFilterTypedKey(ke) { return false } if cursor.HandleKey(ke) { return true } switch { case ke.MatchString("enter"): if len(filtered) > 0 && props.OnSelect != nil { props.OnSelect(filtered[cur]) } return true case ke.MatchString("esc", "escape"): if props.OnCancel != nil { props.OnCancel() } return true } for _, k := range slices.Sorted(maps.Keys(props.ConfirmActions)) { if ke.MatchString(k) && len(filtered) > 0 { ca := props.ConfirmActions[k] if ca.DisabledReason != nil { if reason := strings.TrimSpace(ca.DisabledReason(filtered[cur])); reason != "" { setNotice(reason) return true } } if ca.Prompt != nil && strings.TrimSpace(ca.Prompt(filtered[cur])) == "" { return true } setModal(pickerModalState{ mode: pickerModeConfirm, targetOpt: filtered[cur], activeConfirm: ca, }) return true } } for _, k := range slices.Sorted(maps.Keys(props.InputActions)) { if ke.MatchString(k) && len(filtered) > 0 { ia := props.InputActions[k] if ia.DisabledReason != nil { if reason := strings.TrimSpace(ia.DisabledReason(filtered[cur])); reason != "" { setNotice(reason) return true } } initVal := "" if ia.InitialValue != nil { initVal = ia.InitialValue(filtered[cur]) } setModal(pickerModalState{ mode: pickerModeInput, targetOpt: filtered[cur], activeInput: ia, inputVal: initVal, }) return true } } for _, k := range slices.Sorted(maps.Keys(props.Keys)) { if ke.MatchString(k) && len(filtered) > 0 { props.Keys[k](filtered[cur]) return true } } return false } trail.UseInput(func(input string, k event.KeyEvent) { mst := modal() if mst.mode == pickerModeConfirm { if input == "y" || input == "Y" || k.MatchString("y", "enter") { if mst.activeConfirm.OnConfirm != nil { mst.activeConfirm.OnConfirm(mst.targetOpt) } setModal(pickerModalState{mode: pickerModeBrowse}) return } if input == "n" || input == "N" || k.MatchString("n", "esc", "escape") { setModal(pickerModalState{mode: pickerModeBrowse}) return } return } if mst.mode == pickerModeBrowse && !props.Filterable { handleBrowseKey(k) } }) var rows []trail.Node if props.Title != "" { titleStyle := style.S().Bold(true).Foreground(scheme.Color.Text.Primary) rows = append(rows, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: titleStyle, }, trail.Text(props.Title)))) } if props.Subtitle != "" { subtitleStyle := style.S().Foreground(scheme.Color.Text.Muted) subtitleMargin := style.S().FlexDirection(style.FlexRow) if !props.Filterable { subtitleMargin = subtitleMargin.Margin(0, 0, 1, 0) } rows = append(rows, trail.Box(trail.BoxProps{ Style: subtitleMargin, }, trail.Span(trail.SpanProps{ Style: subtitleStyle, }, trail.Text(props.Subtitle)))) } if props.Filterable && st.mode == pickerModeBrowse { filterPromptStyle := style.S().Bold(true).Margin(0, 1, 0, 0).Flex(0, 0).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Primary) rows = append(rows, trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignCenter). Width(style.Percent(100)), }, trail.Span(trail.SpanProps{ Style: filterPromptStyle, }, trail.Text("Filter:")), kitex.Input(kitex.InputProps{ Ref: filterInputRef, Value: filter(), Style: style.S().Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { setFilter(ie.Value) cursor.Set(0) } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { if handleBrowseKey(*ke) { e.PreventDefault() e.StopPropagation() } } }, }), )) } maxVis := props.MaxVisible if maxVis <= 0 { maxVis = components.DefaultPickerMaxVisible } optionStyles := &components.OptionListStyles{ Option: style.S().Foreground(scheme.Color.Text.Secondary), Selected: style.S().Bold(true).Foreground(scheme.Color.Icon.Primary), Description: style.S().Foreground(scheme.Color.Text.Muted), } if props.Header != nil { rows = append(rows, props.Header) } rows = append(rows, components.OptionList(components.OptionListProps{ Options: filtered, Selected: cur, EmptyText: " No matching options.", MaxVisible: maxVis, Columns: props.Columns, Styles: optionStyles, GroupLabel: props.GroupLabel, })) if props.Footer != nil && len(filtered) > 0 { if detail := strings.TrimSpace(props.Footer(filtered[cur])); detail != "" { if winSize.Width > 2 { detail = format.CompactSingleLine(detail, winSize.Width-2) } footerStyle := style.S().Margin(1, 0, 0, 0).Foreground(scheme.Color.Text.Muted) rows = append(rows, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: footerStyle.WhiteSpace(style.WhiteSpacePre), }, trail.Text(" "+detail)))) } } switch st.mode { case pickerModeConfirm: promptText := "" if st.activeConfirm.Prompt != nil { promptText = st.activeConfirm.Prompt(st.targetOpt) } warnStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary) hintStyle := style.S().Foreground(scheme.Color.Text.Secondary) rows = append(rows, trail.Newline(1), trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: warnStyle, }, trail.Text("? "+promptText+" ")), trail.Span(trail.SpanProps{ Style: hintStyle, }, trail.Text("(y/N)")), )) case pickerModeInput: infoStyle := style.S().Bold(true).Margin(0, 1, 0, 0).Flex(0, 0).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Primary) rows = append(rows, trail.Newline(1), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignCenter). Width(style.Percent(100)), }, trail.Span(trail.SpanProps{ Style: infoStyle, }, trail.Text(st.activeInput.Prompt)), kitex.Input(kitex.InputProps{ Ref: actionInputRef, Value: st.inputVal, Style: style.S().Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { current := modal() current.inputVal = ie.Value setModal(current) } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { switch { case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() current := modal() if current.activeInput.OnSubmit != nil { current.activeInput.OnSubmit(current.targetOpt, current.inputVal) } setModal(pickerModalState{mode: pickerModeBrowse}) case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() setModal(pickerModalState{mode: pickerModeBrowse}) } } }, }), )) } var activeBindings []components.KeyBinding switch st.mode { case pickerModeConfirm: activeBindings = []components.KeyBinding{ {Key: "y/enter", Label: "Confirm"}, {Key: "n/esc", Label: "Cancel"}, } case pickerModeInput: activeBindings = []components.KeyBinding{ {Key: "enter", Label: "Submit"}, {Key: "esc", Label: "Cancel"}, } default: activeBindings = props.Bindings if len(activeBindings) == 0 { activeBindings = DefaultPickerBindings } } if n := notice(); n != "" { noticeStyle := style.S().Margin(1, 0, 0, 0).Foreground(scheme.Color.Text.Secondary) rows = append(rows, trail.Span(trail.SpanProps{Style: noticeStyle}, trail.Text(" "+n))) } rows = append(rows, components.KeyboardHint(components.KeyboardHintProps{ Bindings: activeBindings, })) border := style.SingleBorder().Top(true).Bottom(false).Left(false).Right(false).Color(scheme.Color.Border.Default) return trail.Box(trail.BoxProps{ Style: style.S(). Border(border). Width(style.Percent(100)). FlexDirection(style.FlexColumn), }, rows...) })
Picker is a trail functional component managing interactive item selection, filtering, custom actions, and keyboard navigation.
var PlanReviewPrompt = trail.FC("PlanReviewPrompt", func(props PlanReviewPromptProps) trail.Node { scheme := theme.UseTheme() state, setState := kitex.UseState(planReviewState{}) feedbackRef := kitex.UseRef[dom.Element](nil) s := state() req := props.Request trail.UseFocus(feedbackRef, trail.FocusOptions{ AutoFocus: true, IsActive: s.editing && !s.submitting, }) submit := func(selectedID, feedback string, canceled bool) { if props.OnSubmit == nil || s.submitting { return } next := state() next.submitting = true next.err = "" setState(next) var dec api.PlanReviewDecision if canceled { dec.Canceled = true } else { switch api.PermissionMode(selectedID) { case api.ModeAcceptEdits, api.ModeDefault, api.ModeAuto: dec.Approved = true dec.Mode = api.PermissionMode(selectedID) default: dec.Approved = false dec.Feedback = strings.TrimSpace(feedback) } } props.OnSubmit(req, dec, func(err error) { if err != nil { cur := state() cur.submitting = false cur.err = err.Error() setState(cur) } }) } trail.UseInput(func(input string, k event.KeyEvent) { cur := state() if cur.submitting || cur.editing || cur.viewing { return } switch { case input == "p" || input == "P" || k.MatchString("p"): cur.viewing = true cur.err = "" setState(cur) case k.MatchString("esc", "escape"): submit("", "", true) } }, trail.InputOptions{IsActive: !s.submitting && !s.editing && !s.viewing}) titleStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary).WhiteSpace(style.WhiteSpacePreWrap) pathStyle := style.S().Foreground(scheme.Color.Text.Secondary).WhiteSpace(style.WhiteSpacePreWrap).OverflowWrap(style.OverflowWrapAnywhere) selectedStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary).WhiteSpace(style.WhiteSpacePreWrap) optionStyle := style.S().Foreground(scheme.Color.Text.Primary).WhiteSpace(style.WhiteSpacePreWrap) mutedStyle := style.S().Foreground(scheme.Color.Text.Muted).WhiteSpace(style.WhiteSpacePreWrap) planPath := req.Path planContent := req.Content hasContent := strings.TrimSpace(planContent) != "" headerNodes := []trail.Node{ trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text("Plan review")), } if planPath != "" { headerNodes = append(headerNodes, trail.Span(trail.SpanProps{Style: pathStyle}, trail.Text(" · "+planPath)), ) } if hasContent { lineCount := strings.Count(strings.TrimRight(planContent, "\r\n"), "\n") + 1 headerNodes = append(headerNodes, trail.Span(trail.SpanProps{Style: mutedStyle}, trail.Text(fmt.Sprintf(" (%d lines)", lineCount))), ) } var children []trail.Node if s.viewing { closeViewer := func() { cur := state() cur.viewing = false setState(cur) } previewBorder := style.SingleBorder().Top(true).Bottom(true).Left(false).Right(false).Color(scheme.Color.Border.Default) viewportStyle := style.S().Border(previewBorder).Margin(1, 0) children = append(children, components.ScrollViewer(components.ScrollViewerProps{ Header: headerNodes, Markdown: planContent, EmptyText: "(empty plan file)", InitialScroll: s.scrollPos, OnScroll: func(pos int) { cur := state() cur.scrollPos = pos setState(cur) }, ViewportStyle: &viewportStyle, Disabled: s.submitting, OnClose: closeViewer, Actions: []components.ScrollViewerAction{ {Keys: []string{"p", "P", "q", "enter"}, Handler: closeViewer}, }, Bindings: []components.KeyBinding{ {Key: "↑/↓ or j/k", Label: "Scroll"}, {Key: "pgup/pgdn", Label: "Page"}, {Key: "g/G", Label: "Top/Bottom"}, {Key: "p/esc", Label: "Back to review"}, }, })) } else { children = append(children, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100))}, headerNodes...), trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)).Margin(1, 0), }, trail.Span(trail.SpanProps{Style: optionStyle}, trail.Text("Approve implementation plan?")), trail.Span(trail.SpanProps{Style: mutedStyle}, trail.Text(" (press p to view full plan)")), ), ) menuItems := make([]components.ActionMenuItem, len(planReviewOptions)) for i, opt := range planReviewOptions { item := components.ActionMenuItem{ ID: opt.id, Label: opt.label, } if opt.id == "keep_planning" { item.Shortcut = "r" } menuItems[i] = item } children = append(children, components.ActionMenu(components.ActionMenuProps{ Items: menuItems, Selected: &s.cursor, Numbered: true, Disabled: s.editing || s.submitting, OnChange: func(index int) { cur := state() cur.cursor = index setState(cur) }, OnSelect: func(_ int, item components.ActionMenuItem) { if item.ID == "keep_planning" { cur := state() cur.editing = true cur.err = "" setState(cur) return } submit(item.ID, "", false) }, })) if s.editing { children = append(children, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)).MarginTop(1), }, trail.Span(trail.SpanProps{Style: selectedStyle}, trail.Text("Feedback (optional): ")), kitex.Input(kitex.InputProps{ Ref: feedbackRef, Value: s.feedback, Style: optionStyle.Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { cur := state() cur.feedback = ie.Value setState(cur) } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { switch { case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() cur := state() submit("keep_planning", cur.feedback, false) case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() cur := state() cur.editing = false setState(cur) } } }, }), )) } if s.submitting { children = append(children, trail.Box(trail.BoxProps{Style: style.S().Width(style.Percent(100)).MarginTop(1)}, trail.Span(trail.SpanProps{Style: mutedStyle}, trail.Text("Submitting…")), )) } if s.err != "" { children = append(children, trail.Box(trail.BoxProps{Style: style.S().Width(style.Percent(100))}, trail.Span(trail.SpanProps{Style: style.S().Foreground(scheme.Color.Text.Error)}, trail.Text(s.err)), )) } if !s.submitting { var bindings []components.KeyBinding if s.editing { bindings = []components.KeyBinding{ {Key: "enter", Label: "Submit"}, {Key: "esc", Label: "Back"}, } } else { bindings = []components.KeyBinding{ {Key: "↑/↓", Label: "Navigate"}, {Key: "1-4/enter", Label: "Select"}, {Key: "p", Label: "View plan"}, {Key: "r", Label: "Feedback"}, {Key: "esc", Label: "Cancel"}, } } children = append(children, components.KeyboardHint(components.KeyboardHintProps{Bindings: bindings})) } } return trail.Box(trail.BoxProps{ Style: style.S(). Border(style.RoundedBorder().Color(scheme.Color.Border.Default)). Padding(0, 1). Width(style.Percent(100)). FlexDirection(style.FlexColumn), }, children...) })
PlanReviewPrompt renders a compact plan approval prompt for exit_plan_mode, with a toggleable scrollable Markdown plan viewer.
var ProviderReauthPrompt = trail.FC("ProviderReauthPrompt", func(props ProviderReauthPromptProps) trail.Node { scheme := theme.UseTheme() display := ProviderDisplayName(props.Request.Provider, "") if display == "" { display = "provider" } message := strings.TrimSpace(props.Request.Message) if message == "" { message = fmt.Sprintf("Authentication for %s has expired.", display) } header := trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Warning).WhiteSpace(style.WhiteSpacePreWrap), }, trail.Text(message)), ) options := []uicomponents.Option{ { Value: "signin", Label: fmt.Sprintf("Sign in to %s now", display), Description: "Open the provider sign-in flow", }, { Value: "dismiss", Label: "Dismiss", Description: "Stay in the conversation", }, } return Picker(PickerProps{ Title: fmt.Sprintf("%s sign-in required", display), Header: header, Bindings: []uicomponents.KeyBinding{ {Key: "↑/↓", Label: "navigate"}, {Key: "enter", Label: "select"}, {Key: "esc", Label: "dismiss"}, }, Options: options, OnSelect: func(opt uicomponents.Option) { if opt.Value == "signin" { if props.OnSignIn != nil { props.OnSignIn() } return } if props.OnDismiss != nil { props.OnDismiss() } }, OnCancel: props.OnDismiss, }) })
ProviderReauthPrompt offers a one-step sign-in action or dismissal when an OAuth provider reports an expired session during a turn.
var QuestionPrompt = trail.FC("QuestionPrompt", func(props QuestionPromptProps) trail.Node { scheme := theme.UseTheme() form, setForm := kitex.UseState(newQuestionForm(props.Request)) inputRef := kitex.UseRef[dom.Element](nil) f := form() req := props.Request trail.UseFocus(inputRef, trail.FocusOptions{AutoFocus: true, IsActive: f.editing && !f.canceling && !f.submitting}) if len(req.Questions) == 0 { return nil } update := func(next questionForm) { setForm(next) } clone := func() questionForm { n := form() n.answers = slices.Clone(n.answers) n.answered = slices.Clone(n.answered) return n } move := func(n *questionForm, step int) { n.step, n.cursor, n.err = step, 0, "" n.editing = step < len(req.Questions) && req.Questions[step].Type == string(api.QuestionTypeText) if step < len(req.Questions) { q := req.Questions[step] a := n.answers[step] if q.Type == string(api.QuestionTypeSingle) { if a.Text != "" { n.cursor = len(q.Options) } else if len(a.Selected) > 0 { for i, option := range q.Options { if option.ID == a.Selected[0] { n.cursor = i break } } } } else if q.Type == string(api.QuestionTypeConfirm) && a.Confirmed != nil && !*a.Confirmed { n.cursor = 1 } } if n.editing { n.input = n.answers[step].Text } } submit := func(n questionForm, canceled bool) { if props.OnSubmit == nil || n.submitting { return } n.submitting, n.err = true, "" update(n) response := api.QuestionResponse{Canceled: canceled} if !canceled { response.Answers = slices.Clone(n.answers) } props.OnSubmit(req, response, func(err error) { if err != nil { current := form() current.submitting, current.canceling, current.err = false, false, err.Error() if current.step < len(req.Questions) && req.Questions[current.step].Type == string(api.QuestionTypeText) { current.editing = true } update(current) } }) } advance := func(n questionForm) { n.answered[n.step] = true if len(req.Questions) == 1 { submit(n, false) return } for i := range n.answered { if !n.answered[i] { move(&n, i) update(n) return } } move(&n, len(req.Questions)) update(n) } commitInput := func() { n := clone() if strings.TrimSpace(n.input) == "" { if req.Questions[n.step].Type == string(api.QuestionTypeMulti) { n.answers[n.step].Text = "" n.editing, n.err = false, "" n.cursor = 0 update(n) return } n.err = "Enter an answer." update(n) return } q := req.Questions[n.step] n.answers[n.step].Text = strings.TrimSpace(n.input) if q.Type == string(api.QuestionTypeSingle) { n.answers[n.step].Selected = nil } n.editing = false if q.Type == string(api.QuestionTypeMulti) { n.err = "" n.cursor = 0 update(n) } else { advance(n) } } trail.UseInput(func(input string, k event.KeyEvent) { n := clone() if n.submitting || n.editing && !n.canceling { return } if n.canceling { switch { case k.MatchString("esc", "escape", "n"): n.canceling = false update(n) case k.MatchString("y", "enter"): submit(n, true) } return } if k.MatchString("esc", "escape") { n.canceling = true update(n) return } if k.MatchString("left", "shift+tab") && n.step > 0 { move(&n, n.step-1) update(n) return } if k.MatchString("right", "tab") && n.step < len(req.Questions) && len(req.Questions) > 1 { if n.answered[n.step] { move(&n, n.step+1) } else { n.err = "Answer this question before continuing." } update(n) return } if n.step == len(req.Questions) { if k.MatchString("enter") { for i, answered := range n.answered { if !answered { move(&n, i) n.err = "Answer this question before submitting." update(n) return } } submit(n, false) } return } q := req.Questions[n.step] rows := len(q.Options) + 1 if q.Type == string(api.QuestionTypeConfirm) { rows = 2 } if next, ok := components.StepCursor(n.cursor, rows, k); ok { n.cursor = next update(n) return } switch { case q.Type == string(api.QuestionTypeMulti) && (input == " " || k.MatchString("space")): if n.cursor == len(q.Options) { n.editing, n.input = true, n.answers[n.step].Text } else { id := q.Options[n.cursor].ID selected := slices.Clone(n.answers[n.step].Selected) if slices.Contains(selected, id) { selected = slices.DeleteFunc(selected, func(s string) bool { return s == id }) } else { selected = append(selected, id) } n.answers[n.step].Selected = selected } n.err = "" update(n) case k.MatchString("enter"): if q.Type == string(api.QuestionTypeConfirm) { n.answers[n.step].Confirmed = new(n.cursor == 0) advance(n) } else if q.Type == string(api.QuestionTypeSingle) { if n.cursor == len(q.Options) { n.editing, n.input = true, n.answers[n.step].Text update(n) } else { n.answers[n.step].Selected = []string{q.Options[n.cursor].ID} n.answers[n.step].Text = "" advance(n) } } else if q.Type == string(api.QuestionTypeMulti) { if n.cursor == len(q.Options) { n.editing, n.input = true, n.answers[n.step].Text update(n) } else if len(n.answers[n.step].Selected) == 0 && strings.TrimSpace(n.answers[n.step].Text) == "" { n.err = "Select at least one option or enter a custom answer." update(n) } else { advance(n) } } } }) primary := style.S().Foreground(scheme.Color.Text.Primary).WhiteSpace(style.WhiteSpacePreWrap).OverflowWrap(style.OverflowWrapAnywhere) secondary := style.S().Foreground(scheme.Color.Text.Secondary).WhiteSpace(style.WhiteSpacePreWrap).OverflowWrap(style.OverflowWrapAnywhere) answerStyle := primary.Bold(true) titleStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary).WhiteSpace(style.WhiteSpacePreWrap) activeTabStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary).WhiteSpace(style.WhiteSpacePre) inactiveTabStyle := style.S().Foreground(scheme.Color.Text.Secondary).WhiteSpace(style.WhiteSpacePre) line := func(text string, s style.Style) trail.Node { return trail.Box(trail.BoxProps{Style: style.S().Width(style.Percent(100))}, trail.Span(trail.SpanProps{Style: s}, trail.Text(text))) } var children []trail.Node title := req.Title if title == "" { title = "Question" } children = append(children, line(title, titleStyle)) if req.Description != "" { children = append(children, line(req.Description, secondary)) } if len(req.Questions) > 1 { var tabs []trail.Node for i, q := range req.Questions { if i > 0 { tabs = append(tabs, trail.Span(trail.SpanProps{Style: inactiveTabStyle}, trail.Text(" "))) } label := fmt.Sprintf("%d %s", i+1, questionLabel(q)) tabStyle := inactiveTabStyle if i == f.step { label = "[" + label + "]" tabStyle = activeTabStyle } tabs = append(tabs, trail.Span(trail.SpanProps{Style: tabStyle}, trail.Text(label))) } review, reviewStyle := "Review", inactiveTabStyle if f.step == len(req.Questions) { review, reviewStyle = "[Review]", activeTabStyle } tabs = append(tabs, trail.Span(trail.SpanProps{Style: inactiveTabStyle}, trail.Text(" ")), trail.Span(trail.SpanProps{Style: reviewStyle}, trail.Text(review))) children = append(children, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)).MarginTop(1)}, tabs...)) } children = append(children, trail.Newline(1)) if f.step == len(req.Questions) { children = append(children, line("Review your answers", titleStyle), trail.Newline(1)) for i, q := range req.Questions { children = append(children, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100))}, trail.Span(trail.SpanProps{Style: secondary}, trail.Text(questionLabel(q)+": ")), trail.Span(trail.SpanProps{Style: answerStyle}, trail.Text(questionAnswerText(q, f.answers[i]))), )) } children = append(children, trail.Newline(1), line("❯ Submit answers", answerStyle)) } else { q := req.Questions[f.step] children = append(children, line(q.Question, titleStyle), line(q.Description, secondary), trail.Newline(1)) if q.Type == string(api.QuestionTypeSingle) || q.Type == string(api.QuestionTypeMulti) || q.Type == string(api.QuestionTypeConfirm) { options := q.Options if q.Type == string(api.QuestionTypeConfirm) { options = []api.QuestionOption{{Label: "Yes"}, {Label: "No"}} } else { options = append(slices.Clone(options), api.QuestionOption{Label: "Other — type an answer"}) } for i, opt := range options { prefix := " " if i == f.cursor { prefix = "❯ " } mark := "○ " if q.Type == string(api.QuestionTypeMulti) { mark = "[ ] " if i < len(q.Options) && slices.Contains(f.answers[f.step].Selected, opt.ID) || i == len(q.Options) && f.answers[f.step].Text != "" { mark = "[x] " } } else if i < len(q.Options) && slices.Contains(f.answers[f.step].Selected, opt.ID) || i == len(q.Options) && q.Type == string(api.QuestionTypeSingle) && f.answers[f.step].Text != "" { mark = "● " } children = append(children, line(prefix+mark+opt.Label, answerStyle)) if opt.Description != "" { children = append(children, line(" "+opt.Description, secondary)) } } } if f.editing && !f.canceling { children = append(children, trail.Box(trail.BoxProps{Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100))}, trail.Span(trail.SpanProps{Style: primary}, trail.Text("Answer: ")), kitex.Input(kitex.InputProps{Ref: inputRef, Value: f.input, Style: answerStyle.Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { n := form() n.input = ie.Value setForm(n) } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { switch { case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() commitInput() case ke.MatchString("tab") && !ke.MatchString("shift+tab") && q.Type == string(api.QuestionTypeText) && len(req.Questions) > 1: e.PreventDefault() e.StopPropagation() n := clone() if strings.TrimSpace(n.input) == "" { n.err = "Enter an answer." } else { n.answers[n.step].Text = strings.TrimSpace(n.input) n.answered[n.step] = true move(&n, n.step+1) if n.step == len(req.Questions) { for i, answered := range n.answered { if !answered { move(&n, i) n.err = "Answer this question before continuing." break } } } } setForm(n) case ke.MatchString("shift+tab") && q.Type == string(api.QuestionTypeText) && f.step > 0: e.PreventDefault() e.StopPropagation() n := clone() n.answers[n.step].Text = n.input move(&n, n.step-1) setForm(n) case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() n := form() if q.Type == string(api.QuestionTypeText) { n.canceling = true } else { n.editing = false } setForm(n) } } }, }), )) } } if f.canceling { children = append(children, line("Cancel this question? y/enter: yes n/esc: no", titleStyle)) } if f.submitting { children = append(children, line("Submitting…", secondary)) } if f.err != "" { children = append(children, line(f.err, style.S().Foreground(scheme.Color.Text.Error))) } if !f.submitting && !f.canceling { bindings := []components.KeyBinding{{Key: "↑/↓", Label: "Navigate"}, {Key: "enter", Label: "Next"}, {Key: "esc", Label: "Cancel"}} if f.step < len(req.Questions) && req.Questions[f.step].Type == string(api.QuestionTypeMulti) { bindings = append(bindings, components.KeyBinding{Key: "space", Label: "Toggle"}) } if len(req.Questions) > 1 { backKey := "←/→" if f.editing && req.Questions[f.step].Type == string(api.QuestionTypeText) { backKey = "shift+tab/tab" } bindings = append(bindings, components.KeyBinding{Key: backKey, Label: "Questions"}) } children = append(children, components.KeyboardHint(components.KeyboardHintProps{Bindings: bindings})) } return trail.Box(trail.BoxProps{Style: style.S().Border(style.RoundedBorder().Color(scheme.Color.Border.Default)).Padding(0, 1).Width(style.Percent(100)).FlexDirection(style.FlexColumn)}, children...) })
var Queue = trail.SimpleFC("Queue", func() trail.Node { queuePtr := store.UseStream(func(s store.StreamState) *[]api.QueueItem { return s.Queue }) if queuePtr == nil || len(*queuePtr) == 0 { return nil } items := *queuePtr scheme := theme.UseTheme() queuedColor := scheme.Color.Transcript.QueuedText rows := make([]trail.Node, 0, len(items)) for _, item := range items { if item.Kind == api.QueueKindTask || item.Kind == api.QueueKindSubagent { continue } txt := queueItemText(item) if txt == "" { continue } prefix := "> " if item.Kind == api.QueueKindCommand { prefix = "! " } rowStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). Foreground(queuedColor) prefixStyle := style.S(). Bold(true). WhiteSpace(style.WhiteSpaceNoWrap). Flex(0, 0). Foreground(queuedColor) textStyle := style.S(). Foreground(queuedColor) rows = append(rows, trail.Box(trail.BoxProps{ Style: rowStyle, Key: item.ID, }, trail.Span(trail.SpanProps{Style: prefixStyle}, trail.Text(prefix)), trail.Span(trail.SpanProps{Style: textStyle}, trail.Text(txt)), )) } if len(rows) == 0 { return nil } return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)). MarginBottom(1), }, rows...) })
Queue renders the list of queued user messages and commands pending execution.
var RemoveToolWidget = trail.FC("RemoveToolWidget", func(props RemoveToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.RemoveInput](tool.Call) output := parseToolOutput[api.RemoveOutput](tool.Response) path := input.Path if output.Path != "" { path = output.Path } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Removing" if tool.Status == store.ToolSucceeded || failed { verb = "Removed" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := path != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { headerNodes = append(headerNodes, renderPathNodes(path, false, scheme)...) } if tool.Response != nil && !tool.Response.IsError { headerNodes = append(headerNodes, renderDiffStatNodes(0, output.Deletions, 0, scheme)...) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var SandboxConfigEditor = trail.FC("SandboxConfigEditor", func(props SandboxConfigEditorProps) trail.Node { scheme := theme.UseTheme() winSize := trail.UseWindowSize() tab, setTab := kitex.UseState(sandboxTabPolicy) scopeIndex, setScopeIndex := kitex.UseState(0) offset, setOffset := kitex.UseState(0) inInput, setInInput := kitex.UseState(false) editing, setEditing := kitex.UseState("") inputText, setInputText := kitex.UseState("") localError, setLocalError := kitex.UseState("") inputRef := kitex.UseRef[dom.Element](nil) trail.UseFocus(inputRef, trail.FocusOptions{ AutoFocus: true, IsActive: inInput(), }) activeScope := api.ScopeProject scopeTitle := "Project" scopeSettings := props.Response.Project if scopeIndex() == 1 { activeScope = api.ScopeGlobal scopeTitle = "Global" scopeSettings = props.Response.Global } avail := props.Response.Availability excluded := scopeSettings.ExcludedCommands inherited := props.Response.Global.ExcludedCommands activeLocked := props.LockedKnobs[activeScope] effExclusionsOff := knobValue(props.Response.Effective, KnobAllowUnsandboxed) != nil && !*knobValue(props.Response.Effective, KnobAllowUnsandboxed) policyRows := sandboxPolicyRows() maxRows := len(policyRows) if tab() == sandboxTabExcluded { maxRows = len(excluded) } cursor := components.UseCursor(maxRows, 0) cur := cursor.Index var resolvedContent []sandboxLine if tab() == sandboxTabResolved { resolvedContent = resolvedLines(props.Response) } const reserved = 7 viewport := 22 if winSize.Height > 0 { viewport = max(winSize.Height-reserved, 4) } maxOffset := max(0, len(resolvedContent)-viewport) pos := min(offset(), maxOffset) clearError := func() { setLocalError("") if props.OnClearError != nil { props.OnClearError() } } trail.UseInput(func(input string, k event.KeyEvent) { if inInput() { return } switch { case k.MatchString("shift+tab"), k.MatchString("left"): if tab() > sandboxTabPolicy { setTab(tab() - 1) } else { setTab(sandboxTabResolved) } cursor.Set(0) setOffset(0) clearError() case k.MatchString("tab", "right"): if tab() < sandboxTabResolved { setTab(tab() + 1) } else { setTab(sandboxTabPolicy) } cursor.Set(0) setOffset(0) clearError() case k.MatchString("1"): setTab(sandboxTabPolicy) cursor.Set(0) setOffset(0) clearError() case k.MatchString("2"): setTab(sandboxTabExcluded) cursor.Set(0) setOffset(0) clearError() case k.MatchString("3"): setTab(sandboxTabResolved) cursor.Set(0) setOffset(0) clearError() case tab() != sandboxTabResolved && k.MatchString("s"): if scopeIndex() == 0 { setScopeIndex(1) } else { setScopeIndex(0) } cursor.Set(0) clearError() case k.MatchString("up", "k", "ctrl+p"): if tab() == sandboxTabResolved { setOffset(max(0, pos-1)) } else { cursor.HandleKey(k) } case k.MatchString("down", "j", "ctrl+n"): if tab() == sandboxTabResolved { setOffset(min(maxOffset, pos+1)) } else { cursor.HandleKey(k) } case tab() == sandboxTabResolved && k.MatchString("pgup"): setOffset(max(0, pos-viewport)) case tab() == sandboxTabResolved && k.MatchString("pgdown", "space"): setOffset(min(maxOffset, pos+viewport)) case tab() == sandboxTabResolved && input == "g": setOffset(0) case tab() == sandboxTabResolved && input == "G": setOffset(maxOffset) case k.MatchString("esc", "escape"): if props.OnClose != nil { props.OnClose() } } switch tab() { case sandboxTabPolicy: switch { case k.MatchString("enter", "t", "space"): if cur < 0 || cur >= len(policyRows) { return } row := policyRows[cur] if row.knob == "" { if props.OnSetMode != nil { props.OnSetMode(activeScope, nextSandboxMode(scopeSettings.Mode, props.Response.Effective.Mode)) } return } if activeLocked[row.knob] != "" || props.OnToggleKnob == nil { return } base := knobValue(scopeSettings, row.knob) if base == nil { base = knobValue(props.Response.Effective, row.knob) } if base != nil { next := !*base props.OnToggleKnob(activeScope, row.knob, &next) } case input == "x" || input == "X" || k.MatchString("x", "backspace", "delete"): if cur < 0 || cur >= len(policyRows) { return } row := policyRows[cur] if row.knob == "" { if props.OnSetMode != nil { props.OnSetMode(activeScope, "") } return } if activeLocked[row.knob] == "" && props.OnToggleKnob != nil { props.OnToggleKnob(activeScope, row.knob, nil) } } case sandboxTabExcluded: switch { case input == "a" || input == "A" || k.MatchString("a"): setEditing("") setInInput(true) setInputText("") clearError() case input == "e" || input == "E" || k.MatchString("e"): if len(excluded) > 0 && cur < len(excluded) { setEditing(excluded[cur]) setInInput(true) setInputText(excluded[cur]) clearError() } case input == "d" || input == "D" || k.MatchString("d", "backspace", "delete"): if len(excluded) > 0 && cur < len(excluded) && props.OnRemoveExcluded != nil { props.OnRemoveExcluded(activeScope, excluded[cur]) } } } }) border := style.SingleBorder().Top(true).Bottom(false).Left(false).Right(false).Color(scheme.Color.Border.Default) titleStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary) barStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) primaryStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Primary) textPrimaryStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Primary) secondaryStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) mutedStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Muted) accentStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Accent) textSuccessStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Success) textWarnStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Warning) textErrorStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Error) errorStyle := style.S().Foreground(scheme.Color.Text.Error) successStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Success) warnStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Warning) wrapStyle := style.S().Foreground(scheme.Color.Text.Muted).OverflowWrap(style.OverflowWrapAnywhere) var contentWidth int if winSize.Width > 0 { contentWidth = max(winSize.Width-6, 24) } truncate := func(s string) string { if contentWidth <= 0 { return s } out, _ := strutils.TruncateLine(s, contentWidth, "…") return out } row := func(st style.Style, text string) trail.Node { if text == "" { text = " " } return trail.Box(trail.BoxProps{}, trail.Span(trail.SpanProps{Style: st}, trail.Text(truncate(text)))) } var children []trail.Node tabsText, metaText := sandboxTabStrip(tab(), scopeTitle, len(excluded), props.Saving) barChildren := []trail.Node{ trail.Span(trail.SpanProps{Style: barStyle.Flex(0, 0)}, trail.Text(truncate(tabsText))), } if metaText != "" { barChildren = append(barChildren, trail.Span(trail.SpanProps{Style: barStyle.Flex(0, 0)}, trail.Text(truncate(metaText))), ) } children = append(children, row(titleStyle, "Sandbox"), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). FlexWrap(style.FlexWrapOn). Gap(0, 4). Width(style.Percent(100)), }, barChildren...), row(mutedStyle, ""), ) switch tab() { case sandboxTabPolicy: children = append(children, policyTabNodes(policyTabParams{ scopeTitle: scopeTitle, scopeSettings: scopeSettings, effective: props.Response.Effective, sessionMode: props.SessionMode, availability: avail, restricted: props.Response.Restricted, locked: activeLocked, cursor: cur, styles: editorStyles{ primary: primaryStyle, secondary: secondaryStyle, muted: mutedStyle, success: successStyle, warn: warnStyle, }, row: row, wrapColumn: func(text string, indent int) trail.Node { return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).Width(style.Percent(100)).PaddingLeft(indent), }, trail.Span(trail.SpanProps{Style: wrapStyle}, trail.Text(text))) }, })...) case sandboxTabExcluded: listHeight := max(winSize.Height-12, 5) start, end := windowIndex(cur, len(excluded), listHeight) children = append(children, excludedTabNodes(excludedTabParams{ scopeTitle: scopeTitle, excluded: excluded, inherited: inherited, showInherit: activeScope == api.ScopeProject && len(inherited) > 0, cursor: cur, start: start, end: end, warnOff: effExclusionsOff, styles: editorStyles{ primary: primaryStyle, secondary: secondaryStyle, muted: mutedStyle, warn: warnStyle, }, row: row, })...) case sandboxTabResolved: children = append(children, resolvedTabNodes(resolvedTabParams{ lines: resolvedContent, pos: pos, end: min(len(resolvedContent), pos+viewport), total: len(resolvedContent), contentWidth: contentWidth, styles: resolvedStyles{ heading: primaryStyle, primaryText: textPrimaryStyle, secondary: secondaryStyle, muted: mutedStyle, accent: accentStyle, success: textSuccessStyle, warn: textWarnStyle, danger: textErrorStyle, }, row: row, })...) } errText := localError() if errText == "" && props.ErrorMessage != "" { errText = props.ErrorMessage } if errText != "" { children = append(children, row(errorStyle, errText)) } if inInput() { inputTitle := fmt.Sprintf("Add excluded command pattern (%s):", scopeTitle) if editing() != "" { inputTitle = fmt.Sprintf("Edit excluded command pattern (%s):", scopeTitle) } children = append(children, trail.Box(trail.BoxProps{}, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text(inputTitle))), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). AlignItems(style.AlignCenter). Width(style.Percent(100)), }, trail.Span(trail.SpanProps{Style: primaryStyle}, trail.Text("❯ ")), kitex.Input(kitex.InputProps{ Ref: inputRef, Value: inputText(), Style: style.S().Flex(1), OnChange: func(e event.Event) { if ie, ok := e.(*event.InputEvent); ok { setInputText(ie.Value) if localError() != "" { setLocalError("") } } }, OnKeyDown: func(e event.Event) { if ke, ok := e.(*event.KeyEvent); ok { switch { case ke.MatchString("enter"): e.PreventDefault() e.StopPropagation() pattern := strings.TrimSpace(inputText()) if pattern == "" { setLocalError("Pattern must not be empty") return } if strings.ContainsAny(pattern, "\n\r") { setLocalError("Pattern must be a single line") return } if editing() != "" { if pattern != editing() { if containsPattern(excluded, pattern) { setLocalError("Another exclusion already uses that pattern") return } if props.OnEditExcluded != nil { props.OnEditExcluded(activeScope, editing(), pattern) } } } else { if containsPattern(excluded, pattern) { setLocalError("That pattern is already excluded") return } if props.OnAddExcluded != nil { props.OnAddExcluded(activeScope, pattern) } } setInInput(false) setEditing("") setInputText("") case ke.MatchString("esc", "escape"): e.PreventDefault() e.StopPropagation() clearError() setInInput(false) setEditing("") setInputText("") } } }, }), ), trail.Box(trail.BoxProps{}, trail.Span(trail.SpanProps{Style: mutedStyle}, trail.Text("Examples: git commit *, docker build *, make release"))), components.KeyboardHint(components.KeyboardHintProps{Bindings: []components.KeyBinding{ {Key: "enter", Label: "Save"}, {Key: "esc", Label: "Cancel"}, }}), ) } else { var bindings []components.KeyBinding switch tab() { case sandboxTabPolicy: bindings = []components.KeyBinding{ {Key: "←/→", Label: "Tab"}, {Key: "s", Label: "Scope"}, {Key: "↑/↓", Label: "Move"}, {Key: "space", Label: "Toggle"}, {Key: "x", Label: "Reset"}, {Key: "esc", Label: "Close"}, } case sandboxTabExcluded: bindings = []components.KeyBinding{ {Key: "←/→", Label: "Tab"}, {Key: "s", Label: "Scope"}, {Key: "↑/↓", Label: "Move"}, {Key: "a", Label: "Add"}, {Key: "e", Label: "Edit"}, {Key: "d", Label: "Delete"}, {Key: "esc", Label: "Close"}, } case sandboxTabResolved: bindings = []components.KeyBinding{ {Key: "←/→", Label: "Tab"}, {Key: "↑/↓", Label: "Scroll"}, {Key: "pgup/pgdn", Label: "Page"}, {Key: "esc", Label: "Close"}, } } children = append(children, components.KeyboardHint(components.KeyboardHintProps{Bindings: bindings})) } return trail.Box(trail.BoxProps{ Style: style.S(). Border(border). Width(style.Percent(100)). FlexDirection(style.FlexColumn), }, children...) })
SandboxConfigEditor is a 3-tab interactive sandbox.json configuration manager.
var Slot = trail.SimpleFC("Slot", func() trail.Node { active := store.UseActiveSlot() mode := store.UseMode() if active == nil { return nil } var child trail.Node switch active.Kind { case store.SlotKindPermission: if p, ok := active.Data.(PermissionPromptProps); ok { child = PermissionPrompt(p) } else if req, ok := active.Data.(api.PermissionRequest); ok { props := PermissionPromptProps{ Request: req, OnDecision: store.DecidePermission, } if req.Action == api.ActionWrite && req.Safety != api.SafetyUnsafe && !req.BypassSandbox && mode != api.ModeAcceptEdits && mode != api.ModeAuto { props.OnAcceptEdits = store.ApprovePermissionAndAcceptEdits } child = PermissionPrompt(props) } case store.SlotKindQuestion: if props, ok := active.Data.(QuestionPromptProps); ok { child = QuestionPrompt(props) } else if req, ok := active.Data.(api.QuestionRequest); ok { child = QuestionPrompt(QuestionPromptProps{Request: req, OnSubmit: store.SubmitQuestion}) } case store.SlotKindPlanReview: if props, ok := active.Data.(PlanReviewPromptProps); ok { child = PlanReviewPrompt(props) } else if req, ok := active.Data.(api.PlanReviewRequest); ok { child = PlanReviewPrompt(PlanReviewPromptProps{Request: req, OnSubmit: store.SubmitPlanReview}) } case store.SlotKindPicker: switch v := active.Data.(type) { case PickerProps: origSelect := v.OnSelect v.OnSelect = func(opt uicomponents.Option) { store.RemoveSlot(active.ID) if origSelect != nil { origSelect(opt) } } origCancel := v.OnCancel v.OnCancel = func() { store.RemoveSlot(active.ID) if origCancel != nil { origCancel() } } child = Picker(v) case SlotComponent: child = v(active.ID) case func(slotID string) trail.Node: child = v(active.ID) case trail.Node: child = v } case store.SlotKindAutocomplete: child = nil case store.SlotKindModelSwitch: if req, ok := active.Data.(store.ModelSwitchRequest); ok { child = ModelSwitchPrompt(ModelSwitchPromptProps{ Request: req, OnForce: func() { store.RemoveSlot(active.ID) store.ForceSetModel(req.Model) }, OnCancel: func() { store.RemoveSlot(active.ID) store.AppendCommandOutput("/model "+req.Model, "Canceled model switch") }, }) } case store.SlotKindProviderReauth: if req, ok := active.Data.(store.ProviderReauthRequest); ok { child = ProviderReauthPrompt(ProviderReauthPromptProps{ Request: req, OnSignIn: func() { store.RemoveSlot(active.ID) store.LaunchProviderAuth(req.Provider) }, OnDismiss: func() { store.RemoveSlot(active.ID) }, }) } default: return nil } if child == nil { return nil } return trail.Box(trail.BoxProps{ Key: active.ID, Style: style.S(). FlexDirection(style.FlexColumn). Width(style.Percent(100)), }, child) })
Slot is the host component that renders the currently active slot item.
var Spinner = trail.FC("Spinner", func(props SpinnerProps) trail.Node { scheme := theme.UseTheme() frame, setFrame := kitex.UseState(0) kitex.UseInterval(func() { setFrame((frame() + 1) % len(SpinnerFrames)) }, 80*time.Millisecond, nil) var ( fgColor color.Color baseVerb string ) switch props.Status { case api.StatusCompacting: fgColor = scheme.Color.Agent.Thinking baseVerb = "Compacting" case api.StatusGenerating: fgColor = scheme.Color.Agent.Generating baseVerb = "Generating" case api.StatusExecuting: fgColor = scheme.Color.Agent.Executing baseVerb = "Executing" case api.StatusThinking: fgColor = scheme.Color.Agent.Thinking baseVerb = "Thinking" default: fgColor = scheme.Color.Agent.Thinking baseVerb = "Thinking" } var defaultText string if props.ActiveText != "" { defaultText = fmt.Sprintf("%s (%s)...", baseVerb, props.ActiveText) } else { defaultText = baseVerb + "..." } frameGlyph := SpinnerFrames[frame()%len(SpinnerFrames)] text := cmp.Or(props.Text, defaultText) children := []trail.Node{ trail.Span(trail.SpanProps{ Style: style.S().Foreground(fgColor).Bold(true), }, trail.Text(frameGlyph+" ")), trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(text)), } if stats := SpinnerStats(props.StartedAt, props.Input, props.Output, time.Now()); stats != "" { children = append(children, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text(" "+stats))) } return trail.Box(trail.BoxProps{}, children...) })
Spinner is a trail functional component rendering an animated braille spinner and status text.
var SpinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
SpinnerFrames defines the braille spinner glyph animation cycle.
var StandardModelAliases = []StandardModelAlias{
{"default", "Primary session & main agent model"},
{"fast", "Fast subagents: explore, title-generator"},
{"balanced", "General coding & subagent tier"},
{"smart", "Stronger reasoning, review & planning"},
{"flagship", "Frontier reasoning ceiling"},
}
StandardModelAliases are the built-in tiers listed in display order.
var StreamingHint = trail.FC("StreamingHint", func(props StreamingHintProps) trail.Node { hint := "streaming • esc to cancel" if props.Delegated { hint = "subagent running • esc to cancel" } store.UseHint(hint) return nil })
StreamingHint registers the streaming cancellation hint in the store while mounted. Delegated turns cancel a subagent rather than this session's own work, so the hint says whose work esc interrupts.
var SubagentAlert = trail.SimpleFC("SubagentAlert", func() trail.Node { if store.UseHasActiveSlot() { return nil } waiting := store.UseWaitingSubagents() if len(waiting) == 0 { return nil } sub := waiting[0] scheme := theme.UseTheme() title := strings.TrimSpace(strings.ReplaceAll(sub.Title, "\n", " ")) if title == "" { title = sub.ID } agentName := sub.Config.Agent if agentName == "" { agentName = "subagent" } agentColor := SubagentColor(scheme, agentName) border := style.SingleBorder().Top(false).Bottom(false).Right(false).Left(true).Color(scheme.Color.Border.Warning) containerStyle := style.S(). Border(border). PaddingLeft(1). MarginBottom(1). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)) headerStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). WhiteSpace(style.WhiteSpaceNoWrap) var lines []trail.Node moreWaiting := "" if len(waiting) > 1 { moreWaiting = fmt.Sprintf(" (+%d more waiting)", len(waiting)-1) } if len(sub.PendingPermissions) > 0 { req := sub.PendingPermissions[0] lines = append(lines, trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Warning), }, trail.Text("⚠ Subagent ")), trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(agentColor), }, trail.Text("@"+agentName)), trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Primary), }, trail.Text(fmt.Sprintf(" (%s) requires permission", title))), )) targetOrSummary := req.Target if targetOrSummary == "" { targetOrSummary = req.Summary } if targetOrSummary == "" { targetOrSummary = req.ID } toolLabel := req.ToolName if toolLabel == "" { toolLabel = "tool" } lines = append(lines, trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(toolLabel+" · "+targetOrSummary)), )) actionHint := "ctrl+y allow once • ctrl+g manage subagent" + moreWaiting lines = append(lines, trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(actionHint)), )) } else if len(sub.PendingQuestions) > 0 || sub.Status == api.StatusWaitingQuestion { lines = append(lines, trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Warning), }, trail.Text("⚠ Subagent ")), trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(agentColor), }, trail.Text("@"+agentName)), trail.Span(trail.SpanProps{ Style: style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Primary), }, trail.Text(fmt.Sprintf(" (%s) is waiting for an answer", title))), )) actionHint := "ctrl+g manage subagent" + moreWaiting lines = append(lines, trail.Box(trail.BoxProps{Style: headerStyle}, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text(actionHint)), )) } return trail.Box(trail.BoxProps{ Style: containerStyle, }, lines...) })
SubagentAlert renders a non-blocking alert banner above the composer when a child subagent requires user authorization or an answer to a question.
var SystemMessage = trail.FC("SystemMessage", func(props MessageProps) trail.Node { scheme := theme.UseTheme() parts := messageParts(props.Message) if len(parts) == 0 { return nil } rowStyle := messageStyle.FlexDirection(style.FlexRow).Foreground(scheme.Color.Text.Secondary) return trail.Box(trail.BoxProps{Key: props.Message.ID, Style: rowStyle}, trail.Span(trail.SpanProps{ Style: style.S().WhiteSpace(style.WhiteSpaceNoWrap).Flex(0, 0), }, trail.Text("[system] ")), trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexColumn).Flex(1, 1).MinWidth(style.Cells(0)), }, parts...), ) })
var Tasks = trail.SimpleFC("Tasks", func() trail.Node { hasActiveSlot := store.UseHasActiveSlot() runningSubs := store.UseRunningSubagents() runningTasks := store.UseRunningTasks() if hasActiveSlot || (len(runningSubs) == 0 && len(runningTasks) == 0) { return nil } return tasksBar(tasksBarProps{Subagents: runningSubs, Tasks: runningTasks}) })
Tasks renders an indicator list of active background tasks and running subagents.
var TasksToolWidget = trail.FC("TasksToolWidget", func(props TasksToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.TasksInput](tool.Call) output := parseToolOutput[api.TasksOutput](tool.Response) failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) isDone := tool.Status == store.ToolSucceeded || failed status := tool.Status if failed { status = store.ToolFailed } var verb string var target string var suffix string switch input.Action { case "list": verb = "Listing tasks" if isDone { verb = "Listed tasks" } if tool.Response != nil && !tool.Response.IsError { n := len(output.Tasks) if n == 1 { suffix = " (1 task)" } else { suffix = fmt.Sprintf(" (%d tasks)", n) } } case "status": verb = "Checking task" if isDone { verb = "Checked task" } target = input.TaskID if tool.Response != nil && !tool.Response.IsError && output.Status != "" { suffix = fmt.Sprintf(" (%s)", output.Status) } case "kill": verb = "Killing task" if isDone { verb = "Killed task" } target = input.TaskID if tool.Response != nil && !tool.Response.IsError && output.Status != "" { suffix = fmt.Sprintf(" (%s)", output.Status) } case "send_input": verb = "Sending input" if isDone { verb = "Sent input" } if input.TaskID != "" { target = "to " + input.TaskID } default: verb = "Managing tasks" if isDone { verb = "Managed tasks" } target = input.TaskID } hasTarget := target != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { targetSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(target)) headerNodes = append(headerNodes, targetSpan) } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var TerminalStatus = trail.SimpleFC("TerminalStatus", func() trail.Node { workspace := store.UseApp(func(s store.AppState) string { return s.Workspace }) onboardingActive := store.UseOnboarding(func(s store.OnboardingState) bool { return s.Active }) sessionTitle := store.UseSession(func(s store.SessionState) string { if s.Session == nil { return "" } return s.Session.Title }) activity := store.UseSession(func(s store.SessionState) string { if s.Session == nil { return "" } return s.Session.Activity }) stream := store.UseStream(func(s store.StreamState) streamKey { return streamKey{ Streaming: s.Streaming, WaitingPermission: s.WaitingPermission, WaitingQuestion: s.WaitingQuestion, WaitingPlanReview: s.WaitingPlanReview, TurnFailed: s.TurnFailed, } }) live := liveTerminalState(stream, onboardingActive) held, setHeld := kitex.UseState(stateIdle) display := live if held() != stateIdle && live == stateIdle { display = held() } titleText := terminalTitleText(sessionTitle, workspace) messageText := statusMessageText(display, activity) kind := terminal.ProgramStatusKind("") if display == stateBlocked { kind = blockedKind(stream, onboardingActive) } // The latest projection, readable from callbacks that outlive the render // that created them. type statusSnapshot struct { state terminalState title string message string kind terminal.ProgramStatusKind } current := kitex.UseRef(statusSnapshot{}) kitex.UseLayoutEffect(func() { current.Current = statusSnapshot{ state: display, title: titleText, message: messageText, kind: kind, } }, []any{display, titleText, messageText, kind}) getTerm := kitex.UseTerminal() _, setTitle := kitex.UseTitle(titleText) kitex.UseEffect(func() { setTitle(titleText) }, []any{titleText}) reportStatus := kitex.UseCallback(func() { term := getTerm() if term == nil { return } cur := current.Current term.SetProgressBar(progressBarState(cur.state), 0) term.SetProgramStatus(&terminal.ProgramStatus{ State: programState(cur.state), App: terminalAppName, Kind: cur.kind, Title: cur.title, Message: cur.message, }) }, []any{display, titleText, messageText, kind}) kitex.UseEffect(func() { reportStatus() }, []any{display, titleText, messageText, kind, reportStatus}) doc := kitex.UseDocument() kitex.UseEffectCleanup(func() func() { d := doc() if d == nil { return nil } sub := d.AddEventListener(event.EventProgramStatusSupport, func(event.Event) { kitex.PostMacro(reportStatus) }) return sub.Cancel }, []any{reportStatus}) wasBusy := kitex.UseRef(false) prevFailed := kitex.UseRef(false) kitex.UseEffect(func() { failed := stream.TurnFailed switch { case failed && !prevFailed.Current: setHeld(stateError) case live == stateIdle && wasBusy.Current: setHeld(stateDone) case live != stateIdle: setHeld(stateIdle) } prevFailed.Current = failed wasBusy.Current = live == stateWorking || live == stateBlocked || stream.Streaming }, []any{live, stream.TurnFailed}) kitex.UseTimeout(func() { if isHeldState(held()) { setHeld(stateIdle) } }, statusHold, []any{held()}) kitex.UseEffectCleanup(func() func() { term := getTerm() if term == nil { return nil } term.OnClose(func() { term.SetTitle("") term.SetProgressBar(terminal.ProgressBarHide, 0) term.SetProgramStatus(nil) }) return nil }, []any{}) return nil })
TerminalStatus is a headless component that mirrors the session's live state onto the terminal itself: the window/tab title (OSC 2), the native progress bar (OSC 9;4), and the Program Status Protocol (OSC 7501), so tabs, taskbars, and multiplexers show when TaskSmith is working, blocked on the user, done, or errored. It renders nothing, and every write is gated by the engine's terminal capability probe, so unsupported terminals see nothing at all.
var TimelineEvent = trail.FC("TimelineEvent", func(entry api.TimelineEntry) trail.Node { var text string switch entry.Kind { case api.TimelineKindCommand: if entry.Command != nil { return BashCommand(*entry.Command) } return nil case api.TimelineKindMode: if entry.Mode != nil && entry.Mode.To != "" { text = "Mode set to " + string(entry.Mode.To) } case api.TimelineKindModel: if entry.Model != nil && entry.Model.To != "" { text = "Model set to " + entry.Model.To } case api.TimelineKindEffort: if entry.Effort != nil && entry.Effort.To != "" { text = "Thinking effort set to " + entry.Effort.To } case api.TimelineKindThinking: if entry.Thinking != nil { value := entry.Thinking.To if value == nil { text = "Thinking reset to default" } else { switch value.Type { case "effort": text = "Thinking effort set to " + value.Effort case "budget", "budget_tokens": text = fmt.Sprintf("Thinking budget set to %d tokens", value.Budget) case "toggle": if value.Enabled { text = "Thinking enabled" } else { text = "Thinking disabled" } } } } case api.TimelineKindAgent: if entry.Agent != nil && entry.Agent.To != "" { text = "Agent set to " + entry.Agent.To } case api.TimelineKindPermission: if entry.Permission != nil && entry.Permission.Request.ToolName == "net" && entry.Permission.Review != nil { target := entry.Permission.Request.Target model := entry.Permission.Review.Model if model != "" { text = fmt.Sprintf("Host access auto-approved · %s (%s)", target, model) } else { text = fmt.Sprintf("Host access auto-approved · %s", target) } } case api.TimelineKindPlanReview: return nil case api.TimelineKindInterrupted: text = "Interrupted by user" case api.TimelineKindCompacted: if entry.Compacted != nil && entry.Compacted.BeforeTokens > 0 { text = fmt.Sprintf("Context compacted (%s → %s)", format.Tokens(entry.Compacted.BeforeTokens), format.Tokens(entry.Compacted.AfterTokens)) } else { text = "Context compacted" } return Notice(store.NoticeData{Text: text}) case api.TimelineKindTurnCompleted: if entry.TurnCompleted == nil { return nil } return Notice(store.NoticeData{Text: FormatTurnSummary(*entry.TurnCompleted, entry.ID, entry.CreatedAt)}) case api.TimelineKindCacheBroken: if entry.CacheBroken != nil { text = fmt.Sprintf("Prompt cache miss (%s → %s cached tokens)", format.Tokens(entry.CacheBroken.PrevCached), format.Tokens(entry.CacheBroken.CurrCached)) } else { text = "Prompt cache miss" } return Notice(store.NoticeData{Text: text}) case api.TimelineKindRule: if entry.Rule == nil { return nil } rec := entry.Rule switch rec.Trigger { case "glob": text = fmt.Sprintf("● Loaded Rule %s (matched %s)", rec.Rule, rec.Matched) case "tool": text = fmt.Sprintf("● Loaded Rule %s (tool: %s)", rec.Rule, rec.Matched) case "manual": text = fmt.Sprintf("● Loaded Rule %s (%s)", rec.Rule, rec.Matched) default: text = fmt.Sprintf("● Loaded Rule %s", rec.Rule) } return Notice(store.NoticeData{Text: text}) case api.TimelineKindForked: if entry.Forked == nil { return nil } rec := entry.Forked switch rec.Direction { case api.ForkDirectionInto: if rec.Title != "" { text = fmt.Sprintf("⑂ Forked into %q", rec.Title) } else { text = "⑂ Forked into a new session" } default: if rec.Title != "" { text = fmt.Sprintf("⑂ Forked from %q", rec.Title) } else { text = "⑂ Forked from another session" } } return Notice(store.NoticeData{Text: text}) default: text = "Timeline event: " + string(entry.Kind) } if text == "" { return nil } return Notice(store.NoticeData{Text: text}) })
TimelineEvent renders a timeline state change (mode, model, effort) as a notice.
var TodosToolWidget = trail.FC("TodosToolWidget", func(props TodosToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool status := tool.Status isDone := status == store.ToolSucceeded || status == store.ToolFailed input := parseToolInput[api.TodosInput](tool.Call) output := parseToolOutput[api.TodosOutput](tool.Response) verb := "Updating todos" if isDone { verb = "Updated todos" } done := output.Completed inProgress := output.InProgress pending := output.Pending if output.Total == 0 && len(input.Todos) > 0 { for _, item := range input.Todos { switch item.Status { case "completed": done++ case "in_progress": inProgress++ case "pending": pending++ } } } suffix := "" if done > 0 || inProgress > 0 || pending > 0 || output.Total > 0 || len(input.Todos) > 0 { suffix = fmt.Sprintf(" (%d done, %d in progress, %d pending)", done, inProgress, pending) } leading := toolHeaderLeading(status, verb, false, scheme) headerNodes := append([]trail.Node{}, leading...) if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var ToolDefaultWidget = trail.FC("ToolDefaultWidget", func(props ToolDefaultWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool name := tool.ID if tool.Call != nil { name = tool.Call.Name } else if tool.Response != nil && tool.Response.Name != "" { name = tool.Response.Name } verbs := [2]string{"Calling " + name, "Called " + name} failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := verbs[0] if tool.Status == store.ToolSucceeded || failed { verb = verbs[1] } status := tool.Status if failed { status = store.ToolFailed } arg := toolPrimaryArg(tool.Call) hasArg := arg != "" leading := toolHeaderLeading(status, verb, hasArg, scheme) headerNodes := append([]trail.Node{}, leading...) if hasArg { argSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 0). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Secondary), }, trail.Text("("+arg+")")) headerNodes = append(headerNodes, argSpan) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var ToolSearchToolWidget = trail.FC("ToolSearchToolWidget", func(props ToolSearchToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.ToolSearchInput](tool.Call) output := parseToolOutput[api.ToolSearchOutput](tool.Response) query := strings.TrimSpace(input.Query) completed := tool.Response != nil failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) status := tool.Status if failed { status = store.ToolFailed } matched := len(output.Tools) verb := "Searching tools" switch { case failed: verb = "Failed to search tools" case completed: verb = "Searched tools" } target := "" if query != "" { target = `"` + query + `"` } headerNodes := toolHeaderLeading(status, verb, target != "", scheme) if target != "" { headerNodes = append(headerNodes, trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). WhiteSpace(style.WhiteSpaceNoWrap). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Primary), }, trail.Text(target))) } var suffix string switch { case failed: case completed && matched == 0: suffix = " (no matches)" case completed: toolWord := fmt.Sprintf("%d tools", matched) if matched == 1 { toolWord = "1 tool" } suffix = " (" + toolWord + ": " + strings.Join(output.Tools, ", ") + ")" } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil && !failed { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
ToolSearchToolWidget reports how many deferred tools a tool_search call loaded, so a productive search is distinguishable from an empty one. The matched names ride along because a timeline row is immutable once it reaches scrollback, so there is no later view in which to expand them.
var Transcript = trail.SimpleFC("Transcript", func() trail.Node { app := trail.UseApp() liveHeader := store.UseHeaderData() epoch := store.UseTranscript(func(s store.TranscriptState) int { return s.Epoch }) frozen := store.UseTranscript(func(s store.TranscriptState) bool { return s.Frozen }) itemsPtr := store.UseTranscript(func(s store.TranscriptState) *[]store.TranscriptItem { return s.Items }) var items []store.TranscriptItem if itemsPtr != nil { items = *itemsPtr } width := trail.UseWindowSize().Width hasScrollback := frozen && len(items) > 0 lastWidth := kitex.UseRef(0) latest := kitex.UseRef(transcriptResizeSnapshot{}) latest.Current = transcriptResizeSnapshot{ width: width, epoch: epoch, hasScrollback: hasScrollback, } mounted := kitex.UseRef(true) kitex.UseEffectCleanup(func() func() { mounted.Current = true return func() { mounted.Current = false } }, []any{}) redrawGen, setRedrawGen := kitex.UseState(0) generation := transcriptGeneration{epoch, redrawGen()} cleared, setCleared := kitex.UseState(generation) kitex.UseLayoutEffect(func() { if generation == cleared() { return } lastWidth.Current = width if app != nil { app.Clear() app.Engine().Post(func() { setCleared(generation) }) } else { setCleared(generation) } }, []any{generation}) kitex.UseEffectCleanup(func() func() { if !hasScrollback || lastWidth.Current == 0 { lastWidth.Current = width return nil } if width <= 0 || width == lastWidth.Current || app == nil { return nil } eng := app.Engine() targetWidth := width targetEpoch := epoch cancelled := false stopTimer := afterTranscriptResize(transcriptResizeDebounce, func() { eng.Post(func() { if cancelled || !mounted.Current { return } cur := latest.Current if !cur.hasScrollback || cur.width != targetWidth || cur.epoch != targetEpoch || lastWidth.Current == targetWidth { return } setRedrawGen(redrawGen() + 1) }) }) return func() { cancelled = true stopTimer() } }, []any{width, hasScrollback, epoch}) var children []trail.Node if generation == cleared() { if !frozen { children = make([]trail.Node, 0, len(items)+1) children = append(children, Header(HeaderProps{HeaderData: liveHeader, AnimateMascot: true})) for i, item := range items { if n := renderTranscriptItem(item, i); n != nil { children = append(children, n) } } } else { if len(items) > 0 { children = []trail.Node{trail.Static(items, renderTranscriptItem)} } } } return trail.Box(trail.BoxProps{ Key: fmt.Sprintf("transcript-%d-%d", cleared().epoch, cleared().redraw), Style: style.S(). FlexDirection(style.FlexColumn). Width(style.Percent(100)), }, children...) })
Transcript is the host component that prints the header and finalized items. In draft mode (!Frozen), Header and draft command outputs remain live children. When Frozen, the snapshot Header and items are frozen into trail.Static and flushed into scrollback.
var TrustPrompt = trail.FC("TrustPrompt", func(props TrustPromptProps) trail.Node { scheme := theme.UseTheme() folderPath := props.Status.Path parentPath := filepath.Dir(folderPath) headerNodes := []trail.Node{ trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow).MarginBottom(0), }, trail.Span(trail.SpanProps{ Style: style.S().Bold(true).Foreground(scheme.Color.Text.Primary), }, trail.Text(folderPath)), ), ), } execs := props.Status.Executables if len(execs.MCPServers) > 0 || len(execs.CustomTools) > 0 || len(execs.Decisions) > 0 || execs.HasEnv { var execLines []trail.Node execLines = append(execLines, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Secondary), }, trail.Text("This project ships executable configuration:"))) if len(execs.MCPServers) > 0 { label := fmt.Sprintf(" ▸ %d MCP server(s) %s", len(execs.MCPServers), strings.Join(execs.MCPServers, ", ")) execLines = append(execLines, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text(label))) } if len(execs.CustomTools) > 0 { label := fmt.Sprintf(" ▸ %d custom tool(s) %s", len(execs.CustomTools), strings.Join(execs.CustomTools, ", ")) execLines = append(execLines, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text(label))) } if len(execs.Decisions) > 0 { label := fmt.Sprintf(" ▸ %d decision(s) %s", len(execs.Decisions), strings.Join(execs.Decisions, ", ")) execLines = append(execLines, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text(label))) } if execs.HasEnv { execLines = append(execLines, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text(" ▸ .env loaded into tool environments"))) } headerNodes = append(headerNodes, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, execLines...)) } else { headerNodes = append(headerNodes, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).MarginBottom(1), }, trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text("No project tools or MCP servers found.")), )) } header := trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn), }, headerNodes...) options := []uicomponents.Option{ { Value: string(TrustDecisionFolder), Label: "Trust this folder", Description: "Load project agents, tools, MCP servers and .env", }, { Value: string(TrustDecisionParent), Label: fmt.Sprintf("Trust all folders in %s", parentPath), Description: "Remember trust for every repo under the parent directory", }, { Value: string(TrustDecisionRestricted), Label: "Restricted mode", Description: "Read-only session. Project tools, MCP and .env are ignored", }, { Value: string(TrustDecisionExit), Label: "Exit", Description: "Quit without running TaskSmith", }, } pickerProps := PickerProps{ Title: "Do you trust the files in this folder?", Header: header, Bindings: []uicomponents.KeyBinding{ {Key: "↑/↓", Label: "navigate"}, {Key: "enter", Label: "select"}, {Key: "esc", Label: "exit"}, }, Options: options, OnSelect: func(opt uicomponents.Option) { if props.OnSelect != nil { props.OnSelect(TrustDecision(opt.Value)) } }, OnCancel: func() { if props.OnCancel != nil { props.OnCancel() } else if props.OnSelect != nil { props.OnSelect(TrustDecisionExit) } }, } return Picker(pickerProps) })
TrustPrompt renders the interactive repository trust gate matching section 4.1.
var UserMessage = trail.FC("UserMessage", func(props MessageProps) trail.Node { scheme := theme.UseTheme() parts := messageParts(props.Message) if len(parts) == 0 { return nil } rowStyle := messageStyle.FlexDirection(style.FlexRow).Bold(true).Foreground(scheme.Color.Icon.Primary) return trail.Box(trail.BoxProps{Key: props.Message.ID, Style: rowStyle}, trail.Span(trail.SpanProps{ Style: style.S().WhiteSpace(style.WhiteSpaceNoWrap).Flex(0, 0).Bold(true).Foreground(scheme.Color.Icon.Primary), }, trail.Text("> ")), trail.Box(trail.BoxProps{ Style: style.S().Display(style.DisplayFlex).FlexDirection(style.FlexColumn).Flex(1, 1).MinWidth(style.Cells(0)), }, parts...), ) })
var ViewToolWidget = trail.FC("ViewToolWidget", func(props ViewToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.ViewInput](tool.Call) output := parseToolOutput[api.ViewOutput](tool.Response) path := input.Path if output.Path != "" { path = output.Path } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Reading" if tool.Status == store.ToolSucceeded || failed { verb = "Read" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := path != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { headerNodes = append(headerNodes, renderPathNodes(path, false, scheme)...) } var suffix string if output.MimeType != "" { parts := []string{output.MimeType} if output.ByteSize > 0 { parts = append(parts, format.Bytes(output.ByteSize)) } if output.Pages != "" { parts = append(parts, "pages "+output.Pages) } if output.Omitted { parts = append(parts, "omitted") } suffix = " (" + strings.Join(parts, ", ") + ")" } else if output.StartLine > 0 && output.EndLine > 0 && output.TotalLines > 0 && (output.StartLine > 1 || output.EndLine < output.TotalLines) { suffix = fmt.Sprintf(" (lines %d-%d of %d)", output.StartLine, output.EndLine, output.TotalLines) } else if input.Offset > 0 && input.Limit > 0 { suffix = fmt.Sprintf(" (lines %d-%d)", input.Offset, input.Offset+input.Limit-1) } else if input.Offset > 0 { suffix = fmt.Sprintf(" (from line %d)", input.Offset) } else if input.Limit > 0 { suffix = fmt.Sprintf(" (first %d lines)", input.Limit) } else if output.TotalLines > 0 { suffix = fmt.Sprintf(" (%d lines)", output.TotalLines) } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } var warnSubline *toolSubline if toolErrorSubline(tool, scheme) == nil && output.Omitted && output.Content != "" { warnSubline = &toolSubline{ prefixColor: scheme.Color.Text.Warning, nodes: []trail.Node{ trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). WhiteSpace(style.WhiteSpacePre). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). Foreground(scheme.Color.Text.Warning), }, trail.Text(output.Content)), }, } } return wrapToolWidget(tool, scheme, headerNodes, warnSubline) })
var WebFetchToolWidget = trail.FC("WebFetchToolWidget", func(props WebFetchToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.WebFetchInput](tool.Call) output := parseToolOutput[api.WebFetchOutput](tool.Response) rawURL := input.URL if output.URL != "" { rawURL = output.URL } rawURL = strings.TrimSpace(rawURL) failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) || output.StatusCode >= 400 verb := "Fetching" if tool.Status == store.ToolSucceeded || failed { verb = "Fetched" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := rawURL != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { iconBox := trail.Span(trail.SpanProps{ Style: style.S().Flex(0, 0).WhiteSpace(style.WhiteSpacePre), }, icon.Globe, trail.Text(" ")) urlSpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(rawURL)) headerNodes = append(headerNodes, iconBox, urlSpan) } var suffix string if output.StatusCode > 0 { ct, _, _ := strings.Cut(output.ContentType, ";") ct = strings.TrimSpace(ct) if ct != "" { suffix = fmt.Sprintf(" (%d, %s)", output.StatusCode, ct) } else { suffix = fmt.Sprintf(" (%d)", output.StatusCode) } } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var WebSearchToolWidget = trail.FC("WebSearchToolWidget", func(props WebSearchToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.WebSearchInput](tool.Call) output := parseToolOutput[api.WebSearchOutput](tool.Response) query := strings.TrimSpace(input.Query) if output.Query != "" { query = strings.TrimSpace(output.Query) } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Searching" if tool.Status == store.ToolSucceeded || failed { verb = "Searched" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := query != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { iconBox := trail.Span(trail.SpanProps{ Style: style.S().Flex(0, 0).WhiteSpace(style.WhiteSpacePre), }, icon.Globe, trail.Text(" ")) querySpan := trail.Span(trail.SpanProps{ Style: style.S(). Flex(0, 1). MinWidth(style.Cells(0)). Overflow(style.OverflowHidden). TextOverflow(style.TextOverflowEllipsis). WhiteSpace(style.WhiteSpacePre). Foreground(scheme.Color.Text.Primary), }, trail.Text(query)) headerNodes = append(headerNodes, iconBox, querySpan) } var suffix string if tool.Response != nil && !tool.Response.IsError { suffix = fmt.Sprintf("(%d results)", len(output.Results)) } if suffixNode := renderSuffixSpan(suffix, scheme); suffixNode != nil { headerNodes = append(headerNodes, suffixNode) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
var WriteToolWidget = trail.FC("WriteToolWidget", func(props WriteToolWidgetProps) trail.Node { scheme := theme.UseTheme() tool := props.Tool input := parseToolInput[api.WriteInput](tool.Call) output := parseToolOutput[api.WriteOutput](tool.Response) path := input.Path if output.Path != "" { path = output.Path } failed := tool.Status == store.ToolFailed || (tool.Response != nil && tool.Response.IsError) verb := "Writing" if tool.Status == store.ToolSucceeded || failed { verb = "Wrote" } status := tool.Status if failed { status = store.ToolFailed } hasTarget := path != "" leading := toolHeaderLeading(status, verb, hasTarget, scheme) headerNodes := append([]trail.Node{}, leading...) if hasTarget { headerNodes = append(headerNodes, renderPathNodes(path, false, scheme)...) } if tool.Response != nil && !tool.Response.IsError { headerNodes = append(headerNodes, renderDiffStatNodes(output.Additions, output.Deletions, 0, scheme)...) } if stateSuffix := toolStateSuffix(tool.Status, scheme); stateSuffix != nil { headerNodes = append(headerNodes, stateSuffix) } return wrapToolWidget(tool, scheme, headerNodes) })
Functions ¶
func FormatTurnSummary ¶
FormatTurnSummary renders the one-line summary of a finished turn, for example "Smithed for 42s · ↑12.4k ↓1.8k · $0.03 · done 2:15 PM".
func IsStandardModelAlias ¶
IsStandardModelAlias reports whether alias names one built-in tier.
func LogoLines ¶
LogoLines returns the resting mascot rows paired with their per-row colors for callers rendering the mark outside the component tree, such as the post-REPL exit summary.
func NormalizeVersion ¶
NormalizeVersion ensures a version string starts with 'v' and defaults to build info or "v0.0.0-dev".
func OpenWarnings ¶
func OpenWarnings()
func PlanToolRenderer ¶
PlanToolRenderer renders enter_plan_mode and exit_plan_mode tool invocations.
func ProviderDisplayName ¶
func ShortenHomePath ¶
ShortenHomePath replaces a leading user home directory with "~".
func SpinnerStats ¶
SpinnerStats renders the elapsed time and token counts shown next to the spinner, for example "(12s · ↑12.4k ↓1.8k)". input and output are the tokens sent and received in the turn so far, summed across its calls; they are not the context size. It returns "" when there is nothing to show.
func SubagentColor ¶
SubagentColor deterministically picks a palette color for an agent persona.
Types ¶
type AlignedRow ¶
AlignedRow represents a single line in a unified diff layout.
type BashToolWidgetProps ¶
type ComposerProps ¶
type ComposerProps struct {
Disabled bool
OnSubmit func(text string, attachments []api.Attachment)
OnCycleMode func()
OnCancel func()
Autocomplete *autocomplete.Engine
CompletionViews map[string]uicomponents.AutocompleteView
}
ComposerProps defines the properties for the Composer functional component.
type ConfirmAction ¶
type ConfirmAction struct {
Prompt func(opt components.Option) string
DisabledReason func(opt components.Option) string
OnConfirm func(opt components.Option)
}
ConfirmAction defines an inline confirmation prompt triggered by a custom key.
type DownloadToolWidgetProps ¶
type DraftEdit ¶
type DraftEdit = uicomponents.AutocompleteEdit
DraftEdit holds the current draft value and cursor offset.
type EditToolWidgetProps ¶
type GlobToolWidgetProps ¶
type GrepToolWidgetProps ¶
type HeaderProps ¶
type HeaderProps struct {
store.HeaderData
AnimateMascot bool
}
type HistoryEntry ¶
type HistoryEntry struct {
Text string `json:"text"`
Attachments []api.Attachment `json:"attachments,omitempty"`
}
HistoryEntry holds a prompt's text and its structured attachments.
func (*HistoryEntry) UnmarshalJSON ¶
func (h *HistoryEntry) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshals either a rich HistoryEntry object or a legacy JSON string.
type InputAction ¶
type InputAction struct {
Prompt string
InitialValue func(opt components.Option) string
// DisabledReason optionally explains, per option, why the prompt must not
// open (e.g. the highlighted row is not editable). A non-empty reason
// surfaces as an inline notice instead of the input modal.
DisabledReason func(opt components.Option) string
OnSubmit func(opt components.Option, value string)
}
InputAction defines an inline text input prompt triggered by a custom key.
type LoadRuleToolWidgetProps ¶
type LsToolWidgetProps ¶
type MessageProps ¶
type MessageTextProps ¶
type MessageTextProps struct {
Text string
}
type MessageThoughtProps ¶
type MessageToolProps ¶
type ModelAliasEditorProps ¶
type ModelAliasEditorProps struct {
Provider string
// ModelID is the raw manifest model id (not the qualified "provider/model" form).
ModelID string
// ModelName is the display name shown in the header.
ModelName string
// ManifestPath is the home-shortened owning *.provider.yaml path.
ManifestPath string
// Scope is the owning provider's scope badge ("User" or "Workspace").
Scope string
// DefaultModel is the manifest's spec.defaultModels.completion value.
DefaultModel string
// Assignments is the live workspace-wide alias report. Loading renders the
// muted placeholder while the parent fetches it.
Assignments []api.AliasAssignment
Loading bool
Saving bool
// ErrorMessage renders inline when the parent's load or save failed.
ErrorMessage string
OnSave func(req api.AssignModelAliasesRequest)
OnCancel func()
}
ModelAliasEditorProps describes the target model whose aliases are edited. The card is presentational: the parent command loads assignments and performs the save, so /model and /providers share one editor and one daemon endpoint.
type ModelSwitchPromptProps ¶
type ModelSwitchPromptProps struct {
Request store.ModelSwitchRequest
OnForce func()
OnCancel func()
}
ModelSwitchPromptProps configures the capability-mismatch confirmation prompt shown in <Slot /> when switching models drops active session modalities.
type OnboardingWizardProps ¶
OnboardingWizardProps configures the interactive onboarding wizard.
type PermissionConfigEditorProps ¶
type PermissionConfigEditorProps struct {
Permissions api.PermissionsResponse
ErrorMessage string
OnAddRule func(scope api.PermissionScope, effect api.PermissionEffect, pattern string)
OnRemoveRule func(scope api.PermissionScope, effect api.PermissionEffect, pattern string)
OnEditRule func(scope api.PermissionScope, effect api.PermissionEffect, oldPattern, newPattern string)
OnClose func()
OnClearError func()
}
PermissionConfigEditorProps defines the properties for the PermissionConfigEditor component.
type PermissionPromptProps ¶
type PermissionPromptProps struct {
Request api.PermissionRequest
OnDecision func(req api.PermissionRequest, dec api.PermissionDecision)
OnAcceptEdits func(req api.PermissionRequest)
}
PermissionPromptProps defines the properties for the interactive PermissionPrompt component.
type PickerProps ¶
type PickerProps struct {
Title string
Subtitle string // Optional muted line under the title (e.g. an item count)
Header trail.Node
Options []components.Option
MaxVisible int // Max visible options before scrolling (defaults to components.DefaultPickerMaxVisible)
Columns []components.Column // Column specifications forwarded to OptionList
Bindings []components.KeyBinding // Optional navigation shortcuts rendered inline via KeyboardHint
// GroupLabel is forwarded to OptionList to render a muted heading whenever the
// grouping changes between adjacent options.
GroupLabel func(opt components.Option) string
Filterable bool
// FilterSafeKeys makes a filterable picker filter-first: single printable
// key bindings (letters, digits, and "space") never fire ConfirmActions,
// InputActions, or Keys while browsing, so every keystroke reaches the
// filter box. Bind function keys or chords (f2, ctrl+s) in that mode.
FilterSafeKeys bool
// Footer renders a muted one-line detail for the highlighted option below
// the list, e.g. a model description that would not fit in a row.
OnOpen func()
OnSelect func(opt components.Option)
Keys map[string]func(opt components.Option)
ConfirmActions map[string]ConfirmAction
InputActions map[string]InputAction
OnCancel func()
}
PickerProps defines the properties for the interactive Picker component.
func NewPicker ¶
func NewPicker(title string, opts []components.Option, onSelect func(opt components.Option)) PickerProps
NewPicker constructs an initialized PickerProps with default bindings and cursor at current.
type PlanReviewPromptProps ¶
type PlanReviewPromptProps struct {
Request api.PlanReviewRequest
OnSubmit func(api.PlanReviewRequest, api.PlanReviewDecision, func(error))
}
PlanReviewPromptProps defines the properties for the interactive plan review prompt opened when exit_plan_mode pauses a turn.
type PromptHistory ¶
type PromptHistory struct {
History []HistoryEntry
HistoryIdx int
Draft HistoryEntry
Browsing func() bool
Up func(current HistoryEntry) (HistoryEntry, bool)
Down func() (HistoryEntry, bool)
Add func(entry HistoryEntry)
Cancel func() HistoryEntry
Exit func(entry HistoryEntry)
}
PromptHistory holds state and operations for traversing input prompt history.
type ProviderReauthPromptProps ¶
type ProviderReauthPromptProps struct {
Request store.ProviderReauthRequest
OnSignIn func()
OnDismiss func()
}
ProviderReauthPromptProps configures the inline re-authentication prompt shown in <Slot /> when a turn fails because an OAuth provider session expired.
type QuestionPromptProps ¶
type QuestionPromptProps struct {
Request api.QuestionRequest
OnSubmit func(api.QuestionRequest, api.QuestionResponse, func(error))
}
type RemoveToolWidgetProps ¶
type SandboxConfigEditorProps ¶
type SandboxConfigEditorProps struct {
Response api.SandboxResponse
// SessionMode is the backend the active session actually runs under; the
// stored default mode only applies to sessions created after a change.
SessionMode api.SandboxMode
// LockedKnobs holds, per scope, the knobs the user cannot change from that
// scope because the opposite scope (or the workspace trust floor) already
// pins them via the monotonic merge rules. The scope a knob was set in is
// never locked to itself, and the Global scope is never locked at all, so
// a lock can always be undone where it was written.
LockedKnobs map[api.PermissionScope]map[SandboxPolicyKnob]string
// Saving marks an in-flight settings write; it renders inline in the tab
// strip so toggling never shifts rows vertically.
Saving bool
ErrorMessage string
// OnSetMode requests a new default backend for the scope ("" clears the
// override so the scope inherits).
OnSetMode func(scope api.PermissionScope, mode api.SandboxMode)
// OnToggleKnob requests setting one boolean posture knob; a nil value
// clears the override so the scope inherits again.
OnToggleKnob func(scope api.PermissionScope, knob SandboxPolicyKnob, value *bool)
// OnAddExcluded requests appending one excludedCommands pattern.
OnAddExcluded func(scope api.PermissionScope, pattern string)
// OnEditExcluded requests replacing one excludedCommands pattern in place.
OnEditExcluded func(scope api.PermissionScope, oldPattern, newPattern string)
// OnRemoveExcluded requests deleting one excludedCommands pattern.
OnRemoveExcluded func(scope api.PermissionScope, pattern string)
OnClose func()
OnClearError func()
}
SandboxConfigEditorProps defines the properties for the SandboxConfigEditor component.
type SandboxPolicyKnob ¶
type SandboxPolicyKnob string
SandboxPolicyKnob identifies one boolean sandbox.json posture toggle.
const ( KnobFailIfUnavailable SandboxPolicyKnob = "failIfUnavailable" // KnobAllowUnsandboxed toggles per-command unsandboxed execution. KnobAllowUnsandboxed SandboxPolicyKnob = "allowUnsandboxed" // KnobAutoAllowBash toggles auto-approval of safe sandboxed bash plans. KnobAutoAllowBash SandboxPolicyKnob = "autoAllowBash" )
type SlotComponent ¶
SlotComponent is a functional slot node generator parameterized by slotID.
type SpinnerProps ¶
type SpinnerProps struct {
Text string
Status api.SessionStatus
ActiveText string
// StartedAt is when the turn started; when set, the spinner shows the
// elapsed time. Input and Output are the tokens used by the turn so far
// and are shown with arrows when either is non-zero.
StartedAt time.Time
Input int64
Output int64
}
SpinnerProps defines the properties for the animated thinking spinner.
type StandardModelAlias ¶
StandardModelAlias is one built-in alias tier the editor always renders.
type StreamingHintProps ¶
type StreamingHintProps struct {
Delegated bool
}
StreamingHintProps defines the properties for the streaming cancellation hint.
type TasksToolWidgetProps ¶
type TodosToolWidgetProps ¶
type ToolDefaultWidgetProps ¶
type TrustDecision ¶
type TrustDecision string
TrustDecision represents the user's selected trust action.
const ( TrustDecisionFolder TrustDecision = "folder" TrustDecisionParent TrustDecision = "parent" TrustDecisionRestricted TrustDecision = "restricted" TrustDecisionExit TrustDecision = "exit" )
type TrustPromptProps ¶
type TrustPromptProps struct {
Status api.TrustStatus
OnSelect func(decision TrustDecision)
OnCancel func()
}
TrustPromptProps configures the interactive TrustPrompt component.
type ViewToolWidgetProps ¶
type WebFetchToolWidgetProps ¶
type WriteToolWidgetProps ¶
Source Files
¶
- active_stream.go
- changes.go
- composer.go
- context_usage.go
- daemon_alert.go
- doc.go
- header.go
- logo.go
- message.go
- message_part.go
- message_tools.go
- model_alias_editor.go
- model_switch_prompt.go
- notice.go
- onboarding.go
- permission_editor.go
- permission_prompt.go
- picker.go
- plan_review_prompt.go
- plan_tool.go
- provider_display.go
- provider_reauth_prompt.go
- question_prompt.go
- question_tool.go
- queue.go
- quota_clock.go
- rule_tool.go
- sandbox_editor.go
- skill_tool.go
- slot.go
- spinner.go
- status_line.go
- subagent_alert.go
- subagent_tool.go
- tasks.go
- terminal_status.go
- tool_search_tool.go
- transcript.go
- trust_prompt.go
- turn_summary.go
- warnings.go