Files
kandev/apps/backend/internal/workflow/models/export.go
T
José Almeida 74a8d7563e feat: split file search from command panel, add inline task search & configurable shortcuts (#383)
* feat(web): split file search from command panel and add inline task search

Separate the command panel (Cmd+K) from file search (Cmd+Shift+K) to
prevent file results from overpowering commands. Add inline task search
directly in the command panel — tasks appear in a "Tasks" group when
typing ≥2 characters, with workflow step badges and archived state
indicators. Archived tasks are sorted last with reduced opacity.

- Add "search-files" mode to CommandPanelMode
- Add FILE_SEARCH shortcut (Cmd/Ctrl+Shift+K)
- Move file search to dedicated mode, remove from commands mode
- Add useInlineTaskSearchEffect for commands mode task search
- Remove "Search Tasks" sub-mode entry point (now inline)
- Show file search shortcut hint in command panel footer

* feat(web): add configurable keyboard shortcuts in general settings

Add localStorage-based shortcut override system for the command panel
and file search keybindings. Users can record new key combos via the
settings UI and reset to defaults.

- Add shortcut-overrides module (get/set/reset via localStorage)
- Add KeyboardShortcutsCard with shortcut recorder UI
- Add "Keyboard Shortcuts" section to general settings page

* test(web): add e2e tests for command panel and file search split

Cover the key use cases: Cmd+K opens commands without files,
Cmd+Shift+K opens file search, inline task search with workflow step
badges, escape/backspace navigation, and panel toggle behavior.

* fix(test): remove unused seedData variable in command panel e2e test

* feat(settings): persist keyboard shortcuts to user settings API

Replace localStorage-based shortcut overrides with server-persisted
storage via the user settings API. Adds keyboard_shortcuts field to
the backend model, DTO, store, service, and controller. Frontend
reads overrides from Zustand store (hydrated from SSR/WS) and saves
via PATCH /api/v1/user/settings.

* fix(ui): prioritize tasks over commands, add step colors, fix shortcut display

- Move task results above command results in cmd+K for faster task switching
- Replace magnifier icon with task icon (IconSubtask) for task results
- Apply workflow step color to task badges
- Fix formatShortcut early return bug that dropped Shift modifier
  when ctrlOrCmd was set (e.g. Cmd+Shift+K showed as Cmd+K)
- Fix same bug in shortcutToCodeMirrorKeybinding

* fix(ui): use clipboard icon for task results in command panel

* style: format command panel footer

* fix(ui): use hammer icon and map step colors to hex for task badges

* feat(ui): show repo directory and agent name on task results

Display secondary details (repository directory, agent name, last
updated) on the right side of task results in the command panel.

* fix: avoid inline selector closure to prevent getServerSnapshot loop

Select the raw repositories map from the store instead of using an
inline selector that closes over workspaceId and returns new array
references, which triggers React's getServerSnapshot infinite loop.

* feat(task): expose agent name and working directory in task DTO

Add primary_agent_name (from AgentProfileSnapshot) and
primary_working_directory (from RepositorySnapshot) to TaskDTO.
Extend the primary session info query to fetch agent_profile_snapshot
and repository_snapshot columns, and extract the new fields in the
handler layer.

* feat(ui): show agent name and working directory on command panel tasks

Replace executor name with agent name from the primary session and
display the working directory (with repository path fallback) in the
task result details.

* fix(ui): add Commands heading to separate tasks from commands in search

* fix(task): use profile display name instead of agent slug

* feat(workflow): add show_in_command_panel per-step configuration

Add a configurable boolean to each workflow step that controls whether
tasks in that step appear in the command panel (Cmd+K). Default
templates mark backlog/done steps as hidden, active steps as visible.

- Add show_in_command_panel to WorkflowStep, StepDefinition, StepPortable
- Add column with idempotent migration (DEFAULT 1 for backwards compat)
- Include field in DTO serialization and export/import round-trip
- Update all default templates (Plan & Build, Architecture, Kanban, PR Review)
- Add tests for export preservation and import round-trip

* feat(ui): wire show_in_command_panel through frontend and settings

- Add field to HTTP types (WorkflowStep, WorkflowStepDTO, StepDefinition)
- Add to kanban state types and KanbanUpdatePayload
- Map in SSR snapshot mapper and WS kanban handler
- Add "Show in command panel" checkbox to workflow step settings
- Extract StepCheckboxRow component to stay within lint limits

* feat(ui): filter command panel tasks by show_in_command_panel flag

Replace position-based heuristic (resolveExcludedStepIds) with the
per-step show_in_command_panel configuration. Tasks in steps where
the flag is false are hidden from the default Cmd+K view but still
accessible via search.

- Replace resolveExcludedStepIds with resolveVisibleStepIds
- Consolidate useInlineTaskSearchEffect params into options object

* fix(ui): differentiate task sections in command panel

Rename the inline task results heading to "Active Tasks" when showing
the default view, distinguishing it from the "Tasks" command group
that contains "Create New Task".

* fix(ui): keep auto-archive checkbox inline with other step options

* fix(ui): include show_in_command_panel in step update action

The server action was missing show_in_command_panel from its Pick type
and body builder, so the checkbox change was silently dropped.

* fix(ui): pass is_start_step and show_in_command_panel from template steps

Both normalizeWorkflowTemplate mappers (workflow-api.ts and
workspaces.ts) were only picking name/position/color/prompt/events
from backend template steps, dropping is_start_step and
show_in_command_panel. This caused all template steps to appear
with show_in_command_panel checked when creating a new workflow.

* fix(ui): fix command panel empty tasks and step update losing checkbox state

Two fixes:
- Command panel: when kanban steps haven't loaded yet, don't filter
  tasks by visibility (resolveVisibleStepIds returns null for empty
  steps instead of an empty Set that rejects everything)
- Workflow settings: BackendWorkflowStep type and transformWorkflowStep
  were missing show_in_command_panel, so refreshing steps after an
  update dropped the field and the checkbox always reverted

* fix(ui): prevent back button from stealing focus in command panel

The back button was focusable and appeared before CommandInput, so
opening file search mode focused the button instead of the input.
Add tabIndex={-1} to keep focus on the search input.

* feat(web): show archive icon for archived tasks in command panel

Replace the text badge (e.g. "COMPLETED") with an IconArchive for
archived tasks in the command panel search results. Active tasks
keep the existing IconHammer icon.

* style: fix Prettier formatting and extract useStepMaps hook

Fix Prettier formatting issues in command-panel.tsx and
workflow-pipeline-editor-panels.tsx. Extract useStepMaps hook
from useInlineTaskSearchEffect to stay within the 100-line
function limit.

* fix: address PR review feedback

- Validate keyboard shortcut payload shape before persisting (service.go)
- Normalize KeyboardShortcuts to {} on read path for legacy rows (sqlite.go)
- Deduplicate getRepoDir into getFileName (command-panel-footer.tsx)
- Show toast on shortcut persistence failure instead of swallowing (keyboard-shortcuts-card.tsx)
- Reset keyboard_shortcuts in E2E test fixture for deterministic tests (test-base.ts)
2026-03-07 03:59:01 +00:00

236 lines
7.3 KiB
Go

package models
import (
"fmt"
"maps"
taskmodels "github.com/kandev/kandev/internal/task/models"
)
const (
ExportVersion = 1
ExportType = "kandev_workflow"
)
// WorkflowExport is the portable JSON format for sharing workflows.
type WorkflowExport struct {
Version int `json:"version"`
Type string `json:"type"`
Workflows []WorkflowPortable `json:"workflows"`
}
// WorkflowPortable is a workflow without instance-specific fields (IDs, timestamps).
type WorkflowPortable struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Steps []StepPortable `json:"steps"`
}
// StepPortable is a workflow step without instance-specific fields.
type StepPortable struct {
Name string `json:"name"`
Position int `json:"position"`
Color string `json:"color"`
Prompt string `json:"prompt,omitempty"`
Events StepEvents `json:"events"`
IsStartStep bool `json:"is_start_step"`
ShowInCommandPanel bool `json:"show_in_command_panel"`
AllowManualMove bool `json:"allow_manual_move"`
AutoArchiveAfterHours int `json:"auto_archive_after_hours,omitempty"`
}
// BuildWorkflowExport builds a portable WorkflowExport from domain models.
// stepsByWorkflow maps workflow ID → its steps (ordered by position).
func BuildWorkflowExport(workflows []*taskmodels.Workflow, stepsByWorkflow map[string][]*WorkflowStep) *WorkflowExport {
portable := make([]WorkflowPortable, 0, len(workflows))
for _, wf := range workflows {
steps := stepsByWorkflow[wf.ID]
portable = append(portable, buildWorkflowPortable(wf, steps))
}
return &WorkflowExport{
Version: ExportVersion,
Type: ExportType,
Workflows: portable,
}
}
func buildWorkflowPortable(wf *taskmodels.Workflow, steps []*WorkflowStep) WorkflowPortable {
portableSteps := make([]StepPortable, 0, len(steps))
// Build step ID → position map for converting move_to_step references.
idToPos := make(map[string]int, len(steps))
for _, s := range steps {
idToPos[s.ID] = s.Position
}
for _, s := range steps {
portableSteps = append(portableSteps, StepPortable{
Name: s.Name,
Position: s.Position,
Color: s.Color,
Prompt: s.Prompt,
Events: convertStepIDToPosition(s.Events, idToPos),
IsStartStep: s.IsStartStep,
ShowInCommandPanel: s.ShowInCommandPanel,
AllowManualMove: s.AllowManualMove,
AutoArchiveAfterHours: s.AutoArchiveAfterHours,
})
}
return WorkflowPortable{
Name: wf.Name,
Description: wf.Description,
Steps: portableSteps,
}
}
// Validate checks that the export data is well-formed.
func (e *WorkflowExport) Validate() error {
if e.Version != ExportVersion {
return fmt.Errorf("unsupported export version: %d (expected %d)", e.Version, ExportVersion)
}
if e.Type != ExportType {
return fmt.Errorf("unsupported export type: %q (expected %q)", e.Type, ExportType)
}
if len(e.Workflows) == 0 {
return fmt.Errorf("export contains no workflows")
}
for i, wf := range e.Workflows {
if wf.Name == "" {
return fmt.Errorf("workflow %d: name is required", i)
}
positions := make(map[int]bool, len(wf.Steps))
for j, step := range wf.Steps {
if step.Name == "" {
return fmt.Errorf("workflow %d step %d: name is required", i, j)
}
if positions[step.Position] {
return fmt.Errorf("workflow %d: duplicate step position %d", i, step.Position)
}
positions[step.Position] = true
}
// Validate that move_to_step references point to valid positions.
if err := validateStepPositionRefs(wf.Steps, positions); err != nil {
return fmt.Errorf("workflow %d: %w", i, err)
}
}
return nil
}
func validateStepPositionRefs(steps []StepPortable, validPositions map[int]bool) error {
for _, step := range steps {
for _, a := range step.Events.OnTurnStart {
if a.Type == OnTurnStartMoveToStep {
if err := checkPositionRef(a.Config, validPositions); err != nil {
return fmt.Errorf("step %q on_turn_start: %w", step.Name, err)
}
}
}
for _, a := range step.Events.OnTurnComplete {
if a.Type == OnTurnCompleteMoveToStep {
if err := checkPositionRef(a.Config, validPositions); err != nil {
return fmt.Errorf("step %q on_turn_complete: %w", step.Name, err)
}
}
}
}
return nil
}
func checkPositionRef(config map[string]any, validPositions map[int]bool) error {
if config == nil {
return fmt.Errorf("move_to_step action missing config")
}
pos, exists := config["step_position"]
if !exists {
return fmt.Errorf("move_to_step action missing step_position")
}
posInt, ok := toInt(pos)
if !ok {
return fmt.Errorf("step_position has unexpected type %T", pos)
}
if !validPositions[posInt] {
return fmt.Errorf("step_position %d does not match any step", posInt)
}
return nil
}
// convertStepIDToPosition rewrites move_to_step events: step_id → step_position.
func convertStepIDToPosition(events StepEvents, idToPos map[string]int) StepEvents {
return remapStepEvents(events, "step_id", "step_position", func(v any) (any, bool) {
s, ok := v.(string)
if !ok {
return nil, false
}
pos, found := idToPos[s]
return pos, found
})
}
// ConvertPositionToStepID rewrites move_to_step events: step_position → step_id.
// posToID maps position → new step ID.
func ConvertPositionToStepID(events StepEvents, posToID map[int]string) StepEvents {
return remapStepEvents(events, "step_position", "step_id", func(v any) (any, bool) {
pos, ok := toInt(v)
if !ok {
return nil, false
}
id, found := posToID[pos]
return id, found
})
}
// remapStepEvents rewrites move_to_step config in OnTurnStart and OnTurnComplete actions,
// replacing fromKey with toKey using the provided lookup function.
func remapStepEvents(events StepEvents, fromKey, toKey string, lookup func(any) (any, bool)) StepEvents {
result := StepEvents{
OnEnter: append([]OnEnterAction{}, events.OnEnter...),
OnExit: append([]OnExitAction{}, events.OnExit...),
}
for _, a := range events.OnTurnStart {
if a.Type == OnTurnStartMoveToStep {
if cfg, ok := remapConfigKey(a.Config, fromKey, toKey, lookup); ok {
a = OnTurnStartAction{Type: a.Type, Config: cfg}
}
}
result.OnTurnStart = append(result.OnTurnStart, a)
}
for _, a := range events.OnTurnComplete {
if a.Type == OnTurnCompleteMoveToStep {
if cfg, ok := remapConfigKey(a.Config, fromKey, toKey, lookup); ok {
a = OnTurnCompleteAction{Type: a.Type, Config: cfg}
}
}
result.OnTurnComplete = append(result.OnTurnComplete, a)
}
return result
}
// remapConfigKey copies config, replaces fromKey with toKey using lookup.
func remapConfigKey(config map[string]any, fromKey, toKey string, lookup func(any) (any, bool)) (map[string]any, bool) {
if config == nil {
return nil, false
}
val, exists := config[fromKey]
if !exists {
return nil, false
}
newVal, found := lookup(val)
if !found {
return nil, false
}
cfg := make(map[string]any, len(config))
maps.Copy(cfg, config)
delete(cfg, fromKey)
cfg[toKey] = newVal
return cfg, true
}
func toInt(v any) (int, bool) {
switch val := v.(type) {
case float64:
return int(val), true
case int:
return val, true
default:
return 0, false
}
}