command

package
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 39 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package command implements the REPL slash command system for the TaskSmith CLI. It defines a command registry, the built-in slash commands, and the interactive browser views that render inside the store's slot area, bridging the interactive CLI store and the daemon API client.

Command Registry

A Registry maintains the collection of Command values, each pairing a name (and optional aliases) with a Handler that runs when the command is invoked. NewRegistry returns a registry pre-populated with every built-in command. Registry.Register adds or replaces a command and indexes its name and aliases (normalized to lowercase with any leading "/" stripped), while Registry.Lookup resolves a command by its primary name or alias. Registry.Execute parses a raw slash command line, resolves it through Registry.Lookup, and invokes the matching handler with the remaining arguments; an unknown command or a command with no handler returns an error. Registry.List returns all registered commands in registration order.

Built-in Commands

NewRegistry registers the built-in commands, grouped by purpose:

  • System: /help, /mode, /model, /agent, /effort, /budget, /thinking, /theme, and /exit.
  • Session: /new, /clear, and /sessions.
  • Changes: /changes and /revert.
  • Permissions: /permissions.
  • Tasks: /tasks.
  • Context: /compact and /context.
  • Usage: /usage.
  • Skills: /skills.
  • Rules: /rules.
  • Tools: /tools.

Each command either mutates the store directly (for example /mode and /model) or enqueues an interactive browser into the store's slot area.

Interactive Browsers

Several commands render interactive, slot-scoped views built as trail functional components: ChangesBrowser, PermissionBrowser, SessionBrowser, SkillsBrowser, RulesBrowser, ToolsBrowser, TasksBrowser, ModelPicker, and AgentPicker. Each view is enqueued into the store, reads live data from the daemon client, and closes itself through the store when the user cancels.

Workspace Commands and Skills

Registry.RegisterWorkspace adapts workspace Command and Skill manifests (via Registry.RegisterCommandResource and Registry.RegisterSkillResource) into interactive slash commands. Executing one validates its declared arguments client-side and then forwards the reconstructed line to the store, so workspace commands and skills run through the same pipeline as user input. SkillScope and EstimateSkillTokens provide the canonical scope label and token estimate used to present skills.

Autocomplete

Registry.Sources snapshots the registered commands as headless autocomplete sources for the REPL, including per-command argument completers. CompletionViews returns command-specific completion views for the active permission mode.

Index

Constants

View Source
const (
	// MCPRefPrefix is the slash trigger for invoking an MCP prompt. It is
	// exported so the composer can tell an MCP prompt reference apart from a
	// slash command.
	MCPRefPrefix = "/mcp:"
)

mcpPromptRefPrefix and mcpResourceRefPrefix are the composer triggers for invoking an MCP prompt and attaching an MCP resource. The trigger character ("/" or "@") is consumed by the autocomplete engine, so candidate insert text starts at the body; parseMCPRef accepts both the full reference and the body.

Variables

View Source
var AgentPicker = trail.FC("AgentPicker", func(slotID string) trail.Node {
	c := store.Client()

	result := wind.Use("agents", promise.WrapWithProps(func(ctx context.Context, _ string) ([]api.Agent, error) {
		if c == nil {
			return nil, nil
		}
		return c.ListAgents(ctx)
	}), wind.Options{Enabled: c != nil})

	kitex.UseEffect(func() {
		if c == nil {
			store.RemoveSlot(slotID)
			store.AppendNotice("Client unavailable.")
			return
		}
		if result.IsLoading {
			return
		}
		if result.IsError {
			store.RemoveSlot(slotID)
			store.AppendError("Error", result.Error.Error())
		} else if len(result.Data) == 0 {
			store.RemoveSlot(slotID)
			store.AppendNotice("No agents available.")
		}
	}, []any{c == nil, result.IsLoading, result.IsError, result.Error, len(result.Data)})

	if c == nil {
		return nil
	}
	if result.IsLoading {
		return loadingHint("Loading agents...")
	}
	if result.IsError || len(result.Data) == 0 {
		return nil
	}

	currentAgent := store.GetSession().Config.Agent
	if store.GetSession().Session != nil {
		currentAgent = store.GetSession().Session.Config.Agent
	}

	opts := make([]uicomponents.Option, len(result.Data))
	for i, a := range result.Data {
		opts[i] = uicomponents.Option{
			Value:       a.Name,
			Label:       a.Name,
			Description: agentDescription(a),
			Current:     a.Name == currentAgent,
		}
	}

	picker := components.NewPicker("Select agent:", opts, func(opt uicomponents.Option) {
		store.RemoveSlot(slotID)
		for _, a := range result.Data {
			if a.Name == opt.Value {
				if !a.CanHumanTrigger() {
					store.AppendError("Error", fmt.Sprintf("Agent %q cannot be triggered by human (triggers: %s)", a.Name, strings.Join(a.Triggers, ", ")))
					return
				}
				break
			}
		}
		store.SetAgent(opt.Value)
	})
	picker.Filterable = true
	picker.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/agent", "Exited /agent command")
	}

	return components.Picker(picker)
})

AgentPicker renders an interactive agent picker querying daemon agents via wind.

View Source
var ChangesBrowser = trail.FC("ChangesBrowser", func(slotID string) trail.Node {
	sess := store.GetSession().Session
	c := store.Client()

	selectedChange, setSelectedChange := kitex.UseState[*api.FileChange](nil)
	changesState, setChangesState := kitex.UseState[[]api.FileChange](nil)
	isLoading, setIsLoading := kitex.UseState(true)
	errorState, setErrorState := kitex.UseState[error](nil)
	fetchCount, setFetchCount := kitex.UseState(0)

	sessID := ""
	if sess != nil {
		sessID = sess.ID
	}

	refetch := func() {
		setFetchCount(fetchCount() + 1)
	}

	kitex.UseEffectCleanup(func() func() {
		if sess == nil || sess.ID == "" || c == nil {
			setIsLoading(false)
			return nil
		}
		ctx, cancel := context.WithCancel(context.Background())
		setIsLoading(true)
		go func() {
			data, err := c.Changes(ctx, sess.ID)
			if ctx.Err() != nil {
				return
			}
			if err != nil {
				setErrorState(err)
			} else {
				setChangesState(data)
				setErrorState(nil)
			}
			setIsLoading(false)
		}()
		return cancel
	}, []any{sessID, fetchCount()})

	if sess == nil || sess.ID == "" {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/changes", "No active session.")
		return nil
	}
	if c == nil {
		store.RemoveSlot(slotID)
		store.AppendNotice("Client unavailable.")
		return nil
	}

	if sel := selectedChange(); sel != nil {
		return changeDiffViewer(changeDiffProps{
			sessionID: sess.ID,
			change:    sel,
			onClose: func() {
				setSelectedChange(nil)
			},
		})
	}

	if isLoading() {
		return loadingHint("Loading changes...")
	}
	if err := errorState(); err != nil {
		store.RemoveSlot(slotID)
		store.AppendError("Error", err.Error())
		return nil
	}

	aggregated := aggregateFileChanges(changesState())
	if len(aggregated) == 0 {
		return emptyChangesView(emptyChangesViewProps{slotID: slotID})
	}

	scheme := theme.UseTheme()
	opts := make([]uicomponents.Option, len(aggregated))
	for i, ch := range aggregated {
		stats := fmt.Sprintf("+%d/-%d", ch.Additions, ch.Deletions)
		statsNode := trail.Span(trail.SpanProps{
			Style: style.S().WhiteSpace(style.WhiteSpacePre),
		},
			trail.Span(trail.SpanProps{
				Style: style.S().Foreground(scheme.Color.Diff.AddedText),
			}, trail.Text(fmt.Sprintf("+%d", ch.Additions))),
			trail.Span(trail.SpanProps{
				Style: style.S().Foreground(scheme.Color.Text.Secondary),
			}, trail.Text("/")),
			trail.Span(trail.SpanProps{
				Style: style.S().Foreground(scheme.Color.Diff.RemovedText),
			}, trail.Text(fmt.Sprintf("-%d", ch.Deletions))),
		)
		opts[i] = uicomponents.Option{
			Value:     ch.Path,
			Label:     ch.Path,
			Cells:     []string{ch.Path, string(ch.Kind), stats},
			CellNodes: []trail.Node{nil, nil, statsNode},
		}
	}

	pickerProps := components.NewPicker("Tracked Changes", opts, func(opt uicomponents.Option) {
		for i := range aggregated {
			if aggregated[i].Path == opt.Value {
				ch := aggregated[i]
				setSelectedChange(&ch)
				break
			}
		}
	})
	pickerProps.Columns = []uicomponents.Column{
		{Width: 0},
		{Width: 16, Align: style.TextAlignLeft},
		{Width: 16, Align: style.TextAlignRight},
	}
	pickerProps.Filterable = true
	pickerProps.Bindings = []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "View diff"},
		{Key: "r", Label: "Revert"},
		{Key: "esc", Label: "Close"},
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
	}
	pickerProps.ConfirmActions = map[string]components.ConfirmAction{
		"r": {
			Prompt: func(opt uicomponents.Option) string {
				return fmt.Sprintf("Revert changes to %s?", opt.Label)
			},
			OnConfirm: func(opt uicomponents.Option) {
				go func() {
					err := c.Revert(context.Background(), sess.ID, api.RevertRequest{
						Path: opt.Value,
					})
					if err != nil {
						store.AppendError("Revert Error", err.Error())
						return
					}
					refetch()
				}()
			},
		},
	}

	return components.Picker(pickerProps)
})

ChangesBrowser renders an interactive changes list and inline diff viewer inside <Slot />.

View Source
var DaemonBrowser = trail.FC("DaemonBrowser", func(slotID string) trail.Node {
	status := store.UseDaemonStatus()
	health, setHealth := kitex.UseState[*api.HealthResponse](nil)
	inProgress, setInProgress := kitex.UseState(false)

	refreshHealth := func() {
		c := store.Client()
		if c == nil {
			setHealth(nil)
			return
		}
		go func() {
			ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
			defer cancel()
			h, err := c.Health(ctx)
			if err == nil {
				setHealth(h)
			} else {
				setHealth(nil)
			}
		}()
	}

	kitex.UseEffect(func() {
		c := store.Client()
		if c == nil {
			setHealth(nil)
			return
		}
		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
		defer cancel()
		h, err := c.Health(ctx)
		if err == nil {
			setHealth(h)
		} else {
			setHealth(nil)
		}
	}, []any{status})

	doStart := func() {
		if inProgress() {
			return
		}
		setInProgress(true)
		go func() {
			defer setInProgress(false)
			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			defer cancel()
			h, err := store.StartDaemon(ctx)
			if err == nil && h != nil {
				setHealth(h)
			} else {
				setHealth(nil)
			}
		}()
	}

	doRestart := func() {
		if inProgress() {
			return
		}
		setInProgress(true)
		go func() {
			defer setInProgress(false)
			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			defer cancel()
			h, err := store.RestartDaemon(ctx)
			if err == nil && h != nil {
				setHealth(h)
			} else {
				setHealth(nil)
			}
		}()
	}

	doStop := func() {
		if inProgress() {
			return
		}
		setInProgress(true)
		go func() {
			defer setInProgress(false)
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			_ = store.StopDaemon(ctx)
			setHealth(nil)
		}()
	}

	trail.UseInput(func(_ string, k event.KeyEvent) {
		switch {
		case k.MatchString("esc", "escape", "q"):
			store.RemoveSlot(slotID)
		case k.MatchString("g"):
			refreshHealth()
		case k.MatchString("r"):
			if status == store.DaemonDisconnected || health() == nil {
				doStart()
			} else {
				doRestart()
			}
		case k.MatchString("s"):
			if status == store.DaemonDisconnected || health() == nil {
				doStart()
			}
		case k.MatchString("x"):
			if status == store.DaemonConnected && health() != nil {
				doStop()
			}
		}
	})

	scheme := theme.UseTheme()
	border := style.SingleBorder().Top(true).Bottom(false).Left(false).Right(false).Color(scheme.Color.Border.Default)
	boxStyle := style.S().
		Border(border).
		Width(style.Percent(100)).
		FlexDirection(style.FlexColumn)

	titleStyle := style.S().Bold(true).Margin(0, 0, 1, 0).Foreground(scheme.Color.Text.Primary)

	sockPath := store.SocketPath()
	if sockPath == "" {
		if c := store.Client(); c != nil {
			sockPath = c.SocketPath()
		}
	}

	kvRow := func(label, value string, valColor color.Color) trail.Node {
		return trail.Box(trail.BoxProps{
			Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)),
		},
			trail.Span(trail.SpanProps{
				Style: style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary),
			}, trail.Text(label)),
			trail.Span(trail.SpanProps{
				Style: style.S().WhiteSpace(style.WhiteSpacePre).Foreground(valColor),
			}, trail.Text(value)),
		)
	}

	msgRow := func(msg string) trail.Node {
		return trail.Box(trail.BoxProps{
			Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)).Margin(0, 0, 1, 0),
		},
			trail.Span(trail.SpanProps{
				Style: style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary),
			}, trail.Text(msg)),
		)
	}

	var children []trail.Node
	children = append(children, trail.Span(trail.SpanProps{Style: titleStyle}, trail.Text("Brain Daemon")))

	h := health()
	isRestarting := status == store.DaemonRestarting || inProgress()

	if isRestarting {
		children = append(children,
			kvRow("  Status:      ", "↻ Restarting...", scheme.Color.Text.Warning),
			kvRow("  Socket:      ", sockPath, scheme.Color.Text.Primary),
			msgRow("  Stopping existing daemon and spawning a new background process..."),
			uicomponents.KeyboardHint(uicomponents.KeyboardHintProps{
				Bindings: []uicomponents.KeyBinding{
					{Key: "esc", Label: "Close"},
				},
			}),
		)
	} else if status == store.DaemonConnected && h != nil {
		durationStr := format.Duration(time.Since(h.StartedAt))
		timeStr := h.StartedAt.Format("2006-01-02 15:04:05")

		runningChildren := []trail.Node{
			kvRow("  Status:      ", "● Running", scheme.Color.Text.Success),
			kvRow("  Version:     ", daemonDisplayVersion(h), scheme.Color.Text.Primary),
			kvRow("  PID:         ", fmt.Sprintf("%d", h.PID), scheme.Color.Text.Primary),
			kvRow("  Uptime:      ", fmt.Sprintf("%s (started %s)", durationStr, timeStr), scheme.Color.Text.Primary),
			kvRow("  Socket:      ", sockPath, scheme.Color.Text.Primary),
			kvRow("  Workspaces:  ", fmt.Sprintf("%d active", len(h.Workspaces)), scheme.Color.Text.Primary),
		}

		for _, ws := range h.Workspaces {
			runningChildren = append(runningChildren, trail.Box(trail.BoxProps{
				Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)),
			},
				trail.Span(trail.SpanProps{
					Style: style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary),
				}, trail.Text(fmt.Sprintf("               • %s", ws))),
			))
		}

		runningChildren = append(runningChildren, uicomponents.KeyboardHint(uicomponents.KeyboardHintProps{
			Bindings: []uicomponents.KeyBinding{
				{Key: "r", Label: "Restart"},
				{Key: "x", Label: "Stop"},
				{Key: "g", Label: "Refresh"},
				{Key: "esc", Label: "Close"},
			},
		}))

		children = append(children, runningChildren...)
	} else {

		children = append(children,
			kvRow("  Status:      ", "○ Offline", scheme.Color.Text.Error),
			kvRow("  Socket:      ", sockPath, scheme.Color.Text.Primary),
			msgRow("  The background daemon is not running. Press s or r to start it."),
			uicomponents.KeyboardHint(uicomponents.KeyboardHintProps{
				Bindings: []uicomponents.KeyBinding{
					{Key: "s/r", Label: "Start"},
					{Key: "g", Label: "Refresh"},
					{Key: "esc", Label: "Close"},
				},
			}),
		)
	}

	return trail.Box(trail.BoxProps{Style: boxStyle}, children...)
})

DaemonBrowser renders an interactive view of daemon health and controls in <Slot />.

View Source
var ErrUnknownCommand = errors.New("unknown command")

ErrUnknownCommand reports a slash command no local handler owns. Callers forward such a line to the daemon, which resolves workspace commands, skills, and MCP prompts, so the TUI, exec, and ACP share one workflow surface.

View Source
var ModelPicker = trail.FC("ModelPicker", func(slotID string) trail.Node {
	c := store.Client()
	winSize := trail.UseWindowSize()

	currentModel := store.UseSession(store.SessionState.ActiveModelID)

	result := wind.Use("models", promise.WrapWithProps(func(ctx context.Context, _ string) ([]api.Model, error) {
		if c == nil {
			return nil, nil
		}
		return c.ListModels(ctx)
	}), wind.Options{Enabled: c != nil})
	windClient := wind.UseClient()

	aliasState, setAliasState := kitex.UseState[[]api.AliasAssignment](nil)
	showEditor, setShowEditor := kitex.UseState(false)
	editorTarget := kitex.UseRef[api.Model](api.Model{})
	kitex.UseEffect(func() {
		if c == nil {
			return
		}
		go func() {
			list, err := c.ListAliasAssignments(context.Background())
			if err == nil {
				setAliasState(list)
			}
		}()
	}, []any{c != nil})

	opts := modelPickerOptions(result.Data, currentModel)

	kitex.UseEffect(func() {
		if c == nil {
			store.RemoveSlot(slotID)
			store.AppendNotice("Client unavailable.")
			return
		}
		if result.IsLoading {
			return
		}
		switch {
		case result.IsError:
			store.RemoveSlot(slotID)
			store.AppendError("Error", result.Error.Error())
		case len(result.Data) == 0:
			store.RemoveSlot(slotID)
			store.AppendNotice("No models available.")
		case len(opts) == 0:
			store.RemoveSlot(slotID)
			store.AppendNotice("No chat-capable models available.")
		}
	}, []any{c == nil, result.IsLoading, result.IsError, result.Error, len(result.Data), len(opts)})

	if c == nil {
		return nil
	}
	if result.IsLoading {
		return loadingHint("Loading models...")
	}
	if result.IsError || len(result.Data) == 0 || len(opts) == 0 {
		return nil
	}

	if showEditor() && editorTarget.Current.Provider != "" {
		return modelAliasEditorSlot(modelAliasEditorSlotProps{
			ProviderName: editorTarget.Current.Provider,
			ModelID:      modelIDPart(editorTarget.Current.ID),
			ModelName:    firstNonEmpty(editorTarget.Current.Label, editorTarget.Current.Name),
			onDone: func(message string, err error) {
				setShowEditor(false)
				if err != nil {
					store.AppendError("Alias editor", err.Error())
					return
				}
				store.AppendCommandOutput("/model", message)
				refreshPickerAliases(c, setAliasState)

				if windClient != nil {
					windClient.InvalidateQueries("models")
				}
				refreshProviderWorkspaceContext(context.Background())
			},
			onCancel: func() { setShowEditor(false) },
		})
	}

	picker := components.NewPicker("Select model:", opts, func(opt uicomponents.Option) {
		store.RemoveSlot(slotID)
		store.SetModel(opt.Value)
	})
	picker.Filterable = true
	picker.Subtitle = modelAliasStatusLine(aliasState(), winSize.Width)
	picker.Columns = modelPickerColumns(opts, winSize.Width)
	picker.GroupLabel = modelPickerGroupLabel(result.Data)
	picker.Footer = modelPickerFooter(result.Data)
	picker.Bindings = append(slices.Clone(components.DefaultPickerBindings),
		uicomponents.KeyBinding{Key: "f2", Label: "Edit aliases"},
	)
	picker.Keys = map[string]func(uicomponents.Option){

		"f2": func(opt uicomponents.Option) {
			editorTarget.Current = api.Model{}
			for _, m := range result.Data {
				if m.ID == opt.Value {
					editorTarget.Current = m
					break
				}
			}
			if editorTarget.Current.Provider != "" {
				setShowEditor(true)
			}
		},
	}
	picker.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/model", "Exited /model command")
	}

	return components.Picker(picker)
})

ModelPicker renders an interactive model picker querying daemon models via wind.

View Source
var PermissionBrowser = trail.FC("PermissionBrowser", func(slotID string) trail.Node {
	c := store.Client()
	errMsg, setErrMsg := kitex.UseState("")

	permsQuery := wind.Use("permissions", promise.WrapWithProps(func(ctx context.Context, _ string) (api.PermissionsResponse, error) {
		if c == nil {
			return api.PermissionsResponse{}, errors.New("client unavailable")
		}
		resp, err := c.Permissions(ctx)
		if err != nil {
			return api.PermissionsResponse{}, err
		}
		if resp == nil {
			return api.PermissionsResponse{}, nil
		}
		return *resp, nil
	}), wind.Options{Enabled: c != nil})

	addMutation := wind.UseMutation(func(ctx context.Context, req api.PermissionRuleRequest) *promise.Promise[any] {
		return promise.Wrap(func(ctx context.Context) (any, error) {
			if c == nil {
				return nil, errors.New("client unavailable")
			}
			_, err := c.AddPermissionRule(ctx, req)
			return nil, err
		})(ctx)
	}, wind.MutationOptions[api.PermissionRuleRequest, any]{
		OnSuccess: func(_ any, _ api.PermissionRuleRequest, _ wind.MutationContext) {
			permsQuery.Refetch()
			setErrMsg("")
		},
		OnError: func(err error, _ api.PermissionRuleRequest, _ wind.MutationContext) {
			setErrMsg(err.Error())
		},
	})

	removeMutation := wind.UseMutation(func(ctx context.Context, req api.PermissionRuleRequest) *promise.Promise[any] {
		return promise.Wrap(func(ctx context.Context) (any, error) {
			if c == nil {
				return nil, errors.New("client unavailable")
			}
			_, err := c.RemovePermissionRule(ctx, req)
			return nil, err
		})(ctx)
	}, wind.MutationOptions[api.PermissionRuleRequest, any]{
		OnSuccess: func(_ any, _ api.PermissionRuleRequest, _ wind.MutationContext) {
			permsQuery.Refetch()
			setErrMsg("")
		},
		OnError: func(err error, _ api.PermissionRuleRequest, _ wind.MutationContext) {
			setErrMsg(err.Error())
		},
	})

	editMutation := wind.UseMutation(func(ctx context.Context, p editRuleParams) *promise.Promise[any] {
		return promise.Wrap(func(ctx context.Context) (any, error) {
			if c == nil {
				return nil, errors.New("client unavailable")
			}
			addReq := api.PermissionRuleRequest{
				Scope:  p.scope,
				Effect: p.effect,
				Rule:   p.newRule,
			}
			if _, err := c.AddPermissionRule(ctx, addReq); err != nil {
				return nil, err
			}
			removeOldReq := api.PermissionRuleRequest{
				Scope:  p.scope,
				Effect: p.effect,
				Rule:   p.oldRule,
			}
			if _, err := c.RemovePermissionRule(ctx, removeOldReq); err != nil {
				return nil, err
			}
			return nil, nil
		})(ctx)
	}, wind.MutationOptions[editRuleParams, any]{
		OnSuccess: func(_ any, _ editRuleParams, _ wind.MutationContext) {
			permsQuery.Refetch()
			setErrMsg("")
		},
		OnError: func(err error, _ editRuleParams, _ wind.MutationContext) {
			setErrMsg(err.Error())
		},
	})

	kitex.UseEffect(func() {
		if c == nil {
			store.RemoveSlot(slotID)
			store.AppendNotice("Client unavailable.")
			return
		}
		if permsQuery.IsLoading {
			return
		}
		if permsQuery.IsError {
			store.RemoveSlot(slotID)
			store.AppendError("Error", permsQuery.Error.Error())
		}
	}, []any{c == nil, permsQuery.IsLoading, permsQuery.IsError, permsQuery.Error})

	if c == nil {
		return nil
	}

	if permsQuery.IsLoading {
		return loadingHint("Loading permissions...")
	}
	if permsQuery.IsError {
		return nil
	}

	return components.PermissionConfigEditor(components.PermissionConfigEditorProps{
		Permissions:  permsQuery.Data,
		ErrorMessage: errMsg(),
		OnAddRule: func(scope api.PermissionScope, effect api.PermissionEffect, rule string) {
			addMutation.Mutate(api.PermissionRuleRequest{
				Scope:  scope,
				Effect: effect,
				Rule:   rule,
			})
		},
		OnEditRule: func(scope api.PermissionScope, effect api.PermissionEffect, oldRule, newRule string) {
			editMutation.Mutate(editRuleParams{
				scope:   scope,
				effect:  effect,
				oldRule: oldRule,
				newRule: newRule,
			})
		},
		OnRemoveRule: func(scope api.PermissionScope, effect api.PermissionEffect, rule string) {
			removeMutation.Mutate(api.PermissionRuleRequest{
				Scope:  scope,
				Effect: effect,
				Rule:   rule,
			})
		},
		OnClearError: func() {
			setErrMsg("")
		},
		OnClose: func() {
			store.RemoveSlot(slotID)
			store.AppendCommandOutput("/permissions", "Exited /permissions command")
		},
	})
})

PermissionBrowser renders an interactive permission configuration editor inside <Slot />.

View Source
var RulesBrowser = trail.FC("RulesBrowser", func(slotID string) trail.Node {
	rulesPtr := store.UseApp(func(s store.AppState) *[]api.Rule { return s.Rules })
	transcriptItems := store.UseTranscript(func(s store.TranscriptState) *[]store.TranscriptItem { return s.Items })
	streamMessages := store.UseStream(func(s store.StreamState) *[]store.Message { return s.Messages })
	selectedRule, setSelectedRule := kitex.UseState[*api.Rule](nil)
	notice, setNotice := kitex.UseState("")
	isReloading, setIsReloading := kitex.UseState(false)

	var rules []api.Rule
	if rulesPtr != nil {
		rules = *rulesPtr
	}

	c := store.Client()
	kitex.UseEffect(func() {
		if rulesPtr == nil && c != nil {
			go func() {
				if rls, err := c.ListRules(context.Background()); err == nil {
					store.SetWorkspaceRules(rls)
				}
			}()
		}
	}, []any{rulesPtr == nil, c == nil})

	doReload := func() {
		if isReloading() {
			return
		}
		setIsReloading(true)
		setNotice("Reloading workspace rules via registry.Reload...")
		go func() {
			defer setIsReloading(false)
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			err := store.ReloadWorkspace(ctx)
			if err != nil {
				setNotice("Failed to reload workspace: " + err.Error())
			} else {
				count := 0
				if s := store.GetApp().Rules; s != nil {
					count = len(*s)
				}
				setNotice(fmt.Sprintf("Workspace reloaded via registry.Reload (%d rules available).", count))
			}
		}()
	}

	if sel := selectedRule(); sel != nil {
		return ruleMarkdownViewer(ruleMarkdownProps{
			slotID:  slotID,
			rule:    *sel,
			onClose: func() { setSelectedRule(nil) },
		})
	}

	if len(rules) == 0 {
		return emptyRulesView(emptyRulesViewProps{
			slotID:   slotID,
			notice:   notice(),
			onReload: doReload,
		})
	}

	title := fmt.Sprintf("Rules (%d available)", len(rules))
	if n := notice(); n != "" {
		title = fmt.Sprintf("Rules (%d available) — %s", len(rules), n)
	}

	scheme := theme.UseTheme()

	winSize := trail.UseWindowSize()
	availDescWidth := 0
	if winSize.Width > 0 {
		availDescWidth = max(20, winSize.Width-30-12-10-8-4)
	}

	loaded := loadedRuleNamesFromSession(transcriptItems, streamMessages)

	opts := make([]uicomponents.Option, len(rules))
	for i, rl := range rules {
		scope := RuleScope(rl)
		estTokens := rl.Tokens
		if estTokens == 0 && rl.Instructions != "" {
			estTokens = EstimateRuleTokens(rl.Instructions)
		}
		tokStr := format.Tokens(estTokens)

		statusCol := ruleStatusBadge(rl, loaded)
		scopeCol := fmt.Sprintf("[%s]", scope)
		desc := format.CompactSingleLine(rl.Description, availDescWidth)

		descNode := trail.Box(trail.BoxProps{
			Style: style.S().
				FlexDirection(style.FlexRow).
				Width(style.Percent(100)).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden),
		}, trail.Span(trail.SpanProps{
			Style: style.S().
				Flex(0, 1).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden).
				WhiteSpace(style.WhiteSpacePre).
				Foreground(scheme.Color.Text.Muted),
		}, trail.Text(desc)))

		opts[i] = uicomponents.Option{
			Value:       rl.Name,
			Label:       rl.Name,
			Description: desc,
			Cells:       []string{rl.Name, statusCol, scopeCol, tokStr, desc},
			CellNodes:   []trail.Node{nil, nil, nil, nil, descNode},
		}
	}

	pickerProps := components.NewPicker(title, opts, func(opt uicomponents.Option) {
		for i := range rules {
			if rules[i].Name == opt.Value {
				setSelectedRule(&rules[i])
				return
			}
		}
	})
	pickerProps.Columns = []uicomponents.Column{
		{Width: 30, Align: style.TextAlignLeft},
		{Width: 12, Align: style.TextAlignLeft},
		{Width: 10, Align: style.TextAlignLeft},
		{Width: 8, Align: style.TextAlignRight},
		{Width: 0, Align: style.TextAlignLeft},
	}
	pickerProps.Filterable = false
	pickerProps.Bindings = []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "Inspect rule"},
		{Key: "r", Label: "Reload workspace"},
		{Key: "esc", Label: "Close"},
	}
	pickerProps.Keys = map[string]func(uicomponents.Option){
		"r": func(_ uicomponents.Option) {
			doReload()
		},
		"i": func(opt uicomponents.Option) {
			for i := range rules {
				if rules[i].Name == opt.Value {
					setSelectedRule(&rules[i])
					return
				}
			}
		},
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/rules", "Exited /rules command")
	}

	return components.Picker(pickerProps)
})

RulesBrowser renders an interactive rules list and markdown inspector inside <Slot />.

View Source
var SandboxBrowser = trail.FC("SandboxBrowser", func(slotID string) trail.Node {
	c := store.Client()
	errMsg, setErrMsg := kitex.UseState("")
	saving, setSaving := kitex.UseState(false)

	sandboxQuery := wind.Use("sandbox", promise.WrapWithProps(func(ctx context.Context, _ string) (api.SandboxResponse, error) {
		if c == nil {
			return api.SandboxResponse{}, errors.New("client unavailable")
		}
		resp, err := c.GetSandbox(ctx)
		if err != nil {
			return api.SandboxResponse{}, err
		}
		if resp == nil {
			return api.SandboxResponse{}, nil
		}
		return *resp, nil
	}), wind.Options{Enabled: c != nil})

	updateMutation := wind.UseMutation(func(ctx context.Context, p sandboxUpdateParams) *promise.Promise[any] {
		return promise.Wrap(func(ctx context.Context) (any, error) {
			if c == nil {
				return nil, errors.New("client unavailable")
			}
			_, err := c.UpdateSandbox(ctx, api.UpdateSandboxRequest{Scope: p.scope, Settings: p.settings})
			return nil, err
		})(ctx)
	}, wind.MutationOptions[sandboxUpdateParams, any]{
		OnSuccess: func(_ any, _ sandboxUpdateParams, _ wind.MutationContext) {
			setSaving(false)
			sandboxQuery.Refetch()
			setErrMsg("")
		},
		OnError: func(err error, _ sandboxUpdateParams, _ wind.MutationContext) {
			setSaving(false)
			setErrMsg(err.Error())
		},
	})

	kitex.UseEffect(func() {
		if c == nil {
			store.RemoveSlot(slotID)
			store.AppendNotice("Client unavailable.")
			return
		}
		if sandboxQuery.IsLoading {
			return
		}
		if sandboxQuery.IsError {
			store.RemoveSlot(slotID)
			store.AppendError("Error", sandboxQuery.Error.Error())
		}
	}, []any{c == nil, sandboxQuery.IsLoading, sandboxQuery.IsError, sandboxQuery.Error})

	sessionMode := store.UseSession(func(s store.SessionState) api.SandboxMode { return s.SandboxMode })

	if c == nil {
		return nil
	}

	if sandboxQuery.IsLoading {
		return loadingHint("Loading sandbox settings...")
	}
	if sandboxQuery.IsError {
		return nil
	}

	resp := sandboxQuery.Data

	scopeSettings := func(scope api.PermissionScope) api.SandboxSettings {
		if scope == api.ScopeGlobal {
			return resp.Global.Clone()
		}
		return resp.Project.Clone()
	}

	return components.SandboxConfigEditor(components.SandboxConfigEditorProps{
		Response:     resp,
		SessionMode:  sessionMode,
		LockedKnobs:  sandboxLockedKnobs(resp),
		Saving:       saving(),
		ErrorMessage: errMsg(),
		OnSetMode: func(scope api.PermissionScope, mode api.SandboxMode) {
			settings := scopeSettings(scope)
			settings.Mode = mode
			setSaving(true)
			updateMutation.Mutate(sandboxUpdateParams{scope: scope, settings: settings})
		},
		OnToggleKnob: func(scope api.PermissionScope, knob components.SandboxPolicyKnob, value *bool) {
			settings := scopeSettings(scope)
			switch knob {
			case components.KnobFailIfUnavailable:
				settings.FailIfUnavailable = value
			case components.KnobAllowUnsandboxed:
				settings.AllowUnsandboxed = value
			case components.KnobAutoAllowBash:
				settings.AutoAllowBash = value
			default:
				setSaving(false)
				setErrMsg(fmt.Sprintf("unknown sandbox setting %q", knob))
				return
			}
			setSaving(true)
			updateMutation.Mutate(sandboxUpdateParams{scope: scope, settings: settings})
		},
		OnAddExcluded: func(scope api.PermissionScope, pattern string) {
			settings := scopeSettings(scope)
			settings.ExcludedCommands = append(settings.ExcludedCommands, pattern)
			setSaving(true)
			updateMutation.Mutate(sandboxUpdateParams{scope: scope, settings: settings})
		},
		OnEditExcluded: func(scope api.PermissionScope, oldPattern, newPattern string) {
			settings := scopeSettings(scope)
			edited := make([]string, 0, len(settings.ExcludedCommands))
			replaced := false
			for _, p := range settings.ExcludedCommands {
				if p == oldPattern && !replaced {
					edited = append(edited, newPattern)
					replaced = true
					continue
				}
				if p == newPattern {
					continue
				}
				edited = append(edited, p)
			}
			settings.ExcludedCommands = edited
			setSaving(true)
			updateMutation.Mutate(sandboxUpdateParams{scope: scope, settings: settings})
		},
		OnRemoveExcluded: func(scope api.PermissionScope, pattern string) {
			settings := scopeSettings(scope)
			kept := make([]string, 0, len(settings.ExcludedCommands))
			for _, p := range settings.ExcludedCommands {
				if p != pattern {
					kept = append(kept, p)
				}
			}
			settings.ExcludedCommands = kept
			setSaving(true)
			updateMutation.Mutate(sandboxUpdateParams{scope: scope, settings: settings})
		},
		OnClearError: func() {
			setErrMsg("")
		},
		OnClose: func() {
			store.RemoveSlot(slotID)
			store.AppendCommandOutput("/sandbox", "Exited /sandbox command")
		},
	})
})

SandboxBrowser renders an interactive sandbox configuration editor inside <Slot />.

View Source
var SessionBrowser = trail.FC("SessionBrowser", func(slotID string) trail.Node {
	c := store.Client()

	result := wind.Use("sessions", promise.WrapWithProps(func(ctx context.Context, _ string) ([]api.Session, error) {
		if c == nil {
			return nil, nil
		}
		return c.ListSessions(ctx)
	}), wind.Options{Enabled: c != nil})

	type renamePayload struct {
		id    string
		title string
	}
	renameMutation := wind.UseMutation(func(ctx context.Context, p renamePayload) *promise.Promise[*api.Session] {
		return promise.Wrap(func(ctx context.Context) (*api.Session, error) {
			if c == nil {
				return nil, fmt.Errorf("client unavailable")
			}
			return c.UpdateSession(ctx, p.id, api.UpdateSessionRequest{Title: p.title})
		})(ctx)
	}, wind.MutationOptions[renamePayload, *api.Session]{
		OnSuccess: func(s *api.Session, v renamePayload, mc wind.MutationContext) {
			result.Refetch()
			if store.GetSession().Session != nil && store.GetSession().Session.ID == v.id {
				store.SetSession(s)
			}
		},
		OnError: func(err error, _ renamePayload, _ wind.MutationContext) {
			store.AppendError("Error renaming session", err.Error())
		},
	})

	deleteMutation := wind.UseMutation(func(ctx context.Context, id string) *promise.Promise[any] {
		return promise.Wrap(func(ctx context.Context) (any, error) {
			if c == nil {
				return nil, fmt.Errorf("client unavailable")
			}
			err := c.DeleteSession(ctx, id)
			return nil, err
		})(ctx)
	}, wind.MutationOptions[string, any]{
		OnSuccess: func(_ any, id string, mc wind.MutationContext) {
			result.Refetch()
			if store.GetSession().Session != nil && store.GetSession().Session.ID == id {
				store.NewDraftSession("")
			}
		},
		OnError: func(err error, _ string, _ wind.MutationContext) {
			store.AppendError("Error deleting session", err.Error())
		},
	})

	kitex.UseEffect(func() {
		if c == nil {
			store.RemoveSlot(slotID)
			store.AppendNotice("Client unavailable.")
			return
		}
		if result.IsLoading {
			return
		}
		if result.IsError {
			store.RemoveSlot(slotID)
			store.AppendError("Error", result.Error.Error())
		} else if len(result.Data) == 0 {
			store.RemoveSlot(slotID)
			store.AppendCommandOutput("/sessions", "No sessions found.")
		}
	}, []any{c == nil, result.IsLoading, result.IsError, result.Error, len(result.Data)})

	if c == nil {
		return nil
	}
	if result.IsLoading {
		return loadingHint("Loading sessions...")
	}
	if result.IsError || len(result.Data) == 0 {
		return nil
	}

	activeID := ""
	if store.GetSession().Session != nil {
		activeID = store.GetSession().Session.ID
	}

	opts := make([]uicomponents.Option, len(result.Data))
	for i, s := range result.Data {
		title := strings.TrimSpace(s.Title)
		if title == "" {
			title = "Untitled"
		}
		model := strings.TrimSpace(s.Config.Model)
		if model == "" {
			model = "-"
		}
		relTime := humanize.Time(s.UpdatedAt)
		opts[i] = uicomponents.Option{
			Value:   s.ID,
			Label:   title,
			Cells:   []string{title, model, relTime},
			Current: activeID != "" && s.ID == activeID,
		}
	}

	pickerProps := components.NewPicker("Sessions", opts, func(opt uicomponents.Option) {
		store.RemoveSlot(slotID)
		store.SwitchSession(opt.Value)
	})
	pickerProps.Columns = []uicomponents.Column{
		{Width: 0},
		{Width: 24, Align: style.TextAlignLeft},
		{Width: 26, Align: style.TextAlignRight},
	}
	pickerProps.Filterable = true
	pickerProps.Bindings = []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "Switch"},
		{Key: "f2", Label: "Rename"},
		{Key: "f3", Label: "Fork"},
		{Key: "f4", Label: "Delete"},
		{Key: "esc", Label: "Cancel"},
	}
	pickerProps.Keys = map[string]func(uicomponents.Option){
		"f3": func(opt uicomponents.Option) {
			store.RemoveSlot(slotID)
			store.ForkSession(opt.Value, "")
		},
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/sessions", "Exited /sessions command")
	}
	pickerProps.InputActions = map[string]components.InputAction{
		"f2": {
			Prompt: "Rename session:",
			InitialValue: func(opt uicomponents.Option) string {
				return opt.Label
			},
			OnSubmit: func(opt uicomponents.Option, val string) {
				renameMutation.Mutate(renamePayload{id: opt.Value, title: val})
			},
		},
	}
	pickerProps.ConfirmActions = map[string]components.ConfirmAction{
		"f4": {
			Prompt: func(opt uicomponents.Option) string {
				return fmt.Sprintf("Delete session %q?", opt.Label)
			},
			OnConfirm: func(opt uicomponents.Option) {
				deleteMutation.Mutate(opt.Value)
			},
		},
	}

	return components.Picker(pickerProps)
})

SessionBrowser renders an interactive session browser with rename (f2), fork (f3), and delete (f4).

View Source
var SkillsBrowser = trail.FC("SkillsBrowser", func(slotID string) trail.Node {
	skillsPtr := store.UseApp(func(s store.AppState) *[]api.Skill { return s.Skills })
	selectedSkill, setSelectedSkill := kitex.UseState[*api.Skill](nil)
	notice, setNotice := kitex.UseState("")
	isReloading, setIsReloading := kitex.UseState(false)

	var skills []api.Skill
	if skillsPtr != nil {
		skills = *skillsPtr
	}

	c := store.Client()
	kitex.UseEffect(func() {
		if skillsPtr == nil && c != nil {
			go func() {
				if sks, err := c.ListSkills(context.Background()); err == nil {
					store.SetWorkspaceSkills(sks)
				}
			}()
		}
	}, []any{skillsPtr == nil, c == nil})

	doReload := func() {
		if isReloading() {
			return
		}
		setIsReloading(true)
		setNotice("Reloading workspace skills via registry.Reload...")
		go func() {
			defer setIsReloading(false)
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			err := store.ReloadWorkspace(ctx)
			if err != nil {
				setNotice("Failed to reload workspace: " + err.Error())
			} else {
				count := 0
				if s := store.GetApp().Skills; s != nil {
					count = len(*s)
				}
				setNotice(fmt.Sprintf("Workspace reloaded via registry.Reload (%d skills available).", count))
			}
		}()
	}

	if sel := selectedSkill(); sel != nil {
		return skillMarkdownViewer(skillMarkdownProps{
			slotID:  slotID,
			skill:   *sel,
			onClose: func() { setSelectedSkill(nil) },
		})
	}

	if len(skills) == 0 {
		return emptySkillsView(emptySkillsViewProps{
			slotID:   slotID,
			notice:   notice(),
			onReload: doReload,
		})
	}

	title := fmt.Sprintf("Skills (%d available)", len(skills))
	if n := notice(); n != "" {
		title = fmt.Sprintf("Skills (%d available) — %s", len(skills), n)
	}

	scheme := theme.UseTheme()

	winSize := trail.UseWindowSize()
	availDescWidth := 0
	if winSize.Width > 0 {
		availDescWidth = max(20, winSize.Width-30-10-8-4)
	}

	opts := make([]uicomponents.Option, len(skills))
	for i, sk := range skills {
		scope := SkillScope(sk)
		estTokens := sk.Tokens
		if estTokens == 0 && sk.Instructions != "" {
			estTokens = EstimateSkillTokens(sk.Instructions)
		}
		tokStr := format.Tokens(estTokens)

		scopeCol := fmt.Sprintf("[%s]", scope)
		desc := format.CompactSingleLine(sk.Description, availDescWidth)

		descNode := trail.Box(trail.BoxProps{
			Style: style.S().
				FlexDirection(style.FlexRow).
				Width(style.Percent(100)).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden),
		}, trail.Span(trail.SpanProps{
			Style: style.S().
				Flex(0, 1).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden).
				WhiteSpace(style.WhiteSpacePre).
				Foreground(scheme.Color.Text.Muted),
		}, trail.Text(desc)))

		opts[i] = uicomponents.Option{
			Value:       sk.Name,
			Label:       sk.Name,
			Description: desc,
			Cells:       []string{sk.Name, scopeCol, tokStr, desc},
			CellNodes:   []trail.Node{nil, nil, nil, descNode},
		}
	}

	pickerProps := components.NewPicker(title, opts, func(opt uicomponents.Option) {
		for i := range skills {
			if skills[i].Name == opt.Value {
				setSelectedSkill(&skills[i])
				return
			}
		}
	})
	pickerProps.Columns = []uicomponents.Column{
		{Width: 30, Align: style.TextAlignLeft},
		{Width: 10, Align: style.TextAlignLeft},
		{Width: 8, Align: style.TextAlignRight},
		{Width: 0, Align: style.TextAlignLeft},
	}
	pickerProps.Filterable = false
	pickerProps.Bindings = []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "Inspect runbook"},
		{Key: "r", Label: "Reload workspace"},
		{Key: "esc", Label: "Close"},
	}
	pickerProps.Keys = map[string]func(uicomponents.Option){
		"r": func(_ uicomponents.Option) {
			doReload()
		},
		"i": func(opt uicomponents.Option) {
			for i := range skills {
				if skills[i].Name == opt.Value {
					setSelectedSkill(&skills[i])
					return
				}
			}
		},
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/skills", "Exited /skills command")
	}

	return components.Picker(pickerProps)
})

SkillsBrowser renders an interactive skills list and markdown inspector inside <Slot />.

View Source
var StatusLineEditor = trail.FC("StatusLineEditor", func(slotID string) trail.Node {
	scheme := theme.UseTheme()

	original := kitex.UseRef(store.GetStatusLine())
	issues := kitex.UseRef(store.GetStatusLineDropped())
	draft, setDraft := kitex.UseState(original.Current)
	all := statusLineEditorSegments(draft().Rows)
	cursor := uicomponents.UseCursor(len(all), 0)

	trail.UseInput(func(_ string, k event.KeyEvent) {
		if cursor.HandleKey(k) {
			return
		}
		id := all[cursor.Index]
		cfg := draft()
		cfg.Rows = slices.Clone(cfg.Rows)
		row, index := statusLineSegmentPosition(cfg.Rows, id)
		switch {
		case k.MatchString("esc", "escape"):
			if _, err := store.ApplyStatusLine(original.Current); err != nil {
				store.AppendError("/statusline", "Failed to restore status line: "+err.Error())
				return
			}
			store.RemoveSlot(slotID)
			store.AppendCommandOutput("/statusline", "Exited /statusline without saving.")
			return
		case k.MatchString("space", "enter", "t"):
			if row < 0 {
				defaultRow, _ := statusLineSegmentPosition(store.DefaultStatusLineRows, id)
				cfg.Rows[defaultRow] = append(slices.Clone(cfg.Rows[defaultRow]), id)
			} else {
				if len(cfg.Rows[0])+len(cfg.Rows[1]) == 1 {
					return
				}
				cfg.Rows[row] = slices.Delete(slices.Clone(cfg.Rows[row]), index, index+1)
			}
		case k.MatchString("left", "h", "right", "l"):
			if row < 0 {
				return
			}
			target := index + 1
			if k.MatchString("left", "h") {
				target = index - 1
			}
			if target < 0 || target >= len(cfg.Rows[row]) {
				return
			}
			segments := slices.Clone(cfg.Rows[row])
			segments[index], segments[target] = segments[target], segments[index]
			cfg.Rows[row] = segments
		case k.MatchString("r"):
			if row < 0 {
				return
			}
			other := 1 - row
			cfg.Rows[row] = slices.Delete(slices.Clone(cfg.Rows[row]), index, index+1)
			cfg.Rows[other] = append(slices.Clone(cfg.Rows[other]), id)
		case k.MatchString("c"):
			cfg.Compact = !cfg.Compact
		case k.MatchString("s"):
			dropped, err := store.SaveStatusLine(cfg)
			if err != nil {
				store.AppendError("/statusline", "Failed to save statusline.json: "+err.Error())
				return
			}
			msg := "Status line saved to statusline.json."
			if len(dropped) > 0 {
				msg += " Ignored entries: " + strings.Join(dropped, ", ") + "."
			}
			store.RemoveSlot(slotID)
			store.AppendCommandOutput("/statusline", msg)
			return
		default:
			return
		}
		if _, err := store.ApplyStatusLine(cfg); err != nil {
			store.AppendError("/statusline", "Failed to preview status line: "+err.Error())
			return
		}
		setDraft(cfg)
		cursor.Set(slices.Index(statusLineEditorSegments(cfg.Rows), id))
	})

	options := make([]uicomponents.Option, 0, len(all))
	for _, id := range all {
		i := slices.IndexFunc(statusLineSegmentLabels, func(segment statusLineSegmentLabel) bool {
			return segment.id == id
		})
		options = append(options, uicomponents.Option{
			Value: string(id),
			Cells: []string{string(id), statusLineSegmentLabels[i].description},
		})
	}

	titleStyle := style.S().Bold(true).Foreground(scheme.Color.Text.Primary)
	compactStyle := style.S().Foreground(scheme.Color.Mode.Plan)
	var diagnostics trail.Node
	if len(issues.Current) > 0 {
		diagnostics = trail.Box(trail.BoxProps{}, trail.Span(trail.SpanProps{
			Style: style.S().Foreground(scheme.Color.Text.Warning).OverflowWrap(style.OverflowWrapAnywhere),
		}, trail.Text("Ignored entries: "+strings.Join(issues.Current, ", "))))
	}
	return trail.Box(trail.BoxProps{
		Style: style.S().FlexDirection(style.FlexColumn).Width(style.Percent(100)),
	},
		trail.Box(trail.BoxProps{Style: titleStyle}, trail.Text("Status line configuration")),
		diagnostics,
		uicomponents.OptionList(uicomponents.OptionListProps{
			Options:  options,
			Selected: cursor.Index,
			Columns:  []uicomponents.Column{{Width: 12}, {}},
			GroupLabel: func(opt uicomponents.Option) string {
				row, _ := statusLineSegmentPosition(draft().Rows, store.StatusLineSegmentID(opt.Value))
				if row < 0 {
					return "Disabled"
				}
				return fmt.Sprintf("Row %d", row+1)
			},
		}),
		trail.Box(trail.BoxProps{Style: compactStyle}, trail.Text(fmt.Sprintf("compact: %s (c to toggle)", onOff(draft().Compact)))),
		uicomponents.KeyboardHint(uicomponents.KeyboardHintProps{
			Bindings: []uicomponents.KeyBinding{
				{Key: "↑/↓", Label: "Select"},
				{Key: "Space", Label: "Toggle segment"},
				{Key: "←/→", Label: "Reorder in row"},
				{Key: "r", Label: "Move to other row"},
				{Key: "C", Label: "Compact"},
				{Key: "S", Label: "Save"},
				{Key: "Esc", Label: "Discard & exit"},
			},
		}),
	)
})

StatusLineEditor renders an interactive status line configuration view inside <Slot />. Edits apply live (the rendered status line below previews them); s saves to statusline.json, esc discards and restores.

View Source
var SubagentViewer = trail.FC("SubagentViewer", func(props SubagentViewerProps) trail.Node {
	scheme := theme.UseTheme()
	allSubs := store.UseSubagents()
	var sub *api.Session
	for i := range allSubs {
		if allSubs[i].ID == props.SubagentID {
			sub = &allSubs[i]
			break
		}
	}

	subSession, setSubSession := kitex.UseState[*api.Session](nil)
	if sub == nil && subSession() != nil {
		sub = subSession()
	}

	conv := kitex.UseMemo(func() *store.SubagentConversation {
		return store.NewSubagentConversation(props.SubagentID)
	}, []any{props.SubagentID})

	rev, setRev := kitex.UseState(0)
	scroll := uicomponents.UseScroll(uicomponents.ScrollOptions{
		FollowTail: true,
		ExtraDeps:  []any{rev()},
	})

	kitex.UseEffectCleanup(func() func() {
		ctx, cancel := context.WithCancel(context.Background())
		c := store.Client()
		if c == nil {
			return cancel
		}
		go func() {
			localRev := 0
			if loaded, err := c.GetSession(ctx, props.SubagentID); err == nil && loaded != nil {
				setSubSession(loaded)
				if tl, err := c.Timeline(ctx, props.SubagentID); err == nil {
					conv.LoadTimelineSnapshot(loaded, tl, loaded.PendingQuestions)
				}
				if len(loaded.PendingPermissions) > 0 {
					conv.SeedPermissions(loaded.PendingPermissions)
				}
				conv.ReconcileStreamStatus(loaded)
				localRev++
				setRev(localRev)
			}
			for ev, err := range c.Watch(ctx, "", api.SessionStreamTopic(props.SubagentID)) {
				if err != nil {
					break
				}
				conv.ApplyEvent(ev)
				localRev++
				setRev(localRev)
			}
		}()
		return cancel
	}, []any{props.SubagentID})

	var perms []api.PermissionRequest
	var questions []api.QuestionRequest
	if sub != nil {
		perms = sub.PendingPermissions
		questions = sub.PendingQuestions
	}
	if len(perms) == 0 {
		perms = conv.PendingPermissions()
	}
	if len(questions) == 0 {
		questions = conv.PendingQuestions()
	}
	hasPrompt := len(perms) > 0 || len(questions) > 0

	trail.UseInput(func(input string, k event.KeyEvent) {
		if k.MatchString("esc", "escape") {
			if props.OnClose != nil {
				props.OnClose()
			}
			return
		}

		if !hasPrompt {
			if scroll.HandleKey(input, k) {
				return
			}
			if k.MatchString("x") && sub != nil && sub.Status != api.StatusIdle {
				_ = store.KillSubagent(props.SubagentID)
			}
			return
		}

		if k.MatchString("pgup", "ctrl+u", "b", "ctrl+b", "pgdown", "ctrl+d", "f", "ctrl+f") {
			scroll.HandleKey(input, k)
		}
	})

	border := style.
		SingleBorder().
		Top(true).
		Bottom(false).
		Left(false).
		Right(false).
		Color(scheme.Color.Border.Default)

	agentName := "subagent"
	title := props.SubagentID
	status := api.StatusExecuting
	isWorktree := false

	if sub != nil {
		if sub.Config.Agent != "" {
			agentName = sub.Config.Agent
		}
		if strings.TrimSpace(sub.Title) != "" {
			title = strings.TrimSpace(strings.ReplaceAll(sub.Title, "\n", " "))
		}
		if sub.Status != "" {
			status = sub.Status
		}
		if sub.WorkDir != "" {
			mainSess := store.GetSession().Session
			if mainSess != nil && mainSess.WorkDir != "" && sub.WorkDir != mainSess.WorkDir {
				isWorktree = true
			}
		}
	}
	agentColor := components.SubagentColor(scheme, agentName)

	headerChildren := []trail.Node{
		trail.Span(trail.SpanProps{
			Style: style.S().Bold(true).Foreground(agentColor),
		}, trail.Text("@"+agentName)),
	}
	if sub != nil {
		headerChildren = append(headerChildren, components.SubagentModelBadge(scheme, *sub))
	}
	headerChildren = append(headerChildren, trail.Span(trail.SpanProps{
		Style: style.S().Bold(true).Foreground(scheme.Color.Text.Primary),
	}, trail.Text(" · "+title+" ("+formatSubagentStatus(status)+")")))
	if isWorktree {
		headerChildren = append(headerChildren, trail.Span(trail.SpanProps{
			Style: style.S().Foreground(scheme.Color.Text.Secondary),
		}, trail.Text(" · worktree")))
	}
	if !scroll.AutoScroll && scroll.Pos > 0 {
		headerChildren = append(headerChildren, trail.Span(trail.SpanProps{
			Style: style.S().Foreground(scheme.Color.Text.Secondary),
		}, trail.Text(" [scrolled up]")))
	}

	headerNode := trail.Box(trail.BoxProps{
		Style: style.S().
			Display(style.DisplayFlex).
			FlexDirection(style.FlexRow).
			Width(style.Percent(100)).
			Margin(0, 0, 1, 0),
	}, headerChildren...)

	chatChildren := make([]trail.Node, 0)
	for _, msg := range conv.Messages() {
		chatChildren = append(chatChildren, components.Message(components.MessageProps{Message: msg}))
	}

	if conv.IsStreaming() && status != api.StatusIdle && status != api.StatusWaitingPermission && status != api.StatusWaitingQuestion && status != api.StatusWaitingPlanReview {
		startedAt, input, output := conv.TurnStats()
		todos := conv.Todos()
		activeText := ""
		for _, it := range todos {
			if it.Status == "in_progress" {
				activeText = it.Content
				break
			}
		}
		spinnerProps := components.SpinnerProps{
			Status:     conv.SessionStatus(),
			ActiveText: activeText,
			StartedAt:  startedAt,
			Input:      input,
			Output:     output,
		}
		chatChildren = append(chatChildren, components.Spinner(spinnerProps))
	}

	chatBox := trail.Box(trail.BoxProps{
		Ref: scroll.Ref,
		Style: style.S().
			MaxHeight(style.Cells(18)).
			OverflowY(style.OverflowAuto).
			ScrollbarY(true).
			Width(style.Percent(100)).
			FlexDirection(style.FlexColumn).
			Margin(0, 0, 1, 0),
	}, chatChildren...)

	var promptNode trail.Node
	if len(perms) > 0 {
		promptNode = components.PermissionPrompt(components.PermissionPromptProps{
			Request: perms[0],
			OnDecision: func(req api.PermissionRequest, dec api.PermissionDecision) {
				conv.RemovePermission(req.ID)
				store.DecideSubagentPermission(props.SubagentID, req, dec)
			},
		})
	} else if len(questions) > 0 {
		promptNode = components.QuestionPrompt(components.QuestionPromptProps{
			Request: questions[0],
			OnSubmit: func(req api.QuestionRequest, resp api.QuestionResponse, done func(error)) {
				conv.RemoveQuestion(req.ID)
				store.SubmitSubagentQuestion(props.SubagentID, req, resp, done)
			},
		})
	}

	var bindings []uicomponents.KeyBinding
	if !hasPrompt {
		bindings = append(bindings,
			uicomponents.KeyBinding{Key: "↑/↓ or j/k", Label: "Scroll"},
			uicomponents.KeyBinding{Key: "pgup/pgdn", Label: "Page"},
			uicomponents.KeyBinding{Key: "g/G", Label: "Top/Bottom"},
		)
	} else {
		bindings = append(bindings,
			uicomponents.KeyBinding{Key: "pgup/pgdn", Label: "Scroll chat"},
		)
	}
	if sub != nil && sub.Status != api.StatusIdle {
		bindings = append(bindings, uicomponents.KeyBinding{Key: "x", Label: "Kill subagent"})
	}
	bindings = append(bindings, uicomponents.KeyBinding{Key: "esc", Label: "Return"})

	hintBar := uicomponents.KeyboardHint(uicomponents.KeyboardHintProps{
		Bindings: bindings,
	})

	mainChildren := []trail.Node{headerNode, chatBox}
	if promptNode != nil {
		mainChildren = append(mainChildren, promptNode)
	}
	mainChildren = append(mainChildren, hintBar)

	return trail.Box(trail.BoxProps{
		Style: style.S().
			Border(border).
			Width(style.Percent(100)).
			FlexDirection(style.FlexColumn),
	}, mainChildren...)
})

SubagentViewer renders a live, non-static, navigable chat view of a subagent session.

View Source
var SubagentsBrowser = trail.FC("SubagentsBrowser", func(slotID string) trail.Node {
	scheme := theme.UseTheme()
	showAll, setShowAll := kitex.UseState(false)
	allSubs := store.UseSubagents()

	selectedSubagentID, setSelectedSubagentID := kitex.UseState("")

	var visibleSubs []api.Session
	if showAll() {
		visibleSubs = allSubs
	} else {
		for _, s := range allSubs {
			if s.Status != "" && s.Status != api.StatusIdle {
				visibleSubs = append(visibleSubs, s)
			}
		}
	}

	toggleLabel := "Show all"
	if showAll() {
		toggleLabel = "Hide idle"
	}

	title := "Subagents"
	if showAll() {
		title = "Subagents (all)"
	}

	if selID := selectedSubagentID(); selID != "" {
		return SubagentViewer(SubagentViewerProps{
			SubagentID: selID,
			OnClose: func() {
				setSelectedSubagentID("")
			},
		})
	}

	if len(visibleSubs) == 0 {
		emptyMsg := "  No subagents."
		if !showAll() && len(allSubs) > 0 {
			emptyMsg = "  No running subagents."
		}
		return emptySubagentsView(emptySubagentsViewProps{
			slotID:          slotID,
			title:           title,
			emptyMsg:        emptyMsg,
			toggleLabel:     toggleLabel,
			hasAllSubagents: len(allSubs) > 0 || showAll(),
			onToggle: func() {
				if len(allSubs) > 0 || showAll() {
					setShowAll(!showAll())
				}
			},
		})
	}

	mainSess := store.GetSession().Session
	opts := make([]uicomponents.Option, len(visibleSubs))
	for i, s := range visibleSubs {
		timeStr := "--:--:--"
		if !s.CreatedAt.IsZero() {
			timeStr = s.CreatedAt.Local().Format("15:04:05")
		}

		agentName := cmp.Or(s.Config.Agent, "subagent")
		taskTitle := strings.TrimSpace(strings.ReplaceAll(s.Title, "\n", " "))
		if taskTitle == "" {
			taskTitle = s.ID
		}

		label := fmt.Sprintf("[%s] @%s · %s", timeStr, agentName, taskTitle)
		if s.WorkDir != "" && mainSess != nil && mainSess.WorkDir != "" && s.WorkDir != mainSess.WorkDir {
			label += " (worktree)"
		}

		var durStr string
		if s.CreatedAt.IsZero() {
			durStr = "-"
		} else if s.Status != api.StatusIdle {
			durStr = formatSubagentDuration(time.Since(s.CreatedAt))
		} else if !s.UpdatedAt.IsZero() {
			durStr = formatSubagentDuration(s.UpdatedAt.Sub(s.CreatedAt))
		} else {
			durStr = "-"
		}

		opts[i] = uicomponents.Option{
			Value: s.ID,
			Label: label,
			Cells: []string{label, formatSubagentStatus(s.Status), durStr},
			Icon:  components.SubagentModelBadge(scheme, s),
		}
	}

	var hasKillable bool
	for _, s := range visibleSubs {
		if s.Status != api.StatusIdle {
			hasKillable = true
			break
		}
	}

	bindings := []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "Inspect"},
	}
	if hasKillable {
		bindings = append(bindings, uicomponents.KeyBinding{Key: "x", Label: "Kill"})
	}
	bindings = append(bindings,
		uicomponents.KeyBinding{Key: "a", Label: toggleLabel},
		uicomponents.KeyBinding{Key: "esc", Label: "Close"},
	)

	pickerProps := components.NewPicker(title, opts, func(opt uicomponents.Option) {
		setSelectedSubagentID(opt.Value)
	})
	pickerProps.Columns = []uicomponents.Column{
		{Width: 0},
		{Width: 20, Align: style.TextAlignLeft},
		{Width: 14, Align: style.TextAlignRight},
	}
	pickerProps.Filterable = false
	pickerProps.Bindings = bindings
	pickerProps.Keys = map[string]func(uicomponents.Option){
		"a": func(_ uicomponents.Option) {
			setShowAll(!showAll())
		},
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/subagents", "Exited /subagents command")
	}
	pickerProps.ConfirmActions = map[string]components.ConfirmAction{
		"x": {
			DisabledReason: func(opt uicomponents.Option) string {
				for _, s := range visibleSubs {
					if s.ID == opt.Value {
						if s.Status == api.StatusIdle {
							return "Subagent is already idle."
						}
						return ""
					}
				}
				return ""
			},
			Prompt: func(opt uicomponents.Option) string {
				for _, s := range visibleSubs {
					if s.ID == opt.Value {
						if s.Status == api.StatusIdle {
							return ""
						}
						return fmt.Sprintf("Kill subagent %s?", opt.Label)
					}
				}
				return ""
			},
			OnConfirm: func(opt uicomponents.Option) {
				_ = store.KillSubagent(opt.Value)
			},
		},
	}

	return components.Picker(pickerProps)
})

SubagentsBrowser renders an interactive subagents list and inline live viewer inside <Slot />.

View Source
var TasksBrowser = trail.FC("TasksBrowser", func(slotID string) trail.Node {
	showAll, setShowAll := kitex.UseState(false)
	allTasks := store.UseTasks()

	selectedTaskID, setSelectedTaskID := kitex.UseState("")

	var visibleTasks []api.Task
	if showAll() {
		visibleTasks = allTasks
	} else {
		for _, t := range allTasks {
			if t.Status == api.TaskStatusRunning || t.Status == api.TaskStatusPending {
				visibleTasks = append(visibleTasks, t)
			}
		}
	}

	toggleLabel := "Show all"
	if showAll() {
		toggleLabel = "Hide completed"
	}

	title := "Background Tasks"
	if showAll() {
		title = "Background Tasks (all)"
	}

	if selID := selectedTaskID(); selID != "" {
		var sel *api.Task
		for i := range allTasks {
			if allTasks[i].ID == selID {
				sel = &allTasks[i]
				break
			}
		}
		if sel != nil {
			return taskOutputViewer(taskOutputProps{
				task: *sel,
				onClose: func() {
					setSelectedTaskID("")
				},
			})
		}
	}

	if len(visibleTasks) == 0 {
		emptyMsg := "  No background tasks."
		if !showAll() && len(allTasks) > 0 {
			emptyMsg = "  No running background tasks."
		}
		return emptyTasksView(emptyTasksViewProps{
			slotID:      slotID,
			title:       title,
			emptyMsg:    emptyMsg,
			toggleLabel: toggleLabel,
			hasAllTasks: len(allTasks) > 0 || showAll(),
			onToggle: func() {
				if len(allTasks) > 0 || showAll() {
					setShowAll(!showAll())
				}
			},
		})
	}

	opts := make([]uicomponents.Option, len(visibleTasks))
	for i, t := range visibleTasks {
		timeStr := "--:--:--"
		if !t.StartedAt.IsZero() {
			timeStr = t.StartedAt.Local().Format("15:04:05")
		}

		titleStr := strings.TrimSpace(strings.ReplaceAll(t.Title, "\n", " "))
		cmdStr := strings.TrimSpace(strings.ReplaceAll(t.Command, "\n", " "))

		var label string
		if titleStr != "" && cmdStr != "" && titleStr != cmdStr {
			label = fmt.Sprintf("[%s] %s (%s)", timeStr, titleStr, cmdStr)
		} else {
			label = fmt.Sprintf("[%s] %s", timeStr, cmp.Or(titleStr, cmdStr, t.ID))
		}

		dur := fmt.Sprintf("%dms", t.DurationMs)
		if t.DurationMs >= 1000 {
			dur = fmt.Sprintf("%.1fs", float64(t.DurationMs)/1000.0)
		}
		opts[i] = uicomponents.Option{
			Value: t.ID,
			Label: label,
			Cells: []string{label, string(t.Status), dur},
		}
	}

	var hasKillable bool
	for _, t := range visibleTasks {
		if t.Status == api.TaskStatusRunning || t.Status == api.TaskStatusPending {
			hasKillable = true
			break
		}
	}

	bindings := []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "View output"},
	}
	if hasKillable {
		bindings = append(bindings, uicomponents.KeyBinding{Key: "x", Label: "Kill"})
	}
	bindings = append(bindings,
		uicomponents.KeyBinding{Key: "a", Label: toggleLabel},
		uicomponents.KeyBinding{Key: "esc", Label: "Close"},
	)

	pickerProps := components.NewPicker(title, opts, func(opt uicomponents.Option) {
		setSelectedTaskID(opt.Value)
	})
	pickerProps.Columns = []uicomponents.Column{
		{Width: 0},
		{Width: 14, Align: style.TextAlignLeft},
		{Width: 14, Align: style.TextAlignRight},
	}
	pickerProps.Filterable = false
	pickerProps.Bindings = bindings
	pickerProps.Keys = map[string]func(uicomponents.Option){
		"a": func(_ uicomponents.Option) {
			setShowAll(!showAll())
		},
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/tasks", "Exited /tasks command")
	}
	pickerProps.ConfirmActions = map[string]components.ConfirmAction{
		"x": {
			DisabledReason: func(opt uicomponents.Option) string {
				for _, t := range visibleTasks {
					if t.ID == opt.Value {
						if t.Status != api.TaskStatusRunning && t.Status != api.TaskStatusPending {
							return fmt.Sprintf("Task is already %s.", t.Status)
						}
						return ""
					}
				}
				return ""
			},
			Prompt: func(opt uicomponents.Option) string {
				for _, t := range visibleTasks {
					if t.ID == opt.Value {
						if t.Status != api.TaskStatusRunning && t.Status != api.TaskStatusPending {
							return ""
						}
						return fmt.Sprintf("Kill background task %s?", opt.Label)
					}
				}
				return ""
			},
			OnConfirm: func(opt uicomponents.Option) {
				for _, t := range visibleTasks {
					if t.ID == opt.Value {
						if t.Status == api.TaskStatusRunning || t.Status == api.TaskStatusPending {
							_ = store.KillTask(opt.Value)
						}
						break
					}
				}
			},
		},
	}

	return components.Picker(pickerProps)
})

TasksBrowser renders an interactive tasks list and inline output viewer inside <Slot />.

View Source
var ToolsBrowser = trail.FC("ToolsBrowser", func(slotID string) trail.Node {
	toolsPtr := store.UseApp(func(s store.AppState) *[]api.Tool { return s.Tools })
	cachedAgent := store.UseApp(func(s store.AppState) string { return s.ToolsAgent })
	toolsFetched := store.UseApp(func(s store.AppState) bool { return s.ToolsFetched })
	defaultAgent := store.UseApp(func(s store.AppState) string { return s.DefaultAgent })
	sessionAgent := store.UseSession(func(s store.SessionState) string { return s.Config.Agent })
	selectedTool, setSelectedTool := kitex.UseState[*api.Tool](nil)
	notice, setNotice := kitex.UseState("")
	isReloading, setIsReloading := kitex.UseState(false)
	toggling, setToggling := kitex.UseState("")

	var tools []api.Tool
	if toolsPtr != nil {
		tools = *toolsPtr
	}

	agent := strings.TrimSpace(sessionAgent)
	if agent == "" {
		agent = strings.TrimSpace(defaultAgent)
	}

	kitex.UseEffect(func() {
		if toolsFetched && cachedAgent == agent {
			return
		}
		if store.Client() == nil {
			return
		}
		go func() {
			if _, err := store.RefreshWorkspaceTools(context.Background(), agent); err != nil {
				store.AppendCommandOutput("/tools", "Failed to load workspace tools: "+err.Error())
			}
		}()
	}, []any{agent, cachedAgent, toolsFetched})

	doReload := func() {
		if isReloading() {
			return
		}
		setIsReloading(true)
		setNotice("Reloading workspace tools via registry.Reload...")
		go func() {
			defer setIsReloading(false)
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			if err := store.ReloadWorkspace(ctx); err != nil {
				setNotice("Failed to reload workspace: " + err.Error())
				return
			}
			count := 0
			if s := store.GetApp().Tools; s != nil {
				for _, t := range *s {
					if t.Enabled {
						count++
					}
				}
			}
			setNotice(fmt.Sprintf("Workspace reloaded via registry.Reload (%d tools available).", count))
		}()
	}

	toggleEnabled := func(opt uicomponents.Option) {
		c := store.Client()
		if c == nil || toggling() != "" {
			return
		}
		target := false
		for i := range tools {
			if tools[i].Name == opt.Value {
				target = tools[i].Enabled
				break
			}
		}
		setToggling(opt.Value)
		goMCPBackground(func() {
			defer setToggling("")
			ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
			defer cancel()
			if _, err := c.SetToolEnabled(ctx, opt.Value, !target); err != nil {
				setNotice("Failed to update " + opt.Value + ": " + err.Error())
				return
			}
			if _, err := store.ForceRefreshWorkspaceTools(ctx); err != nil {
				setNotice("Updated " + opt.Value + ", but refreshing the tool listing failed: " + err.Error())
				return
			}
			if target {
				setNotice("Disabled " + opt.Value + ".")
			} else {
				setNotice("Enabled " + opt.Value + ".")
			}
		})
	}

	if sel := selectedTool(); sel != nil {
		return toolInspector(toolInspectorProps{
			slotID:  slotID,
			tool:    *sel,
			onClose: func() { setSelectedTool(nil) },
		})
	}

	if len(tools) == 0 {
		return emptyToolsView(emptyToolsViewProps{
			slotID:   slotID,
			notice:   notice(),
			onReload: doReload,
		})
	}

	enabledCount := 0
	for i := range tools {
		if tools[i].Enabled {
			enabledCount++
		}
	}
	title := fmt.Sprintf("Tools (%d available)", enabledCount)
	if enabledCount < len(tools) {
		title = fmt.Sprintf("Tools (%d of %d available)", enabledCount, len(tools))
	}
	if n := notice(); n != "" {
		title = fmt.Sprintf("%s — %s", title, n)
	}

	scheme := theme.UseTheme()

	winSize := trail.UseWindowSize()
	nameCol, statusCol, scopeCol, annotationCol, availDescWidth := toolColumnWidths(tools, winSize.Width)

	opts := make([]uicomponents.Option, len(tools))
	for i, tl := range tools {
		statusBadge := toolStatusBadge(tl)
		scopeBadge := fmt.Sprintf("[%s]", ToolScope(tl))
		annotations := toolAnnotationBadges(tl)
		desc := format.CompactSingleLine(tl.Description, availDescWidth)

		statusNode := trail.Box(trail.BoxProps{
			Style: style.S().
				FlexDirection(style.FlexRow).
				Width(style.Percent(100)).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden),
		}, trail.Span(trail.SpanProps{
			Style: toolStatusColor(scheme, tl.Status).
				WhiteSpace(style.WhiteSpacePre).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden),
		}, trail.Text(statusBadge)))

		descNode := trail.Box(trail.BoxProps{
			Style: style.S().
				FlexDirection(style.FlexRow).
				Width(style.Percent(100)).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden),
		}, trail.Span(trail.SpanProps{
			Style: style.S().
				Flex(0, 1).
				MinWidth(style.Cells(0)).
				Overflow(style.OverflowHidden).
				WhiteSpace(style.WhiteSpacePre).
				Foreground(scheme.Color.Text.Muted),
		}, trail.Text(desc)))

		opts[i] = uicomponents.Option{
			Value:       tl.Name,
			Label:       tl.Name,
			Description: desc,
			Cells:       []string{tl.Name, statusBadge, scopeBadge, annotations, desc},
			CellNodes:   []trail.Node{nil, statusNode, nil, nil, descNode},
		}
	}

	inspect := func(opt uicomponents.Option) {
		for i := range tools {
			if tools[i].Name == opt.Value {
				setSelectedTool(&tools[i])
				return
			}
		}
	}

	pickerProps := components.NewPicker(title, opts, inspect)
	pickerProps.Columns = []uicomponents.Column{
		{Width: nameCol, Align: style.TextAlignLeft},
		{Width: statusCol, Align: style.TextAlignLeft},
		{Width: scopeCol, Align: style.TextAlignLeft},
		{Width: annotationCol, Align: style.TextAlignLeft},
		{Width: 0, Align: style.TextAlignLeft},
	}
	pickerProps.Filterable = false
	pickerProps.Bindings = []uicomponents.KeyBinding{
		{Key: "↑/↓", Label: "Select"},
		{Key: "enter", Label: "Inspect tool"},
		{Key: "space", Label: "Enable/disable"},
		{Key: "r", Label: "Reload workspace"},
		{Key: "esc", Label: "Close"},
	}
	pickerProps.Keys = map[string]func(uicomponents.Option){
		"space": toggleEnabled,
		"r": func(_ uicomponents.Option) {
			doReload()
		},
		"i": inspect,
	}
	pickerProps.OnCancel = func() {
		store.RemoveSlot(slotID)
		store.AppendCommandOutput("/tools", "Exited /tools command")
	}

	return components.Picker(pickerProps)
})

ToolsBrowser renders an interactive tool table and schema inspector inside <Slot />.

Functions

func CompletionViews

func CompletionViews(activeMode api.PermissionMode) map[string]uicomponents.AutocompleteView

CompletionViews returns command-specific completion views for the active mode.

func EnqueueProviderAuth

func EnqueueProviderAuth(provider string)

EnqueueProviderAuth opens the sign-in screen for one provider. An empty name lets the daemon resolve the sole OAuth preset.

func EstimateRuleTokens

func EstimateRuleTokens(instructions string) int

EstimateRuleTokens calculates approximate tokens for rule instructions using the code-calibrated tokenizer density (⌈bytes / 3⌉).

func EstimateSkillTokens

func EstimateSkillTokens(instructions string) int

EstimateSkillTokens calculates approximate tokens for skill instructions using the code-calibrated tokenizer density (⌈bytes / 3⌉).

func RuleScope

func RuleScope(r api.Rule) string

RuleScope returns the canonical scope string for a rule: [Workspace], [Project], [User], or [Builtin] (System and Builtin are treated as Builtin).

func SkillScope

func SkillScope(sk api.Skill) string

SkillScope returns the canonical scope string for a skill: [Workspace], [Project], [User], or [Builtin] (System and Builtin are treated as Builtin).

func SubmitMCPReference

func SubmitMCPReference(text string, attachments ...api.Attachment) bool

SubmitMCPReference routes a submitted composer line containing an MCP reference. Allowed items run immediately; prohibited ones present the Option B confirmation. It reports whether the line was handled, so the caller only forwards an ordinary message when this returns false.

func ToolScope

func ToolScope(t api.Tool) string

ToolScope returns the canonical scope string for a tool: [Builtin], [Workspace], [Project], or [User].

Types

type Command

type Command struct {
	Name        string
	Aliases     []string
	Usage       string
	Description string
	Handler     Handler
	Complete    autocomplete.Completer
	// contains filtered or unexported fields
}

Command defines a REPL slash command and its metadata.

type Handler

type Handler func(args []string) error

Handler executes a slash command with supplied arguments.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry maintains the collection of REPL slash commands.

func NewRegistry

func NewRegistry() *Registry

NewRegistry constructs a Registry pre-populated with all built-in REPL commands.

func (*Registry) Execute

func (r *Registry) Execute(line string) error

Execute parses a raw slash command line and invokes the matching Handler.

func (*Registry) List

func (r *Registry) List() []Command

List returns all registered commands in registration order.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) (Command, bool)

Lookup resolves a command by its primary name or alias, ignoring any leading "/".

func (*Registry) Register

func (r *Registry) Register(cmd Command)

Register adds or replaces a Command in the registry and indexes its name and aliases.

func (*Registry) RegisterCommandResource

func (r *Registry) RegisterCommandResource(cmd api.Command)

RegisterCommandResource registers a workspace Command manifest as a REPL slash command.

func (*Registry) RegisterSkillResource

func (r *Registry) RegisterSkillResource(sk api.Skill)

RegisterSkillResource registers a workspace Skill manifest as a REPL slash command.

func (*Registry) RegisterWorkspace

func (r *Registry) RegisterWorkspace(commands []api.Command, skills []api.Skill)

RegisterWorkspace registers workspace commands and skills as interactive slash commands.

func (*Registry) Sources

func (r *Registry) Sources() []autocomplete.Source

Sources snapshots the registered commands as headless autocomplete sources.

type SubagentViewerProps

type SubagentViewerProps struct {
	SubagentID string
	OnClose    func()
}

SubagentViewerProps defines the properties for the live SubagentViewer component.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL