From f6bd83da3318a78036ab85da215e23ab50a1d505 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Sun, 17 May 2026 20:16:15 +0100 Subject: [PATCH] refactor: tighten type system across backend + frontend (#920) --- .agents/agents/pr-poller.md | 30 +- apps/backend/cmd/kandev/agents.go | 15 +- apps/backend/cmd/kandev/cron.go | 4 +- apps/backend/cmd/kandev/helpers.go | 4 +- .../agent/runtime/lifecycle/env_preparer.go | 17 +- .../env_preparer_worktree_dup_test.go | 8 +- .../env_preparer_worktree_multi_test.go | 6 +- .../agent/runtime/lifecycle/events.go | 2 +- .../runtime/lifecycle/executor_backend.go | 5 +- .../runtime/lifecycle/executor_docker.go | 4 +- .../runtime/lifecycle/executor_sprites.go | 2 +- .../lifecycle/executor_sprites_lifecycle.go | 6 +- .../runtime/lifecycle/executor_standalone.go | 2 +- .../agent/runtime/lifecycle/manager.go | 3 +- .../runtime/lifecycle/manager_execution.go | 4 +- .../lifecycle/manager_execution_test.go | 2 +- .../runtime/lifecycle/manager_interaction.go | 29 +- .../lifecycle/manager_interaction_test.go | 18 +- .../agent/runtime/lifecycle/manager_launch.go | 31 +- .../runtime/lifecycle/manager_launch_test.go | 11 +- .../lifecycle/manager_remote_status.go | 14 +- .../internal/agent/runtime/lifecycle/types.go | 15 +- .../internal/agentctl/server/acp/client.go | 2 +- .../agentctl/server/process/manager.go | 2 +- .../agentctl/types/streams/permission.go | 45 +- apps/backend/internal/agentctl/types/types.go | 2 + .../gateway/websocket/vscode_proxy.go | 2 +- .../internal/office/approvals/service.go | 3 +- .../internal/office/channels/handler.go | 6 +- .../backend/internal/office/channels/relay.go | 2 +- .../internal/office/channels/service.go | 6 +- apps/backend/internal/office/config/import.go | 8 +- .../backend/internal/office/config/service.go | 4 +- apps/backend/internal/office/config/sync.go | 4 +- .../internal/office/config/sync_util.go | 2 +- .../internal/office/configloader/yaml.go | 4 +- apps/backend/internal/office/costs/budgets.go | 8 +- apps/backend/internal/office/costs/handler.go | 41 +- .../office/dashboard/handler_inbox.go | 4 +- .../internal/office/dashboard/routing_dto.go | 6 +- .../internal/office/dashboard/run_detail.go | 10 +- .../dashboard/run_detail_routing_test.go | 4 +- .../office/dashboard/service_inbox.go | 6 +- .../office/dashboard/service_inbox_routing.go | 2 +- apps/backend/internal/office/models/enums.go | 403 ++++++++++++++++++ .../office/models/enums_alignment_test.go | 34 ++ apps/backend/internal/office/models/models.go | 236 +++++----- .../repository/sqlite/route_attempts.go | 4 +- .../office/repository/sqlite/routines.go | 2 +- .../repository/sqlite/run_events_test.go | 6 +- .../office/repository/sqlite/run_routing.go | 2 +- .../repository/sqlite/run_routing_test.go | 4 +- .../internal/office/routines/catch_up_test.go | 10 +- .../internal/office/routines/handler.go | 36 +- .../internal/office/routines/service.go | 61 +-- .../internal/office/routines/service_test.go | 2 +- .../internal/office/routing/resolver.go | 12 +- .../internal/office/routing/resolver_test.go | 2 +- .../office/scheduler/dispatch_routing.go | 12 +- .../office/scheduler/routing_events.go | 2 +- .../office/scheduler/routing_lifecycle.go | 2 +- .../internal/office/service/activity.go | 10 +- .../internal/office/service/channel_relay.go | 2 +- .../office/service/channel_relay_test.go | 2 +- .../internal/office/service/channels.go | 6 +- .../internal/office/service/config_export.go | 4 +- .../internal/office/service/config_import.go | 8 +- .../internal/office/service/config_sync.go | 4 +- .../office/service/config_sync_util.go | 2 +- .../office/service/continuation_summary.go | 2 +- .../service/run_lifecycle_events_test.go | 2 +- .../internal/office/shared/activity.go | 6 +- .../backend/internal/office/skills/handler.go | 4 +- apps/backend/internal/office/skills/import.go | 2 +- .../internal/office/skills/runtime_adapter.go | 2 +- .../backend/internal/office/skills/service.go | 2 +- .../office/testharness/routes_office.go | 6 +- .../internal/office/wakeup/dispatcher.go | 2 +- .../internal/office/wakeup/dispatcher_test.go | 4 +- apps/backend/internal/orchestrator/dto/dto.go | 22 +- .../orchestrator/event_handlers_streaming.go | 4 +- .../event_handlers_workflow_moved_test.go | 6 +- .../orchestrator/executor/executor.go | 5 +- .../executor/executor_environment_test.go | 2 +- .../internal/orchestrator/task_operations.go | 4 +- .../orchestrator/workflow_store_test.go | 4 +- .../runs/repository/sqlite/run_events.go | 4 +- apps/backend/internal/task/dto/dto.go | 16 +- .../task/handlers/task_http_handlers.go | 2 +- apps/backend/internal/task/models/models.go | 33 +- .../task/repository/sqlite/session.go | 6 +- .../internal/task/service/service_events.go | 4 +- .../task/service/service_workflow_test.go | 9 +- apps/web/app/actions/workspaces.ts | 3 +- apps/web/app/demo/agent-messages/page.tsx | 6 +- .../app/demo/messages/demo-messages-data.ts | 6 +- .../agent-configuration-tab.test.tsx | 8 +- .../components/agent-configuration-tab.tsx | 3 +- .../projects/[id]/project-tasks-section.tsx | 3 +- .../office/projects/projects-page-client.tsx | 3 +- .../workspace/org/org-tree-layout.test.ts | 5 +- .../[agentId]/agent-save-helpers.test.ts | 4 +- .../app/settings/agents/[agentId]/page.tsx | 5 +- apps/web/app/settings/executor/[id]/page.tsx | 6 +- .../settings/executors/[profileId]/page.tsx | 8 +- .../settings/executors/new/[type]/page.tsx | 14 +- .../workspace/workspace-edit-client.tsx | 6 +- .../workspace-repositories-client.tsx | 12 +- .../workspace/workspace-workflows-client.tsx | 50 ++- .../workspace/workspaces-page-client.tsx | 4 +- .../agent/cli-profile-editor.test.tsx | 3 +- .../components/config-chat/use-config-chat.ts | 11 +- .../components/github/issue-watch-dialog.tsx | 5 +- .../components/github/review-watch-dialog.tsx | 5 +- .../jira/jira-issue-watch-dialog.tsx | 5 +- apps/web/components/kanban-card.tsx | 4 +- .../components/kanban-display-dropdown.tsx | 10 +- .../components/kanban/mobile-menu-sheet.tsx | 10 +- .../linear/linear-issue-watch-dialog.tsx | 5 +- .../settings/settings-app-sidebar.tsx | 9 +- .../components/task-create-dialog-options.tsx | 5 +- .../components/task-create-dialog-state.ts | 6 +- .../components/task-create-dialog-types.ts | 13 +- .../task/chat/messages/chat-message.test.tsx | 6 +- .../chat/messages/monitor-message.test.tsx | 10 +- .../messages/permission-request-message.tsx | 5 +- .../task/chat/messages/tool-call-message.tsx | 5 +- .../components/task/dockview-session-tabs.ts | 3 +- .../session-task-switcher-sheet-hooks.ts | 17 +- .../mobile/session-task-switcher-sheet.tsx | 3 +- .../components/task/new-subtask-dialog.tsx | 6 +- .../task/recent-task-switcher-model.test.ts | 19 +- apps/web/components/task/session-sort.test.ts | 26 +- .../components/agents-multi-picker.test.tsx | 7 +- .../pending-approval-badge.test.tsx | 7 +- .../topbar-working-indicator.test.tsx | 23 +- .../web/components/task/task-page-content.tsx | 17 +- .../kanban/use-implement-fresh.test.ts | 13 +- .../session/use-base-branch-by-repo.ts | 4 +- .../session/use-clarification-group.test.ts | 6 +- .../domains/session/use-session-resumption.ts | 24 +- .../settings/use-workflow-settings.test.ts | 12 +- .../domains/settings/use-workflow-settings.ts | 12 +- apps/web/hooks/use-processed-messages.test.ts | 11 +- apps/web/hooks/use-processed-messages.ts | 12 +- .../use-task-pending-clarification.test.tsx | 6 +- apps/web/hooks/use-user-display-settings.ts | 60 +-- .../domains/agent-profile-normalize.test.ts | 5 +- .../api/domains/agent-profile-normalize.ts | 3 +- apps/web/lib/api/domains/office-api.ts | 8 +- apps/web/lib/ssr/session-page-state.ts | 4 +- .../state/slices/office/office-agents.test.ts | 5 +- .../migrate-env-keyed-data.test.ts | 17 +- .../state/slices/session/selectors.test.ts | 105 +++-- .../session/session-slice.upsert.test.ts | 29 +- apps/web/lib/state/slices/ui/types.ts | 3 +- apps/web/lib/types/agent-profile.ts | 8 +- apps/web/lib/types/connection.ts | 15 + apps/web/lib/types/executor-payloads.ts | 4 +- apps/web/lib/types/executor.ts | 23 + apps/web/lib/types/http.test.ts | 31 +- apps/web/lib/types/http.ts | 140 +++--- apps/web/lib/types/ids.ts | 41 ++ apps/web/lib/types/permission.ts | 38 ++ apps/web/lib/types/workflow-actions.ts | 95 +++++ .../lib/utils/pending-clarification.test.ts | 6 +- apps/web/lib/utils/session-info.test.ts | 16 +- apps/web/lib/ws/client.ts | 38 +- apps/web/lib/ws/handlers/agent-session.ts | 30 +- apps/web/lib/ws/handlers/messages.ts | 10 +- apps/web/lib/ws/handlers/tasks.ts | 8 +- apps/web/lib/ws/handlers/turns.ts | 5 +- apps/web/lib/ws/use-websocket.tsx | 25 +- 173 files changed, 1840 insertions(+), 849 deletions(-) create mode 100644 apps/backend/internal/office/models/enums.go create mode 100644 apps/backend/internal/office/models/enums_alignment_test.go create mode 100644 apps/web/lib/types/connection.ts create mode 100644 apps/web/lib/types/executor.ts create mode 100644 apps/web/lib/types/ids.ts create mode 100644 apps/web/lib/types/permission.ts create mode 100644 apps/web/lib/types/workflow-actions.ts diff --git a/.agents/agents/pr-poller.md b/.agents/agents/pr-poller.md index 724ce14e23..e2cc4f32e4 100644 --- a/.agents/agents/pr-poller.md +++ b/.agents/agents/pr-poller.md @@ -30,12 +30,15 @@ bots: cubic: reviews= unresolved_review_threads: issue_comments_from_bots: +claude_summary: blockers= suggestions= verdict= recommendation: === end === ``` Free-form notes are forbidden outside the markers. The parent parses this verbatim. If something unexpected happens, surface it through `recommendation:` (one sentence). +The `claude_summary` line carries the **latest** Claude summary's structured findings table. Pure issue-comment counts (`issue_comments_from_bots`) miss this because the count alone can't tell the parent whether the comment is actionable (e.g. CodeRabbit's "review skipped, too many files" boilerplate ≠ a Claude finding). Use `claude_summary` to drive triage, not the raw count. + ## Procedure 1. **Resolve PR.** `gh pr view --json number,url,headRefName,baseRefName` (or `gh pr view --json …` if the parent passed a number). Capture `number` and `headRefName`. @@ -107,9 +110,34 @@ Free-form notes are forbidden outside the markers. The parent parses this verbat gh pr view --json comments --jq '[.comments[] | select(.author.login | IN("coderabbitai","github-actions"))] | length' ``` -6. **Emit the report.** Fill in the shape above exactly. The `recommendation:` line is one short sentence chosen from this menu, picking the first that applies: +6. **Parse the latest Claude summary** for structured findings. Claude posts its review summary as an *issue comment* (not a review) — either as `claude[bot]` (same-repo app) or as `github-actions` with a body that begins `**Claude finished ` (fork path). Each summary ends with a markdown table of the form `| Blocker | |` / `| Suggestion | |` and a `**Verdict:** ...` line. Read only the **latest** such comment — earlier summaries reflect previous commit states. + + ```bash + body=$(gh api repos/:owner/:repo/issues//comments --jq ' + [.[] | select( + .user.login == "claude[bot]" or + (.user.login == "github-actions" and ((.body | startswith("**Claude finished ")) or (.body | startswith("## Code Review")))) + )] | sort_by(.created_at) | last | .body // "" + ') + blockers=$(printf '%s' "$body" | grep -oE '\| Blocker \| [0-9]+ \|' | grep -oE '[0-9]+' | head -1) + suggestions=$(printf '%s' "$body" | grep -oE '\| Suggestion \| [0-9]+ \|' | grep -oE '[0-9]+' | head -1) + verdict_raw=$(printf '%s' "$body" | grep -oE '\*\*Verdict:\*\* [A-Za-z][^.]*' | sed 's/\*\*Verdict:\*\* //' | head -1) + ``` + + Map `verdict_raw` to the emitted token: + - starts with `Blocked` → `blocked` + - starts with `Ready with suggestions` → `ready_with_suggestions` + - starts with `Ready` (and not "Ready with") → `ready` + - empty body or no match → `none` + - anything else → `unknown` + + If `body` was empty (no Claude summary yet), emit `claude_summary: blockers=0 suggestions=0 verdict=none`. Default missing counts to `0`. + +7. **Emit the report.** Fill in the shape above exactly. The `recommendation:` line is one short sentence chosen from this menu, picking the first that applies: - `"CI failed — parent should read failing logs and fix."` if `ci_failed` is non-empty + - `"Claude summary flags blocker(s); parent should fetch the latest claude[bot] comment and address them."` if `claude_summary.blockers > 0` - `"All checks green; parent should triage unresolved review threads."` if `unresolved_review_threads > 0` + - `"All threads resolved; Claude has pending suggestion(s) in its latest summary — parent should fetch and triage."` if `claude_summary.suggestions > 0` - `"All checks green and no unresolved comments — parent may close out."` otherwise - `"Polling timed out with pending items; parent should decide whether to keep waiting."` if any axis hit the cap diff --git a/apps/backend/cmd/kandev/agents.go b/apps/backend/cmd/kandev/agents.go index 88459c8d32..7d558d278f 100644 --- a/apps/backend/cmd/kandev/agents.go +++ b/apps/backend/cmd/kandev/agents.go @@ -7,7 +7,6 @@ import ( "go.uber.org/zap" "github.com/kandev/kandev/internal/agent/credentials" - agentexecutor "github.com/kandev/kandev/internal/agent/executor" "github.com/kandev/kandev/internal/agent/mcpconfig" "github.com/kandev/kandev/internal/agent/registry" agentctl "github.com/kandev/kandev/internal/agent/runtime/agentctl" @@ -18,6 +17,7 @@ import ( "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/events/bus" "github.com/kandev/kandev/internal/secrets" + "github.com/kandev/kandev/internal/task/models" ) func provideLifecycleManager( @@ -101,11 +101,16 @@ func provideLifecycleManager( log, ) - // Register environment preparers + // Register environment preparers (keyed by ExecutorType — the + // "local"/"worktree"/"local_docker"/"sprites" taxonomy, not Runtime). + // The Worktree preparer is registered separately in + // Manager.SetWorktreeManager once a worktree.Manager is wired. preparerRegistry := lifecycle.NewPreparerRegistry(log) - preparerRegistry.Register(agentexecutor.NameStandalone, lifecycle.NewLocalPreparer(log)) - preparerRegistry.Register(agentexecutor.NameDocker, lifecycle.NewDockerPreparer(log)) - preparerRegistry.Register(agentexecutor.NameSprites, lifecycle.NewSpritesPreparer(log)) + localPreparer := lifecycle.NewLocalPreparer(log) + preparerRegistry.Register(models.ExecutorTypeLocal, localPreparer) + preparerRegistry.Register(models.ExecutorTypeMockRemote, localPreparer) + preparerRegistry.Register(models.ExecutorTypeLocalDocker, lifecycle.NewDockerPreparer(log)) + preparerRegistry.Register(models.ExecutorTypeSprites, lifecycle.NewSpritesPreparer(log)) lifecycleMgr.SetPreparerRegistry(preparerRegistry) lifecycleMgr.SetSecretStore(secretStore) // Wire the agent_profiles reader so the launch-prep skill deploy hook diff --git a/apps/backend/cmd/kandev/cron.go b/apps/backend/cmd/kandev/cron.go index 3e5ce31264..04a9c233b1 100644 --- a/apps/backend/cmd/kandev/cron.go +++ b/apps/backend/cmd/kandev/cron.go @@ -203,11 +203,11 @@ func (e *budgetEvaluator) EvaluatePolicies(ctx context.Context) ([]schedulercron } out = append(out, schedulercron.BudgetCheckResult{ WorkspaceID: ws.ID, - ScopeType: p.ScopeType, + ScopeType: string(p.ScopeType), ScopeID: p.ScopeID, SpentSubcents: spent, LimitSubcents: p.LimitSubcents, - Period: p.Period, + Period: string(p.Period), }) } } diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index 0a34f79ec5..70de787359 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -157,8 +157,8 @@ func appendSessionStateMessage(sessionID string, session *models.TaskSession, re "task_id": session.TaskID, "new_state": string(session.State), } - if session.ReviewStatus != nil && *session.ReviewStatus != "" { - payload["review_status"] = *session.ReviewStatus + if session.ReviewStatus != models.ReviewStatusNone { + payload["review_status"] = string(session.ReviewStatus) } if session.Metadata != nil { payload["session_metadata"] = session.Metadata diff --git a/apps/backend/internal/agent/runtime/lifecycle/env_preparer.go b/apps/backend/internal/agent/runtime/lifecycle/env_preparer.go index 83cc9ae181..eb6f03b3bc 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/env_preparer.go +++ b/apps/backend/internal/agent/runtime/lifecycle/env_preparer.go @@ -7,6 +7,7 @@ import ( "github.com/kandev/kandev/internal/agent/executor" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/task/models" ) // PrepareStepStatus represents the status of a preparation step. @@ -201,26 +202,32 @@ func SerializePrepareResult(result *EnvPrepareResult) map[string]interface{} { } } -// PreparerRegistry maps executor types to environment preparers. +// PreparerRegistry maps executor types (models.ExecutorType — the "local", +// "worktree", "local_docker", "sprites" taxonomy) to environment preparers. +// +// Keyed by ExecutorType, not Runtime: preparers do per-executor-type filesystem +// setup (e.g. worktree creation for the worktree type), and different +// ExecutorTypes that share a Runtime (local + worktree both run on standalone) +// can still get distinct preparation logic. type PreparerRegistry struct { - preparers map[executor.Name]EnvironmentPreparer + preparers map[models.ExecutorType]EnvironmentPreparer logger *logger.Logger } // NewPreparerRegistry creates a new PreparerRegistry. func NewPreparerRegistry(log *logger.Logger) *PreparerRegistry { return &PreparerRegistry{ - preparers: make(map[executor.Name]EnvironmentPreparer), + preparers: make(map[models.ExecutorType]EnvironmentPreparer), logger: log, } } // Register adds a preparer for the given executor type. -func (r *PreparerRegistry) Register(execType executor.Name, preparer EnvironmentPreparer) { +func (r *PreparerRegistry) Register(execType models.ExecutorType, preparer EnvironmentPreparer) { r.preparers[execType] = preparer } // Get returns the preparer for the given executor type, or nil if not found. -func (r *PreparerRegistry) Get(execType executor.Name) EnvironmentPreparer { +func (r *PreparerRegistry) Get(execType models.ExecutorType) EnvironmentPreparer { return r.preparers[execType] } diff --git a/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_dup_test.go b/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_dup_test.go index 447f7caa39..0a0ce5e1a5 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_dup_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_dup_test.go @@ -109,7 +109,7 @@ func TestWorktreePreparer_MultiRepo_RunsSetupScriptOncePerRepo(t *testing.T) { TaskID: "task-multi-once", SessionID: "sess-multi-once", TaskTitle: "Once Task", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "once-task_xxx", Repositories: []RepoPrepareSpec{ { @@ -184,7 +184,7 @@ func TestWorktreePreparer_MultiRepo_NonIdempotentSetupScriptSucceeds(t *testing. TaskID: "task-multi-nonidempotent", SessionID: "sess-multi-nonidempotent", TaskTitle: "Non-Idempotent Task", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "nonidempotent_yyy", Repositories: []RepoPrepareSpec{ { @@ -233,7 +233,7 @@ func TestWorktreePreparer_SingleRepo_RunsSetupScriptOnce(t *testing.T) { TaskID: "task-single-once", SessionID: "sess-single-once", TaskTitle: "Single Once", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "single-once_zzz", UseWorktree: true, RepositoryID: "repo-single", @@ -287,7 +287,7 @@ func TestWorktreePreparer_SingleRepo_NonIdempotentSetupScriptSucceeds(t *testing TaskID: "task-single-nonidempotent", SessionID: "sess-single-nonidempotent", TaskTitle: "Single Non-Idempotent", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "single-nonidempotent_qqq", UseWorktree: true, RepositoryID: "repo-single", diff --git a/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_multi_test.go b/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_multi_test.go index 1fd583996d..73bff333c9 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_multi_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/env_preparer_worktree_multi_test.go @@ -196,7 +196,7 @@ func TestWorktreePreparer_MultiRepo_CreatesWorktreePerRepo(t *testing.T) { TaskID: "task-multi-1", SessionID: "sess-multi-1", TaskTitle: "Multi Repo Task", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "multi-repo-task_aaa", Repositories: []RepoPrepareSpec{ {RepositoryID: "repo-front", RepositoryPath: repoA, RepoName: "frontend", BaseBranch: "main"}, @@ -249,7 +249,7 @@ func TestWorktreePreparer_MultiRepo_RollbackOnPartialFailure(t *testing.T) { TaskID: "task-multi-fail", SessionID: "sess-multi-fail", TaskTitle: "Failing Task", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "failing-task_bbb", Repositories: []RepoPrepareSpec{ {RepositoryID: "repo-good", RepositoryPath: repoA, RepoName: "good", BaseBranch: "main"}, @@ -296,7 +296,7 @@ func TestWorktreePreparer_MultiRepo_RunsPerRepoSetupScript(t *testing.T) { TaskID: "task-multi-setup", SessionID: "sess-multi-setup", TaskTitle: "Setup Task", - ExecutorType: executor.Name("worktree"), + ExecutorType: executor.NameStandalone, TaskDirName: "setup-task_ccc", Repositories: []RepoPrepareSpec{ { diff --git a/apps/backend/internal/agent/runtime/lifecycle/events.go b/apps/backend/internal/agent/runtime/lifecycle/events.go index 4e25258267..166cf9e581 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/events.go +++ b/apps/backend/internal/agent/runtime/lifecycle/events.go @@ -354,7 +354,7 @@ func (p *EventPublisher) PublishPermissionRequest(execution *AgentExecution, eve options[i] = PermissionOption{ OptionID: opt.OptionID, Name: opt.Name, - Kind: opt.Kind, + Kind: string(opt.Kind), } } diff --git a/apps/backend/internal/agent/runtime/lifecycle/executor_backend.go b/apps/backend/internal/agent/runtime/lifecycle/executor_backend.go index b9572f1b2f..a74338f455 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/executor_backend.go +++ b/apps/backend/internal/agent/runtime/lifecycle/executor_backend.go @@ -10,6 +10,7 @@ import ( "github.com/kandev/kandev/internal/agent/executor" agentctl "github.com/kandev/kandev/internal/agent/runtime/agentctl" "github.com/kandev/kandev/internal/agentctl/server/process" + "github.com/kandev/kandev/internal/agentruntime" v1 "github.com/kandev/kandev/pkg/api/v1" ) @@ -154,7 +155,7 @@ func FilterPersistentMetadata(src map[string]interface{}) map[string]interface{} // RemoteStatus describes runtime health/details for remote executors. // It is intentionally generic so each executor can include extra details in Details. type RemoteStatus struct { - RuntimeName string `json:"runtime_name"` + RuntimeName agentruntime.Runtime `json:"runtime_name"` RemoteName string `json:"remote_name,omitempty"` State string `json:"state,omitempty"` CreatedAt *time.Time `json:"created_at,omitempty"` @@ -209,7 +210,7 @@ type ExecutorInstance struct { SessionID string // Runtime name (e.g., "docker", "standalone") - set by the runtime that created this instance - RuntimeName string + RuntimeName agentruntime.Runtime // Agentctl client for communicating with this instance Client *agentctl.Client diff --git a/apps/backend/internal/agent/runtime/lifecycle/executor_docker.go b/apps/backend/internal/agent/runtime/lifecycle/executor_docker.go index f5e99f5ad6..098fedb1f9 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/executor_docker.go +++ b/apps/backend/internal/agent/runtime/lifecycle/executor_docker.go @@ -224,7 +224,7 @@ func (r *DockerExecutor) buildCreatedInstance(req *ExecutorCreateRequest, result InstanceID: req.InstanceID, TaskID: req.TaskID, SessionID: req.SessionID, - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), Client: result.Client, ContainerID: result.ContainerID, ContainerIP: containerIP, @@ -273,7 +273,7 @@ func (r *DockerExecutor) reconnectToContainer(ctx context.Context, dockerClient InstanceID: req.InstanceID, TaskID: req.TaskID, SessionID: req.SessionID, - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), Client: client, ContainerID: info.ID, ContainerIP: containerIP, diff --git a/apps/backend/internal/agent/runtime/lifecycle/executor_sprites.go b/apps/backend/internal/agent/runtime/lifecycle/executor_sprites.go index acdc61ec69..cc52548d16 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/executor_sprites.go +++ b/apps/backend/internal/agent/runtime/lifecycle/executor_sprites.go @@ -463,7 +463,7 @@ func (r *SpritesExecutor) buildInstanceResult( InstanceID: req.InstanceID, TaskID: req.TaskID, SessionID: req.SessionID, - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), Client: agentctl.NewClient("127.0.0.1", localPort, r.logger, agentctl.WithExecutionID(req.InstanceID), agentctl.WithSessionID(req.SessionID)), diff --git a/apps/backend/internal/agent/runtime/lifecycle/executor_sprites_lifecycle.go b/apps/backend/internal/agent/runtime/lifecycle/executor_sprites_lifecycle.go index 4a1c8aee2e..994e9ffbc1 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/executor_sprites_lifecycle.go +++ b/apps/backend/internal/agent/runtime/lifecycle/executor_sprites_lifecycle.go @@ -156,7 +156,7 @@ func (r *SpritesExecutor) GetRemoteStatus(ctx context.Context, instance *Executo spriteName := strings.TrimSpace(getMetadataString(instance.Metadata, MetadataKeySpriteName)) if spriteName == "" { return &RemoteStatus{ - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), State: "unknown", LastCheckedAt: time.Now().UTC(), }, nil @@ -170,7 +170,7 @@ func (r *SpritesExecutor) GetRemoteStatus(ctx context.Context, instance *Executo } if token == "" { return &RemoteStatus{ - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), RemoteName: spriteName, State: "unknown", LastCheckedAt: time.Now().UTC(), @@ -187,7 +187,7 @@ func (r *SpritesExecutor) GetRemoteStatus(ctx context.Context, instance *Executo } return &RemoteStatus{ - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), RemoteName: spriteName, State: spritesutil.NormalizeSpriteStatus(sprite.Status), CreatedAt: nonZeroTimePtr(sprite.CreatedAt), diff --git a/apps/backend/internal/agent/runtime/lifecycle/executor_standalone.go b/apps/backend/internal/agent/runtime/lifecycle/executor_standalone.go index 77e686de8f..e0b05af78b 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/executor_standalone.go +++ b/apps/backend/internal/agent/runtime/lifecycle/executor_standalone.go @@ -156,7 +156,7 @@ func (r *StandaloneExecutor) CreateInstance(ctx context.Context, req *ExecutorCr InstanceID: req.InstanceID, TaskID: req.TaskID, SessionID: req.SessionID, - RuntimeName: string(r.Name()), + RuntimeName: r.Name(), Client: client, StandaloneInstanceID: resp.ID, StandalonePort: resp.Port, diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager.go b/apps/backend/internal/agent/runtime/lifecycle/manager.go index 0aad32a5ed..268bfb839d 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager.go @@ -17,6 +17,7 @@ import ( "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/events/bus" "github.com/kandev/kandev/internal/secrets" + "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/worktree" ) @@ -238,7 +239,7 @@ func (m *Manager) SetWorktreeManager(worktreeMgr *worktree.Manager) { // worktree-specific preparation (create git worktree, checkout PR branch) // instead of the generic local preparer. if m.preparerRegistry != nil { - m.preparerRegistry.Register(executor.Name("worktree"), NewWorktreePreparer(worktreeMgr, m.logger)) + m.preparerRegistry.Register(models.ExecutorTypeWorktree, NewWorktreePreparer(worktreeMgr, m.logger)) } } diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go b/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go index 9117533e2b..41aaaeeb0e 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go @@ -412,7 +412,7 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work } execution := runtimeInstance.ToAgentExecution(req) - execution.RuntimeName = string(rt.Name()) + execution.RuntimeName = rt.Name() // Set the ACP session ID for session resumption if info.ACPSessionID != "" { @@ -464,7 +464,7 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work zap.String("execution_id", executionID), zap.String("task_id", taskID), zap.String("workspace_path", info.WorkspacePath), - zap.String("runtime", execution.RuntimeName)) + zap.Stringer("runtime", execution.RuntimeName)) return execution, nil } diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_execution_test.go b/apps/backend/internal/agent/runtime/lifecycle/manager_execution_test.go index b866700b89..d5e3a6fd4d 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_execution_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_execution_test.go @@ -643,7 +643,7 @@ func (e *createInstanceExecutor) CreateInstance(ctx context.Context, req *Execut InstanceID: req.InstanceID, TaskID: req.TaskID, SessionID: req.SessionID, - RuntimeName: string(e.Name()), + RuntimeName: e.Name(), Client: e.client, WorkspacePath: req.WorkspacePath, AuthToken: e.authToken, diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_interaction.go b/apps/backend/internal/agent/runtime/lifecycle/manager_interaction.go index 7fa81744e4..efeaedd270 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_interaction.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_interaction.go @@ -13,7 +13,6 @@ import ( "github.com/kandev/kandev/internal/agent/runtime/routingerr" agentctltypes "github.com/kandev/kandev/internal/agentctl/types" "github.com/kandev/kandev/internal/agentctl/types/streams" - "github.com/kandev/kandev/internal/agentruntime" "github.com/kandev/kandev/internal/events" "github.com/kandev/kandev/internal/task/models" v1 "github.com/kandev/kandev/pkg/api/v1" @@ -398,7 +397,7 @@ func (m *Manager) StopAgentWithReason(ctx context.Context, executionID string, r zap.String("execution_id", executionID), zap.String("reason", reason), zap.Bool("force", force), - zap.String("runtime", execution.RuntimeName)) + zap.Stringer("runtime", execution.RuntimeName)) // Try to gracefully stop via agentctl first, then always close connections if execution.agentctl != nil { @@ -671,7 +670,7 @@ func (m *Manager) ResolveTaskEnvironmentID(ctx context.Context, sessionID string func (m *Manager) IsRemoteSession(ctx context.Context, sessionID string) bool { // Check in-memory execution first (fast path). if execution, exists := m.executionStore.GetBySessionID(sessionID); exists { - if execution.RuntimeName == string(executor.NameSprites) { + if execution.RuntimeName == executor.NameSprites { return true } if execution.Metadata != nil { @@ -694,7 +693,7 @@ func (m *Manager) IsRemoteSession(ctx context.Context, sessionID string) bool { return true } // Backwards compatibility: old records may only have RuntimeName set. - return info.RuntimeName == string(executor.NameSprites) || info.RuntimeName == string(executor.NameRemoteDocker) + return info.RuntimeName == executor.NameSprites || info.RuntimeName == executor.NameRemoteDocker } // ShouldUseContainerShell checks whether a session's shell should run inside a container/sandbox @@ -704,8 +703,8 @@ func (m *Manager) ShouldUseContainerShell(ctx context.Context, sessionID string) // Check in-memory execution first (fast path). if execution, exists := m.executionStore.GetBySessionID(sessionID); exists { // Docker and Sprites executors run shells inside the container/sandbox - if execution.RuntimeName == string(executor.NameDocker) || - execution.RuntimeName == string(executor.NameSprites) { + if execution.RuntimeName == executor.NameDocker || + execution.RuntimeName == executor.NameSprites { return true } if execution.Metadata != nil { @@ -728,9 +727,9 @@ func (m *Manager) ShouldUseContainerShell(ctx context.Context, sessionID string) return true } // Backwards compatibility: old records may only have RuntimeName set. - return info.RuntimeName == string(executor.NameDocker) || - info.RuntimeName == string(executor.NameSprites) || - info.RuntimeName == string(executor.NameRemoteDocker) + return info.RuntimeName == executor.NameDocker || + info.RuntimeName == executor.NameSprites || + info.RuntimeName == executor.NameRemoteDocker } // GetAvailableCommandsForSession returns the available slash commands for a session. @@ -1078,11 +1077,11 @@ func (m *Manager) stopAgentViaBackend(ctx context.Context, executionID string, e if execution.RuntimeName == "" || m.executorRegistry == nil { return } - rt, err := m.executorRegistry.GetBackend(executor.Name(execution.RuntimeName)) + rt, err := m.executorRegistry.GetBackend(execution.RuntimeName) if err != nil { m.logger.Warn("failed to get runtime for stopping execution", zap.String("execution_id", executionID), - zap.String("runtime", execution.RuntimeName), + zap.Stringer("runtime", execution.RuntimeName), zap.Error(err)) return } @@ -1164,14 +1163,10 @@ func (m *Manager) buildFreshAgentCommand(ctx context.Context, execution *AgentEx SessionID: "", // Fresh start — no resume flags AutoApprove: autoApprove, PermissionValues: permissionValues, - // RuntimeName is "standalone" / "docker" / "sprites" — MockAgent + // Runtime is "standalone" / "docker" / "sprites" — MockAgent // reads this to pick a bare name (container PATH lookup) vs. // an absolute host path. - // TODO: retype AgentExecution.RuntimeName to agentruntime.Runtime - // so this cast disappears. Ripples to ~14 files (executor impls - // + tests) — deferred from the typed-enum refactor that - // introduced this site. - Runtime: agentruntime.Runtime(execution.RuntimeName), + Runtime: execution.RuntimeName, } return m.commandBuilder.BuildCommandString(agentConfig, opts), m.commandBuilder.BuildContinueCommandString(agentConfig, opts) diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_interaction_test.go b/apps/backend/internal/agent/runtime/lifecycle/manager_interaction_test.go index 2b28135997..56a85d2b83 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_interaction_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_interaction_test.go @@ -550,7 +550,7 @@ func TestIsRemoteSession(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-1", SessionID: "session-1", - RuntimeName: string(executor.NameSprites), + RuntimeName: executor.NameSprites, Status: v1.AgentStatusRunning, }) mgr := &Manager{executionStore: store} @@ -562,7 +562,7 @@ func TestIsRemoteSession(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-2", SessionID: "session-2", - RuntimeName: string(executor.NameStandalone), + RuntimeName: executor.NameStandalone, Status: v1.AgentStatusRunning, Metadata: map[string]interface{}{MetadataKeyIsRemote: true}, }) @@ -575,7 +575,7 @@ func TestIsRemoteSession(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-3", SessionID: "session-3", - RuntimeName: string(executor.NameStandalone), + RuntimeName: executor.NameStandalone, Status: v1.AgentStatusRunning, }) mgr := &Manager{executionStore: store} @@ -608,7 +608,7 @@ func TestIsRemoteSession(t *testing.T) { store := NewExecutionStore() provider := &mockWorkspaceInfoProvider{ infos: map[string]*WorkspaceInfo{ - "session-6": {RuntimeName: string(executor.NameSprites)}, + "session-6": {RuntimeName: executor.NameSprites}, }, } mgr := &Manager{executionStore: store, workspaceInfoProvider: provider} @@ -646,7 +646,7 @@ func TestShouldUseContainerShell(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-1", SessionID: "session-1", - RuntimeName: string(executor.NameDocker), + RuntimeName: executor.NameDocker, Status: v1.AgentStatusRunning, }) mgr := &Manager{executionStore: store} @@ -658,7 +658,7 @@ func TestShouldUseContainerShell(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-2", SessionID: "session-2", - RuntimeName: string(executor.NameSprites), + RuntimeName: executor.NameSprites, Status: v1.AgentStatusRunning, }) mgr := &Manager{executionStore: store} @@ -670,7 +670,7 @@ func TestShouldUseContainerShell(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-3", SessionID: "session-3", - RuntimeName: string(executor.NameStandalone), + RuntimeName: executor.NameStandalone, Status: v1.AgentStatusRunning, Metadata: map[string]interface{}{MetadataKeyIsRemote: true}, }) @@ -683,7 +683,7 @@ func TestShouldUseContainerShell(t *testing.T) { store.Add(&AgentExecution{ ID: "exec-4", SessionID: "session-4", - RuntimeName: string(executor.NameStandalone), + RuntimeName: executor.NameStandalone, Status: v1.AgentStatusRunning, }) mgr := &Manager{executionStore: store} @@ -716,7 +716,7 @@ func TestShouldUseContainerShell(t *testing.T) { store := NewExecutionStore() provider := &mockWorkspaceInfoProvider{ infos: map[string]*WorkspaceInfo{ - "session-7": {RuntimeName: string(executor.NameDocker)}, + "session-7": {RuntimeName: executor.NameDocker}, }, } mgr := &Manager{executionStore: store, workspaceInfoProvider: provider} diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go b/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go index b5e8d5a428..b5b53b15d7 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go @@ -493,19 +493,28 @@ func (m *Manager) runEnvironmentPreparerWithProgress( if m.preparerRegistry == nil { return nil } - // Look up preparer by the raw executor type first (e.g. "worktree"), - // then fall back to the backend name (e.g. "standalone"). - // This allows executor types that share a backend (local and worktree - // both map to standalone) to have distinct preparation logic. - execName := executor.Name(req.ExecutorType) - preparer := m.preparerRegistry.Get(execName) - if preparer == nil { - execName = executor.ExecutorTypeToBackend(models.ExecutorType(req.ExecutorType)) - preparer = m.preparerRegistry.Get(execName) + // Preparer registry is keyed by ExecutorType (the "local"/"worktree"/ + // "local_docker"/... taxonomy), not Runtime — so executor types that + // share a runtime backend (local + worktree both run on standalone) + // can still get distinct preparation logic. + execType := models.ExecutorType(req.ExecutorType) + preparer := m.preparerRegistry.Get(execType) + if preparer == nil && execType == "" { + // Fall back to LocalPreparer only for a genuinely empty ExecutorType + // — legacy task rows (e.g. PR-watcher-created tasks without an + // explicit executor) rely on local environment prep, including + // missing-branch detection. Typed-but-unregistered values like + // "remote_docker" intentionally return nil so the caller skips prep + // rather than running local git operations against a remote executor. + preparer = m.preparerRegistry.Get(models.ExecutorTypeLocal) } if preparer == nil { return nil } + // The EnvPrepareRequest carries the resolved Runtime (executor.Name), + // which preparer_script.go uses for runtime-level decisions like + // picking the default prepare template. + execName := execType.Runtime() // Skip environment preparation for repo-less tasks (e.g. config chat). // Preparers assume a repository is available; without one the session @@ -818,7 +827,7 @@ func (m *Manager) launchInternal(ctx context.Context, req *LaunchRequest) (*Agen m.logger.Debug("agentctl execution created (agent not started)", zap.String("execution_id", executionID), zap.String("task_id", req.TaskID), - zap.String("runtime", execution.RuntimeName)) + zap.Stringer("runtime", execution.RuntimeName)) return execution, nil } @@ -836,7 +845,7 @@ func (m *Manager) buildExecutionFromInstance( prepResult *EnvPrepareResult, ) *AgentExecution { execution := execInstance.ToAgentExecution(execReq) - execution.RuntimeName = string(rt.Name()) + execution.RuntimeName = rt.Name() if req.ACPSessionID != "" { execution.ACPSessionID = req.ACPSessionID } diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_launch_test.go b/apps/backend/internal/agent/runtime/lifecycle/manager_launch_test.go index add07db8a1..a01b4cd078 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_launch_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_launch_test.go @@ -14,6 +14,7 @@ import ( agentctl "github.com/kandev/kandev/internal/agent/runtime/agentctl" settingsmodels "github.com/kandev/kandev/internal/agent/settings/models" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/task/models" ) // resumeTestAgent is a minimal agent with a BuildCommand that respects the @@ -176,7 +177,7 @@ func TestLaunch_PublishesPrepareCompletedAfterRuntimeProgress(t *testing.T) { ExecutorFallbackWarn, "", log, ) mgr.preparerRegistry = NewPreparerRegistry(log) - mgr.preparerRegistry.Register(executor.NameDocker, &progressPreparer{}) + mgr.preparerRegistry.Register(models.ExecutorTypeLocalDocker, &progressPreparer{}) t.Cleanup(func() { close(mgr.stopCh) }) errCh := make(chan error, 1) @@ -242,12 +243,12 @@ func TestRunEnvironmentPreparer_CalledOnFreshLaunch(t *testing.T) { mgr := newTestManager() preparer := &trackingPreparer{} mgr.preparerRegistry = NewPreparerRegistry(mgr.logger) - mgr.preparerRegistry.Register(executor.NameStandalone, preparer) + mgr.preparerRegistry.Register(models.ExecutorTypeLocal, preparer) req := &LaunchRequest{ TaskID: "task-1", SessionID: "session-1", - ExecutorType: string(executor.NameStandalone), + ExecutorType: string(models.ExecutorTypeLocal), RepositoryPath: "/tmp/repo", } @@ -261,12 +262,12 @@ func TestRunEnvironmentPreparer_SkippedWithoutRepoPath(t *testing.T) { mgr := newTestManager() preparer := &trackingPreparer{} mgr.preparerRegistry = NewPreparerRegistry(mgr.logger) - mgr.preparerRegistry.Register(executor.NameStandalone, preparer) + mgr.preparerRegistry.Register(models.ExecutorTypeLocal, preparer) req := &LaunchRequest{ TaskID: "task-1", SessionID: "session-1", - ExecutorType: string(executor.NameStandalone), + ExecutorType: string(models.ExecutorTypeLocal), // No RepositoryPath — preparer should be skipped } diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_remote_status.go b/apps/backend/internal/agent/runtime/lifecycle/manager_remote_status.go index 1a4ebe7fa5..96cd395d7a 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_remote_status.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_remote_status.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/kandev/kandev/internal/agent/executor" + "github.com/kandev/kandev/internal/agentruntime" "go.uber.org/zap" ) @@ -35,7 +35,7 @@ func (m *Manager) pollOneRemoteStatus(ctx context.Context, execution *AgentExecu if execution == nil || execution.SessionID == "" || m.executorRegistry == nil { return } - rt, err := m.executorRegistry.GetBackend(executor.Name(execution.RuntimeName)) + rt, err := m.executorRegistry.GetBackend(execution.RuntimeName) if err != nil { return } @@ -66,7 +66,7 @@ func (m *Manager) pollOneRemoteStatus(ctx context.Context, execution *AgentExecu m.logger.Debug("remote status poll failed", zap.String("session_id", execution.SessionID), zap.String("execution_id", execution.ID), - zap.String("runtime", execution.RuntimeName), + zap.Stringer("runtime", execution.RuntimeName), zap.Error(statusErr)) return } @@ -127,7 +127,7 @@ func (m *Manager) GetRemoteStatusBySessionID(ctx context.Context, sessionID stri // for a session that is not currently tracked in the in-memory execution store. type RemoteStatusPollRecord struct { SessionID string - Runtime string + Runtime agentruntime.Runtime AgentExecutionID string ContainerID string Metadata map[string]interface{} @@ -144,7 +144,7 @@ func (m *Manager) PollRemoteStatusForRecords(ctx context.Context, records []Remo if rec.SessionID == "" || rec.Runtime == "" { continue } - rt, err := m.executorRegistry.GetBackend(executor.Name(rec.Runtime)) + rt, err := m.executorRegistry.GetBackend(rec.Runtime) if err != nil { continue } @@ -169,7 +169,7 @@ func (m *Manager) PollRemoteStatusForRecords(ctx context.Context, records []Remo }) m.logger.Debug("startup remote status poll failed", zap.String("session_id", rec.SessionID), - zap.String("runtime", rec.Runtime), + zap.Stringer("runtime", rec.Runtime), zap.Error(statusErr)) continue } @@ -185,7 +185,7 @@ func (m *Manager) PollRemoteStatusForRecords(ctx context.Context, records []Remo m.storeRemoteStatus(rec.SessionID, status) m.logger.Debug("startup remote status polled", zap.String("session_id", rec.SessionID), - zap.String("runtime", rec.Runtime), + zap.Stringer("runtime", rec.Runtime), zap.String("state", status.State)) } } diff --git a/apps/backend/internal/agent/runtime/lifecycle/types.go b/apps/backend/internal/agent/runtime/lifecycle/types.go index 91b946018b..a610ef8337 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/types.go +++ b/apps/backend/internal/agent/runtime/lifecycle/types.go @@ -12,6 +12,7 @@ import ( agentctl "github.com/kandev/kandev/internal/agent/runtime/agentctl" settingsmodels "github.com/kandev/kandev/internal/agent/settings/models" "github.com/kandev/kandev/internal/agentctl/types/streams" + "github.com/kandev/kandev/internal/agentruntime" "github.com/kandev/kandev/internal/common/ports" "github.com/kandev/kandev/internal/task/models" v1 "github.com/kandev/kandev/pkg/api/v1" @@ -30,12 +31,12 @@ type AgentExecution struct { AgentProfileID string AgentID string // Agent type ID (e.g., "claude-acp", "codex") — used for fallback auth methods ContainerID string - ContainerIP string // IP address of the container for agentctl communication - WorkspacePath string // Path to the workspace (worktree or repository path) - ACPSessionID string // ACP session ID to resume, if available - AgentCommand string // Command to start the agent subprocess - ContinueCommand string // Command for follow-up prompts (one-shot agents like Amp) - RuntimeName string // Name of the runtime used (e.g., "docker", "standalone") + ContainerIP string // IP address of the container for agentctl communication + WorkspacePath string // Path to the workspace (worktree or repository path) + ACPSessionID string // ACP session ID to resume, if available + AgentCommand string // Command to start the agent subprocess + ContinueCommand string // Command for follow-up prompts (one-shot agents like Amp) + RuntimeName agentruntime.Runtime // Name of the runtime used (e.g., "docker", "standalone") Status v1.AgentStatus StartedAt time.Time FinishedAt *time.Time @@ -462,7 +463,7 @@ type WorkspaceInfo struct { // Executor-aware fields for correct runtime selection and remote reconnection ExecutorType string // Executor type (e.g., "local_pc", "sprites") - RuntimeName string // Runtime name from ExecutorRunning record + RuntimeName agentruntime.Runtime // Runtime name from ExecutorRunning record AgentExecutionID string // Previous execution ID (for remote reconnect) Metadata map[string]interface{} // Additional metadata (reconnect flags) } diff --git a/apps/backend/internal/agentctl/server/acp/client.go b/apps/backend/internal/agentctl/server/acp/client.go index 2d1f0e9f10..b38354027f 100644 --- a/apps/backend/internal/agentctl/server/acp/client.go +++ b/apps/backend/internal/agentctl/server/acp/client.go @@ -146,7 +146,7 @@ func (c *Client) forwardPermissionRequest(ctx context.Context, handler Permissio options[i] = types.PermissionOption{ OptionID: string(opt.OptionId), Name: opt.Name, - Kind: string(opt.Kind), + Kind: types.PermissionOptionKind(opt.Kind), } } diff --git a/apps/backend/internal/agentctl/server/process/manager.go b/apps/backend/internal/agentctl/server/process/manager.go index 8e9c254f2c..8d6efb7a46 100644 --- a/apps/backend/internal/agentctl/server/process/manager.go +++ b/apps/backend/internal/agentctl/server/process/manager.go @@ -1284,7 +1284,7 @@ func (m *Manager) autoApprovePermission(req *adapter.PermissionRequest) (*adapte m.logger.Info("auto-approving permission request", zap.String("option_id", selectedOption.OptionID), zap.String("option_name", selectedOption.Name), - zap.String("kind", selectedOption.Kind)) + zap.String("kind", string(selectedOption.Kind))) return &adapter.PermissionResponse{ OptionID: selectedOption.OptionID, diff --git a/apps/backend/internal/agentctl/types/streams/permission.go b/apps/backend/internal/agentctl/types/streams/permission.go index e1bf43b521..1bb85cab38 100644 --- a/apps/backend/internal/agentctl/types/streams/permission.go +++ b/apps/backend/internal/agentctl/types/streams/permission.go @@ -2,25 +2,54 @@ package streams import "time" +// PermissionActionType categorizes the kind of action requiring approval. +// Values are stable wire-format strings shared across agentctl, the backend +// orchestrator, and the frontend. +type PermissionActionType string + +func (t PermissionActionType) String() string { return string(t) } + // Permission action types categorize the kind of action requiring approval. const ( // ActionTypeCommand indicates shell command execution. - ActionTypeCommand = "command" + ActionTypeCommand PermissionActionType = "command" // ActionTypeFileWrite indicates file modification or creation. - ActionTypeFileWrite = "file_write" + ActionTypeFileWrite PermissionActionType = "file_write" // ActionTypeFileRead indicates file read (for sensitive files). - ActionTypeFileRead = "file_read" + ActionTypeFileRead PermissionActionType = "file_read" // ActionTypeNetwork indicates network access. - ActionTypeNetwork = "network" + ActionTypeNetwork PermissionActionType = "network" // ActionTypeMCPTool indicates MCP tool invocation. - ActionTypeMCPTool = "mcp_tool" + ActionTypeMCPTool PermissionActionType = "mcp_tool" // ActionTypeOther indicates other/unknown action type. - ActionTypeOther = "other" + ActionTypeOther PermissionActionType = "other" +) + +// PermissionOptionKind identifies the semantics of a permission option +// presented to the user. Values are stable wire-format strings shared with +// the frontend. +type PermissionOptionKind string + +func (k PermissionOptionKind) String() string { return string(k) } + +// Permission option kinds describe the semantics of each available choice. +const ( + // PermissionOptionKindAllowOnce approves the current request only. + PermissionOptionKindAllowOnce PermissionOptionKind = "allow_once" + + // PermissionOptionKindAllowAlways approves and remembers the decision. + PermissionOptionKindAllowAlways PermissionOptionKind = "allow_always" + + // PermissionOptionKindRejectOnce rejects the current request only. + PermissionOptionKindRejectOnce PermissionOptionKind = "reject_once" + + // PermissionOptionKindRejectAlways rejects and remembers the decision. + PermissionOptionKindRejectAlways PermissionOptionKind = "reject_always" ) // PermissionNotification is the message type streamed via the permissions stream. @@ -45,7 +74,7 @@ type PermissionNotification struct { // ActionType categorizes the action requiring approval. // Use ActionType* constants: "command", "file_write", "file_read", "network", "mcp_tool", "other". - ActionType string `json:"action_type,omitempty"` + ActionType PermissionActionType `json:"action_type,omitempty"` // ActionDetails contains structured details about the action. // For commands: {"command": ["ls", "-la"], "cwd": "/path"} @@ -67,7 +96,7 @@ type PermissionOption struct { // Kind indicates the type of permission: "allow_once", "allow_always", // "reject_once", "reject_always". - Kind string `json:"kind"` + Kind PermissionOptionKind `json:"kind"` // Metadata contains protocol-specific option data. // For Codex: {"for_session": true} for session-wide approvals. diff --git a/apps/backend/internal/agentctl/types/types.go b/apps/backend/internal/agentctl/types/types.go index b9bd9fb3e1..6cc34de850 100644 --- a/apps/backend/internal/agentctl/types/types.go +++ b/apps/backend/internal/agentctl/types/types.go @@ -21,6 +21,8 @@ type ( // Permission stream types PermissionNotification = streams.PermissionNotification PermissionOption = streams.PermissionOption + PermissionActionType = streams.PermissionActionType + PermissionOptionKind = streams.PermissionOptionKind PermissionRespondRequest = streams.PermissionRespondRequest PermissionRespondResponse = streams.PermissionRespondResponse diff --git a/apps/backend/internal/gateway/websocket/vscode_proxy.go b/apps/backend/internal/gateway/websocket/vscode_proxy.go index 189c416f78..2e0d09e653 100644 --- a/apps/backend/internal/gateway/websocket/vscode_proxy.go +++ b/apps/backend/internal/gateway/websocket/vscode_proxy.go @@ -156,7 +156,7 @@ func (h *VscodeProxyHandler) resolveProxy(c *gin.Context, sessionID string) (*ht h.logger.Info("created vscode proxy for session", zap.String("session_id", sessionID), zap.String("execution_id", execution.ID), - zap.String("runtime", execution.RuntimeName), + zap.Stringer("runtime", execution.RuntimeName), zap.String("target", baseURL)) return proxy, nil } diff --git a/apps/backend/internal/office/approvals/service.go b/apps/backend/internal/office/approvals/service.go index fb458f3c8b..aaef3d2a01 100644 --- a/apps/backend/internal/office/approvals/service.go +++ b/apps/backend/internal/office/approvals/service.go @@ -7,6 +7,7 @@ import ( "time" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/office/models" "github.com/kandev/kandev/internal/office/shared" "go.uber.org/zap" @@ -100,7 +101,7 @@ func (s *ApprovalService) DecideApproval( } now := time.Now().UTC() - approval.Status = status + approval.Status = models.ApprovalStatus(status) approval.DecisionNote = note approval.DecidedBy = decidedBy approval.DecidedAt = &now diff --git a/apps/backend/internal/office/channels/handler.go b/apps/backend/internal/office/channels/handler.go index 002b3119d1..825e9a11e6 100644 --- a/apps/backend/internal/office/channels/handler.go +++ b/apps/backend/internal/office/channels/handler.go @@ -48,9 +48,9 @@ func (h *Handler) setupChannel(c *gin.Context) { channel := &models.Channel{ WorkspaceID: req.WorkspaceID, AgentProfileID: c.Param("id"), - Platform: req.Platform, + Platform: models.ChannelPlatform(req.Platform), Config: req.Config, - Status: req.Status, + Status: models.ChannelStatus(req.Status), } if err := h.svc.SetupChannel(c.Request.Context(), channel); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) @@ -96,7 +96,7 @@ func (h *Handler) channelInbound(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": "empty message body"}) return } - if channel.WebhookSecret != "" && !verifyWebhookSignature(channel.WebhookSecret, channel.Platform, body, webhookSignature(c)) { + if channel.WebhookSecret != "" && !verifyWebhookSignature(channel.WebhookSecret, string(channel.Platform), body, webhookSignature(c)) { c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid signature"}) return } diff --git a/apps/backend/internal/office/channels/relay.go b/apps/backend/internal/office/channels/relay.go index 9c423ed6a8..d500e04bef 100644 --- a/apps/backend/internal/office/channels/relay.go +++ b/apps/backend/internal/office/channels/relay.go @@ -63,7 +63,7 @@ func (r *ChannelRelay) RelayComment(ctx context.Context, comment *models.TaskCom if r.svc.runs != nil { runID = r.svc.runs.ResolveRunForTask(ctx, comment.TaskID) } - sendErr := r.sendWithRetry(ctx, channel.Platform, config, comment.Body) + sendErr := r.sendWithRetry(ctx, string(channel.Platform), config, comment.Body) if sendErr != nil { r.svc.activity.LogActivityWithRun(ctx, channel.WorkspaceID, "system", "", "channel.delivery_failed", "channel", channel.ID, diff --git a/apps/backend/internal/office/channels/service.go b/apps/backend/internal/office/channels/service.go index 7625f9bd27..318e14b35a 100644 --- a/apps/backend/internal/office/channels/service.go +++ b/apps/backend/internal/office/channels/service.go @@ -116,7 +116,7 @@ func (s *ChannelService) SetupChannel(ctx context.Context, channel *models.Chann s.logger.Info("channel setup complete", zap.String("channel_id", channel.ID), - zap.String("platform", channel.Platform), + zap.String("platform", string(channel.Platform)), zap.String("task_id", taskID)) s.activity.LogActivity(ctx, channel.WorkspaceID, "user", "", @@ -150,7 +150,7 @@ func (s *ChannelService) UpdateChannelStatus(ctx context.Context, id, status str if err != nil { return err } - channel.Status = status + channel.Status = models.ChannelStatus(status) return s.repo.UpdateChannel(ctx, channel) } @@ -177,7 +177,7 @@ func (s *ChannelService) HandleChannelInbound( AuthorType: "user", AuthorID: authorName, Body: body, - Source: channel.Platform, + Source: string(channel.Platform), ReplyChannelID: channel.ID, } return s.CreateComment(ctx, comment) diff --git a/apps/backend/internal/office/config/import.go b/apps/backend/internal/office/config/import.go index c85f1f44a2..411e3fafbf 100644 --- a/apps/backend/internal/office/config/import.go +++ b/apps/backend/internal/office/config/import.go @@ -196,7 +196,7 @@ func (s *ConfigService) applySkills( if skill, ok := bySlug[cfg.Slug]; ok { skill.Name = cfg.Name skill.Description = cfg.Description - skill.SourceType = cfg.SourceType + skill.SourceType = models.SkillSourceType(cfg.SourceType) skill.Content = cfg.Content if err := s.repo.UpdateSkill(ctx, skill); err != nil { return err @@ -208,7 +208,7 @@ func (s *ConfigService) applySkills( Name: cfg.Name, Slug: cfg.Slug, Description: cfg.Description, - SourceType: cfg.SourceType, + SourceType: models.SkillSourceType(cfg.SourceType), Content: cfg.Content, } if err := s.repo.CreateSkill(ctx, skill); err != nil { @@ -235,7 +235,7 @@ func (s *ConfigService) applyRoutines( if routine, ok := byName[cfg.Name]; ok { routine.Description = cfg.Description routine.TaskTemplate = cfg.TaskTemplate - routine.ConcurrencyPolicy = cfg.ConcurrencyPolicy + routine.ConcurrencyPolicy = models.RoutineConcurrencyPolicy(cfg.ConcurrencyPolicy) if err := s.repo.UpdateRoutine(ctx, routine); err != nil { return err } @@ -247,7 +247,7 @@ func (s *ConfigService) applyRoutines( Description: cfg.Description, TaskTemplate: cfg.TaskTemplate, Status: "active", - ConcurrencyPolicy: cfg.ConcurrencyPolicy, + ConcurrencyPolicy: models.RoutineConcurrencyPolicy(cfg.ConcurrencyPolicy), } if err := s.repo.CreateRoutine(ctx, routine); err != nil { return err diff --git a/apps/backend/internal/office/config/service.go b/apps/backend/internal/office/config/service.go index b604917810..19fb7eae6e 100644 --- a/apps/backend/internal/office/config/service.go +++ b/apps/backend/internal/office/config/service.go @@ -102,7 +102,7 @@ func (s *ConfigService) exportSkills(ctx context.Context, _ string, bundle *Conf Name: sk.Name, Slug: sk.Slug, Description: sk.Description, - SourceType: sk.SourceType, + SourceType: string(sk.SourceType), Content: sk.Content, } bundle.Skills = append(bundle.Skills, cfg) @@ -129,7 +129,7 @@ func (s *ConfigService) exportRoutines(ctx context.Context, _ string, bundle *Co Description: r.Description, TaskTemplate: r.TaskTemplate, AssigneeName: nameByID[r.AssigneeAgentProfileID], - ConcurrencyPolicy: r.ConcurrencyPolicy, + ConcurrencyPolicy: string(r.ConcurrencyPolicy), } bundle.Routines = append(bundle.Routines, cfg) } diff --git a/apps/backend/internal/office/config/sync.go b/apps/backend/internal/office/config/sync.go index 26f381858b..7911d5214a 100644 --- a/apps/backend/internal/office/config/sync.go +++ b/apps/backend/internal/office/config/sync.go @@ -27,13 +27,13 @@ func (s *ConfigService) ScanFilesystem(_ context.Context, _ string) (*ConfigBund for _, sk := range s.cfgLoader.GetSkills(defaultWorkspaceName) { bundle.Skills = append(bundle.Skills, SkillConfig{ Name: sk.Name, Slug: sk.Slug, Description: sk.Description, - SourceType: sk.SourceType, Content: sk.Content, + SourceType: string(sk.SourceType), Content: sk.Content, }) } for _, r := range s.cfgLoader.GetRoutines(defaultWorkspaceName) { bundle.Routines = append(bundle.Routines, RoutineConfig{ Name: r.Name, Description: r.Description, TaskTemplate: r.TaskTemplate, - ConcurrencyPolicy: r.ConcurrencyPolicy, + ConcurrencyPolicy: string(r.ConcurrencyPolicy), }) } for _, p := range s.cfgLoader.GetProjects(defaultWorkspaceName) { diff --git a/apps/backend/internal/office/config/sync_util.go b/apps/backend/internal/office/config/sync_util.go index 511a9dc245..804fc326d7 100644 --- a/apps/backend/internal/office/config/sync_util.go +++ b/apps/backend/internal/office/config/sync_util.go @@ -145,7 +145,7 @@ func writeBundleEntities(w *configloader.FileWriter, bundle *ConfigBundle) error for _, r := range bundle.Routines { routine := &models.Routine{ Name: r.Name, Description: r.Description, TaskTemplate: r.TaskTemplate, - ConcurrencyPolicy: r.ConcurrencyPolicy, + ConcurrencyPolicy: models.RoutineConcurrencyPolicy(r.ConcurrencyPolicy), } if err := w.WriteRoutine(defaultWorkspaceName, routine); err != nil { return err diff --git a/apps/backend/internal/office/configloader/yaml.go b/apps/backend/internal/office/configloader/yaml.go index 9bd822fc6c..0bd4ba755b 100644 --- a/apps/backend/internal/office/configloader/yaml.go +++ b/apps/backend/internal/office/configloader/yaml.go @@ -197,7 +197,7 @@ func MarshalRoutine(routine *models.Routine) ([]byte, error) { Description: routine.Description, TaskTemplate: routine.TaskTemplate, Status: routine.Status, - ConcurrencyPolicy: routine.ConcurrencyPolicy, + ConcurrencyPolicy: string(routine.ConcurrencyPolicy), Variables: routine.Variables, } return yaml.Marshal(y) @@ -217,7 +217,7 @@ func UnmarshalRoutine(data []byte, workspaceID string) (*models.Routine, error) Description: y.Description, TaskTemplate: y.TaskTemplate, Status: y.Status, - ConcurrencyPolicy: y.ConcurrencyPolicy, + ConcurrencyPolicy: models.RoutineConcurrencyPolicy(y.ConcurrencyPolicy), Variables: y.Variables, CreatedAt: now, UpdatedAt: now, diff --git a/apps/backend/internal/office/costs/budgets.go b/apps/backend/internal/office/costs/budgets.go index 15ae0a1782..18b4292fe6 100644 --- a/apps/backend/internal/office/costs/budgets.go +++ b/apps/backend/internal/office/costs/budgets.go @@ -103,7 +103,7 @@ func (s *CostService) evaluatePolicy( limit := policy.LimitSubcents result := BudgetCheckResult{ PolicyID: policy.ID, - ActionOnExceed: policy.ActionOnExceed, + ActionOnExceed: string(policy.ActionOnExceed), SpentSubcents: spent, LimitSubcents: limit, } @@ -140,7 +140,7 @@ func (s *CostService) getSpendForPolicy( workspaceID string, policy *BudgetPolicy, ) (int64, error) { - since := periodCutoff(policy.Period, time.Now()) + since := periodCutoff(string(policy.Period), time.Now()) switch policy.ScopeType { case scopeAgent: return s.repo.GetCostForAgentSince(ctx, policy.ScopeID, since) @@ -160,7 +160,7 @@ func (s *CostService) logBudgetAlert( spentSubcents int64, ) { s.activity.LogActivity(ctx, workspaceID, "system", "budget_checker", - "budget.alert", policy.ScopeType, policy.ScopeID, + "budget.alert", string(policy.ScopeType), policy.ScopeID, fmt.Sprintf(`{"spent_subcents":%d,"limit_subcents":%d,"period":%q,"policy_id":%q}`, spentSubcents, policy.LimitSubcents, policy.Period, policy.ID)) } @@ -172,7 +172,7 @@ func (s *CostService) logBudgetExceeded( spentSubcents int64, ) { s.activity.LogActivity(ctx, workspaceID, "system", "budget_checker", - "budget.exceeded", policy.ScopeType, policy.ScopeID, + "budget.exceeded", string(policy.ScopeType), policy.ScopeID, fmt.Sprintf(`{"spent_subcents":%d,"limit_subcents":%d,"period":%q,"action":%q,"policy_id":%q}`, spentSubcents, policy.LimitSubcents, policy.Period, policy.ActionOnExceed, policy.ID)) } diff --git a/apps/backend/internal/office/costs/handler.go b/apps/backend/internal/office/costs/handler.go index f8395a3e6f..cc44b5dae8 100644 --- a/apps/backend/internal/office/costs/handler.go +++ b/apps/backend/internal/office/costs/handler.go @@ -4,6 +4,8 @@ import ( "net/http" "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/office/models" ) // Handler provides HTTP handlers for cost and budget routes. @@ -132,14 +134,29 @@ func (h *Handler) createBudget(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } + scopeType := models.BudgetScopeType(req.ScopeType) + period := models.BudgetPeriod(req.Period) + action := models.BudgetActionOnExceed(req.ActionOnExceed) + if !scopeType.Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid scope_type: " + req.ScopeType}) + return + } + if !period.Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid period: " + req.Period}) + return + } + if !action.Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid action_on_exceed: " + req.ActionOnExceed}) + return + } policy := &BudgetPolicy{ WorkspaceID: c.Param("wsId"), - ScopeType: req.ScopeType, + ScopeType: scopeType, ScopeID: req.ScopeID, LimitSubcents: req.LimitSubcents, - Period: req.Period, + Period: period, AlertThresholdPct: req.AlertThresholdPct, - ActionOnExceed: req.ActionOnExceed, + ActionOnExceed: action, } if err := h.svc.CreateBudgetPolicy(c.Request.Context(), policy); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) @@ -154,6 +171,18 @@ func (h *Handler) updateBudget(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } + if req.ScopeType != nil && !models.BudgetScopeType(*req.ScopeType).Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid scope_type: " + *req.ScopeType}) + return + } + if req.Period != nil && !models.BudgetPeriod(*req.Period).Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid period: " + *req.Period}) + return + } + if req.ActionOnExceed != nil && !models.BudgetActionOnExceed(*req.ActionOnExceed).Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid action_on_exceed: " + *req.ActionOnExceed}) + return + } policy, err := h.svc.GetBudgetPolicy(c.Request.Context(), c.Param("id")) if err != nil { c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) @@ -169,7 +198,7 @@ func (h *Handler) updateBudget(c *gin.Context) { func applyBudgetPatch(policy *BudgetPolicy, req *UpdateBudgetRequest) { if req.ScopeType != nil { - policy.ScopeType = *req.ScopeType + policy.ScopeType = models.BudgetScopeType(*req.ScopeType) } if req.ScopeID != nil { policy.ScopeID = *req.ScopeID @@ -178,13 +207,13 @@ func applyBudgetPatch(policy *BudgetPolicy, req *UpdateBudgetRequest) { policy.LimitSubcents = *req.LimitSubcents } if req.Period != nil { - policy.Period = *req.Period + policy.Period = models.BudgetPeriod(*req.Period) } if req.AlertThresholdPct != nil { policy.AlertThresholdPct = *req.AlertThresholdPct } if req.ActionOnExceed != nil { - policy.ActionOnExceed = *req.ActionOnExceed + policy.ActionOnExceed = models.BudgetActionOnExceed(*req.ActionOnExceed) } } diff --git a/apps/backend/internal/office/dashboard/handler_inbox.go b/apps/backend/internal/office/dashboard/handler_inbox.go index 2ccd2c674c..668e624151 100644 --- a/apps/backend/internal/office/dashboard/handler_inbox.go +++ b/apps/backend/internal/office/dashboard/handler_inbox.go @@ -127,14 +127,14 @@ func runToListItem(r *models.Run) RunListItem { taskID, _ := parseRunPayload(r.Payload) routingBlocked := "" if r.RoutingBlockedStatus != nil { - routingBlocked = *r.RoutingBlockedStatus + routingBlocked = string(*r.RoutingBlockedStatus) } item := RunListItem{ ID: r.ID, AgentProfileID: r.AgentProfileID, Reason: r.Reason, Payload: r.Payload, - Status: r.Status, + Status: string(r.Status), CoalescedCount: r.CoalescedCount, IdempotencyKey: r.IdempotencyKey, ContextSnapshot: r.ContextSnapshot, diff --git a/apps/backend/internal/office/dashboard/routing_dto.go b/apps/backend/internal/office/dashboard/routing_dto.go index 5116f8e2d2..8f726f5c08 100644 --- a/apps/backend/internal/office/dashboard/routing_dto.go +++ b/apps/backend/internal/office/dashboard/routing_dto.go @@ -123,10 +123,10 @@ func routeAttemptToDTO(a models.RouteAttempt) RouteAttemptDTO { ProviderID: a.ProviderID, Model: a.Model, Tier: a.Tier, - Outcome: a.Outcome, + Outcome: string(a.Outcome), ErrorCode: a.ErrorCode, - ErrorConfidence: a.ErrorConfidence, - AdapterPhase: a.AdapterPhase, + ErrorConfidence: string(a.ErrorConfidence), + AdapterPhase: string(a.AdapterPhase), ClassifierRule: a.ClassifierRule, ExitCode: a.ExitCode, RawExcerpt: a.RawExcerpt, diff --git a/apps/backend/internal/office/dashboard/run_detail.go b/apps/backend/internal/office/dashboard/run_detail.go index a824fd4099..133aa796f1 100644 --- a/apps/backend/internal/office/dashboard/run_detail.go +++ b/apps/backend/internal/office/dashboard/run_detail.go @@ -135,7 +135,7 @@ func buildRunSummaryDTO(run *models.Run) AgentRunSummaryDTO { ID: run.ID, IDShort: shortID(run.ID), Reason: run.Reason, - Status: run.Status, + Status: string(run.Status), ErrorMessage: run.ErrorMessage, TaskID: taskIDFromPayload(run.Payload), CommentID: commentID, @@ -234,8 +234,8 @@ func GetRunDetail( for i, e := range events { eventDTOs[i] = RunEventDTO{ Seq: e.Seq, - EventType: e.EventType, - Level: e.Level, + EventType: string(e.EventType), + Level: string(e.Level), Payload: e.Payload, CreatedAt: e.CreatedAt.UTC().Format(time.RFC3339), } @@ -253,7 +253,7 @@ func GetRunDetail( IDShort: shortID(run.ID), AgentID: run.AgentProfileID, Reason: run.Reason, - Status: run.Status, + Status: string(run.Status), ErrorMessage: run.ErrorMessage, TaskID: taskIDFromPayload(run.Payload), RequestedAt: run.RequestedAt.UTC().Format(time.RFC3339), @@ -317,7 +317,7 @@ func buildRunRouting( out.ResolvedModel = *run.ResolvedModel } if run.RoutingBlockedStatus != nil { - out.BlockedStatus = *run.RoutingBlockedStatus + out.BlockedStatus = string(*run.RoutingBlockedStatus) } if run.EarliestRetryAt != nil && !run.EarliestRetryAt.IsZero() { s := run.EarliestRetryAt.UTC().Format(time.RFC3339) diff --git a/apps/backend/internal/office/dashboard/run_detail_routing_test.go b/apps/backend/internal/office/dashboard/run_detail_routing_test.go index 826e9b65b9..a1df966667 100644 --- a/apps/backend/internal/office/dashboard/run_detail_routing_test.go +++ b/apps/backend/internal/office/dashboard/run_detail_routing_test.go @@ -54,7 +54,7 @@ func TestBuildRunRouting_PopulatesAttemptsAndSnapshot(t *testing.T) { tier := "frontier" prov := "claude-acp" model := "opus" - blocked := "waiting_for_provider_capacity" + blocked := models.RoutingBlockedStatus("waiting_for_provider_capacity") retry := time.Now().UTC().Add(time.Minute) run := &models.Run{ ID: "r1", @@ -85,7 +85,7 @@ func TestBuildRunRouting_PopulatesAttemptsAndSnapshot(t *testing.T) { if len(out.LogicalProviderOrder) != 2 || out.LogicalProviderOrder[0] != "claude-acp" { t.Errorf("order = %v", out.LogicalProviderOrder) } - if out.BlockedStatus != blocked { + if out.BlockedStatus != string(blocked) { t.Errorf("blocked = %q", out.BlockedStatus) } if out.EarliestRetryAt == nil { diff --git a/apps/backend/internal/office/dashboard/service_inbox.go b/apps/backend/internal/office/dashboard/service_inbox.go index 249a6162da..f4cd3573f7 100644 --- a/apps/backend/internal/office/dashboard/service_inbox.go +++ b/apps/backend/internal/office/dashboard/service_inbox.go @@ -123,7 +123,7 @@ func (s *DashboardService) inboxApprovalItems(ctx context.Context, wsID string) ID: a.ID, Type: "approval", Title: approvalTitle(a), - Status: a.Status, + Status: string(a.Status), EntityID: a.ID, EntityType: "approval", CreatedAt: a.CreatedAt, @@ -150,7 +150,7 @@ func (s *DashboardService) inboxBudgetAlertItems(ctx context.Context, wsID strin Description: e.Details, Status: "active", EntityID: e.TargetID, - EntityType: e.TargetType, + EntityType: string(e.TargetType), CreatedAt: e.CreatedAt, } items = append(items, item) @@ -172,7 +172,7 @@ func (s *DashboardService) inboxAgentErrorItems(ctx context.Context, wsID string Description: e.Details, Status: "active", EntityID: e.TargetID, - EntityType: e.TargetType, + EntityType: string(e.TargetType), CreatedAt: e.CreatedAt, } items = append(items, item) diff --git a/apps/backend/internal/office/dashboard/service_inbox_routing.go b/apps/backend/internal/office/dashboard/service_inbox_routing.go index e0a6044cf2..acca55404a 100644 --- a/apps/backend/internal/office/dashboard/service_inbox_routing.go +++ b/apps/backend/internal/office/dashboard/service_inbox_routing.go @@ -116,7 +116,7 @@ func buildProviderDegradedItem( Type: inboxProviderDegradedType, Title: providerDegradedTitle(h), Description: truncateInboxDescription(h.RawExcerpt), - Status: h.State, + Status: string(h.State), EntityID: h.ProviderID, EntityType: "provider", Payload: map[string]interface{}{ diff --git a/apps/backend/internal/office/models/enums.go b/apps/backend/internal/office/models/enums.go new file mode 100644 index 0000000000..351572754f --- /dev/null +++ b/apps/backend/internal/office/models/enums.go @@ -0,0 +1,403 @@ +// Package models — enum types. +// +// This file colocates the named string types used by office structs. +// Each type wraps the existing magic-string vocabulary so callsites can +// compare against typed constants instead of bare string literals. The +// underlying type is `string` in every case, so `database/sql` Scan / +// `driver.Value` bind, and JSON marshaling, all continue to work +// without custom hooks. +// +// Convention: typed-string + untyped const, with a `String()` method. +// Untyped consts let existing comparison sites keep working when the +// struct field gets re-typed. +package models + +// ApprovalStatus is the lifecycle state of an Approval row. +type ApprovalStatus string + +// Approval status values. See internal/office/approvals/service.go for +// the state machine (pending → approved | rejected). +const ( + ApprovalStatusPending ApprovalStatus = "pending" + ApprovalStatusApproved ApprovalStatus = "approved" + ApprovalStatusRejected ApprovalStatus = "rejected" +) + +// String implements fmt.Stringer. +func (s ApprovalStatus) String() string { return string(s) } + +// RunStatus is the scheduler queue state for a Run row. +// See internal/office/scheduler/run.go for the state machine. +type RunStatus string + +// Run queue status values. +const ( + RunStatusQueued RunStatus = "queued" + RunStatusClaimed RunStatus = "claimed" + RunStatusFinished RunStatus = "finished" + RunStatusFailed RunStatus = "failed" +) + +// String implements fmt.Stringer. +func (s RunStatus) String() string { return string(s) } + +// RoutineRunStatus is the lifecycle state of a RoutineRun row. +// See internal/office/routines/service.go for the state machine. +type RoutineRunStatus string + +// Routine run status values. +const ( + RoutineRunStatusReceived RoutineRunStatus = "received" + RoutineRunStatusTaskCreated RoutineRunStatus = "task_created" + RoutineRunStatusSkipped RoutineRunStatus = "skipped" + RoutineRunStatusCoalesced RoutineRunStatus = "coalesced" + RoutineRunStatusFailed RoutineRunStatus = "failed" + RoutineRunStatusDone RoutineRunStatus = "done" + RoutineRunStatusCancelled RoutineRunStatus = "cancelled" +) + +// String implements fmt.Stringer. +func (s RoutineRunStatus) String() string { return string(s) } + +// RoutineConcurrencyPolicy controls what happens when a routine fires +// while a previous run is still in flight. +type RoutineConcurrencyPolicy string + +// Routine concurrency policy values. +const ( + ConcurrencyPolicySkipIfActive RoutineConcurrencyPolicy = "skip_if_active" + ConcurrencyPolicyCoalesceIfActive RoutineConcurrencyPolicy = "coalesce_if_active" + ConcurrencyPolicyAlwaysCreate RoutineConcurrencyPolicy = "always_create" +) + +// String implements fmt.Stringer. +func (p RoutineConcurrencyPolicy) String() string { return string(p) } + +// Valid reports whether p is one of the declared RoutineConcurrencyPolicy values. +// Use at trust boundaries (HTTP handlers, config loaders) to reject malformed input. +func (p RoutineConcurrencyPolicy) Valid() bool { + switch p { + case ConcurrencyPolicySkipIfActive, ConcurrencyPolicyCoalesceIfActive, ConcurrencyPolicyAlwaysCreate: + return true + } + return false +} + +// RoutineCatchUpPolicy controls what happens when a scheduled routine +// missed fires (e.g. backend was down). +type RoutineCatchUpPolicy string + +// Routine catch-up policy values. The DB default is +// `enqueue_missed_with_cap`; the alternative skips missed fires entirely. +const ( + CatchUpPolicyEnqueueMissedWithCap RoutineCatchUpPolicy = "enqueue_missed_with_cap" + CatchUpPolicySkipMissed RoutineCatchUpPolicy = "skip_missed" +) + +// String implements fmt.Stringer. +func (p RoutineCatchUpPolicy) String() string { return string(p) } + +// Valid reports whether p is one of the declared RoutineCatchUpPolicy values. +func (p RoutineCatchUpPolicy) Valid() bool { + switch p { + case CatchUpPolicyEnqueueMissedWithCap, CatchUpPolicySkipMissed: + return true + } + return false +} + +// BudgetScopeType selects what a BudgetPolicy applies to. +type BudgetScopeType string + +// Budget scope-type values. +const ( + BudgetScopeAgent BudgetScopeType = "agent" + BudgetScopeProject BudgetScopeType = "project" + BudgetScopeWorkspace BudgetScopeType = "workspace" +) + +// String implements fmt.Stringer. +func (s BudgetScopeType) String() string { return string(s) } + +// Valid reports whether s is one of the declared BudgetScopeType values. +// Use at trust boundaries (HTTP handlers, config loaders) to reject +// malformed input before it reaches the cost service. +func (s BudgetScopeType) Valid() bool { + switch s { + case BudgetScopeAgent, BudgetScopeProject, BudgetScopeWorkspace: + return true + } + return false +} + +// BudgetPeriod is the time window a BudgetPolicy limit applies to. +type BudgetPeriod string + +// Budget period values. +const ( + BudgetPeriodDaily BudgetPeriod = "daily" + BudgetPeriodMonthly BudgetPeriod = "monthly" + BudgetPeriodYearly BudgetPeriod = "yearly" +) + +// String implements fmt.Stringer. +func (p BudgetPeriod) String() string { return string(p) } + +// Valid reports whether p is one of the declared BudgetPeriod values. +func (p BudgetPeriod) Valid() bool { + switch p { + case BudgetPeriodDaily, BudgetPeriodMonthly, BudgetPeriodYearly: + return true + } + return false +} + +// BudgetActionOnExceed is the side-effect a BudgetPolicy triggers on +// limit breach. +type BudgetActionOnExceed string + +// Budget action values. The set matches what the cost service writes; +// see internal/office/costs/budgets.go. +const ( + BudgetActionPauseAgent BudgetActionOnExceed = "pause_agent" + BudgetActionBlockNewTasks BudgetActionOnExceed = "block_new_tasks" + BudgetActionNotifyOnly BudgetActionOnExceed = "notify_only" +) + +// String implements fmt.Stringer. +func (a BudgetActionOnExceed) String() string { return string(a) } + +// Valid reports whether a is one of the declared BudgetActionOnExceed values. +func (a BudgetActionOnExceed) Valid() bool { + switch a { + case BudgetActionPauseAgent, BudgetActionBlockNewTasks, BudgetActionNotifyOnly: + return true + } + return false +} + +// ProviderHealthScope identifies what slice of a provider a +// ProviderHealth row covers. +type ProviderHealthScope string + +// Provider-health scope values. The triple +// (workspace_id, provider_id, scope, scope_value) is the PK so a +// tier-specific failure does not take the whole provider down. +const ( + ProviderHealthScopeProvider ProviderHealthScope = "provider" + ProviderHealthScopeTier ProviderHealthScope = "tier" + ProviderHealthScopeModel ProviderHealthScope = "model" +) + +// String implements fmt.Stringer. +func (s ProviderHealthScope) String() string { return string(s) } + +// ProviderHealthState is the current eligibility state of a +// (workspace, provider, scope) tuple. +type ProviderHealthState string + +// Provider-health state values. user_action_required is the +// "blocked, won't auto-recover" terminal state; degraded is auto-retryable. +const ( + ProviderHealthHealthy ProviderHealthState = "healthy" + ProviderHealthDegraded ProviderHealthState = "degraded" + ProviderHealthUserActionRequired ProviderHealthState = "user_action_required" +) + +// String implements fmt.Stringer. +func (s ProviderHealthState) String() string { return string(s) } + +// RoutingBlockedStatus is the "park reason" written onto Run when no +// provider can be selected. +type RoutingBlockedStatus string + +// Routing blocked-status values. +const ( + RoutingBlockedWaitingForCapacity RoutingBlockedStatus = "waiting_for_provider_capacity" + RoutingBlockedActionRequired RoutingBlockedStatus = "blocked_provider_action_required" +) + +// String implements fmt.Stringer. +func (s RoutingBlockedStatus) String() string { return string(s) } + +// RouteAttemptOutcome is the result of one route attempt persisted to +// office_route_attempts. See internal/office/scheduler/dispatch_routing.go +// for the lifecycle. +type RouteAttemptOutcome string + +// Route attempt outcome values. +const ( + RouteAttemptOutcomeLaunched RouteAttemptOutcome = "launched" + RouteAttemptOutcomeFailedProviderUnavail RouteAttemptOutcome = "failed_provider_unavailable" + RouteAttemptOutcomeFailedOther RouteAttemptOutcome = "failed_other" + RouteAttemptOutcomeSkippedDegraded RouteAttemptOutcome = "skipped_degraded" + RouteAttemptOutcomeSkippedUserAction RouteAttemptOutcome = "skipped_user_action" + RouteAttemptOutcomeSkippedMissingMapping RouteAttemptOutcome = "skipped_missing_mapping" + RouteAttemptOutcomeMaxAttempts RouteAttemptOutcome = "skipped_max_attempts" +) + +// String implements fmt.Stringer. +func (o RouteAttemptOutcome) String() string { return string(o) } + +// AdapterPhase narrows the lifecycle stage at which a routing error +// surfaced. Mirrors routingerr.Phase; redeclared so office-tier types +// have no dependency on the runtime tier. +type AdapterPhase string + +// Adapter phase values. Source of truth: +// internal/agent/runtime/routingerr/routingerr.go. +const ( + AdapterPhaseAuthCheck AdapterPhase = "auth_check" + AdapterPhaseProcessStart AdapterPhase = "process_start" + AdapterPhaseSessionInit AdapterPhase = "session_init" + AdapterPhasePromptSend AdapterPhase = "prompt_send" + AdapterPhaseStreaming AdapterPhase = "streaming" + AdapterPhaseToolExecution AdapterPhase = "tool_execution" + AdapterPhaseShutdown AdapterPhase = "shutdown" +) + +// String implements fmt.Stringer. +func (p AdapterPhase) String() string { return string(p) } + +// ErrorConfidence is the classifier's confidence in its verdict. +// Mirrors routingerr.Confidence. +type ErrorConfidence string + +// Error confidence values. +const ( + ErrorConfidenceHigh ErrorConfidence = "high" + ErrorConfidenceMedium ErrorConfidence = "medium" + ErrorConfidenceLow ErrorConfidence = "low" +) + +// String implements fmt.Stringer. +func (c ErrorConfidence) String() string { return string(c) } + +// SkillSourceType identifies where a Skill row's content came from. +// Mirrors the TS union in apps/web/lib/state/slices/office/types.ts. +type SkillSourceType string + +// Skill source-type values. +const ( + SkillSourceTypeInline SkillSourceType = "inline" + SkillSourceTypeLocalPath SkillSourceType = "local_path" + SkillSourceTypeGit SkillSourceType = "git" + SkillSourceTypeSkillsSh SkillSourceType = "skills_sh" + SkillSourceTypeUserHome SkillSourceType = "user_home" + SkillSourceTypeSystem SkillSourceType = "system" +) + +// String implements fmt.Stringer. +func (s SkillSourceType) String() string { return string(s) } + +// SkillApprovalState gates whether a Skill row is usable. +type SkillApprovalState string + +// Skill approval-state values. +const ( + SkillApprovalStatePending SkillApprovalState = "pending" + SkillApprovalStateApproved SkillApprovalState = "approved" + SkillApprovalStateRejected SkillApprovalState = "rejected" +) + +// String implements fmt.Stringer. +func (s SkillApprovalState) String() string { return string(s) } + +// RunEventLevel is the severity classification of a RunEvent row. +// Free-form by convention: info | warn | error. +type RunEventLevel string + +// Run event level values. +const ( + RunEventLevelInfo RunEventLevel = "info" + RunEventLevelWarn RunEventLevel = "warn" + RunEventLevelError RunEventLevel = "error" +) + +// String implements fmt.Stringer. +func (l RunEventLevel) String() string { return string(l) } + +// RunEventType is the kind of a RunEvent. Open set (init, step, +// adapter.invoke, complete, error, runtime.denied, runtime.action, …). +// Typed for documentation, not for exhaustiveness. +type RunEventType string + +// Well-known run event types. Adapters may emit additional values. +const ( + RunEventTypeInit RunEventType = "init" + RunEventTypeAdapterInvoke RunEventType = "adapter.invoke" + RunEventTypeStep RunEventType = "step" + RunEventTypeComplete RunEventType = "complete" + RunEventTypeError RunEventType = "error" + RunEventTypeRuntimeDenied RunEventType = "runtime.denied" + RunEventTypeRuntimeAction RunEventType = "runtime.action" +) + +// String implements fmt.Stringer. +func (t RunEventType) String() string { return string(t) } + +// ChannelPlatform is the external service a Channel row relays to. +// Open set — new adapters add new platforms. +type ChannelPlatform string + +// Known channel platforms. +const ( + ChannelPlatformSlack ChannelPlatform = "slack" + ChannelPlatformWebhook ChannelPlatform = "webhook" +) + +// String implements fmt.Stringer. +func (p ChannelPlatform) String() string { return string(p) } + +// ChannelStatus is the operational state of a Channel row. Free-form; +// typed for documentation. +type ChannelStatus string + +// Known channel statuses. +const ( + ChannelStatusActive ChannelStatus = "active" + ChannelStatusDisconnected ChannelStatus = "disconnected" + ChannelStatusError ChannelStatus = "error" +) + +// String implements fmt.Stringer. +func (s ChannelStatus) String() string { return string(s) } + +// ActivityActorType identifies who emitted an ActivityEntry. Open set +// (typed for documentation): user | agent | system. +type ActivityActorType string + +// Known activity actor types. +const ( + ActivityActorUser ActivityActorType = "user" + ActivityActorAgent ActivityActorType = "agent" + ActivityActorSystem ActivityActorType = "system" +) + +// String implements fmt.Stringer. +func (a ActivityActorType) String() string { return string(a) } + +// ActivityTargetType identifies what an ActivityEntry happened to. +// Free-form; typed for documentation. +type ActivityTargetType string + +// Known activity target types (subset; new domains add new values). +const ( + ActivityTargetAgent ActivityTargetType = "agent" + ActivityTargetTask ActivityTargetType = "task" + ActivityTargetProject ActivityTargetType = "project" + ActivityTargetBudget ActivityTargetType = "budget" + ActivityTargetSkill ActivityTargetType = "skill" + ActivityTargetChannel ActivityTargetType = "channel" + ActivityTargetRoutine ActivityTargetType = "routine" +) + +// String implements fmt.Stringer. +func (t ActivityTargetType) String() string { return string(t) } + +// ActivityAction is the verb describing an ActivityEntry (free-form, +// dotted convention e.g. "budget.alert", "agent.hired"). +type ActivityAction string + +// String implements fmt.Stringer. +func (a ActivityAction) String() string { return string(a) } diff --git a/apps/backend/internal/office/models/enums_alignment_test.go b/apps/backend/internal/office/models/enums_alignment_test.go new file mode 100644 index 0000000000..ca43d44a50 --- /dev/null +++ b/apps/backend/internal/office/models/enums_alignment_test.go @@ -0,0 +1,34 @@ +package models_test + +import ( + "testing" + + "github.com/kandev/kandev/internal/agent/runtime/routingerr" + "github.com/kandev/kandev/internal/office/models" +) + +// TestAdapterPhaseAlignment fails to compile (referenced constant removed) or +// fails at runtime (value drift) if the office-tier AdapterPhase set drifts +// from routingerr.Phase. The duplication in office/models/enums.go is +// intentional — it keeps the office tier free of a runtime-tier import in +// production code — but this *_test.go anchor catches drift on every test +// run without imposing the dependency on production builds. +func TestAdapterPhaseAlignment(t *testing.T) { + pairs := []struct { + office models.AdapterPhase + runtime routingerr.Phase + }{ + {models.AdapterPhaseAuthCheck, routingerr.PhaseAuthCheck}, + {models.AdapterPhaseProcessStart, routingerr.PhaseProcessStart}, + {models.AdapterPhaseSessionInit, routingerr.PhaseSessionInit}, + {models.AdapterPhasePromptSend, routingerr.PhasePromptSend}, + {models.AdapterPhaseStreaming, routingerr.PhaseStreaming}, + {models.AdapterPhaseToolExecution, routingerr.PhaseToolExecution}, + {models.AdapterPhaseShutdown, routingerr.PhaseShutdown}, + } + for _, p := range pairs { + if string(p.office) != string(p.runtime) { + t.Errorf("AdapterPhase drift: office=%q runtime=%q", p.office, p.runtime) + } + } +} diff --git a/apps/backend/internal/office/models/models.go b/apps/backend/internal/office/models/models.go index 5062c10814..14f3af685f 100644 --- a/apps/backend/internal/office/models/models.go +++ b/apps/backend/internal/office/models/models.go @@ -71,24 +71,24 @@ type AgentInstance = settingsmodels.AgentProfile // create (e.g. ["ceo"]). Empty array for "no auto-attach". Ignored // for is_system = false. type Skill struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - Name string `json:"name" db:"name"` - Slug string `json:"slug" db:"slug"` - Description string `json:"description" db:"description"` - SourceType string `json:"source_type" db:"source_type"` - SourceLocator string `json:"source_locator" db:"source_locator"` - Content string `json:"content" db:"content"` - FileInventory string `json:"file_inventory" db:"file_inventory"` - Version string `json:"version" db:"version"` - ContentHash string `json:"content_hash" db:"content_hash"` - ApprovalState string `json:"approval_state" db:"approval_state"` - CreatedByAgentProfileID string `json:"created_by_agent_profile_id" db:"created_by_agent_profile_id"` - IsSystem bool `json:"is_system" db:"is_system"` - SystemVersion string `json:"system_version" db:"system_version"` - DefaultForRoles string `json:"default_for_roles" db:"default_for_roles"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + Name string `json:"name" db:"name"` + Slug string `json:"slug" db:"slug"` + Description string `json:"description" db:"description"` + SourceType SkillSourceType `json:"source_type" db:"source_type"` + SourceLocator string `json:"source_locator" db:"source_locator"` + Content string `json:"content" db:"content"` + FileInventory string `json:"file_inventory" db:"file_inventory"` + Version string `json:"version" db:"version"` + ContentHash string `json:"content_hash" db:"content_hash"` + ApprovalState SkillApprovalState `json:"approval_state" db:"approval_state"` + CreatedByAgentProfileID string `json:"created_by_agent_profile_id" db:"created_by_agent_profile_id"` + IsSystem bool `json:"is_system" db:"is_system"` + SystemVersion string `json:"system_version" db:"system_version"` + DefaultForRoles string `json:"default_for_roles" db:"default_for_roles"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // RunSkillSnapshot records the exact skill package attached to a run. @@ -314,16 +314,16 @@ type CostEvent struct { // hundredths of a cent (matches CostEvent.CostSubcents); the UI divides // by 10000 to render dollars via apps/web/lib/utils.ts:formatDollars. type BudgetPolicy struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - ScopeType string `json:"scope_type" db:"scope_type"` - ScopeID string `json:"scope_id" db:"scope_id"` - LimitSubcents int64 `json:"limit_subcents" db:"limit_subcents"` - Period string `json:"period" db:"period"` - AlertThresholdPct int `json:"alert_threshold_pct" db:"alert_threshold_pct"` - ActionOnExceed string `json:"action_on_exceed" db:"action_on_exceed"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + ScopeType BudgetScopeType `json:"scope_type" db:"scope_type"` + ScopeID string `json:"scope_id" db:"scope_id"` + LimitSubcents int64 `json:"limit_subcents" db:"limit_subcents"` + Period BudgetPeriod `json:"period" db:"period"` + AlertThresholdPct int `json:"alert_threshold_pct" db:"alert_threshold_pct"` + ActionOnExceed BudgetActionOnExceed `json:"action_on_exceed" db:"action_on_exceed"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // Run represents a run queue entry. @@ -332,7 +332,7 @@ type Run struct { AgentProfileID string `json:"agent_profile_id" db:"agent_profile_id"` Reason string `json:"reason" db:"reason"` Payload string `json:"payload" db:"payload"` - Status string `json:"status" db:"status"` + Status RunStatus `json:"status" db:"status"` CoalescedCount int `json:"coalesced_count" db:"coalesced_count"` IdempotencyKey *string `json:"idempotency_key" db:"idempotency_key"` ContextSnapshot string `json:"context_snapshot" db:"context_snapshot"` @@ -395,7 +395,7 @@ type Run struct { // RoutingBlockedStatus is set when every provider candidate is // unavailable; values: 'waiting_for_provider_capacity' | // 'blocked_provider_action_required'. - RoutingBlockedStatus *string `json:"routing_blocked_status,omitempty" db:"routing_blocked_status"` + RoutingBlockedStatus *RoutingBlockedStatus `json:"routing_blocked_status,omitempty" db:"routing_blocked_status"` // EarliestRetryAt is the earliest moment a parked run should be re- // resolved. Set only when at least one degraded route is auto-retryable. EarliestRetryAt *time.Time `json:"earliest_retry_at,omitempty" db:"earliest_retry_at"` @@ -406,21 +406,21 @@ type Run struct { // Persisted by the routing scheduler dispatcher in // internal/office/scheduler/dispatch_routing.go. type RouteAttempt struct { - RunID string `json:"run_id" db:"run_id"` - Seq int `json:"seq" db:"seq"` - ProviderID string `json:"provider_id" db:"provider_id"` - Model string `json:"model" db:"model"` - Tier string `json:"tier" db:"tier"` - Outcome string `json:"outcome" db:"outcome"` - ErrorCode string `json:"error_code,omitempty" db:"error_code"` - ErrorConfidence string `json:"error_confidence,omitempty" db:"error_confidence"` - AdapterPhase string `json:"adapter_phase,omitempty" db:"adapter_phase"` - ClassifierRule string `json:"classifier_rule,omitempty" db:"classifier_rule"` - ExitCode *int `json:"exit_code,omitempty" db:"exit_code"` - RawExcerpt string `json:"raw_excerpt,omitempty" db:"raw_excerpt"` - ResetHint *time.Time `json:"reset_hint,omitempty" db:"reset_hint"` - StartedAt time.Time `json:"started_at" db:"started_at"` - FinishedAt *time.Time `json:"finished_at,omitempty" db:"finished_at"` + RunID string `json:"run_id" db:"run_id"` + Seq int `json:"seq" db:"seq"` + ProviderID string `json:"provider_id" db:"provider_id"` + Model string `json:"model" db:"model"` + Tier string `json:"tier" db:"tier"` + Outcome RouteAttemptOutcome `json:"outcome" db:"outcome"` + ErrorCode string `json:"error_code,omitempty" db:"error_code"` + ErrorConfidence ErrorConfidence `json:"error_confidence,omitempty" db:"error_confidence"` + AdapterPhase AdapterPhase `json:"adapter_phase,omitempty" db:"adapter_phase"` + ClassifierRule string `json:"classifier_rule,omitempty" db:"classifier_rule"` + ExitCode *int `json:"exit_code,omitempty" db:"exit_code"` + RawExcerpt string `json:"raw_excerpt,omitempty" db:"raw_excerpt"` + ResetHint *time.Time `json:"reset_hint,omitempty" db:"reset_hint"` + StartedAt time.Time `json:"started_at" db:"started_at"` + FinishedAt *time.Time `json:"finished_at,omitempty" db:"finished_at"` } // ProviderHealth records the health state of one (workspace, provider, @@ -429,18 +429,18 @@ type RouteAttempt struct { // tier mapping on this provider). The resolver checks scopes in order // provider → tier → model before considering a candidate eligible. type ProviderHealth struct { - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - ProviderID string `json:"provider_id" db:"provider_id"` - Scope string `json:"scope" db:"scope"` - ScopeValue string `json:"scope_value" db:"scope_value"` - State string `json:"state" db:"state"` - ErrorCode string `json:"error_code,omitempty" db:"error_code"` - RetryAt *time.Time `json:"retry_at,omitempty" db:"retry_at"` - BackoffStep int `json:"backoff_step" db:"backoff_step"` - LastFailure *time.Time `json:"last_failure,omitempty" db:"last_failure"` - LastSuccess *time.Time `json:"last_success,omitempty" db:"last_success"` - RawExcerpt string `json:"raw_excerpt,omitempty" db:"raw_excerpt"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + ProviderID string `json:"provider_id" db:"provider_id"` + Scope ProviderHealthScope `json:"scope" db:"scope"` + ScopeValue string `json:"scope_value" db:"scope_value"` + State ProviderHealthState `json:"state" db:"state"` + ErrorCode string `json:"error_code,omitempty" db:"error_code"` + RetryAt *time.Time `json:"retry_at,omitempty" db:"retry_at"` + BackoffStep int `json:"backoff_step" db:"backoff_step"` + LastFailure *time.Time `json:"last_failure,omitempty" db:"last_failure"` + LastSuccess *time.Time `json:"last_success,omitempty" db:"last_success"` + RawExcerpt string `json:"raw_excerpt,omitempty" db:"raw_excerpt"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // RunEvent is one row in office_run_events. Each row is a discrete @@ -448,30 +448,30 @@ type ProviderHealth struct { // complete, error. The frontend renders these in the run detail // page's Events log. type RunEvent struct { - RunID string `json:"run_id" db:"run_id"` - Seq int `json:"seq" db:"seq"` - EventType string `json:"event_type" db:"event_type"` - Level string `json:"level" db:"level"` - Payload string `json:"payload" db:"payload"` - CreatedAt time.Time `json:"created_at" db:"created_at"` + RunID string `json:"run_id" db:"run_id"` + Seq int `json:"seq" db:"seq"` + EventType RunEventType `json:"event_type" db:"event_type"` + Level RunEventLevel `json:"level" db:"level"` + Payload string `json:"payload" db:"payload"` + CreatedAt time.Time `json:"created_at" db:"created_at"` } // Routine represents a recurring task definition. type Routine struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - Name string `json:"name" db:"name"` - Description string `json:"description" db:"description"` - TaskTemplate string `json:"task_template" db:"task_template"` - AssigneeAgentProfileID string `json:"assignee_agent_profile_id" db:"assignee_agent_profile_id"` - Status string `json:"status" db:"status"` - ConcurrencyPolicy string `json:"concurrency_policy" db:"concurrency_policy"` - CatchUpPolicy string `json:"catch_up_policy" db:"catch_up_policy"` - CatchUpMax int `json:"catch_up_max" db:"catch_up_max"` - Variables string `json:"variables" db:"variables"` - LastRunAt *time.Time `json:"last_run_at" db:"last_run_at"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + Name string `json:"name" db:"name"` + Description string `json:"description" db:"description"` + TaskTemplate string `json:"task_template" db:"task_template"` + AssigneeAgentProfileID string `json:"assignee_agent_profile_id" db:"assignee_agent_profile_id"` + Status string `json:"status" db:"status"` + ConcurrencyPolicy RoutineConcurrencyPolicy `json:"concurrency_policy" db:"concurrency_policy"` + CatchUpPolicy RoutineCatchUpPolicy `json:"catch_up_policy" db:"catch_up_policy"` + CatchUpMax int `json:"catch_up_max" db:"catch_up_max"` + Variables string `json:"variables" db:"variables"` + LastRunAt *time.Time `json:"last_run_at" db:"last_run_at"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // RoutineTrigger represents a trigger for a routine. @@ -493,18 +493,18 @@ type RoutineTrigger struct { // RoutineRun represents a single run of a routine. type RoutineRun struct { - ID string `json:"id" db:"id"` - RoutineID string `json:"routine_id" db:"routine_id"` - TriggerID string `json:"trigger_id" db:"trigger_id"` - Source string `json:"source" db:"source"` - Status string `json:"status" db:"status"` - TriggerPayload string `json:"trigger_payload" db:"trigger_payload"` - LinkedTaskID string `json:"linked_task_id" db:"linked_task_id"` - CoalescedIntoRunID string `json:"coalesced_into_run_id" db:"coalesced_into_run_id"` - DispatchFingerprint string `json:"dispatch_fingerprint" db:"dispatch_fingerprint"` - StartedAt *time.Time `json:"started_at" db:"started_at"` - CompletedAt *time.Time `json:"completed_at" db:"completed_at"` - CreatedAt time.Time `json:"created_at" db:"created_at"` + ID string `json:"id" db:"id"` + RoutineID string `json:"routine_id" db:"routine_id"` + TriggerID string `json:"trigger_id" db:"trigger_id"` + Source string `json:"source" db:"source"` + Status RoutineRunStatus `json:"status" db:"status"` + TriggerPayload string `json:"trigger_payload" db:"trigger_payload"` + LinkedTaskID string `json:"linked_task_id" db:"linked_task_id"` + CoalescedIntoRunID string `json:"coalesced_into_run_id" db:"coalesced_into_run_id"` + DispatchFingerprint string `json:"dispatch_fingerprint" db:"dispatch_fingerprint"` + StartedAt *time.Time `json:"started_at" db:"started_at"` + CompletedAt *time.Time `json:"completed_at" db:"completed_at"` + CreatedAt time.Time `json:"created_at" db:"created_at"` } // ApprovalType constants for approval request types. @@ -518,29 +518,29 @@ const ( // Approval represents a pending or resolved approval request. type Approval struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - Type string `json:"type" db:"type"` - RequestedByAgentProfileID string `json:"requested_by_agent_profile_id" db:"requested_by_agent_profile_id"` - Status string `json:"status" db:"status"` - Payload string `json:"payload" db:"payload"` - DecisionNote string `json:"decision_note" db:"decision_note"` - DecidedBy string `json:"decided_by" db:"decided_by"` - DecidedAt *time.Time `json:"decided_at" db:"decided_at"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + Type string `json:"type" db:"type"` + RequestedByAgentProfileID string `json:"requested_by_agent_profile_id" db:"requested_by_agent_profile_id"` + Status ApprovalStatus `json:"status" db:"status"` + Payload string `json:"payload" db:"payload"` + DecisionNote string `json:"decision_note" db:"decision_note"` + DecidedBy string `json:"decided_by" db:"decided_by"` + DecidedAt *time.Time `json:"decided_at" db:"decided_at"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // ActivityEntry represents an entry in the activity log. type ActivityEntry struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - ActorType string `json:"actor_type" db:"actor_type"` - ActorID string `json:"actor_id" db:"actor_id"` - Action string `json:"action" db:"action"` - TargetType string `json:"target_type" db:"target_type"` - TargetID string `json:"target_id" db:"target_id"` - Details string `json:"details" db:"details"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + ActorType ActivityActorType `json:"actor_type" db:"actor_type"` + ActorID string `json:"actor_id" db:"actor_id"` + Action ActivityAction `json:"action" db:"action"` + TargetType ActivityTargetType `json:"target_type" db:"target_type"` + TargetID string `json:"target_id" db:"target_id"` + Details string `json:"details" db:"details"` // RunID + SessionID let the run detail page join activity rows // back to the originating run for the "Tasks Touched" surface. // Empty string for activity not produced under a run (manual @@ -564,16 +564,16 @@ type AgentMemory struct { // Channel represents a communication channel for an agent. type Channel struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspace_id" db:"workspace_id"` - AgentProfileID string `json:"agent_profile_id" db:"agent_profile_id"` - Platform string `json:"platform" db:"platform"` - Config string `json:"config" db:"config"` - WebhookSecret string `json:"webhook_secret,omitempty" db:"webhook_secret"` - Status string `json:"status" db:"status"` - TaskID string `json:"task_id" db:"task_id"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspace_id" db:"workspace_id"` + AgentProfileID string `json:"agent_profile_id" db:"agent_profile_id"` + Platform ChannelPlatform `json:"platform" db:"platform"` + Config string `json:"config" db:"config"` + WebhookSecret string `json:"webhook_secret,omitempty" db:"webhook_secret"` + Status ChannelStatus `json:"status" db:"status"` + TaskID string `json:"task_id" db:"task_id"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // TaskBlocker represents a blocker relationship between tasks. diff --git a/apps/backend/internal/office/repository/sqlite/route_attempts.go b/apps/backend/internal/office/repository/sqlite/route_attempts.go index 786c8f4811..25e6d76bcc 100644 --- a/apps/backend/internal/office/repository/sqlite/route_attempts.go +++ b/apps/backend/internal/office/repository/sqlite/route_attempts.go @@ -27,8 +27,8 @@ func (r *Repository) AppendRouteAttempt( exit_code, raw_excerpt, reset_hint, started_at, finished_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `), a.RunID, a.Seq, a.ProviderID, a.Model, a.Tier, a.Outcome, - nullableString(a.ErrorCode), nullableString(a.ErrorConfidence), - nullableString(a.AdapterPhase), nullableString(a.ClassifierRule), + nullableString(a.ErrorCode), nullableString(string(a.ErrorConfidence)), + nullableString(string(a.AdapterPhase)), nullableString(a.ClassifierRule), a.ExitCode, nullableString(a.RawExcerpt), a.ResetHint, a.StartedAt, a.FinishedAt) if err != nil { diff --git a/apps/backend/internal/office/repository/sqlite/routines.go b/apps/backend/internal/office/repository/sqlite/routines.go index c0dae844db..771c284143 100644 --- a/apps/backend/internal/office/repository/sqlite/routines.go +++ b/apps/backend/internal/office/repository/sqlite/routines.go @@ -271,7 +271,7 @@ func (r *Repository) GetActiveRunForFingerprint( // UpdateRunStatus updates a run's status and optionally its linked task. func (r *Repository) UpdateRunStatus( - ctx context.Context, runID, status, linkedTaskID string, + ctx context.Context, runID string, status models.RoutineRunStatus, linkedTaskID string, ) error { now := time.Now().UTC() _, err := r.db.ExecContext(ctx, r.db.Rebind(` diff --git a/apps/backend/internal/office/repository/sqlite/run_events_test.go b/apps/backend/internal/office/repository/sqlite/run_events_test.go index b9e6434a20..640658722d 100644 --- a/apps/backend/internal/office/repository/sqlite/run_events_test.go +++ b/apps/backend/internal/office/repository/sqlite/run_events_test.go @@ -10,10 +10,10 @@ import ( func newActivityEntry(wsID, actorType, actorID, action, targetType, targetID string) *models.ActivityEntry { return &models.ActivityEntry{ WorkspaceID: wsID, - ActorType: actorType, + ActorType: models.ActivityActorType(actorType), ActorID: actorID, - Action: action, - TargetType: targetType, + Action: models.ActivityAction(action), + TargetType: models.ActivityTargetType(targetType), TargetID: targetID, Details: "{}", } diff --git a/apps/backend/internal/office/repository/sqlite/run_routing.go b/apps/backend/internal/office/repository/sqlite/run_routing.go index 995dd1a42e..a9ff67ba88 100644 --- a/apps/backend/internal/office/repository/sqlite/run_routing.go +++ b/apps/backend/internal/office/repository/sqlite/run_routing.go @@ -87,7 +87,7 @@ func (r *Repository) UpdateRouteAttemptOutcome( raw_excerpt = ?, reset_hint = ?, finished_at = ? WHERE run_id = ? AND seq = ? `), attempt.Outcome, nullableString(attempt.ErrorCode), - nullableString(attempt.ErrorConfidence), nullableString(attempt.AdapterPhase), + nullableString(string(attempt.ErrorConfidence)), nullableString(string(attempt.AdapterPhase)), nullableString(attempt.ClassifierRule), attempt.ExitCode, nullableString(attempt.RawExcerpt), attempt.ResetHint, attempt.FinishedAt, attempt.RunID, attempt.Seq) diff --git a/apps/backend/internal/office/repository/sqlite/run_routing_test.go b/apps/backend/internal/office/repository/sqlite/run_routing_test.go index 9212fc3e66..928215e57f 100644 --- a/apps/backend/internal/office/repository/sqlite/run_routing_test.go +++ b/apps/backend/internal/office/repository/sqlite/run_routing_test.go @@ -227,11 +227,11 @@ func TestListRunsWaitingOnProvider_WildcardProviderIDMatchesNone(t *testing.T) { } } -func derefStr(p *string) string { +func derefStr[T ~string](p *T) string { if p == nil { return "" } - return *p + return string(*p) } // TestClaimNextEligibleRun_SkipsRoutingBlocked verifies the eligibility diff --git a/apps/backend/internal/office/routines/catch_up_test.go b/apps/backend/internal/office/routines/catch_up_test.go index dd0d32de7d..f797449150 100644 --- a/apps/backend/internal/office/routines/catch_up_test.go +++ b/apps/backend/internal/office/routines/catch_up_test.go @@ -3,6 +3,8 @@ package routines import ( "testing" "time" + + "github.com/kandev/kandev/internal/office/models" ) // TestComputeRoutineMissed_HappyPath: NextRunAt == now, no backlog — @@ -14,7 +16,7 @@ func TestComputeRoutineMissed_HappyPath(t *testing.T) { Timezone: "", NextRunAt: &t0, } - routine := &Routine{CatchUpPolicy: CatchUpPolicyEnqueueWithCap, CatchUpMax: 25} + routine := &Routine{CatchUpPolicy: models.CatchUpPolicyEnqueueMissedWithCap, CatchUpMax: 25} count, advanceTo, err := computeRoutineMissed(trigger, routine, t0) if err != nil { @@ -39,7 +41,7 @@ func TestComputeRoutineMissed_BackendDownTenMinutes(t *testing.T) { Timezone: "", NextRunAt: &tenAgo, } - routine := &Routine{CatchUpPolicy: CatchUpPolicyEnqueueWithCap, CatchUpMax: 25} + routine := &Routine{CatchUpPolicy: models.CatchUpPolicyEnqueueMissedWithCap, CatchUpMax: 25} count, advanceTo, err := computeRoutineMissed(trigger, routine, now) if err != nil { @@ -64,7 +66,7 @@ func TestComputeRoutineMissed_HitsCap(t *testing.T) { Timezone: "", NextRunAt: &hundredAgo, } - routine := &Routine{CatchUpPolicy: CatchUpPolicyEnqueueWithCap, CatchUpMax: 5} + routine := &Routine{CatchUpPolicy: models.CatchUpPolicyEnqueueMissedWithCap, CatchUpMax: 5} count, advanceTo, err := computeRoutineMissed(trigger, routine, now) if err != nil { @@ -88,7 +90,7 @@ func TestComputeRoutineMissed_DefaultCap(t *testing.T) { NextRunAt: &hundredAgo, } // CatchUpMax=0 → defaultCatchUpMax (25). - routine := &Routine{CatchUpPolicy: CatchUpPolicyEnqueueWithCap, CatchUpMax: 0} + routine := &Routine{CatchUpPolicy: models.CatchUpPolicyEnqueueMissedWithCap, CatchUpMax: 0} count, _, err := computeRoutineMissed(trigger, routine, now) if err != nil { diff --git a/apps/backend/internal/office/routines/handler.go b/apps/backend/internal/office/routines/handler.go index d45967ad4b..4c7a9ce54f 100644 --- a/apps/backend/internal/office/routines/handler.go +++ b/apps/backend/internal/office/routines/handler.go @@ -5,12 +5,15 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "fmt" "io" "net/http" "strconv" "strings" "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/office/models" ) // Handler provides HTTP handlers for routine routes. @@ -54,6 +57,25 @@ func (h *Handler) createRoutine(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } + // Apply server defaults when the client omits the policy fields, then + // validate. Empty string in either field means "use default" — the + // agentctl CLI and several internal call sites POST without setting them. + concurrencyPolicy := models.RoutineConcurrencyPolicy(req.ConcurrencyPolicy) + if concurrencyPolicy == "" { + concurrencyPolicy = models.ConcurrencyPolicySkipIfActive + } + catchUpPolicy := models.RoutineCatchUpPolicy(req.CatchUpPolicy) + if catchUpPolicy == "" { + catchUpPolicy = models.CatchUpPolicyEnqueueMissedWithCap + } + if !concurrencyPolicy.Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid concurrency_policy: " + req.ConcurrencyPolicy}) + return + } + if !catchUpPolicy.Valid() { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid catch_up_policy: " + req.CatchUpPolicy}) + return + } routine := &Routine{ WorkspaceID: c.Param("wsId"), Name: req.Name, @@ -61,8 +83,8 @@ func (h *Handler) createRoutine(c *gin.Context) { TaskTemplate: req.TaskTemplate, AssigneeAgentProfileID: req.AssigneeAgentProfileID, Status: "active", - ConcurrencyPolicy: req.ConcurrencyPolicy, - CatchUpPolicy: req.CatchUpPolicy, + ConcurrencyPolicy: concurrencyPolicy, + CatchUpPolicy: catchUpPolicy, CatchUpMax: req.CatchUpMax, Variables: req.Variables, } @@ -101,6 +123,12 @@ func (h *Handler) doUpdateRoutine(c *gin.Context) (*Routine, int, error) { if err := c.ShouldBindJSON(&req); err != nil { return nil, http.StatusBadRequest, err } + if req.ConcurrencyPolicy != nil && !models.RoutineConcurrencyPolicy(*req.ConcurrencyPolicy).Valid() { + return nil, http.StatusBadRequest, fmt.Errorf("invalid concurrency_policy: %s", *req.ConcurrencyPolicy) + } + if req.CatchUpPolicy != nil && !models.RoutineCatchUpPolicy(*req.CatchUpPolicy).Valid() { + return nil, http.StatusBadRequest, fmt.Errorf("invalid catch_up_policy: %s", *req.CatchUpPolicy) + } applyRoutineUpdates(routine, &req) if err := h.svc.UpdateRoutine(ctx, routine); err != nil { return nil, http.StatusInternalServerError, err @@ -260,10 +288,10 @@ func applyRoutineUpdates(routine *Routine, req *UpdateRoutineRequest) { routine.Status = *req.Status } if req.ConcurrencyPolicy != nil { - routine.ConcurrencyPolicy = *req.ConcurrencyPolicy + routine.ConcurrencyPolicy = models.RoutineConcurrencyPolicy(*req.ConcurrencyPolicy) } if req.CatchUpPolicy != nil { - routine.CatchUpPolicy = *req.CatchUpPolicy + routine.CatchUpPolicy = models.RoutineCatchUpPolicy(*req.CatchUpPolicy) } if req.CatchUpMax != nil { routine.CatchUpMax = *req.CatchUpMax diff --git a/apps/backend/internal/office/routines/service.go b/apps/backend/internal/office/routines/service.go index 5f2edc5883..8acce178b3 100644 --- a/apps/backend/internal/office/routines/service.go +++ b/apps/backend/internal/office/routines/service.go @@ -5,34 +5,16 @@ import ( "crypto/sha256" "encoding/json" "fmt" - "strings" "time" "github.com/google/uuid" "go.uber.org/zap" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/office/models" "github.com/kandev/kandev/internal/office/shared" ) -// Concurrency policy constants. -const ( - ConcurrencySkipIfActive = "skip_if_active" - ConcurrencyCoalesceActive = "coalesce_if_active" - ConcurrencyAlwaysCreate = "always_create" -) - -// Run status constants. -const ( - RunStatusReceived = "received" - RunStatusTaskCreated = "task_created" - RunStatusSkipped = "skipped" - RunStatusCoalesced = "coalesced" - RunStatusFailed = "failed" - RunStatusDone = "done" - RunStatusCancelled = "cancelled" -) - // Repository is the persistence interface required by RoutineService. type Repository interface { CreateRoutine(ctx context.Context, routine *Routine) error @@ -53,7 +35,7 @@ type Repository interface { ListRoutineRuns(ctx context.Context, routineID string, limit, offset int) ([]*RoutineRun, error) ListAllRuns(ctx context.Context, workspaceID string, limit int) ([]*RoutineRun, error) GetActiveRunForFingerprint(ctx context.Context, routineID, fingerprint string) (*RoutineRun, error) - UpdateRunStatus(ctx context.Context, runID, status, linkedTaskID string) error + UpdateRunStatus(ctx context.Context, runID string, status models.RoutineRunStatus, linkedTaskID string) error UpdateRunCoalesced(ctx context.Context, runID, coalescedIntoRunID string) error } @@ -176,8 +158,8 @@ func (s *RoutineService) CreateDefaultCoordinatorRoutine( TaskTemplate: "", AssigneeAgentProfileID: agentID, Status: "active", - ConcurrencyPolicy: ConcurrencyCoalesceActive, - CatchUpPolicy: CatchUpPolicyEnqueueWithCap, + ConcurrencyPolicy: models.ConcurrencyPolicyCoalesceIfActive, + CatchUpPolicy: models.CatchUpPolicyEnqueueMissedWithCap, CatchUpMax: 25, Variables: "{}", } @@ -403,7 +385,7 @@ func (s *RoutineService) processCronTrigger(ctx context.Context, trigger *Routin zap.String("trigger_id", trigger.ID), zap.Error(err)) } missedForPayload := 0 - if strings.EqualFold(routine.CatchUpPolicy, CatchUpPolicySkipMissed) { + if routine.CatchUpPolicy == models.CatchUpPolicySkipMissed { // skip_missed: collapse all misses, fire once with no attribution. missedForPayload = 0 } else if runCount > 0 { @@ -415,12 +397,7 @@ func (s *RoutineService) processCronTrigger(ctx context.Context, trigger *Routin return err } -// CatchUpPolicy values mirror the agent-heartbeat enum. -const ( - CatchUpPolicyEnqueueWithCap = "enqueue_missed_with_cap" - CatchUpPolicySkipMissed = "skip_missed" - defaultCatchUpMax = 25 -) +const defaultCatchUpMax = 25 // computeRoutineMissed counts cron ticks between trigger.NextRunAt // (inclusive — that's the tick "due now") and `now`, capped at @@ -536,7 +513,7 @@ func (s *RoutineService) dispatchRoutineRun( RoutineID: routine.ID, TriggerID: triggerID, Source: source, - Status: RunStatusReceived, + Status: models.RoutineRunStatusReceived, TriggerPayload: string(payloadJSON), DispatchFingerprint: fingerprint, StartedAt: &now, @@ -568,7 +545,7 @@ func (s *RoutineService) dispatchRoutineRun( // materialiseRoutineRun branches on tmpl.Title to choose the lightweight // (taskless) or heavy (real task) path. Both paths transition the run -// to RunStatusTaskCreated; only the heavy path attaches a real task id. +// to models.RoutineRunStatusTaskCreated; only the heavy path attaches a real task id. // missedTicks is forwarded to the lightweight wakeup payload; the heavy // path doesn't attribute it (the agent reads context from the task). func (s *RoutineService) materialiseRoutineRun( @@ -607,7 +584,7 @@ func (s *RoutineService) materialiseHeavyRoutineRun( if err != nil { return fmt.Errorf("create routine task: %w", err) } - run.Status = RunStatusTaskCreated + run.Status = models.RoutineRunStatusTaskCreated run.LinkedTaskID = taskID if err := s.repo.UpdateRunStatus(ctx, run.ID, run.Status, run.LinkedTaskID); err != nil { return fmt.Errorf("update run status: %w", err) @@ -630,7 +607,7 @@ func (s *RoutineService) materialiseLightweightRoutineRun( vars map[string]string, missedTicks int, ) error { - run.Status = RunStatusTaskCreated + run.Status = models.RoutineRunStatusTaskCreated if err := s.repo.UpdateRunStatus(ctx, run.ID, run.Status, ""); err != nil { return fmt.Errorf("update run status: %w", err) } @@ -706,8 +683,8 @@ func (s *RoutineService) applyConcurrencyPolicy( routine *Routine, run *RoutineRun, fingerprint string, -) (string, error) { - if routine.ConcurrencyPolicy == ConcurrencyAlwaysCreate { +) (models.RoutineRunStatus, error) { + if routine.ConcurrencyPolicy == models.ConcurrencyPolicyAlwaysCreate { return "", nil } active, err := s.repo.GetActiveRunForFingerprint(ctx, routine.ID, fingerprint) @@ -718,15 +695,15 @@ func (s *RoutineService) applyConcurrencyPolicy( return "", nil } switch routine.ConcurrencyPolicy { - case ConcurrencySkipIfActive: - _ = s.repo.UpdateRunStatus(ctx, run.ID, RunStatusSkipped, "") - run.Status = RunStatusSkipped - return RunStatusSkipped, nil - case ConcurrencyCoalesceActive: + case models.ConcurrencyPolicySkipIfActive: + _ = s.repo.UpdateRunStatus(ctx, run.ID, models.RoutineRunStatusSkipped, "") + run.Status = models.RoutineRunStatusSkipped + return models.RoutineRunStatusSkipped, nil + case models.ConcurrencyPolicyCoalesceIfActive: _ = s.repo.UpdateRunCoalesced(ctx, run.ID, active.ID) - run.Status = RunStatusCoalesced + run.Status = models.RoutineRunStatusCoalesced run.CoalescedIntoRunID = active.ID - return RunStatusCoalesced, nil + return models.RoutineRunStatusCoalesced, nil } return "", nil } diff --git a/apps/backend/internal/office/routines/service_test.go b/apps/backend/internal/office/routines/service_test.go index e347038b32..7dff1ada58 100644 --- a/apps/backend/internal/office/routines/service_test.go +++ b/apps/backend/internal/office/routines/service_test.go @@ -49,7 +49,7 @@ func createTestRoutine(t *testing.T, svc interface { Name: name, TaskTemplate: `{"title":"{{name}} - {{date}}","description":"Run for {{date}}"}`, Status: "active", - ConcurrencyPolicy: policy, + ConcurrencyPolicy: models.RoutineConcurrencyPolicy(policy), Variables: `{"name":{"default":"Daily Check"}}`, } if err := svc.CreateRoutine(context.Background(), r); err != nil { diff --git a/apps/backend/internal/office/routing/resolver.go b/apps/backend/internal/office/routing/resolver.go index 0d4bbd9933..fc90660c20 100644 --- a/apps/backend/internal/office/routing/resolver.go +++ b/apps/backend/internal/office/routing/resolver.go @@ -236,10 +236,10 @@ func (r *Resolver) loadHealthIndex( byScope = map[string]map[string]models.ProviderHealth{} idx[ProviderID(row.ProviderID)] = byScope } - byValue, ok := byScope[row.Scope] + byValue, ok := byScope[string(row.Scope)] if !ok { byValue = map[string]models.ProviderHealth{} - byScope[row.Scope] = byValue + byScope[string(row.Scope)] = byValue } byValue[row.ScopeValue] = row } @@ -267,7 +267,7 @@ func lookupHealth( if !ok { continue } - if row.State == healthStateHealthy { + if string(row.State) == healthStateHealthy { continue } return row, true @@ -285,13 +285,13 @@ func classifyHealthHit( sc := SkippedCandidate{ ProviderID: pid, ErrorCode: row.ErrorCode, - State: row.State, - Scope: row.Scope, + State: string(row.State), + Scope: string(row.Scope), ScopeValue: row.ScopeValue, RawExcerpt: row.RawExcerpt, AutoRetry: IsAutoRetryableCode(row.ErrorCode), } - switch row.State { + switch string(row.State) { case healthStateDegraded: if row.RetryAt == nil || !row.RetryAt.After(now) { return SkippedCandidate{}, false diff --git a/apps/backend/internal/office/routing/resolver_test.go b/apps/backend/internal/office/routing/resolver_test.go index 89cba55b1c..dc6a2382cf 100644 --- a/apps/backend/internal/office/routing/resolver_test.go +++ b/apps/backend/internal/office/routing/resolver_test.go @@ -223,7 +223,7 @@ func timePtr(t time.Time) *time.Time { return &t } func degradedRow(provider, scope, scopeVal, code string, retryAt time.Time) models.ProviderHealth { return models.ProviderHealth{ ProviderID: provider, - Scope: scope, + Scope: models.ProviderHealthScope(scope), ScopeValue: scopeVal, State: "degraded", ErrorCode: code, diff --git a/apps/backend/internal/office/scheduler/dispatch_routing.go b/apps/backend/internal/office/scheduler/dispatch_routing.go index 7348280165..bef2fc221b 100644 --- a/apps/backend/internal/office/scheduler/dispatch_routing.go +++ b/apps/backend/internal/office/scheduler/dispatch_routing.go @@ -217,7 +217,7 @@ func (ss *SchedulerService) parkRunBlocked( return false, &br, nil } -func skipOutcome(reason string) string { +func skipOutcome(reason string) models.RouteAttemptOutcome { switch reason { case routing.SkipReasonDegraded: return RouteAttemptOutcomeSkippedDegraded @@ -451,9 +451,9 @@ func (ss *SchedulerService) degradeProviderForCandidate( row := models.ProviderHealth{ WorkspaceID: workspaceID, ProviderID: string(candidate.ProviderID), - Scope: scope, + Scope: models.ProviderHealthScope(scope), ScopeValue: scopeVal, - State: healthStateFor(e), + State: models.ProviderHealthState(healthStateFor(e)), ErrorCode: string(e.Code), RetryAt: timePtrIfNonZero(retryAt), BackoffStep: step, @@ -499,10 +499,10 @@ func (ss *SchedulerService) finishAttempt( attempt := models.RouteAttempt{ RunID: runID, Seq: seq, - Outcome: outcome, + Outcome: models.RouteAttemptOutcome(outcome), ErrorCode: string(e.Code), - ErrorConfidence: string(e.Confidence), - AdapterPhase: string(e.Phase), + ErrorConfidence: models.ErrorConfidence(e.Confidence), + AdapterPhase: models.AdapterPhase(e.Phase), ClassifierRule: e.ClassifierRule, ExitCode: e.ExitCode, RawExcerpt: e.RawExcerpt, diff --git a/apps/backend/internal/office/scheduler/routing_events.go b/apps/backend/internal/office/scheduler/routing_events.go index dfcf6c4871..36a433dd51 100644 --- a/apps/backend/internal/office/scheduler/routing_events.go +++ b/apps/backend/internal/office/scheduler/routing_events.go @@ -49,7 +49,7 @@ func (ss *SchedulerService) publishProviderHealthy( ss.publishProviderHealthChanged(ctx, models.ProviderHealth{ WorkspaceID: workspaceID, ProviderID: providerID, - Scope: scope, + Scope: models.ProviderHealthScope(scope), ScopeValue: scopeValue, State: "healthy", }) diff --git a/apps/backend/internal/office/scheduler/routing_lifecycle.go b/apps/backend/internal/office/scheduler/routing_lifecycle.go index 34ac9a2e3f..c1bb3f17ff 100644 --- a/apps/backend/internal/office/scheduler/routing_lifecycle.go +++ b/apps/backend/internal/office/scheduler/routing_lifecycle.go @@ -179,7 +179,7 @@ func (ss *SchedulerService) runProberAndApply( ProviderID: providerID, Scope: sqliterepo.HealthScopeProvider, ScopeValue: "", - State: healthStateFor(probeErr), + State: models.ProviderHealthState(healthStateFor(probeErr)), ErrorCode: string(probeErr.Code), RetryAt: timePtrIfNonZero(retryAt), BackoffStep: step, diff --git a/apps/backend/internal/office/service/activity.go b/apps/backend/internal/office/service/activity.go index bed481e214..72b0d3a897 100644 --- a/apps/backend/internal/office/service/activity.go +++ b/apps/backend/internal/office/service/activity.go @@ -32,10 +32,10 @@ func (s *Service) LogActivityWithRun( ) { entry := &models.ActivityEntry{ WorkspaceID: workspaceID, - ActorType: actorType, + ActorType: models.ActivityActorType(actorType), ActorID: actorID, - Action: action, - TargetType: targetType, + Action: models.ActivityAction(action), + TargetType: models.ActivityTargetType(targetType), TargetID: targetID, Details: details, RunID: runID, @@ -107,8 +107,8 @@ func (s *Service) publishRunEventAppended(ctx context.Context, evt *models.RunEv "run_id": evt.RunID, "event": map[string]interface{}{ "seq": evt.Seq, - "event_type": evt.EventType, - "level": evt.Level, + "event_type": string(evt.EventType), + "level": string(evt.Level), "payload": evt.Payload, "created_at": evt.CreatedAt.UTC().Format(time.RFC3339Nano), }, diff --git a/apps/backend/internal/office/service/channel_relay.go b/apps/backend/internal/office/service/channel_relay.go index b41d96f5f1..de98ff19da 100644 --- a/apps/backend/internal/office/service/channel_relay.go +++ b/apps/backend/internal/office/service/channel_relay.go @@ -58,7 +58,7 @@ func (r *ChannelRelay) RelayComment(ctx context.Context, comment *models.TaskCom // claimed for the comment's task. Empty when the comment isn't // attached to an in-flight run (manual user comment, etc.). runID := r.svc.ResolveRunForTask(ctx, comment.TaskID) - sendErr := r.sendWithRetry(ctx, channel.Platform, config, comment.Body) + sendErr := r.sendWithRetry(ctx, string(channel.Platform), config, comment.Body) if sendErr != nil { r.svc.LogActivityWithRun(ctx, channel.WorkspaceID, "system", "", "channel.delivery_failed", "channel", channel.ID, diff --git a/apps/backend/internal/office/service/channel_relay_test.go b/apps/backend/internal/office/service/channel_relay_test.go index 236d1eb15b..0106a9395f 100644 --- a/apps/backend/internal/office/service/channel_relay_test.go +++ b/apps/backend/internal/office/service/channel_relay_test.go @@ -28,7 +28,7 @@ func setupChannelForRelay(t *testing.T, svc *service.Service, platform, config s channel := &models.Channel{ WorkspaceID: "ws-1", AgentProfileID: agent.ID, - Platform: platform, + Platform: models.ChannelPlatform(platform), Config: config, } if err := svc.SetupChannel(ctx, channel); err != nil { diff --git a/apps/backend/internal/office/service/channels.go b/apps/backend/internal/office/service/channels.go index 08f0815b1a..c33297abcd 100644 --- a/apps/backend/internal/office/service/channels.go +++ b/apps/backend/internal/office/service/channels.go @@ -67,7 +67,7 @@ func (s *Service) SetupChannel(ctx context.Context, channel *models.Channel) err s.logger.Info("channel setup complete", zap.String("channel_id", channel.ID), - zap.String("platform", channel.Platform), + zap.String("platform", string(channel.Platform)), zap.String("task_id", taskID)) s.LogActivity(ctx, channel.WorkspaceID, "user", "", @@ -111,7 +111,7 @@ func (s *Service) UpdateChannelStatus(ctx context.Context, id, status string) er if err != nil { return err } - channel.Status = status + channel.Status = models.ChannelStatus(status) return s.repo.UpdateChannel(ctx, channel) } @@ -138,7 +138,7 @@ func (s *Service) HandleChannelInbound( AuthorType: "user", AuthorID: authorName, Body: body, - Source: channel.Platform, + Source: string(channel.Platform), ReplyChannelID: channel.ID, } return s.CreateComment(ctx, comment) diff --git a/apps/backend/internal/office/service/config_export.go b/apps/backend/internal/office/service/config_export.go index 3a92192e72..b71de2e3d0 100644 --- a/apps/backend/internal/office/service/config_export.go +++ b/apps/backend/internal/office/service/config_export.go @@ -124,7 +124,7 @@ func (s *Service) exportSkills(ctx context.Context, _ string, bundle *ConfigBund Name: sk.Name, Slug: sk.Slug, Description: sk.Description, - SourceType: sk.SourceType, + SourceType: string(sk.SourceType), Content: sk.Content, } bundle.Skills = append(bundle.Skills, cfg) @@ -151,7 +151,7 @@ func (s *Service) exportRoutines(ctx context.Context, _ string, bundle *ConfigBu Description: r.Description, TaskTemplate: r.TaskTemplate, AssigneeName: nameByID[r.AssigneeAgentProfileID], - ConcurrencyPolicy: r.ConcurrencyPolicy, + ConcurrencyPolicy: string(r.ConcurrencyPolicy), } bundle.Routines = append(bundle.Routines, cfg) } diff --git a/apps/backend/internal/office/service/config_import.go b/apps/backend/internal/office/service/config_import.go index bcd715408d..da9da8b264 100644 --- a/apps/backend/internal/office/service/config_import.go +++ b/apps/backend/internal/office/service/config_import.go @@ -217,7 +217,7 @@ func (s *Service) applySkills( if skill, ok := bySlug[cfg.Slug]; ok { skill.Name = cfg.Name skill.Description = cfg.Description - skill.SourceType = cfg.SourceType + skill.SourceType = models.SkillSourceType(cfg.SourceType) skill.Content = cfg.Content if err := s.UpdateSkill(ctx, skill); err != nil { return err @@ -228,7 +228,7 @@ func (s *Service) applySkills( Name: cfg.Name, Slug: cfg.Slug, Description: cfg.Description, - SourceType: cfg.SourceType, + SourceType: models.SkillSourceType(cfg.SourceType), Content: cfg.Content, } if err := s.CreateSkill(ctx, skill); err != nil { @@ -255,7 +255,7 @@ func (s *Service) applyRoutines( if routine, ok := byName[cfg.Name]; ok { routine.Description = cfg.Description routine.TaskTemplate = cfg.TaskTemplate - routine.ConcurrencyPolicy = cfg.ConcurrencyPolicy + routine.ConcurrencyPolicy = models.RoutineConcurrencyPolicy(cfg.ConcurrencyPolicy) if err := s.UpdateRoutine(ctx, routine); err != nil { return err } @@ -266,7 +266,7 @@ func (s *Service) applyRoutines( Description: cfg.Description, TaskTemplate: cfg.TaskTemplate, Status: "active", - ConcurrencyPolicy: cfg.ConcurrencyPolicy, + ConcurrencyPolicy: models.RoutineConcurrencyPolicy(cfg.ConcurrencyPolicy), } if err := s.CreateRoutine(ctx, routine); err != nil { return err diff --git a/apps/backend/internal/office/service/config_sync.go b/apps/backend/internal/office/service/config_sync.go index d4cac34ac3..e9433a7cbe 100644 --- a/apps/backend/internal/office/service/config_sync.go +++ b/apps/backend/internal/office/service/config_sync.go @@ -41,13 +41,13 @@ func (s *Service) ScanFilesystem(_ context.Context, _ string) (*ConfigBundle, [] for _, sk := range s.cfgLoader.GetSkills(defaultWorkspaceName) { bundle.Skills = append(bundle.Skills, SkillConfig{ Name: sk.Name, Slug: sk.Slug, Description: sk.Description, - SourceType: sk.SourceType, Content: sk.Content, + SourceType: string(sk.SourceType), Content: sk.Content, }) } for _, r := range s.cfgLoader.GetRoutines(defaultWorkspaceName) { bundle.Routines = append(bundle.Routines, RoutineConfig{ Name: r.Name, Description: r.Description, TaskTemplate: r.TaskTemplate, - ConcurrencyPolicy: r.ConcurrencyPolicy, + ConcurrencyPolicy: string(r.ConcurrencyPolicy), }) } for _, p := range s.cfgLoader.GetProjects(defaultWorkspaceName) { diff --git a/apps/backend/internal/office/service/config_sync_util.go b/apps/backend/internal/office/service/config_sync_util.go index bfdd063e3d..282c67781c 100644 --- a/apps/backend/internal/office/service/config_sync_util.go +++ b/apps/backend/internal/office/service/config_sync_util.go @@ -140,7 +140,7 @@ func writeBundleEntities(w *configloader.FileWriter, bundle *ConfigBundle) error for _, r := range bundle.Routines { routine := &models.Routine{ Name: r.Name, Description: r.Description, TaskTemplate: r.TaskTemplate, - ConcurrencyPolicy: r.ConcurrencyPolicy, + ConcurrencyPolicy: models.RoutineConcurrencyPolicy(r.ConcurrencyPolicy), } if err := w.WriteRoutine(defaultWorkspaceName, routine); err != nil { return err diff --git a/apps/backend/internal/office/service/continuation_summary.go b/apps/backend/internal/office/service/continuation_summary.go index ae3f3612b6..7ed6440086 100644 --- a/apps/backend/internal/office/service/continuation_summary.go +++ b/apps/backend/internal/office/service/continuation_summary.go @@ -22,7 +22,7 @@ func summaryLoadInputs( ctx, repo, repo.ReaderDB(), summary.RunSnapshot{ ID: run.ID, - Status: run.Status, + Status: string(run.Status), ResultJSON: run.ResultJSON, }, agentID, scope, diff --git a/apps/backend/internal/office/service/run_lifecycle_events_test.go b/apps/backend/internal/office/service/run_lifecycle_events_test.go index 1a084b6695..05ca61213c 100644 --- a/apps/backend/internal/office/service/run_lifecycle_events_test.go +++ b/apps/backend/internal/office/service/run_lifecycle_events_test.go @@ -73,7 +73,7 @@ func TestRunLifecycle_StepCompleteEventsEmitted(t *testing.T) { t.Fatalf("event count = %d, want %d (%+v)", len(rowEvents), len(wantTypes), rowEvents) } for i, e := range rowEvents { - if e.EventType != wantTypes[i] { + if string(e.EventType) != wantTypes[i] { t.Errorf("event[%d].type = %q, want %q", i, e.EventType, wantTypes[i]) } if e.Seq != i { diff --git a/apps/backend/internal/office/shared/activity.go b/apps/backend/internal/office/shared/activity.go index 2ff79f5a6f..657178597d 100644 --- a/apps/backend/internal/office/shared/activity.go +++ b/apps/backend/internal/office/shared/activity.go @@ -46,10 +46,10 @@ func (a *ActivityLoggerImpl) LogActivityWithRun( ) { entry := &models.ActivityEntry{ WorkspaceID: wsID, - ActorType: actorType, + ActorType: models.ActivityActorType(actorType), ActorID: actorID, - Action: action, - TargetType: targetType, + Action: models.ActivityAction(action), + TargetType: models.ActivityTargetType(targetType), TargetID: targetID, Details: details, RunID: runID, diff --git a/apps/backend/internal/office/skills/handler.go b/apps/backend/internal/office/skills/handler.go index 726e7c2894..1a82fb385c 100644 --- a/apps/backend/internal/office/skills/handler.go +++ b/apps/backend/internal/office/skills/handler.go @@ -55,7 +55,7 @@ func (h *Handler) createSkill(c *gin.Context) { Name: req.Name, Slug: req.Slug, Description: req.Description, - SourceType: req.SourceType, + SourceType: models.SkillSourceType(req.SourceType), SourceLocator: req.SourceLocator, Content: req.Content, FileInventory: req.FileInventory, @@ -203,7 +203,7 @@ func applySkillUpdates(skill *models.Skill, req *UpdateSkillRequest) { skill.Description = *req.Description } if req.SourceType != nil { - skill.SourceType = *req.SourceType + skill.SourceType = models.SkillSourceType(*req.SourceType) } if req.SourceLocator != nil { skill.SourceLocator = *req.SourceLocator diff --git a/apps/backend/internal/office/skills/import.go b/apps/backend/internal/office/skills/import.go index f31a3eeb64..1fbd81895c 100644 --- a/apps/backend/internal/office/skills/import.go +++ b/apps/backend/internal/office/skills/import.go @@ -250,7 +250,7 @@ func (s *SkillService) importSingleSkill( Name: name, Slug: GenerateSlug(ps.Slug), Description: desc, - SourceType: ps.SourceType, + SourceType: models.SkillSourceType(ps.SourceType), SourceLocator: locator, Content: content, } diff --git a/apps/backend/internal/office/skills/runtime_adapter.go b/apps/backend/internal/office/skills/runtime_adapter.go index b2d21459d2..11d297e5ba 100644 --- a/apps/backend/internal/office/skills/runtime_adapter.go +++ b/apps/backend/internal/office/skills/runtime_adapter.go @@ -52,7 +52,7 @@ func (a *SkillReaderAdapter) GetSkillFromConfig(ctx context.Context, idOrSlug st return &runtimeskill.Skill{ Slug: sk.Slug, Content: sk.Content, - SourceType: sk.SourceType, + SourceType: string(sk.SourceType), }, nil } diff --git a/apps/backend/internal/office/skills/service.go b/apps/backend/internal/office/skills/service.go index afbe4fc7a6..5f07e32f45 100644 --- a/apps/backend/internal/office/skills/service.go +++ b/apps/backend/internal/office/skills/service.go @@ -143,7 +143,7 @@ func (s *SkillService) ValidateAndPrepareSkill(ctx context.Context, skill *model return err } prepareSkillPackageMetadata(skill) - return s.validateSourceType(skill.SourceType) + return s.validateSourceType(string(skill.SourceType)) } func prepareSkillPackageMetadata(skill *models.Skill) { diff --git a/apps/backend/internal/office/testharness/routes_office.go b/apps/backend/internal/office/testharness/routes_office.go index 8a3286c3c2..690f4002a0 100644 --- a/apps/backend/internal/office/testharness/routes_office.go +++ b/apps/backend/internal/office/testharness/routes_office.go @@ -705,10 +705,10 @@ func seedActivityHandler(repo *officesqlite.Repository, log *logger.Logger) gin. entry := &officemodels.ActivityEntry{ ID: uuid.New().String(), WorkspaceID: req.WorkspaceID, - ActorType: req.ActorType, + ActorType: officemodels.ActivityActorType(req.ActorType), ActorID: req.ActorID, - Action: req.Action, - TargetType: req.TargetType, + Action: officemodels.ActivityAction(req.Action), + TargetType: officemodels.ActivityTargetType(req.TargetType), TargetID: req.TargetID, Details: details, RunID: req.RunID, diff --git a/apps/backend/internal/office/wakeup/dispatcher.go b/apps/backend/internal/office/wakeup/dispatcher.go index 18278cc751..f6815d8092 100644 --- a/apps/backend/internal/office/wakeup/dispatcher.go +++ b/apps/backend/internal/office/wakeup/dispatcher.go @@ -190,7 +190,7 @@ func (d *Dispatcher) resolveRoutinePolicy( if err != nil || routine == nil { return PolicyCoalesceIfActive, nil } - return normaliseRoutinePolicy(routine.ConcurrencyPolicy), nil + return normaliseRoutinePolicy(string(routine.ConcurrencyPolicy)), nil } // normaliseRoutinePolicy maps the routines package's legacy enum values diff --git a/apps/backend/internal/office/wakeup/dispatcher_test.go b/apps/backend/internal/office/wakeup/dispatcher_test.go index f27f37d309..7df93fcdba 100644 --- a/apps/backend/internal/office/wakeup/dispatcher_test.go +++ b/apps/backend/internal/office/wakeup/dispatcher_test.go @@ -85,7 +85,7 @@ func (h *testHarness) seedRun(id, status string) { AgentProfileID: h.agentID, Reason: "routine", Payload: "{}", - Status: status, + Status: officemodels.RunStatus(status), CoalescedCount: 1, ContextSnapshot: `{"prior":"snapshot"}`, } @@ -187,7 +187,7 @@ type fakeRoutineLookup struct { } func (f *fakeRoutineLookup) GetRoutine(_ context.Context, id string) (*officemodels.Routine, error) { - return &officemodels.Routine{ID: id, ConcurrencyPolicy: f.policy}, nil + return &officemodels.Routine{ID: id, ConcurrencyPolicy: officemodels.RoutineConcurrencyPolicy(f.policy)}, nil } // dispatchRoutineWith seeds an in-flight run + a routine wakeup-request diff --git a/apps/backend/internal/orchestrator/dto/dto.go b/apps/backend/internal/orchestrator/dto/dto.go index ad69845f77..8c97426d0c 100644 --- a/apps/backend/internal/orchestrator/dto/dto.go +++ b/apps/backend/internal/orchestrator/dto/dto.go @@ -1,6 +1,8 @@ // Package dto provides Data Transfer Objects for the orchestrator module. package dto +import "github.com/kandev/kandev/internal/agentruntime" + // GetStatusRequest is the request for orchestrator.status type GetStatusRequest struct{} @@ -46,16 +48,16 @@ type TaskSessionStatusResponse struct { ACPSessionID string `json:"acp_session_id,omitempty"` // Executor/runtime info - ExecutorID string `json:"executor_id,omitempty"` - ExecutorType string `json:"executor_type,omitempty"` - ExecutorName string `json:"executor_name,omitempty"` - Runtime string `json:"runtime,omitempty"` - IsRemoteExecutor bool `json:"is_remote_executor"` - RemoteState string `json:"remote_state,omitempty"` - RemoteName string `json:"remote_name,omitempty"` - RemoteCreatedAt string `json:"remote_created_at,omitempty"` - RemoteCheckedAt string `json:"remote_checked_at,omitempty"` - RemoteStatusErr string `json:"remote_status_error,omitempty"` + ExecutorID string `json:"executor_id,omitempty"` + ExecutorType string `json:"executor_type,omitempty"` + ExecutorName string `json:"executor_name,omitempty"` + Runtime agentruntime.Runtime `json:"runtime,omitempty"` + IsRemoteExecutor bool `json:"is_remote_executor"` + RemoteState string `json:"remote_state,omitempty"` + RemoteName string `json:"remote_name,omitempty"` + RemoteCreatedAt string `json:"remote_created_at,omitempty"` + RemoteCheckedAt string `json:"remote_checked_at,omitempty"` + RemoteStatusErr string `json:"remote_status_error,omitempty"` // Worktree info WorktreePath *string `json:"worktree_path,omitempty"` diff --git a/apps/backend/internal/orchestrator/event_handlers_streaming.go b/apps/backend/internal/orchestrator/event_handlers_streaming.go index 62c76c594e..d59893a35f 100644 --- a/apps/backend/internal/orchestrator/event_handlers_streaming.go +++ b/apps/backend/internal/orchestrator/event_handlers_streaming.go @@ -433,8 +433,8 @@ func (s *Service) updateTaskSessionState(ctx context.Context, taskID, sessionID "is_passthrough": session.IsPassthrough, } // Include review_status if present to ensure frontend state consistency - if session.ReviewStatus != nil { - eventData["review_status"] = *session.ReviewStatus + if session.ReviewStatus != models.ReviewStatusNone { + eventData["review_status"] = string(session.ReviewStatus) } // Include session metadata (e.g. plan_mode set by workflow events). // Key is "session_metadata" to avoid conflict with message-level "metadata". diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go b/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go index a143c9a57c..67e563f601 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go @@ -236,7 +236,7 @@ func TestHandleTaskMovedWithSession(t *testing.T) { synctest.Wait() updated, _ := repo.GetTaskSession(ctx, "s1") - if updated.ReviewStatus == nil || *updated.ReviewStatus != "pending" { + if updated.ReviewStatus != models.ReviewStatusPending { t.Fatalf("expected pending review status to be preserved, got %#v", updated.ReviewStatus) } }) @@ -275,8 +275,8 @@ func TestHandleTaskMovedWithSession(t *testing.T) { synctest.Wait() updated, _ := repo.GetTaskSession(ctx, "s1") - if updated.ReviewStatus != nil && *updated.ReviewStatus != "" { - t.Fatalf("expected review status to be cleared, got %q", *updated.ReviewStatus) + if updated.ReviewStatus != models.ReviewStatusNone { + t.Fatalf("expected review status to be cleared, got %q", updated.ReviewStatus) } }) }) diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index 42722c186e..63e8a1ac92 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -10,6 +10,7 @@ import ( "github.com/kandev/kandev/internal/agent/runtime/agentctl" "github.com/kandev/kandev/internal/agent/runtime/lifecycle" "github.com/kandev/kandev/internal/agentctl/types/streams" + "github.com/kandev/kandev/internal/agentruntime" "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/secrets" "github.com/kandev/kandev/internal/task/models" @@ -205,7 +206,7 @@ type AgentManagerClient interface { // RemoteRuntimeStatus mirrors runtime status details needed by orchestrator/UI. type RemoteRuntimeStatus struct { - RuntimeName string + RuntimeName agentruntime.Runtime RemoteName string State string CreatedAt *time.Time @@ -216,7 +217,7 @@ type RemoteRuntimeStatus struct { // RemoteStatusPollRequest contains the fields from ExecutorRunning needed for remote status polling. type RemoteStatusPollRequest struct { SessionID string - Runtime string + Runtime agentruntime.Runtime AgentExecutionID string ContainerID string Metadata map[string]interface{} diff --git a/apps/backend/internal/orchestrator/executor/executor_environment_test.go b/apps/backend/internal/orchestrator/executor/executor_environment_test.go index ba85b48770..a1bfcc217c 100644 --- a/apps/backend/internal/orchestrator/executor/executor_environment_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_environment_test.go @@ -262,7 +262,7 @@ func TestBuildResumeRequest_ReusesTaskEnvironmentRuntimeMetadata(t *testing.T) { TaskID: "task-1", AgentExecutionID: "exec-old", ContainerID: "container-old", - Runtime: string(models.ExecutorTypeLocalDocker), + Runtime: models.ExecutorTypeLocalDocker.Runtime(), Metadata: map[string]interface{}{ lifecycle.MetadataKeyAuthTokenSecret: "secret-token", "task_description": "drop me", diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index 8eca00cd8a..bcf0f0c015 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -965,7 +965,7 @@ func (s *Service) StartSessionForWorkflowStep(ctx context.Context, taskID, sessi return fmt.Errorf("failed to get task: %w", err) } - if session.ReviewStatus != nil && *session.ReviewStatus == "pending" { + if session.ReviewStatus == models.ReviewStatusPending { return fmt.Errorf("session is pending approval - use Approve button to proceed or send a message to request changes") } @@ -1006,7 +1006,7 @@ func (s *Service) advanceTaskWorkflowStep(ctx context.Context, task *models.Task zap.String("workflow_step_id", workflowStepID), zap.Error(err)) } - if session.ReviewStatus != nil && *session.ReviewStatus != "" { + if session.ReviewStatus != models.ReviewStatusNone { if err := s.repo.UpdateSessionReviewStatus(ctx, session.ID, ""); err != nil { s.logger.Warn("failed to clear session review status", zap.String("session_id", session.ID), diff --git a/apps/backend/internal/orchestrator/workflow_store_test.go b/apps/backend/internal/orchestrator/workflow_store_test.go index e25a67d113..1aa7ff2673 100644 --- a/apps/backend/internal/orchestrator/workflow_store_test.go +++ b/apps/backend/internal/orchestrator/workflow_store_test.go @@ -137,8 +137,8 @@ func TestWorkflowStore_ApplyTransition(t *testing.T) { if err != nil { t.Fatalf("failed to get session: %v", err) } - if session.ReviewStatus != nil && *session.ReviewStatus != "" { - t.Errorf("expected review status to be cleared, got %q", *session.ReviewStatus) + if session.ReviewStatus != models.ReviewStatusNone { + t.Errorf("expected review status to be cleared, got %q", session.ReviewStatus) } } diff --git a/apps/backend/internal/runs/repository/sqlite/run_events.go b/apps/backend/internal/runs/repository/sqlite/run_events.go index a53116d2d1..3fad6e449a 100644 --- a/apps/backend/internal/runs/repository/sqlite/run_events.go +++ b/apps/backend/internal/runs/repository/sqlite/run_events.go @@ -40,8 +40,8 @@ func (r *Repository) AppendRunEvent( return &models.RunEvent{ RunID: runID, Seq: seq, - EventType: eventType, - Level: level, + EventType: models.RunEventType(eventType), + Level: models.RunEventLevel(level), Payload: payload, CreatedAt: now, }, nil diff --git a/apps/backend/internal/task/dto/dto.go b/apps/backend/internal/task/dto/dto.go index 4f9cc38bda..5c20dba586 100644 --- a/apps/backend/internal/task/dto/dto.go +++ b/apps/backend/internal/task/dto/dto.go @@ -129,7 +129,7 @@ type TaskDTO struct { Position int `json:"position"` PrimarySessionID *string `json:"primary_session_id,omitempty"` SessionCount *int `json:"session_count,omitempty"` - ReviewStatus *string `json:"review_status,omitempty"` + ReviewStatus models.ReviewStatus `json:"review_status,omitempty"` PrimaryExecutorID *string `json:"primary_executor_id,omitempty"` PrimaryExecutorType *string `json:"primary_executor_type,omitempty"` PrimaryExecutorName *string `json:"primary_executor_name,omitempty"` @@ -196,10 +196,10 @@ type TaskSessionDTO struct { CompletedAt *time.Time `json:"completed_at,omitempty"` UpdatedAt time.Time `json:"updated_at"` // Workflow fields - IsPrimary bool `json:"is_primary"` - IsPassthrough bool `json:"is_passthrough"` - ReviewStatus *string `json:"review_status,omitempty"` - TaskEnvironmentID string `json:"task_environment_id,omitempty"` + IsPrimary bool `json:"is_primary"` + IsPassthrough bool `json:"is_passthrough"` + ReviewStatus models.ReviewStatus `json:"review_status,omitempty"` + TaskEnvironmentID string `json:"task_environment_id,omitempty"` } // TaskSessionSummaryDTO is a lightweight version of TaskSessionDTO without snapshot fields. @@ -227,7 +227,7 @@ type TaskSessionSummaryDTO struct { UpdatedAt time.Time `json:"updated_at"` IsPrimary bool `json:"is_primary"` IsPassthrough bool `json:"is_passthrough"` - ReviewStatus *string `json:"review_status,omitempty"` + ReviewStatus models.ReviewStatus `json:"review_status,omitempty"` TaskEnvironmentID string `json:"task_environment_id,omitempty"` // CommandCount is the number of tool_call messages on this session, // surfaced inline in the timeline entry header ("ran N commands"). @@ -529,7 +529,7 @@ func FromTask(task *models.Task) TaskDTO { // FromTaskWithPrimarySession converts a task model to a TaskDTO, including the primary session ID. func FromTaskWithPrimarySession(task *models.Task, primarySessionID *string) TaskDTO { - return FromTaskWithSessionInfo(task, primarySessionID, nil, nil, nil, nil, nil, nil, nil, nil) + return FromTaskWithSessionInfo(task, primarySessionID, nil, models.ReviewStatusNone, nil, nil, nil, nil, nil, nil) } // FromTaskWithSessionInfo converts a task model to a TaskDTO, including session information. @@ -537,7 +537,7 @@ func FromTaskWithSessionInfo( task *models.Task, primarySessionID *string, sessionCount *int, - reviewStatus *string, + reviewStatus models.ReviewStatus, primaryExecutorID *string, primaryExecutorType *string, primaryExecutorName *string, diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 6e8e4ef8d4..2988029bcb 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -130,7 +130,7 @@ func buildTaskDTOsWithSessionInfo(ctx context.Context, svc *service.Service, tas } type sessionInfoFields struct { - reviewStatus *string + reviewStatus models.ReviewStatus sessionState *string executorID *string executorType *string diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index 5f9d9bae9d..f0fb341662 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -296,6 +296,25 @@ type Turn struct { UpdatedAt time.Time `json:"updated_at"` } +// ReviewStatus represents the review state of a TaskSession. The zero value +// (ReviewStatusNone, the empty string) means "no review needed" and serializes +// out via omitempty, preserving the JSON shape of the legacy *string field. +// The persisted column (task_sessions.review_status TEXT DEFAULT ”) is +// compatible with these values without any migration. +type ReviewStatus string + +const ( + // ReviewStatusNone is the zero value meaning no review is needed. + ReviewStatusNone ReviewStatus = "" + // ReviewStatusPending indicates the session is waiting on a human review. + ReviewStatusPending ReviewStatus = "pending" + // ReviewStatusApproved indicates the reviewer accepted the session output. + ReviewStatusApproved ReviewStatus = "approved" +) + +// String returns the underlying string value for the review status. +func (r ReviewStatus) String() string { return string(r) } + // TaskSessionState represents the state of an agent session type TaskSessionState string @@ -372,9 +391,9 @@ type TaskSession struct { TaskEnvironmentID string `json:"task_environment_id,omitempty"` // FK to task_environments for shared env // Workflow-related fields - IsPrimary bool `json:"is_primary"` // Whether this is the primary session for the task - IsPassthrough bool `json:"is_passthrough"` // Whether this session uses passthrough (PTY) mode - ReviewStatus *string `json:"review_status,omitempty"` // pending, approved + IsPrimary bool `json:"is_primary"` // Whether this is the primary session for the task + IsPassthrough bool `json:"is_passthrough"` // Whether this session uses passthrough (PTY) mode + ReviewStatus ReviewStatus `json:"review_status,omitempty"` // zero value = no review needed } // ToAPI converts internal TaskSession to API type @@ -526,10 +545,10 @@ func IsContainerizedExecutorType(t ExecutorType) bool { return t.Runtime().IsContainerized() } -// IsAlwaysResumableRuntime reports whether the given runtime string represents +// IsAlwaysResumableRuntime reports whether the given runtime represents // an executor that can always be resumed even without an explicit resume token. -func IsAlwaysResumableRuntime(runtime string) bool { - return ExecutorType(runtime) == ExecutorTypeSprites +func IsAlwaysResumableRuntime(runtime agentruntime.Runtime) bool { + return runtime == agentruntime.RuntimeSprites } const ( @@ -567,7 +586,7 @@ type ExecutorRunning struct { SessionID string `json:"session_id"` TaskID string `json:"task_id"` ExecutorID string `json:"executor_id"` - Runtime string `json:"runtime,omitempty"` + Runtime agentruntime.Runtime `json:"runtime,omitempty"` Status string `json:"status"` Resumable bool `json:"resumable"` ResumeToken string `json:"resume_token,omitempty"` diff --git a/apps/backend/internal/task/repository/sqlite/session.go b/apps/backend/internal/task/repository/sqlite/session.go index 5c0635b9b0..af728ca311 100644 --- a/apps/backend/internal/task/repository/sqlite/session.go +++ b/apps/backend/internal/task/repository/sqlite/session.go @@ -315,7 +315,7 @@ func (r *Repository) scanTaskSession(ctx context.Context, row *sql.Row, noRowsEr session.IsPrimary = isPrimary == 1 session.IsPassthrough = isPassthrough == 1 if reviewStatus.Valid { - session.ReviewStatus = &reviewStatus.String + session.ReviewStatus = models.ReviewStatus(reviewStatus.String) } if agentProfileID.Valid { session.AgentProfileID = agentProfileID.String @@ -800,7 +800,7 @@ func scanTaskSessionRow(rows *sql.Rows) (*models.TaskSession, error) { session.IsPrimary = isPrimary == 1 session.IsPassthrough = isPassthrough == 1 if reviewStatus.Valid { - session.ReviewStatus = &reviewStatus.String + session.ReviewStatus = models.ReviewStatus(reviewStatus.String) } if agentProfileID.Valid { session.AgentProfileID = agentProfileID.String @@ -1128,7 +1128,7 @@ func (r *Repository) GetPrimarySessionInfoByTaskIDs(ctx context.Context, taskIDs session.State = models.TaskSessionState(sessionState.String) } if reviewStatus.Valid { - session.ReviewStatus = &reviewStatus.String + session.ReviewStatus = models.ReviewStatus(reviewStatus.String) } if executorID.Valid { session.ExecutorID = executorID.String diff --git a/apps/backend/internal/task/service/service_events.go b/apps/backend/internal/task/service/service_events.go index 67f34fac86..d2e50ba5d1 100644 --- a/apps/backend/internal/task/service/service_events.go +++ b/apps/backend/internal/task/service/service_events.go @@ -107,8 +107,8 @@ func (s *Service) addTaskSessionEventFields(ctx context.Context, taskID string, return } data["primary_session_id"] = sessionInfo.ID - if sessionInfo.ReviewStatus != nil { - data["review_status"] = *sessionInfo.ReviewStatus + if sessionInfo.ReviewStatus != models.ReviewStatusNone { + data["review_status"] = string(sessionInfo.ReviewStatus) } if sessionInfo.State != "" { data["primary_session_state"] = string(sessionInfo.State) diff --git a/apps/backend/internal/task/service/service_workflow_test.go b/apps/backend/internal/task/service/service_workflow_test.go index ddbbc14d7f..8d9867cdcf 100644 --- a/apps/backend/internal/task/service/service_workflow_test.go +++ b/apps/backend/internal/task/service/service_workflow_test.go @@ -129,8 +129,7 @@ func TestService_MoveTaskAllowsPendingReviewWhenSessionIdle(t *testing.T) { seedMoveWorkflows(t, ctx, repo) seedMoveSteps(svc) createMoveTask(t, ctx, repo, "task-pending-review", "wf-source", "step-source", nil) - pending := "pending" - createMoveSession(t, ctx, repo, "session-pending-review", "task-pending-review", models.TaskSessionStateWaitingForInput, &pending) + createMoveSession(t, ctx, repo, "session-pending-review", "task-pending-review", models.TaskSessionStateWaitingForInput, models.ReviewStatusPending) moved, err := svc.MoveTask(ctx, "task-pending-review", "wf-source", "step-review-target", 0) if err != nil { @@ -147,7 +146,7 @@ func TestService_MoveTaskRejectsRunningSession(t *testing.T) { seedMoveWorkflows(t, ctx, repo) seedMoveSteps(svc) createMoveTask(t, ctx, repo, "task-running", "wf-source", "step-source", nil) - createMoveSession(t, ctx, repo, "session-running", "task-running", models.TaskSessionStateRunning, nil) + createMoveSession(t, ctx, repo, "session-running", "task-running", models.TaskSessionStateRunning, models.ReviewStatusNone) _, err := svc.MoveTask(ctx, "task-running", "wf-source", "step-review-target", 0) if err == nil { @@ -241,7 +240,7 @@ func TestService_BulkMoveSelectedTasksValidatesBatchBeforeMoving(t *testing.T) { seedMoveSteps(svc) createMoveTask(t, ctx, repo, "task-batch-ok", "wf-source", "step-source", nil) createMoveTask(t, ctx, repo, "task-batch-running", "wf-source", "step-source", nil) - createMoveSession(t, ctx, repo, "session-batch-running", "task-batch-running", models.TaskSessionStateRunning, nil) + createMoveSession(t, ctx, repo, "session-batch-running", "task-batch-running", models.TaskSessionStateRunning, models.ReviewStatusNone) _, err := svc.BulkMoveSelectedTasks(ctx, []string{"task-batch-ok", "task-batch-running"}, "wf-target", "step-target") if err == nil { @@ -348,7 +347,7 @@ func createMoveTask(t *testing.T, ctx context.Context, repo interface { func createMoveSession(t *testing.T, ctx context.Context, repo interface { CreateTaskSession(context.Context, *models.TaskSession) error -}, id, taskID string, state models.TaskSessionState, reviewStatus *string) { +}, id, taskID string, state models.TaskSessionState, reviewStatus models.ReviewStatus) { t.Helper() must(t, repo.CreateTaskSession(ctx, &models.TaskSession{ ID: id, diff --git a/apps/web/app/actions/workspaces.ts b/apps/web/app/actions/workspaces.ts index e0207a37b6..992b8e70d4 100644 --- a/apps/web/app/actions/workspaces.ts +++ b/apps/web/app/actions/workspaces.ts @@ -1,6 +1,7 @@ "use server"; import { getBackendConfig } from "@/lib/config"; +import { workflowId as toWorkflowId } from "@/lib/types/ids"; import type { ApproveSessionResponse, Workflow, @@ -349,7 +350,7 @@ type BackendWorkflowStep = { const transformWorkflowStep = (step: BackendWorkflowStep): WorkflowStep => ({ id: step.id, - workflow_id: step.workflow_id, + workflow_id: toWorkflowId(step.workflow_id), name: step.name, position: step.position, color: step.color, diff --git a/apps/web/app/demo/agent-messages/page.tsx b/apps/web/app/demo/agent-messages/page.tsx index 8967191aad..10670edb2f 100644 --- a/apps/web/app/demo/agent-messages/page.tsx +++ b/apps/web/app/demo/agent-messages/page.tsx @@ -1,7 +1,7 @@ "use client"; import { useEffect, useState, useCallback } from "react"; -import type { Message, MessageType } from "@/lib/types/http"; +import { sessionId, taskId, type Message, type MessageType } from "@/lib/types/http"; import { MessageRenderer } from "@/components/task/chat/message-renderer"; import { fetchFixtureFiles, @@ -39,8 +39,8 @@ function fixtureToMessage(fixture: NormalizedFixture, index: number): Message { return { id: `fixture-${index}`, - session_id: "demo", - task_id: "demo-task", + session_id: sessionId("demo"), + task_id: taskId("demo-task"), author_type: "agent", type: toolType, content, diff --git a/apps/web/app/demo/messages/demo-messages-data.ts b/apps/web/app/demo/messages/demo-messages-data.ts index 6887ccffba..3b0dc4c897 100644 --- a/apps/web/app/demo/messages/demo-messages-data.ts +++ b/apps/web/app/demo/messages/demo-messages-data.ts @@ -1,8 +1,8 @@ -import type { Message } from "@/lib/types/http"; +import { sessionId, taskId, type Message } from "@/lib/types/http"; import { MARKDOWN_DEMO_MESSAGE_CONTENT } from "./demo-messages-content"; const AUTH_CONFIG_PATH = "src/auth/config.ts"; -const B = { session_id: "demo" as const, task_id: "demo-task" }; +const B = { session_id: sessionId("demo"), task_id: taskId("demo-task") }; export const dummyMessages: Message[] = [ // Task description @@ -206,7 +206,7 @@ export const dummyMessages: Message[] = [ metadata: { pending_id: "perm-1", tool_call_id: "tool-4", - action_type: "file_search", + action_type: "file_read", action_details: { path: "/Users/demo/project/src", command: 'grep -r "authentication"', diff --git a/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx b/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx index cbaf1b7f61..1bb329fd57 100644 --- a/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx +++ b/apps/web/app/office/agents/[id]/components/agent-configuration-tab.test.tsx @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanup, render, screen } from "@testing-library/react"; import { StateProvider } from "@/components/state-provider"; import type { AgentProfile } from "@/lib/state/slices/office/types"; +import { agentProfileId as toAgentProfileId } from "@/lib/types/ids"; import { defaultOfficeState } from "@/lib/state/slices/office/office-slice"; import { AgentConfigurationTab } from "./agent-configuration-tab"; @@ -108,7 +109,12 @@ describe("AgentConfigurationTab", () => { }); it("omits create-agent capability for default worker agents", () => { - const worker = { ...baseAgent, id: "agent-worker", name: "Worker", role: "worker" as const }; + const worker = { + ...baseAgent, + id: toAgentProfileId("agent-worker"), + name: "Worker", + role: "worker" as const, + }; render( = { name: form.name, role: form.role, - agentProfileId: form.agentProfileId || undefined, + agentProfileId: form.agentProfileId ? toAgentProfileId(form.agentProfileId) : undefined, budgetMonthlyCents: form.budgetMonthlyCents, maxConcurrentSessions: form.maxConcurrentSessions, executorPreference: form.executorType ? { type: form.executorType } : undefined, diff --git a/apps/web/app/office/projects/[id]/project-tasks-section.tsx b/apps/web/app/office/projects/[id]/project-tasks-section.tsx index 74bdd160f5..8851609e2f 100644 --- a/apps/web/app/office/projects/[id]/project-tasks-section.tsx +++ b/apps/web/app/office/projects/[id]/project-tasks-section.tsx @@ -3,6 +3,7 @@ import { useEffect, useMemo } from "react"; import { useAppStore } from "@/components/state-provider"; import { listTasks } from "@/lib/api/domains/office-tasks-api"; +import { agentProfileId as toAgentProfileId } from "@/lib/types/ids"; import { TaskRow } from "../../tasks/task-row"; type ProjectTasksSectionProps = { @@ -74,7 +75,7 @@ export function ProjectTasksSection({ projectId }: ProjectTasksSectionProps) { onToggleExpand={noop} agentName={ task.assigneeAgentProfileId - ? agentNameById.get(task.assigneeAgentProfileId) + ? agentNameById.get(toAgentProfileId(task.assigneeAgentProfileId)) : undefined } /> diff --git a/apps/web/app/office/projects/projects-page-client.tsx b/apps/web/app/office/projects/projects-page-client.tsx index e45acb9041..dc55dcca7d 100644 --- a/apps/web/app/office/projects/projects-page-client.tsx +++ b/apps/web/app/office/projects/projects-page-client.tsx @@ -6,6 +6,7 @@ import { Button } from "@kandev/ui/button"; import { useAppStore } from "@/components/state-provider"; import { useOfficeRefetch } from "@/hooks/use-office-refetch"; import { listProjects } from "@/lib/api/domains/office-api"; +import { agentProfileId as toAgentProfileId } from "@/lib/types/ids"; import type { Project } from "@/lib/state/slices/office/types"; import { ProjectCard } from "./project-card"; import { CreateProjectDialog } from "./create-project-dialog"; @@ -80,7 +81,7 @@ export function ProjectsPageClient({ initialProjects }: ProjectsPageClientProps) project={project} leadAgentName={ project.leadAgentProfileId - ? agentNameMap.get(project.leadAgentProfileId) + ? agentNameMap.get(toAgentProfileId(project.leadAgentProfileId)) : undefined } /> diff --git a/apps/web/app/office/workspace/org/org-tree-layout.test.ts b/apps/web/app/office/workspace/org/org-tree-layout.test.ts index 06f6444674..604d7ab306 100644 --- a/apps/web/app/office/workspace/org/org-tree-layout.test.ts +++ b/apps/web/app/office/workspace/org/org-tree-layout.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import type { AgentProfile } from "@/lib/state/slices/office/types"; +import { agentProfileId as toAgentProfileId, workspaceId as toWorkspaceId } from "@/lib/types/ids"; import { buildForest, layoutForest, @@ -13,8 +14,8 @@ import { function makeAgent(id: string, name: string, reportsTo?: string): AgentProfile { return { - id, - workspaceId: "ws-1", + id: toAgentProfileId(id), + workspaceId: toWorkspaceId("ws-1"), name, role: "worker", status: "idle", diff --git a/apps/web/app/settings/agents/[agentId]/agent-save-helpers.test.ts b/apps/web/app/settings/agents/[agentId]/agent-save-helpers.test.ts index 5ca77c602d..0c74712df7 100644 --- a/apps/web/app/settings/agents/[agentId]/agent-save-helpers.test.ts +++ b/apps/web/app/settings/agents/[agentId]/agent-save-helpers.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect } from "vitest"; -import type { AgentProfile } from "@/lib/types/http"; +import { agentProfileId as toAgentProfileId, type AgentProfile } from "@/lib/types/http"; import { isProfileDirty, type DraftProfile } from "./agent-save-helpers"; const baseProfile: AgentProfile = { - id: "p1", + id: toAgentProfileId("p1"), agentId: "a1", name: "Profile", agentDisplayName: "Mock", diff --git a/apps/web/app/settings/agents/[agentId]/page.tsx b/apps/web/app/settings/agents/[agentId]/page.tsx index 578ee99f21..6d0974a4f7 100644 --- a/apps/web/app/settings/agents/[agentId]/page.tsx +++ b/apps/web/app/settings/agents/[agentId]/page.tsx @@ -17,6 +17,7 @@ import type { import { buildDefaultPermissions } from "@/lib/agent-permissions"; import { seedDefaultCLIFlags } from "@/lib/cli-flags"; import { generateUUID } from "@/lib/utils"; +import { agentProfileId as toAgentProfileId } from "@/lib/types/ids"; import { useAppStore } from "@/components/state-provider"; import { useAvailableAgents } from "@/hooks/domains/settings/use-available-agents"; import { deleteAgentAction } from "@/app/actions/agents"; @@ -45,7 +46,7 @@ const createDraftProfile = ( defaultModel: string, permissionSettings?: Record, ): DraftProfile => ({ - id: `draft-${generateUUID()}`, + id: toAgentProfileId(`draft-${generateUUID()}`), agentId, name: "", agentDisplayName, @@ -266,7 +267,7 @@ function useProfileHandlers( const [newProfileId, setNewProfileId] = useState(null); const handleAddProfile = () => { - const draftId = `draft-${generateUUID()}`; + const draftId = toAgentProfileId(`draft-${generateUUID()}`); setDraftAgent((current) => ({ ...current, profiles: [ diff --git a/apps/web/app/settings/executor/[id]/page.tsx b/apps/web/app/settings/executor/[id]/page.tsx index d3178d3a0f..7e264ebfc2 100644 --- a/apps/web/app/settings/executor/[id]/page.tsx +++ b/apps/web/app/settings/executor/[id]/page.tsx @@ -21,7 +21,7 @@ import { updateExecutorAction, deleteExecutorAction } from "@/app/actions/execut import { getWebSocketClient } from "@/lib/ws/connection"; import { useAppStore } from "@/components/state-provider"; import { ExecutorProfilesCard } from "@/components/settings/executor-profiles-card"; -import type { Executor } from "@/lib/types/http"; +import type { Executor, ExecutorType } from "@/lib/types/http"; import { EXECUTOR_ICON_MAP } from "@/lib/executor-icons"; const EXECUTORS_ROUTE = "/settings/executors"; @@ -51,8 +51,8 @@ export default function ExecutorEditPage({ params }: { params: Promise<{ id: str return ; } -function getExecutorDescription(type: string): string { - if (type === "local") return "Runs agents directly in the repository folder."; +function getExecutorDescription(type: ExecutorType): string { + if (type === "local_pc") return "Runs agents directly in the repository folder."; if (type === "worktree") return "Creates git worktrees for isolated agent sessions."; if (type === "local_docker") return "Runs Docker containers on this machine."; if (type === "remote_docker") return "Connects to a remote Docker host."; diff --git a/apps/web/app/settings/executors/[profileId]/page.tsx b/apps/web/app/settings/executors/[profileId]/page.tsx index 70cc420b9d..a5016f4449 100644 --- a/apps/web/app/settings/executors/[profileId]/page.tsx +++ b/apps/web/app/settings/executors/[profileId]/page.tsx @@ -43,7 +43,7 @@ import { type SaveStatus, } from "@/components/settings/profile-edit/profile-edit-page-chrome"; import { useToast } from "@/components/toast-provider"; -import type { Executor, ExecutorProfile, ProfileEnvVar } from "@/lib/types/http"; +import type { Executor, ExecutorProfile, ExecutorType, ProfileEnvVar } from "@/lib/types/http"; import type { NetworkPolicyRule } from "@/lib/api/domains/settings-api"; const EXECUTORS_ROUTE = "/settings/executors"; @@ -83,7 +83,7 @@ function parseRemoteCredentials(config?: Record): string[] { } } -function useRemoteExecutorFlags(executorType: string) { +function useRemoteExecutorFlags(executorType: ExecutorType) { const isRemote = executorType === "local_docker" || executorType === "remote_docker" || @@ -552,8 +552,8 @@ function ProfileEditForm({ executor, profile }: { executor: Executor; profile: E ); } -function getExecutorDescription(type: string): string { - if (type === "local") return "Runs agents directly in the repository folder."; +function getExecutorDescription(type: ExecutorType): string { + if (type === "local_pc") return "Runs agents directly in the repository folder."; if (type === "worktree") return "Creates git worktrees for isolated agent sessions."; if (type === "local_docker") return "Runs Docker containers on this machine."; if (type === "remote_docker") return "Connects to a remote Docker host."; diff --git a/apps/web/app/settings/executors/new/[type]/page.tsx b/apps/web/app/settings/executors/new/[type]/page.tsx index 574015d2db..6a36cb2d9c 100644 --- a/apps/web/app/settings/executors/new/[type]/page.tsx +++ b/apps/web/app/settings/executors/new/[type]/page.tsx @@ -40,7 +40,7 @@ import { type GitIdentityState, } from "@/components/settings/profile-edit/remote-credentials-card"; import type { NetworkPolicyRule } from "@/lib/api/domains/settings-api"; -import type { Executor, ProfileEnvVar } from "@/lib/types/http"; +import type { Executor, ExecutorType, ProfileEnvVar } from "@/lib/types/http"; const EXECUTORS_ROUTE = "/settings/executors"; const SPRITES_TOKEN_KEY = "SPRITES_API_TOKEN"; @@ -91,7 +91,7 @@ export default function CreateProfilePage({ params }: { params: Promise<{ type: return ; } - return ; + return ; } function InvalidTypeFallback() { @@ -271,7 +271,7 @@ function useDefaultScripts(executorType: string, setPrepareScript: (v: string) = }, [executorType, setPrepareScript]); } -function useCreateRemoteFlags(executorType: string) { +function useCreateRemoteFlags(executorType: ExecutorType) { const isRemote = executorType === "local_docker" || executorType === "remote_docker" || @@ -283,7 +283,7 @@ function useCreateRemoteFlags(executorType: string) { }; } -function useCreateRemoteAuthState(executorType: string) { +function useCreateRemoteAuthState(executorType: ExecutorType) { const [remoteCredentials, setRemoteCredentials] = useState(() => executorType === "sprites" ? ["gh_cli_token"] : [], ); @@ -346,7 +346,7 @@ function useCreateGitIdentityState(isRemote: boolean) { }; } -function useCreateProfileFormState(executorType: string) { +function useCreateProfileFormState(executorType: ExecutorType) { const [name, setName] = useState(() => (executorType === "local_docker" ? "Docker" : "")); const [mcpPolicy, setMcpPolicy] = useState(""); const [prepareScript, setPrepareScript] = useState(""); @@ -501,7 +501,7 @@ function CreateProfileSections({ form, secrets, }: { - executorType: string; + executorType: ExecutorType; form: ReturnType; secrets: ReturnType["items"]; }) { @@ -604,7 +604,7 @@ function CreateProfileForm({ executorType, typeInfo, }: { - executorType: string; + executorType: ExecutorType; typeInfo: { executorId: string; label: string; description: string }; }) { const { items: secrets } = useSecrets(); diff --git a/apps/web/app/settings/workspace/workspace-edit-client.tsx b/apps/web/app/settings/workspace/workspace-edit-client.tsx index aac0178940..eca781a309 100644 --- a/apps/web/app/settings/workspace/workspace-edit-client.tsx +++ b/apps/web/app/settings/workspace/workspace-edit-client.tsx @@ -19,8 +19,10 @@ import { DialogTitle, } from "@kandev/ui/dialog"; import { updateWorkspaceAction, deleteWorkspaceAction } from "@/app/actions/workspaces"; -import type { Workspace, Executor } from "@/lib/types/http"; -import type { AgentProfileOption } from "@/lib/state/slices"; +import type { Executor } from "@/lib/types/http"; +import type { AgentProfileOption, WorkspaceState } from "@/lib/state/slices"; + +type Workspace = WorkspaceState["items"][number]; import { useRequest } from "@/lib/http/use-request"; import { useToast } from "@/components/toast-provider"; import { useAppStore } from "@/components/state-provider"; diff --git a/apps/web/app/settings/workspace/workspace-repositories-client.tsx b/apps/web/app/settings/workspace/workspace-repositories-client.tsx index 3c298ac5f1..5af0cf2f9d 100644 --- a/apps/web/app/settings/workspace/workspace-repositories-client.tsx +++ b/apps/web/app/settings/workspace/workspace-repositories-client.tsx @@ -19,7 +19,13 @@ import { updateRepositoryScriptAction, validateRepositoryPathAction, } from "@/app/actions/workspaces"; -import type { LocalRepository, Repository, RepositoryScript, Workspace } from "@/lib/types/http"; +import { + repositoryId as toRepositoryId, + type LocalRepository, + type Repository, + type RepositoryScript, + type Workspace, +} from "@/lib/types/http"; import { useRequest } from "@/lib/http/use-request"; import { useToast } from "@/components/toast-provider"; import { useAppStore } from "@/components/state-provider"; @@ -92,7 +98,7 @@ function buildDraftRepo( const name = selectedRepo?.name ?? path.split("/").filter(Boolean).slice(-1)[0] ?? "New Repository"; return { - id: `temp-repo-${generateUUID()}`, + id: toRepositoryId(`temp-repo-${generateUUID()}`), workspace_id: workspace.id, name, source_type: "local", @@ -242,7 +248,7 @@ function useRepositoryHandlers({ const handleAddRepositoryScript = (repoId: string) => { const script: RepositoryScript = { id: `temp-script-${generateUUID()}`, - repository_id: repoId, + repository_id: toRepositoryId(repoId), name: "", command: "", position: repositoryItems.find((repo) => repo.id === repoId)?.scripts.length ?? 0, diff --git a/apps/web/app/settings/workspace/workspace-workflows-client.tsx b/apps/web/app/settings/workspace/workspace-workflows-client.tsx index e179daeb39..ec885ea65f 100644 --- a/apps/web/app/settings/workspace/workspace-workflows-client.tsx +++ b/apps/web/app/settings/workspace/workspace-workflows-client.tsx @@ -40,12 +40,14 @@ import { importWorkflowsAction, reorderWorkflowsAction, } from "@/app/actions/workspaces"; -import type { - Workflow, - StepDefinition, - WorkflowStep, - Workspace, - WorkflowTemplate, +import { + agentProfileId as toAgentProfileId, + workflowId as toWorkflowId, + type Workflow, + type StepDefinition, + type WorkflowStep, + type Workspace, + type WorkflowTemplate, } from "@/lib/types/http"; import { CreateWorkflowDialog, @@ -170,6 +172,20 @@ function useWorkflowImportExport( }; } +function brandWorkflowUpdates(updates: { + name?: string; + description?: string; + agent_profile_id?: string; +}): Partial { + return { + ...(updates.name !== undefined ? { name: updates.name } : {}), + ...(updates.description !== undefined ? { description: updates.description } : {}), + ...(updates.agent_profile_id !== undefined + ? { agent_profile_id: toAgentProfileId(updates.agent_profile_id) } + : {}), + }; +} + function useWorkflowActions({ workspace, workflowItems, @@ -193,7 +209,7 @@ function useWorkflowActions({ ? (workflowTemplates.find((t) => t.id === selectedTemplateId)?.name ?? "New Workflow") : "New Workflow"; const draftWorkflow: Workflow = { - id: `temp-${generateUUID()}`, + id: toWorkflowId(`temp-${generateUUID()}`), workspace_id: workspace.id, name: newWorkflowName.trim() || templateName, description: "", @@ -210,7 +226,18 @@ function useWorkflowActions({ updates: { name?: string; description?: string; agent_profile_id?: string }, ) => { setWorkflowItems((prev) => - prev.map((wf) => (wf.id === workflowId ? { ...wf, ...updates } : wf)), + prev.map((wf) => + wf.id === workflowId + ? { + ...wf, + ...updates, + agent_profile_id: + updates.agent_profile_id !== undefined + ? toAgentProfileId(updates.agent_profile_id) + : wf.agent_profile_id, + } + : wf, + ), ); }; @@ -238,13 +265,14 @@ function useWorkflowActions({ if (workflow.name.trim()) updates.name = workflow.name.trim(); updates.agent_profile_id = workflow.agent_profile_id ?? ""; if (Object.keys(updates).length) await updateWorkflowAction(workflowId, updates); + const branded = brandWorkflowUpdates(updates); setWorkflowItems((prev) => - prev.map((item) => (item.id === workflowId ? { ...item, ...updates } : item)), + prev.map((item) => (item.id === workflowId ? { ...item, ...branded } : item)), ); setSavedWorkflowItems((prev) => prev.some((item) => item.id === workflowId) - ? prev.map((item) => (item.id === workflowId ? { ...workflow, ...updates } : item)) - : [...prev, { ...workflow, ...updates }], + ? prev.map((item) => (item.id === workflowId ? { ...workflow, ...branded } : item)) + : [...prev, { ...workflow, ...branded }], ); }; diff --git a/apps/web/app/settings/workspace/workspaces-page-client.tsx b/apps/web/app/settings/workspace/workspaces-page-client.tsx index 6b8f3cd67a..15b0dd4c1e 100644 --- a/apps/web/app/settings/workspace/workspaces-page-client.tsx +++ b/apps/web/app/settings/workspace/workspaces-page-client.tsx @@ -13,7 +13,9 @@ import { useRequest } from "@/lib/http/use-request"; import { useToast } from "@/components/toast-provider"; import { RequestIndicator } from "@/components/request-indicator"; import { useAppStore } from "@/components/state-provider"; -import type { Workspace } from "@/lib/types/http"; +import type { WorkspaceState } from "@/lib/state/slices"; + +type Workspace = WorkspaceState["items"][number]; type AddWorkspaceFormProps = { newWorkspaceName: string; diff --git a/apps/web/components/agent/cli-profile-editor.test.tsx b/apps/web/components/agent/cli-profile-editor.test.tsx index 08f8cf50f9..1407839c77 100644 --- a/apps/web/components/agent/cli-profile-editor.test.tsx +++ b/apps/web/components/agent/cli-profile-editor.test.tsx @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanup, render, screen, fireEvent, waitFor } from "@testing-library/react"; import { StateProvider } from "@/components/state-provider"; import { CliProfileEditor } from "./cli-profile-editor"; +import { agentProfileId as toAgentProfileId } from "@/lib/types/ids"; vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); @@ -87,7 +88,7 @@ describe("CliProfileEditor", () => { it("shows existing profile values in edit mode", () => { const profile = { - id: "p1", + id: toAgentProfileId("p1"), name: "default", agentId: "claude", agentDisplayName: "Claude", diff --git a/apps/web/components/config-chat/use-config-chat.ts b/apps/web/components/config-chat/use-config-chat.ts index 91b6c31422..063f91a615 100644 --- a/apps/web/components/config-chat/use-config-chat.ts +++ b/apps/web/components/config-chat/use-config-chat.ts @@ -5,6 +5,11 @@ import { useShallow } from "zustand/react/shallow"; import { useAppStore, useAppStoreApi } from "@/components/state-provider"; import { startConfigChat } from "@/lib/api/domains/workspace-api"; import { updateWorkspaceAction } from "@/app/actions/workspaces"; +import { + agentProfileId as toAgentProfileId, + sessionId as toSessionId, + taskId as toTaskId, +} from "@/lib/types/ids"; function useConfigChatStore() { return useAppStore( @@ -71,12 +76,12 @@ export function useConfigChat(workspaceId: string) { // Seed the task session in the main store so QuickChatContent can find it // immediately. The WS event will merge on top when it arrives. storeApi.getState().setTaskSession({ - id: response.session_id, - task_id: response.task_id, + id: toSessionId(response.session_id), + task_id: toTaskId(response.task_id), state: "CREATED", started_at: new Date().toISOString(), updated_at: new Date().toISOString(), - agent_profile_id: agentProfileId, + agent_profile_id: toAgentProfileId(agentProfileId), }); // Store the prompt so QuickChatContent can send it via WS. diff --git a/apps/web/components/github/issue-watch-dialog.tsx b/apps/web/components/github/issue-watch-dialog.tsx index efe428f657..2c963510d4 100644 --- a/apps/web/components/github/issue-watch-dialog.tsx +++ b/apps/web/components/github/issue-watch-dialog.tsx @@ -109,7 +109,10 @@ function useWatchFormData(workspaceId: string) { const agentProfiles = useAppStore((state) => state.agentProfiles.items); const executors = useAppStore((state) => state.executors.items); const allExecutorProfiles = useMemo( - () => executors.filter((e) => e.type !== "local").flatMap((e) => e.profiles ?? []), + () => + executors + .filter((e) => e.type !== "local" && e.type !== "local_pc") + .flatMap((e) => e.profiles ?? []), [executors], ); diff --git a/apps/web/components/github/review-watch-dialog.tsx b/apps/web/components/github/review-watch-dialog.tsx index 1b05c0146c..7e907458f0 100644 --- a/apps/web/components/github/review-watch-dialog.tsx +++ b/apps/web/components/github/review-watch-dialog.tsx @@ -173,7 +173,10 @@ function useWatchFormData(workspaceId: string) { const agentProfiles = useAppStore((state) => state.agentProfiles.items); const executors = useAppStore((state) => state.executors.items); const allExecutorProfiles = useMemo( - () => executors.filter((e) => e.type !== "local").flatMap((e) => e.profiles ?? []), + () => + executors + .filter((e) => e.type !== "local" && e.type !== "local_pc") + .flatMap((e) => e.profiles ?? []), [executors], ); diff --git a/apps/web/components/jira/jira-issue-watch-dialog.tsx b/apps/web/components/jira/jira-issue-watch-dialog.tsx index 4bbbd762d4..689604eb1c 100644 --- a/apps/web/components/jira/jira-issue-watch-dialog.tsx +++ b/apps/web/components/jira/jira-issue-watch-dialog.tsx @@ -99,7 +99,10 @@ function useFormData(workspaceId: string) { const agentProfiles = useAppStore((s) => s.agentProfiles.items); const executors = useAppStore((s) => s.executors.items); const allExecutorProfiles = useMemo( - () => executors.filter((e) => e.type !== "local").flatMap((e) => e.profiles ?? []), + () => + executors + .filter((e) => e.type !== "local" && e.type !== "local_pc") + .flatMap((e) => e.profiles ?? []), [executors], ); const filteredAgentProfiles = useMemo( diff --git a/apps/web/components/kanban-card.tsx b/apps/web/components/kanban-card.tsx index b983dbe798..2291262072 100644 --- a/apps/web/components/kanban-card.tsx +++ b/apps/web/components/kanban-card.tsx @@ -13,7 +13,7 @@ import { TaskArchiveConfirmDialog } from "@/components/task/task-archive-confirm import { TaskDeleteConfirmDialog } from "@/components/task/task-delete-confirm-dialog"; import { useTaskWorkflowMove } from "@/hooks/use-task-workflow-move"; import { getRepositoryDisplayName } from "@/lib/utils"; -import type { Repository, TaskState } from "@/lib/types/http"; +import { repositoryId as toRepositoryId, type Repository, type TaskState } from "@/lib/types/http"; export interface Task { id: string; @@ -269,7 +269,7 @@ export function resolveTaskRepositoryNames(task: Task, repositories: Repository[ const push = (id: string | undefined) => { if (!id || seen.has(id)) return; - const repo = byId.get(id); + const repo = byId.get(toRepositoryId(id)); if (!repo) return; seen.add(id); const display = getRepositoryDisplayName(repo.local_path); diff --git a/apps/web/components/kanban-display-dropdown.tsx b/apps/web/components/kanban-display-dropdown.tsx index 8941aefd75..0007737b7c 100644 --- a/apps/web/components/kanban-display-dropdown.tsx +++ b/apps/web/components/kanban-display-dropdown.tsx @@ -12,8 +12,10 @@ import { import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { IconAdjustmentsHorizontal } from "@tabler/icons-react"; import { useKanbanDisplaySettings } from "@/hooks/use-kanban-display-settings"; -import type { Workspace, Repository } from "@/lib/types/http"; -import type { WorkflowsState } from "@/lib/state/slices"; +import type { Repository } from "@/lib/types/http"; +import type { WorkflowsState, WorkspaceState } from "@/lib/state/slices"; + +type WorkspaceItem = WorkspaceState["items"][number]; import type { ComponentProps } from "react"; type KanbanDisplayDropdownProps = { @@ -35,7 +37,7 @@ function WorkspaceSection({ onWorkspaceChange, }: { activeWorkspaceId: string | null; - workspaces: Workspace[]; + workspaces: WorkspaceItem[]; onWorkspaceChange: (id: string | null) => void; }) { return ( @@ -49,7 +51,7 @@ function WorkspaceSection({ - {workspaces.map((workspace: Workspace) => ( + {workspaces.map((workspace) => ( void; activeWorkflowId: string | null; workflows: WorkflowsState["items"]; @@ -88,7 +90,7 @@ function MobileDisplaySelects({ - {workspaces.map((workspace: Workspace) => ( + {workspaces.map((workspace) => ( {workspace.name} diff --git a/apps/web/components/linear/linear-issue-watch-dialog.tsx b/apps/web/components/linear/linear-issue-watch-dialog.tsx index 3d790bb0e4..abef8ec182 100644 --- a/apps/web/components/linear/linear-issue-watch-dialog.tsx +++ b/apps/web/components/linear/linear-issue-watch-dialog.tsx @@ -106,7 +106,10 @@ function useFormData(workspaceId: string) { const agentProfiles = useAppStore((s) => s.agentProfiles.items); const executors = useAppStore((s) => s.executors.items); const allExecutorProfiles = useMemo( - () => executors.filter((e) => e.type !== "local").flatMap((e) => e.profiles ?? []), + () => + executors + .filter((e) => e.type !== "local" && e.type !== "local_pc") + .flatMap((e) => e.profiles ?? []), [executors], ); const filteredAgentProfiles = useMemo( diff --git a/apps/web/components/settings/settings-app-sidebar.tsx b/apps/web/components/settings/settings-app-sidebar.tsx index 8226c30a1a..60b042dede 100644 --- a/apps/web/components/settings/settings-app-sidebar.tsx +++ b/apps/web/components/settings/settings-app-sidebar.tsx @@ -44,7 +44,10 @@ import { useAvailableAgents } from "@/hooks/domains/settings/use-available-agent import { AgentLogo } from "@/components/agent-logo"; import { getExecutorIcon } from "@/lib/executor-icons"; import { getCapabilityWarning } from "@/lib/capability-warning"; -import type { Workspace, Agent, AgentProfile, Executor } from "@/lib/types/http"; +import type { Agent, AgentProfile, Executor } from "@/lib/types/http"; +import type { WorkspaceState } from "@/lib/state/slices"; + +type WorkspaceItem = WorkspaceState["items"][number]; type GeneralSidebarSectionProps = { pathname: string; @@ -91,7 +94,7 @@ function GeneralSidebarSection({ pathname }: GeneralSidebarSectionProps) { type WorkspacesSidebarSectionProps = { pathname: string; - workspaces: Workspace[]; + workspaces: WorkspaceItem[]; }; function WorkspacesSidebarSection({ pathname, workspaces }: WorkspacesSidebarSectionProps) { @@ -105,7 +108,7 @@ function WorkspacesSidebarSection({ pathname, workspaces }: WorkspacesSidebarSec {workspaces.length > 0 && ( - {workspaces.map((workspace: Workspace) => { + {workspaces.map((workspace) => { const workspacePath = `/settings/workspace/${workspace.id}`; const workflowsPath = `${workspacePath}/workflows`; const repositoriesPath = `${workspacePath}/repositories`; diff --git a/apps/web/components/task-create-dialog-options.tsx b/apps/web/components/task-create-dialog-options.tsx index 0f21a48069..c1daec2bf3 100644 --- a/apps/web/components/task-create-dialog-options.tsx +++ b/apps/web/components/task-create-dialog-options.tsx @@ -178,7 +178,7 @@ export function useExecutorOptions(executors: Executor[]): OptionItem[] { export function useIsLocalExecutor(executors: Executor[], executorId: string): boolean { return useMemo(() => { const selected = executors.find((e: Executor) => e.id === executorId); - return selected?.type === "local"; + return selected?.type === "local" || selected?.type === "local_pc"; }, [executors, executorId]); } @@ -197,7 +197,8 @@ export function computeExecutorHint( if (selectedExecutor?.type === "local_docker" || selectedExecutor?.type === "remote_docker") { return "A Docker container will be created from the selected base branch and checked out on a task branch."; } - if (selectedExecutor?.type === "local") return "The agent will run directly on the repository."; + if (selectedExecutor?.type === "local" || selectedExecutor?.type === "local_pc") + return "The agent will run directly on the repository."; return null; } diff --git a/apps/web/components/task-create-dialog-state.ts b/apps/web/components/task-create-dialog-state.ts index 2757148644..7e4fead44f 100644 --- a/apps/web/components/task-create-dialog-state.ts +++ b/apps/web/components/task-create-dialog-state.ts @@ -1,7 +1,7 @@ "use client"; import { useEffect, useRef, useState, useMemo, useCallback } from "react"; -import type { LocalRepository, Workspace, ExecutorProfile, Branch } from "@/lib/types/http"; +import type { LocalRepository, ExecutorProfile, Branch } from "@/lib/types/http"; import type { TaskFormInputsHandle } from "@/components/task-create-dialog-types"; import { useAppStore } from "@/components/state-provider"; import { useRepositories } from "@/hooks/domains/workspace/use-repositories"; @@ -518,9 +518,7 @@ export function useDialogComputed({ effectiveWorkflowId, snapshots, }); - const workspaceDefaults = workspaceId - ? workspaces.find((ws: Workspace) => ws.id === workspaceId) - : null; + const workspaceDefaults = workspaceId ? workspaces.find((ws) => ws.id === workspaceId) : null; // The form has a repo selection when either: (a) any chip in the unified // list has a repo set, (b) URL mode has a non-empty URL, or (c) the task // is intentionally repo-less (noRepository toggle on). diff --git a/apps/web/components/task-create-dialog-types.ts b/apps/web/components/task-create-dialog-types.ts index 08f99f5f24..8daa0189e8 100644 --- a/apps/web/components/task-create-dialog-types.ts +++ b/apps/web/components/task-create-dialog-types.ts @@ -1,17 +1,12 @@ -import type { - LocalRepository, - Repository, - Workspace, - Executor, - Branch, - Task, -} from "@/lib/types/http"; -import type { AgentProfileOption } from "@/lib/state/slices"; +import type { LocalRepository, Repository, Executor, Branch, Task } from "@/lib/types/http"; +import type { AgentProfileOption, WorkspaceState } from "@/lib/state/slices"; import type { KanbanMultiState, WorkflowSnapshotData, WorkflowsState, } from "@/lib/state/slices/kanban/types"; + +type Workspace = WorkspaceState["items"][number]; import type { useRepositoryOptions, useBranchOptions, diff --git a/apps/web/components/task/chat/messages/chat-message.test.tsx b/apps/web/components/task/chat/messages/chat-message.test.tsx index 1aeacee03b..bf0a6f05be 100644 --- a/apps/web/components/task/chat/messages/chat-message.test.tsx +++ b/apps/web/components/task/chat/messages/chat-message.test.tsx @@ -3,7 +3,7 @@ import type { ReactNode } from "react"; import { render } from "@testing-library/react"; import { StateProvider } from "@/components/state-provider"; import { ChatMessage } from "./chat-message"; -import type { Message } from "@/lib/types/http"; +import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http"; const SENDER_TASK_ID = "task-sender"; const SENDER_TITLE = "Fix login bug"; @@ -12,8 +12,8 @@ const SENDER_BADGE_SELECTOR = "[data-testid='sender-task-badge']"; function userMessage(overrides: Partial): Message { return { id: "msg-1", - session_id: "sess-1", - task_id: "task-target", + session_id: toSessionId("sess-1"), + task_id: toTaskId("task-target"), author_type: "user", content: "hello", type: "message", diff --git a/apps/web/components/task/chat/messages/monitor-message.test.tsx b/apps/web/components/task/chat/messages/monitor-message.test.tsx index b1343b5fe2..da3dc5ea5c 100644 --- a/apps/web/components/task/chat/messages/monitor-message.test.tsx +++ b/apps/web/components/task/chat/messages/monitor-message.test.tsx @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import { MonitorMessage } from "./monitor-message"; -import type { Message } from "@/lib/types/http"; +import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http"; // monitorMessage is a tiny test-helper that constructs the kandev Message // shape produced by the orchestrator for a Monitor tool_call. The fields @@ -18,8 +18,8 @@ function monitorMessage(opts: { }): Message { return { id: "msg-1", - session_id: "s1", - task_id: "t1", + session_id: toSessionId("s1"), + task_id: toTaskId("t1"), author_type: "agent", content: "Monitor", type: "tool_call", @@ -123,8 +123,8 @@ describe("MonitorMessage", () => { // the "watching" baseline rather than crashing. const empty: Message = { id: "msg-1", - session_id: "s1", - task_id: "t1", + session_id: toSessionId("s1"), + task_id: toTaskId("t1"), author_type: "agent", content: "Monitor", type: "tool_call", diff --git a/apps/web/components/task/chat/messages/permission-request-message.tsx b/apps/web/components/task/chat/messages/permission-request-message.tsx index 94db2177f5..8070b09bf3 100644 --- a/apps/web/components/task/chat/messages/permission-request-message.tsx +++ b/apps/web/components/task/chat/messages/permission-request-message.tsx @@ -5,19 +5,20 @@ import { IconAlertTriangle, IconCheck, IconX } from "@tabler/icons-react"; import { cn } from "@/lib/utils"; import { getWebSocketClient } from "@/lib/ws/connection"; import type { Message } from "@/lib/types/http"; +import type { PermissionActionType, PermissionOptionKind } from "@/lib/types/permission"; import { PermissionActionRow } from "./permission-action-row"; type PermissionOption = { option_id: string; name: string; - kind: string; + kind: PermissionOptionKind; }; type PermissionRequestMetadata = { pending_id: string; tool_call_id?: string; options: PermissionOption[]; - action_type: string; + action_type: PermissionActionType; action_details?: { command?: string; path?: string; diff --git a/apps/web/components/task/chat/messages/tool-call-message.tsx b/apps/web/components/task/chat/messages/tool-call-message.tsx index 9218ee10f1..e338a3ee29 100644 --- a/apps/web/components/task/chat/messages/tool-call-message.tsx +++ b/apps/web/components/task/chat/messages/tool-call-message.tsx @@ -16,6 +16,7 @@ import { cn, transformPathsInText } from "@/lib/utils"; import { prettifyToolTitle } from "@/lib/pretty-tool-title"; import { getWebSocketClient } from "@/lib/ws/connection"; import type { Message } from "@/lib/types/http"; +import type { PermissionActionType, PermissionOptionKind } from "@/lib/types/permission"; import type { ToolCallMetadata } from "@/components/task/chat/types"; import { PermissionActionRow } from "./permission-action-row"; import { ExpandableRow } from "./expandable-row"; @@ -24,14 +25,14 @@ import { useExpandState } from "./use-expand-state"; type PermissionOption = { option_id: string; name: string; - kind: string; + kind: PermissionOptionKind; }; type PermissionRequestMetadata = { pending_id: string; tool_call_id: string; options: PermissionOption[]; - action_type: string; + action_type: PermissionActionType; action_details: { command?: string; path?: string; cwd?: string }; status?: "pending" | "approved" | "rejected"; }; diff --git a/apps/web/components/task/dockview-session-tabs.ts b/apps/web/components/task/dockview-session-tabs.ts index eaa40a72bd..83eb69e202 100644 --- a/apps/web/components/task/dockview-session-tabs.ts +++ b/apps/web/components/task/dockview-session-tabs.ts @@ -6,6 +6,7 @@ import { useDockviewStore } from "@/lib/state/dockview-store"; import { focusOrAddPanel } from "@/lib/state/dockview-layout-builders"; import { useAppStore, useAppStoreApi } from "@/components/state-provider"; import { wasPRPanelOffered, markPRPanelOffered } from "@/lib/local-storage"; +import { sessionId as toSessionId } from "@/lib/types/ids"; /** * Sync `activeSessionId` in the store when the user clicks a session tab. @@ -367,7 +368,7 @@ export function useAutoSessionTab(effectiveSessionId: string | null) { // guards against a race where removeTaskSession fires before the active // session is switched, which would cause the deleted session's panel to // be re-created by ensureSessionPanel. - if (!currentSessionIds.includes(effectiveSessionId)) return; + if (!currentSessionIds.includes(toSessionId(effectiveSessionId))) return; if (!prepareLayoutForSessionPanels(api)) { sessionTabCreatedRef.current.add(effectiveSessionId); diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts index e2427caa98..37ac2c9af0 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts +++ b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts @@ -14,12 +14,13 @@ import { hasPendingClarificationForSession, hasPendingPermissionForSession, } from "@/lib/utils/pending-clarification"; -import type { - TaskState, - TaskSessionState, - Repository, - Task, - WorkflowSnapshot, +import { + repositoryId as toRepositoryId, + type TaskState, + type TaskSessionState, + type Repository, + type Task, + type WorkflowSnapshot, } from "@/lib/types/http"; import type { KanbanState } from "@/lib/state/slices"; @@ -120,7 +121,9 @@ export function useSheetData(workspaceId: string | null, workflowId: string | nu sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined), description: task.description, workflowStepId: task.workflowStepId, - repositoryPath: task.repositoryId ? repositoryPathsById.get(task.repositoryId) : undefined, + repositoryPath: task.repositoryId + ? repositoryPathsById.get(toRepositoryId(task.repositoryId)) + : undefined, diffStats: sessionInfo.diffStats, updatedAt: sessionInfo.updatedAt ?? task.updatedAt, isRemoteExecutor: task.isRemoteExecutor, diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet.tsx b/apps/web/components/task/mobile/session-task-switcher-sheet.tsx index 08e11ecad4..c69109d437 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet.tsx +++ b/apps/web/components/task/mobile/session-task-switcher-sheet.tsx @@ -13,7 +13,6 @@ import { WorkspaceSwitcher } from "../workspace-switcher"; import { TaskCreateDialog } from "@/components/task-create-dialog"; import { TaskArchiveConfirmDialog } from "../task-archive-confirm-dialog"; import { useSheetData, useSheetActions } from "./session-task-switcher-sheet-hooks"; -import type { Workspace } from "@/lib/types/http"; type SessionTaskSwitcherSheetProps = { open: boolean; @@ -98,7 +97,7 @@ export const SessionTaskSwitcherSheet = memo(function SessionTaskSwitcherSheet({
({ id: w.id, name: w.name }))} + workspaces={data.workspaces.map((w) => ({ id: w.id, name: w.name }))} activeWorkspaceId={workspaceId} onSelect={actions.handleWorkspaceChange} /> diff --git a/apps/web/components/task/new-subtask-dialog.tsx b/apps/web/components/task/new-subtask-dialog.tsx index 141de83fc4..b1323d4747 100644 --- a/apps/web/components/task/new-subtask-dialog.tsx +++ b/apps/web/components/task/new-subtask-dialog.tsx @@ -21,7 +21,7 @@ import { useSummarizeSession } from "@/hooks/use-summarize-session"; import { useTaskSessions } from "@/hooks/use-task-sessions"; import { getLocalStorage } from "@/lib/local-storage"; import { STORAGE_KEYS } from "@/lib/settings/constants"; -import type { ExecutorProfile, Repository } from "@/lib/types/http"; +import type { ExecutorProfile, ExecutorType, Repository } from "@/lib/types/http"; import type { AgentProfileOption } from "@/lib/state/slices"; import { defaultSubtaskWorkspaceMode, @@ -99,7 +99,7 @@ function useSessionOptions(taskId: string) { } function useExecutorProfiles( - executors: Array<{ id: string; type: string; name: string; profiles?: ExecutorProfile[] }>, + executors: Array<{ id: string; type: ExecutorType; name: string; profiles?: ExecutorProfile[] }>, ) { return useMemo(() => { return executors.flatMap((executor) => @@ -204,7 +204,7 @@ type SubtaskFormProps = { worktreeBranch: string | null; initialPrompt: string | null; agentProfiles: AgentProfileOption[]; - executors: Array<{ id: string; type: string; name: string; profiles?: ExecutorProfile[] }>; + executors: Array<{ id: string; type: ExecutorType; name: string; profiles?: ExecutorProfile[] }>; workspaceId: string | null; workflowId: string | null; /** The parent task's repository — used as the default for the subtask. */ diff --git a/apps/web/components/task/recent-task-switcher-model.test.ts b/apps/web/components/task/recent-task-switcher-model.test.ts index 0d6d926aa8..358bb7dd26 100644 --- a/apps/web/components/task/recent-task-switcher-model.test.ts +++ b/apps/web/components/task/recent-task-switcher-model.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from "vitest"; import type { RecentTaskEntry } from "@/lib/recent-tasks"; -import type { Repository, TaskSession } from "@/lib/types/http"; +import { + repositoryId as toRepositoryId, + sessionId as toSessionId, + taskId as toTaskId, + workspaceId as toWorkspaceId, + type Repository, + type TaskSession, +} from "@/lib/types/http"; import { buildRecentTaskDisplayItems, buildRecentTaskEntry, @@ -34,10 +41,10 @@ function recent(taskId: string, title: string): RecentTaskEntry { }; } -function session(taskId: string, state: TaskSession["state"]): TaskSession { +function session(taskIdStr: string, state: TaskSession["state"]): TaskSession { return { - id: `${taskId}-session`, - task_id: taskId, + id: toSessionId(`${taskIdStr}-session`), + task_id: toTaskId(taskIdStr), state, started_at: visitedAt, updated_at: visitedAt, @@ -47,8 +54,8 @@ function session(taskId: string, state: TaskSession["state"]): TaskSession { function buildContext(): RecentTaskBuildContext { const repository: Repository = { - id: REPOSITORY_ID, - workspace_id: WORKSPACE_ID, + id: toRepositoryId(REPOSITORY_ID), + workspace_id: toWorkspaceId(WORKSPACE_ID), name: "Local Repo", source_type: "local", local_path: "/tmp/local-repo", diff --git a/apps/web/components/task/session-sort.test.ts b/apps/web/components/task/session-sort.test.ts index f48cff5bfa..15cee206e3 100644 --- a/apps/web/components/task/session-sort.test.ts +++ b/apps/web/components/task/session-sort.test.ts @@ -6,19 +6,35 @@ import { resolveAgentLabelFor, sortSessions, } from "./session-sort"; -import type { TaskSession, TaskSessionState } from "@/lib/types/http"; +import { + agentProfileId as toAgentProfileId, + sessionId as toSessionId, + taskId as toTaskId, + type TaskSession, + type TaskSessionState, +} from "@/lib/types/http"; const EPOCH = "2025-01-01T00:00:00Z"; -function makeSession(overrides: Partial): TaskSession { +type SessionOverrides = Partial> & { + id?: string; + task_id?: string; + agent_profile_id?: string; +}; + +function makeSession(overrides: SessionOverrides): TaskSession { + const { id, task_id, agent_profile_id, ...rest } = overrides; return { - id: "s1", - task_id: "t1", + id: toSessionId(id ?? "s1"), + task_id: toTaskId(task_id ?? "t1"), + ...(agent_profile_id !== undefined + ? { agent_profile_id: toAgentProfileId(agent_profile_id) } + : {}), environment_id: "e1", state: "CREATED" as TaskSessionState, started_at: EPOCH, updated_at: EPOCH, - ...overrides, + ...rest, } as TaskSession; } diff --git a/apps/web/components/task/simple/components/agents-multi-picker.test.tsx b/apps/web/components/task/simple/components/agents-multi-picker.test.tsx index 441934f6b7..21ccbf8c5e 100644 --- a/apps/web/components/task/simple/components/agents-multi-picker.test.tsx +++ b/apps/web/components/task/simple/components/agents-multi-picker.test.tsx @@ -6,6 +6,7 @@ import { TooltipProvider } from "@kandev/ui/tooltip"; import { StateProvider, useAppStore } from "@/components/state-provider"; import { TaskOptimisticContextProvider } from "@/hooks/use-optimistic-task-mutation"; import type { AgentProfile } from "@/lib/state/slices/office/types"; +import { agentProfileId as toAgentProfileId, workspaceId as toWorkspaceId } from "@/lib/types/ids"; import { ApproversPicker } from "./approvers-picker"; import { buildDecisionLookup } from "./agents-multi-picker"; import type { Task, TaskDecision } from "@/app/office/tasks/[id]/types"; @@ -16,10 +17,10 @@ const TS = "2026-05-01T00:00:00Z"; function makeAgent(id: string, name: string): AgentProfile { return { - id, - workspaceId: "ws-1", + id: toAgentProfileId(id), + workspaceId: toWorkspaceId("ws-1"), name, - agentProfileId: "p1", + agentProfileId: toAgentProfileId("p1"), role: "worker", icon: "🤖", status: "idle", diff --git a/apps/web/components/task/simple/components/pending-approval-badge.test.tsx b/apps/web/components/task/simple/components/pending-approval-badge.test.tsx index 9ae7a86837..219ebfef0e 100644 --- a/apps/web/components/task/simple/components/pending-approval-badge.test.tsx +++ b/apps/web/components/task/simple/components/pending-approval-badge.test.tsx @@ -5,6 +5,7 @@ import { useEffect } from "react"; import { TooltipProvider } from "@kandev/ui/tooltip"; import { StateProvider, useAppStore } from "@/components/state-provider"; import type { AgentProfile } from "@/lib/state/slices/office/types"; +import { agentProfileId as toAgentProfileId, workspaceId as toWorkspaceId } from "@/lib/types/ids"; import { PendingApprovalBadge, computePendingApprovers, @@ -43,10 +44,10 @@ function SeedAgents({ agents }: { agents: AgentProfile[] }) { function makeAgent(id: string, name: string): AgentProfile { return { - id, - workspaceId: "ws-1", + id: toAgentProfileId(id), + workspaceId: toWorkspaceId("ws-1"), name, - agentProfileId: "p1", + agentProfileId: toAgentProfileId("p1"), role: "worker", icon: "🤖", status: "idle", diff --git a/apps/web/components/task/simple/components/topbar-working-indicator.test.tsx b/apps/web/components/task/simple/components/topbar-working-indicator.test.tsx index 7291a12c4c..fb0727bd5f 100644 --- a/apps/web/components/task/simple/components/topbar-working-indicator.test.tsx +++ b/apps/web/components/task/simple/components/topbar-working-indicator.test.tsx @@ -2,7 +2,12 @@ import { describe, it, expect, afterEach } from "vitest"; import { render, screen, cleanup, fireEvent } from "@testing-library/react"; import type { ReactNode } from "react"; import { StateProvider } from "@/components/state-provider"; -import type { TaskSession } from "@/lib/types/http"; +import { + agentProfileId as toAgentProfileId, + sessionId as toSessionId, + taskId as toTaskId, + type TaskSession, +} from "@/lib/types/http"; import { TopbarWorkingIndicator } from "./topbar-working-indicator"; import { ActiveSessionRefProvider, useActiveSessionRef } from "./active-session-ref-context"; @@ -12,10 +17,10 @@ const INDICATOR_TID = "topbar-working-indicator"; const T_START = "2026-05-01T10:00:00Z"; const T_UPDATE = "2026-05-01T10:01:00Z"; -function liveSession(taskId: string, id = "s-1"): TaskSession { +function liveSession(taskIdStr: string, id = "s-1"): TaskSession { return { - id, - task_id: taskId, + id: toSessionId(id), + task_id: toTaskId(taskIdStr), state: "RUNNING", started_at: T_START, updated_at: T_START, @@ -48,9 +53,9 @@ describe("TopbarWorkingIndicator", () => { it("drops the spinner when an office session goes RUNNING → IDLE", () => { // Office session: agent_profile_id set + state IDLE → not live. const idleOffice: TaskSession = { - id: "s-1", - task_id: "task-1", - agent_profile_id: "agent-a", + id: toSessionId("s-1"), + task_id: toTaskId("task-1"), + agent_profile_id: toAgentProfileId("agent-a"), state: "IDLE", started_at: T_START, updated_at: T_UPDATE, @@ -62,8 +67,8 @@ describe("TopbarWorkingIndicator", () => { it("keeps the spinner up for kanban WAITING_FOR_INPUT (no agent_profile_id)", () => { const waitingKanban: TaskSession = { - id: "s-1", - task_id: "task-1", + id: toSessionId("s-1"), + task_id: toTaskId("task-1"), state: "WAITING_FOR_INPUT", started_at: T_START, updated_at: T_UPDATE, diff --git a/apps/web/components/task/task-page-content.tsx b/apps/web/components/task/task-page-content.tsx index f74d6898ba..dfd443e72d 100644 --- a/apps/web/components/task/task-page-content.tsx +++ b/apps/web/components/task/task-page-content.tsx @@ -4,7 +4,14 @@ import { useEffect, useMemo, useState } from "react"; import { TaskTopBar } from "@/components/task/task-top-bar"; import { TaskLayout } from "@/components/task/task-layout"; import { DebugOverlay } from "@/components/debug-overlay"; -import type { Repository, RepositoryScript, Task } from "@/lib/types/http"; +import { + taskId as toTaskId, + workflowId as toWorkflowId, + workspaceId as toWorkspaceId, + type Repository, + type RepositoryScript, + type Task, +} from "@/lib/types/http"; import type { Terminal } from "@/hooks/domains/session/use-terminals"; import type { KanbanState } from "@/lib/state/slices"; import { DEBUG_UI } from "@/lib/config"; @@ -83,19 +90,19 @@ function buildTaskFromKanban( const prevWorkspaceId = taskDetails?.workspace_id ?? initialTask?.workspace_id; const prevBoardId = taskDetails?.workflow_id ?? initialTask?.workflow_id; return { - id: kanbanTask.id, + id: toTaskId(kanbanTask.id), title: kanbanTask.title, description: kanbanTask.description ?? "", workflow_step_id: kanbanTask.workflowStepId, position: kanbanTask.position, state: kanbanTask.state ?? "CREATED", - workspace_id: prevWorkspaceId ?? "", - workflow_id: prevBoardId ?? "", + workspace_id: prevWorkspaceId ?? toWorkspaceId(""), + workflow_id: prevBoardId ?? toWorkflowId(""), priority: 0, repositories: [], created_at: "", updated_at: kanbanTask.updatedAt ?? "", - } as Task; + }; } function useWorkflowStepsMapped() { diff --git a/apps/web/hooks/domains/kanban/use-implement-fresh.test.ts b/apps/web/hooks/domains/kanban/use-implement-fresh.test.ts index ec693ef552..c7947023ad 100644 --- a/apps/web/hooks/domains/kanban/use-implement-fresh.test.ts +++ b/apps/web/hooks/domains/kanban/use-implement-fresh.test.ts @@ -1,6 +1,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { renderHook, act } from "@testing-library/react"; -import type { TaskSession } from "@/lib/types/http"; +import { + agentProfileId as toAgentProfileId, + sessionId as toSessionId, + taskId as toTaskId, + type TaskSession, +} from "@/lib/types/http"; import type { MessageAttachment } from "@/components/task/chat/chat-input-container"; const mockLaunchSession = vi.fn(); @@ -49,10 +54,10 @@ const SESS_FRESH = "sess-fresh"; function makeSession(overrides: Partial = {}): TaskSession { return { - id: SESS_PLAN, - task_id: TASK_ID, + id: toSessionId(SESS_PLAN), + task_id: toTaskId(TASK_ID), state: "WAITING_FOR_INPUT", - agent_profile_id: "ap-1", + agent_profile_id: toAgentProfileId("ap-1"), executor_id: "ex-1", created_at: "", updated_at: "", diff --git a/apps/web/hooks/domains/session/use-base-branch-by-repo.ts b/apps/web/hooks/domains/session/use-base-branch-by-repo.ts index bdec1a0e5d..fca99367a4 100644 --- a/apps/web/hooks/domains/session/use-base-branch-by-repo.ts +++ b/apps/web/hooks/domains/session/use-base-branch-by-repo.ts @@ -2,7 +2,7 @@ import { useMemo } from "react"; import { useAppStore } from "@/components/state-provider"; -import type { Repository } from "@/lib/types/http"; +import { repositoryId, type Repository } from "@/lib/types/http"; /** * Returns a map from `repository_name` to its task base_branch for the active @@ -24,7 +24,7 @@ export function useBaseBranchByRepo(activeTaskId: string | null): Record [r.id, r.name])); const out: Record = {}; for (const link of task.repositories) { - const name = repoNameById.get(link.repository_id); + const name = repoNameById.get(repositoryId(link.repository_id)); if (name && link.base_branch) out[name] = link.base_branch; } return out; diff --git a/apps/web/hooks/domains/session/use-clarification-group.test.ts b/apps/web/hooks/domains/session/use-clarification-group.test.ts index 47d5123c30..7cdd47a274 100644 --- a/apps/web/hooks/domains/session/use-clarification-group.test.ts +++ b/apps/web/hooks/domains/session/use-clarification-group.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { act, renderHook } from "@testing-library/react"; -import type { Message } from "@/lib/types/http"; +import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http"; vi.mock("@/lib/config", () => ({ getBackendConfig: () => ({ apiBaseUrl: "https://api.test" }), @@ -17,8 +17,8 @@ function clarMessage(opts: { }): Message { return { id: opts.id, - session_id: "s1", - task_id: "t1", + session_id: toSessionId("s1"), + task_id: toTaskId("t1"), author_type: "agent", content: "Q", type: "clarification_request", diff --git a/apps/web/hooks/domains/session/use-session-resumption.ts b/apps/web/hooks/domains/session/use-session-resumption.ts index 38d755a046..0f2a9aa54d 100644 --- a/apps/web/hooks/domains/session/use-session-resumption.ts +++ b/apps/web/hooks/domains/session/use-session-resumption.ts @@ -6,7 +6,13 @@ import { buildRestoreWorkspaceRequest, } from "@/lib/services/session-launch-helpers"; import { useAppStore } from "@/components/state-provider"; -import type { TaskSessionState } from "@/lib/types/http"; +import { + sessionId as toSessionId, + taskId as toTaskId, + type SessionId, + type TaskId, + type TaskSessionState, +} from "@/lib/types/http"; export type SessionStatus = { session_id: string; @@ -50,8 +56,8 @@ export type ResumeStateSetter = { setWorktreePath: (p: string | null) => void; setWorktreeBranch: (b: string | null) => void; setTaskSession: (s: { - id: string; - task_id: string; + id: SessionId; + task_id: TaskId; state: TaskSessionState; started_at: string; updated_at: string; @@ -73,8 +79,8 @@ function applyResumeResponse( setters.setResumptionState("resumed"); if (resp.state) { setters.setTaskSession({ - id: sessionId, - task_id: taskId, + id: toSessionId(sessionId), + task_id: toTaskId(taskId), state: resp.state as TaskSessionState, started_at: session?.started_at ?? "", updated_at: session?.updated_at ?? "", @@ -230,8 +236,8 @@ function applyStatusToState( setters.setWorktreeBranch(status.worktree_branch ?? null); if (status.state) { setters.setTaskSession({ - id: sessionId, - task_id: taskId, + id: toSessionId(sessionId), + task_id: toTaskId(taskId), state: status.state as TaskSessionState, started_at: session?.started_at ?? "", updated_at: session?.updated_at ?? "", @@ -445,8 +451,8 @@ export function useSessionResumption( setResumptionState("resumed"); if (response.state) { setTaskSession({ - id: sessionId, - task_id: taskId, + id: toSessionId(sessionId), + task_id: toTaskId(taskId), state: response.state as TaskSessionState, started_at: session?.started_at ?? "", updated_at: session?.updated_at ?? "", diff --git a/apps/web/hooks/domains/settings/use-workflow-settings.test.ts b/apps/web/hooks/domains/settings/use-workflow-settings.test.ts index de57a2d0a5..22a23dbb39 100644 --- a/apps/web/hooks/domains/settings/use-workflow-settings.test.ts +++ b/apps/web/hooks/domains/settings/use-workflow-settings.test.ts @@ -1,6 +1,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { renderHook, act } from "@testing-library/react"; -import type { Workflow } from "@/lib/types/http"; +import { + workflowId as toWorkflowId, + workspaceId as toWorkspaceId, + type Workflow, +} from "@/lib/types/http"; type StoreWorkflow = { id: string; @@ -24,9 +28,9 @@ function setStore(items: StoreWorkflow[]) { mockState = { workflows: { items } }; } -const wf = (id: string, workspaceId: string, name: string): Workflow => ({ - id, - workspace_id: workspaceId, +const wf = (id: string, wsId: string, name: string): Workflow => ({ + id: toWorkflowId(id), + workspace_id: toWorkspaceId(wsId), name, description: "", created_at: "", diff --git a/apps/web/hooks/domains/settings/use-workflow-settings.ts b/apps/web/hooks/domains/settings/use-workflow-settings.ts index 408748a565..e73efba5f4 100644 --- a/apps/web/hooks/domains/settings/use-workflow-settings.ts +++ b/apps/web/hooks/domains/settings/use-workflow-settings.ts @@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { useAppStore } from "@/components/state-provider"; -import type { Workflow } from "@/lib/types/http"; +import { workflowId, workspaceId as toWorkspaceId, type Workflow } from "@/lib/types/http"; /** * Manages workflow list state for the settings page, synced with WS events @@ -74,7 +74,11 @@ export function useWorkflowSettings(initialWorkflows: Workflow[], workspaceId?: prev.filter((w) => w.id.startsWith("temp-")).map((w) => w.workspace_id), ); return scopedStoreWorkflows - .filter((sw) => !localIds.has(sw.id) && !tempWorkspaceIds.has(sw.workspaceId)) + .filter( + (sw) => + !localIds.has(workflowId(sw.id)) && + !tempWorkspaceIds.has(toWorkspaceId(sw.workspaceId)), + ) .map((sw) => storeItemToWorkflow(sw)); }; @@ -138,8 +142,8 @@ function storeItemToWorkflow(sw: { description?: string | null; }): Workflow { return { - id: sw.id, - workspace_id: sw.workspaceId, + id: workflowId(sw.id), + workspace_id: toWorkspaceId(sw.workspaceId), name: sw.name, description: sw.description, created_at: "", diff --git a/apps/web/hooks/use-processed-messages.test.ts b/apps/web/hooks/use-processed-messages.test.ts index 33f00ffd71..82d49d37b1 100644 --- a/apps/web/hooks/use-processed-messages.test.ts +++ b/apps/web/hooks/use-processed-messages.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect } from "vitest"; -import type { Message, MessageType } from "@/lib/types/http"; +import { + sessionId as toSessionId, + taskId as toTaskId, + type Message, + type MessageType, +} from "@/lib/types/http"; import { deduplicateAgentBootResumes, isAgentBootResumeMessage } from "./use-processed-messages"; function makeMessage( @@ -10,8 +15,8 @@ function makeMessage( ): Message { return { id, - session_id: "s1", - task_id: "t1", + session_id: toSessionId("s1"), + task_id: toTaskId("t1"), author_type: "agent", content, type, diff --git a/apps/web/hooks/use-processed-messages.ts b/apps/web/hooks/use-processed-messages.ts index 22b5b36cce..498a1c1d51 100644 --- a/apps/web/hooks/use-processed-messages.ts +++ b/apps/web/hooks/use-processed-messages.ts @@ -1,5 +1,11 @@ import { useMemo } from "react"; -import type { Message, ClarificationRequestMetadata, MessageType } from "@/lib/types/http"; +import { + sessionId as toSessionId, + taskId as toTaskId, + type ClarificationRequestMetadata, + type Message, + type MessageType, +} from "@/lib/types/http"; import type { ToolCallMetadata } from "@/components/task/chat/types"; import { findPendingClarification, @@ -264,8 +270,8 @@ export function useProcessedMessages( return taskDescription && visibleMessages.length === 0 ? { id: "task-description", - task_id: taskId ?? "", - session_id: resolvedSessionId ?? "", + task_id: toTaskId(taskId ?? ""), + session_id: toSessionId(resolvedSessionId ?? ""), author_type: "user", content: taskDescription, type: "message", diff --git a/apps/web/hooks/use-task-pending-clarification.test.tsx b/apps/web/hooks/use-task-pending-clarification.test.tsx index 5035d48d41..4e1f256ece 100644 --- a/apps/web/hooks/use-task-pending-clarification.test.tsx +++ b/apps/web/hooks/use-task-pending-clarification.test.tsx @@ -2,14 +2,14 @@ import { describe, expect, it } from "vitest"; import { renderHook } from "@testing-library/react"; import type { ReactNode } from "react"; import { StateProvider } from "@/components/state-provider"; -import type { Message } from "@/lib/types/http"; +import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http"; import { useTaskPendingClarification } from "./use-task-pending-clarification"; function message(overrides: Partial): Message { return { id: "msg-1", - session_id: "session-1", - task_id: "task-1", + session_id: toSessionId("session-1"), + task_id: toTaskId("task-1"), author_type: "agent", content: "", type: "message", diff --git a/apps/web/hooks/use-user-display-settings.ts b/apps/web/hooks/use-user-display-settings.ts index 66068e8c26..0109085a76 100644 --- a/apps/web/hooks/use-user-display-settings.ts +++ b/apps/web/hooks/use-user-display-settings.ts @@ -5,7 +5,7 @@ import { mapSelectedRepositoryIds } from "@/lib/kanban/filters"; import { useAppStore } from "@/components/state-provider"; import { useRepositories } from "@/hooks/domains/workspace/use-repositories"; import { mapUserSettingsResponse } from "@/lib/ssr/user-settings"; -import type { Repository } from "@/lib/types/http"; +import { repositoryId, type Repository } from "@/lib/types/http"; import type { UserSettingsState } from "@/lib/state/slices/settings/types"; type DisplaySettings = UserSettingsState; @@ -123,6 +123,39 @@ function useLoadUserSettings( }, [loaded, setUserSettings]); } +function usePruneStaleRepositoryIds( + userSettings: DisplaySettings, + repositories: Repository[], + commitSettings: (next: CommitPayload) => void, +) { + useEffect(() => { + if (!userSettings.loaded || repositories.length === 0) return; + const repoIds = repositories.map((repo: Repository) => repo.id); + const validIds = userSettings.repositoryIds.filter((id: string) => + repoIds.includes(repositoryId(id)), + ); + const isSame = + validIds.length === userSettings.repositoryIds.length && + validIds.every((id: string, index: number) => id === userSettings.repositoryIds[index]); + if (!isSame) { + queueMicrotask(() => { + commitSettings({ + workspaceId: userSettings.workspaceId, + workflowId: userSettings.workflowId, + repositoryIds: validIds, + }); + }); + } + }, [ + commitSettings, + repositories, + userSettings.workflowId, + userSettings.loaded, + userSettings.repositoryIds, + userSettings.workspaceId, + ]); +} + export function useUserDisplaySettings({ workspaceId, workflowId, @@ -191,30 +224,7 @@ export function useUserDisplaySettings({ } }, [workflowId, onWorkflowChange, userSettings.workflowId, userSettings.loaded]); - useEffect(() => { - if (!userSettings.loaded || repositories.length === 0) return; - const repoIds = repositories.map((repo: Repository) => repo.id); - const validIds = userSettings.repositoryIds.filter((id: string) => repoIds.includes(id)); - const isSame = - validIds.length === userSettings.repositoryIds.length && - validIds.every((id: string, index: number) => id === userSettings.repositoryIds[index]); - if (!isSame) { - queueMicrotask(() => { - commitSettings({ - workspaceId: userSettings.workspaceId, - workflowId: userSettings.workflowId, - repositoryIds: validIds, - }); - }); - } - }, [ - commitSettings, - repositories, - userSettings.workflowId, - userSettings.loaded, - userSettings.repositoryIds, - userSettings.workspaceId, - ]); + usePruneStaleRepositoryIds(userSettings, repositories, commitSettings); const allRepositoriesSelected = userSettings.repositoryIds.length === 0; const selectedRepositoryIds = useMemo( diff --git a/apps/web/lib/api/domains/agent-profile-normalize.test.ts b/apps/web/lib/api/domains/agent-profile-normalize.test.ts index f5ff79d1f0..491ad05fc6 100644 --- a/apps/web/lib/api/domains/agent-profile-normalize.test.ts +++ b/apps/web/lib/api/domains/agent-profile-normalize.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from "vitest"; import { normalizeAgentProfile, toAgentProfilePayload } from "./agent-profile-normalize"; +import { agentProfileId as toAgentProfileId } from "@/lib/types/ids"; describe("normalizeAgentProfile", () => { it("converts snake_case wire payload to canonical camelCase", () => { @@ -57,7 +58,7 @@ describe("normalizeAgentProfile", () => { describe("toAgentProfilePayload", () => { it("converts canonical camelCase back to snake_case wire shape", () => { const payload = toAgentProfilePayload({ - id: "p1", + id: toAgentProfileId("p1"), agentId: "claude", name: "default", cliPassthrough: false, @@ -73,7 +74,7 @@ describe("toAgentProfilePayload", () => { }); it("omits undefined fields rather than emitting nullish keys", () => { - const payload = toAgentProfilePayload({ id: "p1", name: "x" }); + const payload = toAgentProfilePayload({ id: toAgentProfileId("p1"), name: "x" }); expect(payload).toEqual({ id: "p1", name: "x" }); expect("agent_id" in payload).toBe(false); }); diff --git a/apps/web/lib/api/domains/agent-profile-normalize.ts b/apps/web/lib/api/domains/agent-profile-normalize.ts index 089d6caa4a..e265678b0f 100644 --- a/apps/web/lib/api/domains/agent-profile-normalize.ts +++ b/apps/web/lib/api/domains/agent-profile-normalize.ts @@ -7,6 +7,7 @@ // `app/actions/agents.ts` and `lib/ws/handlers/agents.ts`. import type { AgentProfile, AgentProfilePayload, CLIFlag } from "@/lib/types/agent-profile"; +import { agentProfileId } from "@/lib/types/ids"; type RawProfile = Partial & Partial & Record; @@ -33,7 +34,7 @@ function pickFlags(raw: RawProfile): CLIFlag[] { export function normalizeAgentProfile(raw: unknown): AgentProfile { const profile = (raw ?? {}) as RawProfile; return { - id: pickString(profile, "id", "id"), + id: agentProfileId(pickString(profile, "id", "id")), name: pickString(profile, "name", "name"), agentId: pickString(profile, "agentId", "agent_id"), agentDisplayName: pickString(profile, "agentDisplayName", "agent_display_name"), diff --git a/apps/web/lib/api/domains/office-api.ts b/apps/web/lib/api/domains/office-api.ts index ff6c3c6cbd..b15591cc1c 100644 --- a/apps/web/lib/api/domains/office-api.ts +++ b/apps/web/lib/api/domains/office-api.ts @@ -15,6 +15,7 @@ import type { LiveRun, } from "@/lib/state/slices/office/types"; import type { CLIFlag, AgentRole, AgentStatus } from "@/lib/types/agent-profile"; +import { agentProfileId, workspaceId } from "@/lib/types/ids"; // Re-export extended API so existing imports continue to work. export { @@ -133,12 +134,13 @@ function boolField(agent: Record, camelKey: string, snakeKey: s function normalizeAgent(raw: unknown): AgentProfile { const agent = raw as Record; - const id = agent.id as string; + const id = agentProfileId(agent.id as string); + const rawAgentProfileId = stringField(agent, "agentProfileId", "agent_profile_id"); return { id, - workspaceId: stringField(agent, "workspaceId", "workspace_id"), + workspaceId: workspaceId(stringField(agent, "workspaceId", "workspace_id")), name: agent.name as string, - agentProfileId: stringField(agent, "agentProfileId", "agent_profile_id") || id, + agentProfileId: rawAgentProfileId ? agentProfileId(rawAgentProfileId) : id, role: agent.role as AgentRole, icon: agent.icon as string | undefined, status: agent.status as AgentStatus, diff --git a/apps/web/lib/ssr/session-page-state.ts b/apps/web/lib/ssr/session-page-state.ts index 37d4003ab5..cddd2f8581 100644 --- a/apps/web/lib/ssr/session-page-state.ts +++ b/apps/web/lib/ssr/session-page-state.ts @@ -108,8 +108,8 @@ function buildResourceState(p: BuildSessionPageStateParams) { // Don't write activeId — null means "All Workflows"; task context lives in kanban.workflowId. workflows: { items: workflows.map((w) => ({ - id: w.id, - workspaceId: w.workspace_id, + id: w.id as string, + workspaceId: w.workspace_id as string, name: w.name, hidden: w.hidden, style: w.style, diff --git a/apps/web/lib/state/slices/office/office-agents.test.ts b/apps/web/lib/state/slices/office/office-agents.test.ts index da2fa3f562..c7a6b7035a 100644 --- a/apps/web/lib/state/slices/office/office-agents.test.ts +++ b/apps/web/lib/state/slices/office/office-agents.test.ts @@ -3,6 +3,7 @@ import { create } from "zustand"; import { immer } from "zustand/middleware/immer"; import { createOfficeSlice } from "./office-slice"; import type { OfficeSlice, AgentProfile } from "./types"; +import { agentProfileId as toAgentProfileId, workspaceId as toWorkspaceId } from "@/lib/types/ids"; function makeStore() { return create()( @@ -13,8 +14,8 @@ function makeStore() { function makeAgent(id: string, name: string): AgentProfile { return { - id, - workspaceId: "ws-1", + id: toAgentProfileId(id), + workspaceId: toWorkspaceId("ws-1"), name, role: "worker", status: "idle", diff --git a/apps/web/lib/state/slices/session-runtime/migrate-env-keyed-data.test.ts b/apps/web/lib/state/slices/session-runtime/migrate-env-keyed-data.test.ts index f9043f6b2c..daf7127275 100644 --- a/apps/web/lib/state/slices/session-runtime/migrate-env-keyed-data.test.ts +++ b/apps/web/lib/state/slices/session-runtime/migrate-env-keyed-data.test.ts @@ -5,6 +5,7 @@ import { createSessionRuntimeSlice } from "./session-runtime-slice"; import { createSessionSlice } from "../session/session-slice"; import type { SessionCommit, SessionRuntimeSlice } from "./types"; import type { SessionSlice } from "../session/types"; +import { sessionId as toSessionId, taskId as toTaskId } from "@/lib/types/ids"; function makeStore() { return create()(immer(createSessionRuntimeSlice)); @@ -186,8 +187,8 @@ describe("setTaskSession — cross-slice migration", () => { // Session update arrives with task_environment_id store.getState().setTaskSession({ - id: "sess-1", - task_id: "task-1", + id: toSessionId("sess-1"), + task_id: toTaskId("task-1"), state: "RUNNING", task_environment_id: "env-1", started_at: "", @@ -208,8 +209,8 @@ describe("setTaskSession — cross-slice migration", () => { store.getState().setGitStatus("sess-2", { branch: "dev" } as never); store.getState().setTaskSession({ - id: "sess-2", - task_id: "task-2", + id: toSessionId("sess-2"), + task_id: toTaskId("task-2"), state: "RUNNING", started_at: "", updated_at: "", @@ -231,16 +232,16 @@ describe("setTaskSessionsForTask — bulk cross-slice migration", () => { store.getState().setTaskSessionsForTask("task-1", [ { - id: "sess-a", - task_id: "task-1", + id: toSessionId("sess-a"), + task_id: toTaskId("task-1"), state: "COMPLETED", task_environment_id: "env-x", started_at: "", updated_at: "", }, { - id: "sess-b", - task_id: "task-1", + id: toSessionId("sess-b"), + task_id: toTaskId("task-1"), state: "RUNNING", task_environment_id: "env-y", started_at: "", diff --git a/apps/web/lib/state/slices/session/selectors.test.ts b/apps/web/lib/state/slices/session/selectors.test.ts index 4aa98d9bbd..5a63139f47 100644 --- a/apps/web/lib/state/slices/session/selectors.test.ts +++ b/apps/web/lib/state/slices/session/selectors.test.ts @@ -8,7 +8,14 @@ import { selectTotalLiveSessions, } from "./selectors"; import type { AppState } from "@/lib/state/store"; -import type { Message, TaskSession, TaskSessionState } from "@/lib/types/http"; +import { + agentProfileId as toAgentProfileId, + sessionId as toSessionId, + taskId as toTaskId, + type Message, + type TaskSession, + type TaskSessionState, +} from "@/lib/types/http"; const AGENT_A = "agent-a"; const AGENT_B = "agent-b"; @@ -23,9 +30,9 @@ function makeSession( overrides: Partial = {}, ): TaskSession { return { - id, - task_id: overrides.task_id ?? `task-${id}`, - agent_profile_id: agentProfileId, + id: toSessionId(id), + task_id: overrides.task_id ?? toTaskId(`task-${id}`), + agent_profile_id: agentProfileId ? toAgentProfileId(agentProfileId) : undefined, state, started_at: overrides.started_at ?? "2026-05-03T00:00:00Z", updated_at: overrides.updated_at ?? "2026-05-03T00:00:00Z", @@ -42,8 +49,8 @@ function stateWithSessions(sessions: TaskSession[]): AppState { function makeMessage(id: string, sessionId: string, type: Message["type"]): Message { return { id, - session_id: sessionId, - task_id: "task-1", + session_id: toSessionId(sessionId), + task_id: toTaskId("task-1"), author_type: "agent", content: "", type, @@ -115,60 +122,64 @@ describe("selectActiveSessionsForAgent", () => { describe("selectLiveSessionForTask", () => { it("returns null when taskId is empty", () => { - const state = stateWithSessions([makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" })]); + const state = stateWithSessions([ + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), + ]); expect(selectLiveSessionForTask(state, "")).toBeNull(); }); it("returns null when no sessions match the task", () => { const state = stateWithSessions([ - makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-other" }), + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-other") }), ]); expect(selectLiveSessionForTask(state, "task-1")).toBeNull(); }); it("returns null when sessions exist but none are live", () => { const state = stateWithSessions([ - makeSession("s1", AGENT_A, "COMPLETED", { task_id: "task-1" }), - makeSession("s2", AGENT_A, "FAILED", { task_id: "task-1" }), + makeSession("s1", AGENT_A, "COMPLETED", { task_id: toTaskId("task-1") }), + makeSession("s2", AGENT_A, "FAILED", { task_id: toTaskId("task-1") }), ]); expect(selectLiveSessionForTask(state, "task-1")).toBeNull(); }); it("returns the only RUNNING session for the task", () => { - const live = makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" }); + const live = makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }); const state = stateWithSessions([live]); expect(selectLiveSessionForTask(state, "task-1")?.id).toBe("s1"); }); it("treats WAITING_FOR_INPUT as live for kanban (no agent_profile_id)", () => { - const live = makeSession("s1", undefined, "WAITING_FOR_INPUT", { task_id: "task-1" }); + const live = makeSession("s1", undefined, "WAITING_FOR_INPUT", { task_id: toTaskId("task-1") }); const state = stateWithSessions([live]); expect(selectLiveSessionForTask(state, "task-1")?.id).toBe("s1"); }); it("does NOT treat IDLE as live for office sessions", () => { - const idle = makeSession("s1", AGENT_A, "IDLE", { task_id: "task-1" }); + const idle = makeSession("s1", AGENT_A, "IDLE", { task_id: toTaskId("task-1") }); const state = stateWithSessions([idle]); expect(selectLiveSessionForTask(state, "task-1")).toBeNull(); }); it("topbar drops the moment a turn ends: RUNNING → IDLE", () => { const before = stateWithSessions([ - makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" }), + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), ]); expect(selectLiveSessionForTask(before, "task-1")?.id).toBe("s1"); - const after = stateWithSessions([makeSession("s1", AGENT_A, "IDLE", { task_id: "task-1" })]); + const after = stateWithSessions([ + makeSession("s1", AGENT_A, "IDLE", { task_id: toTaskId("task-1") }), + ]); expect(selectLiveSessionForTask(after, "task-1")).toBeNull(); }); it("multi-agent task: returns the agent currently RUNNING, ignoring IDLE peers", () => { const state = stateWithSessions([ makeSession("s1", AGENT_A, "IDLE", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: "2026-05-03T11:00:00Z", }), makeSession("s2", AGENT_B, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_03, }), ]); @@ -178,15 +189,15 @@ describe("selectLiveSessionForTask", () => { it("picks the most recently started live session", () => { const state = stateWithSessions([ makeSession("s1", AGENT_A, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_01, }), makeSession("s2", AGENT_A, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_03, }), makeSession("s3", AGENT_A, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_02, }), ]); @@ -196,11 +207,11 @@ describe("selectLiveSessionForTask", () => { it("ignores sessions for other tasks", () => { const state = stateWithSessions([ makeSession("s1", AGENT_A, "RUNNING", { - task_id: "task-other", + task_id: toTaskId("task-other"), started_at: "2026-05-04T10:00:00Z", }), makeSession("s2", AGENT_A, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_01, }), ]); @@ -210,22 +221,24 @@ describe("selectLiveSessionForTask", () => { describe("selectAllSessionsForTask", () => { it("returns empty array when taskId is empty", () => { - const state = stateWithSessions([makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" })]); + const state = stateWithSessions([ + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), + ]); expect(selectAllSessionsForTask(state, "")).toEqual([]); }); it("returns sessions sorted by started_at ascending", () => { const state = stateWithSessions([ makeSession("s1", AGENT_A, "COMPLETED", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_03, }), makeSession("s2", AGENT_A, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_01, }), makeSession("s3", AGENT_A, "FAILED", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_02, }), ]); @@ -235,8 +248,8 @@ describe("selectAllSessionsForTask", () => { it("ignores sessions for other tasks", () => { const state = stateWithSessions([ - makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" }), - makeSession("s2", AGENT_A, "RUNNING", { task_id: "task-2" }), + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), + makeSession("s2", AGENT_A, "RUNNING", { task_id: toTaskId("task-2") }), ]); const result = selectAllSessionsForTask(state, "task-1"); expect(result.map((s) => s.id)).toEqual(["s1"]); @@ -250,11 +263,11 @@ describe("selectTotalLiveSessions", () => { it("counts RUNNING for office and (RUNNING | WAITING_FOR_INPUT) for kanban", () => { const state = stateWithSessions([ - makeSession("s1", AGENT_A, "RUNNING", { task_id: "t-1" }), // office, live - makeSession("s2", AGENT_B, "WAITING_FOR_INPUT", { task_id: "t-2" }), // office, NOT live - makeSession("s3", AGENT_A, "RUNNING", { task_id: "t-3" }), // office, live - makeSession("s4", AGENT_A, "COMPLETED", { task_id: "t-4" }), // not live - makeSession("s5", undefined, "WAITING_FOR_INPUT", { task_id: "t-5" }), // kanban, live + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("t-1") }), // office, live + makeSession("s2", AGENT_B, "WAITING_FOR_INPUT", { task_id: toTaskId("t-2") }), // office, NOT live + makeSession("s3", AGENT_A, "RUNNING", { task_id: toTaskId("t-3") }), // office, live + makeSession("s4", AGENT_A, "COMPLETED", { task_id: toTaskId("t-4") }), // not live + makeSession("s5", undefined, "WAITING_FOR_INPUT", { task_id: toTaskId("t-5") }), // kanban, live ]); expect(selectTotalLiveSessions(state)).toBe(3); }); @@ -274,15 +287,17 @@ describe("selectTotalLiveSessions", () => { describe("selectSessionsByAgentForTask", () => { it("returns an empty Map when taskId is empty", () => { - const state = stateWithSessions([makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" })]); + const state = stateWithSessions([ + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), + ]); expect(selectSessionsByAgentForTask(state, "").size).toBe(0); }); it("groups sessions by agent_profile_id", () => { const state = stateWithSessions([ - makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" }), - makeSession("s2", AGENT_B, "IDLE", { task_id: "task-1" }), - makeSession("s3", AGENT_A, "COMPLETED", { task_id: "task-1" }), + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), + makeSession("s2", AGENT_B, "IDLE", { task_id: toTaskId("task-1") }), + makeSession("s3", AGENT_A, "COMPLETED", { task_id: toTaskId("task-1") }), ]); const result = selectSessionsByAgentForTask(state, "task-1"); expect(result.size).toBe(2); @@ -297,8 +312,8 @@ describe("selectSessionsByAgentForTask", () => { it("buckets kanban sessions (no agent_profile_id) under empty key", () => { const state = stateWithSessions([ - makeSession("s1", undefined, "RUNNING", { task_id: "task-1" }), - makeSession("s2", AGENT_A, "IDLE", { task_id: "task-1" }), + makeSession("s1", undefined, "RUNNING", { task_id: toTaskId("task-1") }), + makeSession("s2", AGENT_A, "IDLE", { task_id: toTaskId("task-1") }), ]); const result = selectSessionsByAgentForTask(state, "task-1"); expect(result.get("")?.map((s) => s.id)).toEqual(["s1"]); @@ -307,8 +322,8 @@ describe("selectSessionsByAgentForTask", () => { it("ignores sessions for other tasks", () => { const state = stateWithSessions([ - makeSession("s1", AGENT_A, "RUNNING", { task_id: "task-1" }), - makeSession("s2", AGENT_A, "RUNNING", { task_id: "task-other" }), + makeSession("s1", AGENT_A, "RUNNING", { task_id: toTaskId("task-1") }), + makeSession("s2", AGENT_A, "RUNNING", { task_id: toTaskId("task-other") }), ]); const result = selectSessionsByAgentForTask(state, "task-1"); expect(result.get(AGENT_A)?.map((s) => s.id)).toEqual(["s1"]); @@ -317,12 +332,12 @@ describe("selectSessionsByAgentForTask", () => { it("orders agent buckets by most-recent activity (latest updated_at desc)", () => { const state = stateWithSessions([ makeSession("s1", AGENT_A, "IDLE", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_01, updated_at: T_MAY_01, }), makeSession("s2", AGENT_B, "RUNNING", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_02, updated_at: T_MAY_03, }), @@ -336,11 +351,11 @@ describe("selectSessionsByAgentForTask", () => { it("sorts within an agent bucket by started_at ascending", () => { const state = stateWithSessions([ makeSession("s1", AGENT_A, "COMPLETED", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_03, }), makeSession("s2", AGENT_A, "IDLE", { - task_id: "task-1", + task_id: toTaskId("task-1"), started_at: T_MAY_01, }), ]); diff --git a/apps/web/lib/state/slices/session/session-slice.upsert.test.ts b/apps/web/lib/state/slices/session/session-slice.upsert.test.ts index b3c4c03bfe..c5f2c78c5c 100644 --- a/apps/web/lib/state/slices/session/session-slice.upsert.test.ts +++ b/apps/web/lib/state/slices/session/session-slice.upsert.test.ts @@ -5,7 +5,13 @@ import { createSessionSlice } from "./session-slice"; import { createSessionRuntimeSlice } from "../session-runtime/session-runtime-slice"; import type { QueuedMessage, SessionSlice } from "./types"; import type { SessionRuntimeSlice } from "../session-runtime/types"; -import type { TaskSession } from "@/lib/types/http"; +import { + agentProfileId as toAgentProfileId, + repositoryId as toRepositoryId, + sessionId as toSessionId, + taskId as toTaskId, + type TaskSession, +} from "@/lib/types/http"; type CombinedSlice = SessionSlice & SessionRuntimeSlice; @@ -20,18 +26,29 @@ function makeStore() { ); } -const TASK_ID = "task-1"; -const SESSION_ID = "session-1"; +const TASK_ID = toTaskId("task-1"); +const SESSION_ID = toSessionId("session-1"); const TS = "2026-04-20T00:00:00Z"; -function makeSession(overrides: Partial = {}): TaskSession { +type SessionOverrides = Partial> & { + id?: string; + agent_profile_id?: string; + repository_id?: string; +}; + +function makeSession(overrides: SessionOverrides = {}): TaskSession { + const { id, agent_profile_id, repository_id, ...rest } = overrides; return { - id: SESSION_ID, + id: id ? toSessionId(id) : SESSION_ID, task_id: TASK_ID, state: "RUNNING", started_at: TS, updated_at: TS, - ...overrides, + ...(agent_profile_id !== undefined + ? { agent_profile_id: toAgentProfileId(agent_profile_id) } + : {}), + ...(repository_id !== undefined ? { repository_id: toRepositoryId(repository_id) } : {}), + ...rest, }; } diff --git a/apps/web/lib/state/slices/ui/types.ts b/apps/web/lib/state/slices/ui/types.ts index e2bc25a613..9765e5c872 100644 --- a/apps/web/lib/state/slices/ui/types.ts +++ b/apps/web/lib/state/slices/ui/types.ts @@ -1,3 +1,4 @@ +import type { ConnectionStatus } from "@/lib/types/connection"; import type { HealthIssue, SystemHealthResponse } from "@/lib/types/health"; import type { FilterClause, @@ -30,7 +31,7 @@ export type DiffState = { }; export type ConnectionState = { - status: "disconnected" | "connecting" | "connected" | "error" | "reconnecting"; + status: ConnectionStatus; error: string | null; }; diff --git a/apps/web/lib/types/agent-profile.ts b/apps/web/lib/types/agent-profile.ts index 4a51426435..6f9badc9fd 100644 --- a/apps/web/lib/types/agent-profile.ts +++ b/apps/web/lib/types/agent-profile.ts @@ -1,3 +1,5 @@ +import type { AgentProfileId, WorkspaceId } from "./ids"; + // Canonical AgentProfile (ADR 0005, Wave E): // ONE camelCase shape used by both kanban and office consumers. The HTTP // transport layer normalizes snake_case server payloads at the API client @@ -50,7 +52,7 @@ export type AgentStatus = "idle" | "working" | "paused" | "stopped" | "pending_a export type AgentProfile = { // --- Identity --- - id: string; + id: AgentProfileId; name: string; /** ID of the agent (CLI) this profile belongs to. */ agentId: string; @@ -71,13 +73,13 @@ export type AgentProfile = { // --- Office orchestration (always populated by office API, // absent on kanban-served rows; consumers should null-check) --- - workspaceId?: string; + workspaceId?: WorkspaceId; /** * FK to a kanban-flavour profile when the office row delegates CLI * subprocess configuration to a separate profile rather than carrying * the CLI fields directly. */ - agentProfileId?: string; + agentProfileId?: AgentProfileId; role?: AgentRole; icon?: string; status?: AgentStatus; diff --git a/apps/web/lib/types/connection.ts b/apps/web/lib/types/connection.ts new file mode 100644 index 0000000000..8617bfb3d4 --- /dev/null +++ b/apps/web/lib/types/connection.ts @@ -0,0 +1,15 @@ +/** + * Canonical WebSocket / connection status used by both the low-level + * `WebSocketClient` and the UI `ConnectionState` slice. Replaces the two + * parallel enums that previously needed a rename mapping in `useWebSocket`. + * + * Names favour the UI vocabulary (`connected` rather than `open`, + * `disconnected` rather than `closed`/`idle`) since most readers are the + * status banner / chrome. + */ +export type ConnectionStatus = + | "disconnected" + | "connecting" + | "connected" + | "error" + | "reconnecting"; diff --git a/apps/web/lib/types/executor-payloads.ts b/apps/web/lib/types/executor-payloads.ts index 72860d2bcd..0ab8a2e3a7 100644 --- a/apps/web/lib/types/executor-payloads.ts +++ b/apps/web/lib/types/executor-payloads.ts @@ -1,9 +1,11 @@ // Executor and environment payload types for WS events +import type { ExecutorType } from "./executor"; + export type ExecutorPayload = { id: string; name: string; - type: string; + type: ExecutorType; status: string; is_system: boolean; config?: Record; diff --git a/apps/web/lib/types/executor.ts b/apps/web/lib/types/executor.ts new file mode 100644 index 0000000000..751f99969f --- /dev/null +++ b/apps/web/lib/types/executor.ts @@ -0,0 +1,23 @@ +/** + * Canonical executor type identifiers. Mirrors the backend's database + * `executors.type` values plus the synthetic `worktree` executor used in the + * settings UI for git worktree isolation. See `CLAUDE.md` -> Executor Types. + * + * Keep this union in sync with the backend: + * apps/backend/internal/task/models/models.go (ExecutorType constants) + * + * Note: `"local"` is the seeded `Executor.type` value (see + * `task/repository/sqlite/defaults.go`). `"local_pc"` appears in the office + * `ExecutorTypeMeta` listing (`office/models/meta.go`) and the SQLite + * backfill default for orphaned tasks — both can flow through `Executor.type` + * in the wild, so the union keeps them both. + */ +export type ExecutorType = + | "local" + | "local_pc" + | "local_docker" + | "sprites" + | "remote_docker" + | "remote_vps" + | "k8s" + | "worktree"; diff --git a/apps/web/lib/types/http.test.ts b/apps/web/lib/types/http.test.ts index fa98948819..a096684953 100644 --- a/apps/web/lib/types/http.test.ts +++ b/apps/web/lib/types/http.test.ts @@ -1,16 +1,31 @@ import { describe, it, expect } from "vitest"; -import { isFromOffice, primaryTaskRepository, type Task, type TaskRepository } from "./http"; +import { + isFromOffice, + primaryTaskRepository, + repositoryId as toRepositoryId, + taskId as toTaskId, + workflowId as toWorkflowId, + workspaceId as toWorkspaceId, + type Task, + type TaskRepository, +} from "./http"; -function repo(overrides: Partial): TaskRepository { +type RepoOverrides = Partial> & { + task_id?: string; + repository_id?: string; +}; + +function repo(overrides: RepoOverrides): TaskRepository { + const { task_id, repository_id, ...rest } = overrides; return { id: "tr-" + Math.random().toString(36).slice(2), - task_id: "task-1", - repository_id: "repo-x", + task_id: toTaskId(task_id ?? "task-1"), + repository_id: toRepositoryId(repository_id ?? "repo-x"), base_branch: "main", position: 0, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), - ...overrides, + ...rest, }; } @@ -37,9 +52,9 @@ describe("primaryTaskRepository", () => { function task(overrides: Partial): Task { return { - id: "task-1", - workspace_id: "ws-1", - workflow_id: "wf-1", + id: toTaskId("task-1"), + workspace_id: toWorkspaceId("ws-1"), + workflow_id: toWorkflowId("wf-1"), workflow_step_id: "ws-step-1", position: 0, title: "t", diff --git a/apps/web/lib/types/http.ts b/apps/web/lib/types/http.ts index f1a5565fe3..4046f4d86d 100644 --- a/apps/web/lib/types/http.ts +++ b/apps/web/lib/types/http.ts @@ -1,3 +1,30 @@ +import type { ExecutorType } from "./executor"; +import type { + AgentProfileId, + RepositoryId, + SessionId, + TaskId, + WorkflowId, + WorkspaceId, +} from "./ids"; +import type { OnEnterActionType, StepEvents } from "./workflow-actions"; + +export type { ExecutorType } from "./executor"; +export * from "./ids"; +export type { + MoveToStepConfig, + OnEnterAction, + OnEnterActionType, + OnExitAction, + OnExitActionType, + OnTurnCompleteAction, + OnTurnCompleteActionType, + OnTurnStartAction, + OnTurnStartActionType, + StepEvents, + TransitionConfig, +} from "./workflow-actions"; + export type TaskState = | "CREATED" | "SCHEDULING" @@ -10,49 +37,6 @@ export type TaskState = | "FAILED" | "CANCELLED"; -// On Enter action types -export type OnEnterActionType = "enable_plan_mode" | "auto_start_agent" | "reset_agent_context"; - -// On Turn Start action types -export type OnTurnStartActionType = "move_to_next" | "move_to_previous" | "move_to_step"; - -// On Turn Complete action types -export type OnTurnCompleteActionType = - | "move_to_next" - | "move_to_previous" - | "move_to_step" - | "disable_plan_mode"; - -// On Exit action types -export type OnExitActionType = "disable_plan_mode"; - -export type OnEnterAction = { - type: OnEnterActionType; - config?: Record; -}; - -export type OnTurnStartAction = { - type: OnTurnStartActionType; - config?: Record; -}; - -export type OnTurnCompleteAction = { - type: OnTurnCompleteActionType; - config?: Record; -}; - -export type OnExitAction = { - type: OnExitActionType; - config?: Record; -}; - -export type StepEvents = { - on_enter?: OnEnterAction[]; - on_turn_start?: OnTurnStartAction[]; - on_turn_complete?: OnTurnCompleteAction[]; - on_exit?: OnExitAction[]; -}; - // Workflow Review Status export type WorkflowReviewStatus = "pending" | "approved" | "changes_requested" | "rejected"; @@ -76,13 +60,13 @@ export type StepDefinition = { events?: StepEvents; is_start_step?: boolean; show_in_command_panel?: boolean; - agent_profile_id?: string; + agent_profile_id?: AgentProfileId; }; // Workflow Step - instance of a step on a workflow export type WorkflowStep = { id: string; - workflow_id: string; + workflow_id: WorkflowId; name: string; position: number; color: string; @@ -105,7 +89,7 @@ export type WorkflowStep = { // Session Step History - audit trail export type SessionStepHistory = { id: string; - session_id: string; + session_id: SessionId; from_step_id?: string; to_step_id: string; trigger: string; @@ -142,12 +126,12 @@ export type TaskSessionState = | "CANCELLED"; export type Workflow = { - id: string; - workspace_id: string; + id: WorkflowId; + workspace_id: WorkspaceId; name: string; description?: string | null; workflow_template_id?: string | null; - agent_profile_id?: string; + agent_profile_id?: AgentProfileId; sort_order?: number; hidden?: boolean; /** @@ -160,22 +144,22 @@ export type Workflow = { }; export type Workspace = { - id: string; + id: WorkspaceId; name: string; description?: string | null; owner_id: string; default_executor_id?: string | null; default_environment_id?: string | null; - default_agent_profile_id?: string | null; - default_config_agent_profile_id?: string | null; - office_workflow_id?: string; + default_agent_profile_id?: AgentProfileId | null; + default_config_agent_profile_id?: AgentProfileId | null; + office_workflow_id?: WorkflowId; created_at: string; updated_at: string; }; export type Repository = { - id: string; - workspace_id: string; + id: RepositoryId; + workspace_id: WorkspaceId; name: string; source_type: string; local_path: string; @@ -196,7 +180,7 @@ export type Repository = { export type RepositoryScript = { id: string; - repository_id: string; + repository_id: RepositoryId; name: string; command: string; position: number; @@ -212,7 +196,7 @@ export type ProcessOutputChunk = { export type ProcessInfo = { id: string; - session_id: string; + session_id: SessionId; kind: string; script_name?: string; command: string; @@ -226,8 +210,8 @@ export type ProcessInfo = { export type TaskRepository = { id: string; - task_id: string; - repository_id: string; + task_id: TaskId; + repository_id: RepositoryId; base_branch: string; /** * Optional branch to fetch and check out after worktree creation @@ -258,9 +242,9 @@ export function primaryTaskRepository( } export type Task = { - id: string; - workspace_id: string; - workflow_id: string; + id: TaskId; + workspace_id: WorkspaceId; + workflow_id: WorkflowId; workflow_step_id: string; position: number; title: string; @@ -268,18 +252,18 @@ export type Task = { state: TaskState; priority: number; repositories?: TaskRepository[]; - primary_session_id?: string | null; + primary_session_id?: SessionId | null; primary_session_state?: TaskSessionState | null; session_count?: number | null; review_status?: "pending" | "approved" | "changes_requested" | "rejected" | null; primary_executor_id?: string | null; - primary_executor_type?: string | null; + primary_executor_type?: ExecutorType | null; primary_executor_name?: string | null; primary_agent_name?: string | null; primary_working_directory?: string | null; is_remote_executor?: boolean; is_ephemeral?: boolean; - parent_id?: string; + parent_id?: TaskId; archived_at?: string | null; created_at: string; updated_at: string; @@ -309,7 +293,7 @@ export type CreateTaskResponse = Task & { // Backend workflow step DTO (flat fields, as returned from API) export type WorkflowStepDTO = { id: string; - workflow_id: string; + workflow_id: WorkflowId; name: string; position: number; color: string; @@ -319,7 +303,7 @@ export type WorkflowStepDTO = { is_start_step?: boolean; show_in_command_panel?: boolean; auto_archive_after_hours?: number; - agent_profile_id?: string; + agent_profile_id?: AgentProfileId; stage_type?: "work" | "review" | "approval" | "custom"; created_at?: string; updated_at?: string; @@ -332,13 +316,13 @@ export type MoveTaskResponse = { }; export type TaskSession = { - id: string; - task_id: string; - agent_profile_id?: string; + id: SessionId; + task_id: TaskId; + agent_profile_id?: AgentProfileId; container_id?: string; executor_id?: string; environment_id?: string; - repository_id?: string; + repository_id?: RepositoryId; base_branch?: string; base_commit_sha?: string; worktree_id?: string; @@ -423,7 +407,7 @@ export type SidebarViewApi = { export type UserSettings = { user_id: string; - workspace_id: string; + workspace_id: WorkspaceId; kanban_view_mode?: string; workflow_filter_id?: string; repository_ids: string[]; @@ -568,7 +552,7 @@ export type ListWorkspacesResponse = { export type Executor = { id: string; name: string; - type: string; + type: ExecutorType; status: string; is_system: boolean; config?: Record; @@ -586,7 +570,7 @@ export type ProfileEnvVar = { export type ExecutorProfile = { id: string; executor_id: string; - executor_type?: string; + executor_type?: ExecutorType; executor_name?: string; name: string; mcp_policy?: string; @@ -655,8 +639,8 @@ export type MessageType = export type Message = { id: string; - session_id: string; - task_id: string; + session_id: SessionId; + task_id: TaskId; turn_id?: string; author_type: MessageAuthorType; author_id?: string; @@ -670,8 +654,8 @@ export type Message = { export type Turn = { id: string; - session_id: string; - task_id: string; + session_id: SessionId; + task_id: TaskId; started_at: string; completed_at?: string; metadata?: Record; diff --git a/apps/web/lib/types/ids.ts b/apps/web/lib/types/ids.ts new file mode 100644 index 0000000000..6474ffc5ee --- /dev/null +++ b/apps/web/lib/types/ids.ts @@ -0,0 +1,41 @@ +/** + * Branded ID types + * + * Branded primitives let TypeScript catch argument-order mixups at compile + * time (e.g. passing a `sessionId` where a `taskId` is expected). They erase + * to `string` at runtime — the brand is a phantom property that only exists + * in the type system. + * + * Usage: + * + * function loadTask(id: TaskId) { ... } + * + * // at a trust boundary (HTTP parse, URL params, WS payload, SSR hydration): + * loadTask(taskId(json.id)); + * + * // values read from already-branded fields propagate the brand: + * loadTask(task.id); // task.id is already TaskId + * + * Comparison with string literals still works because branded types extend + * string. Cross-brand comparison is a compile error — which is the goal. + */ + +export type TaskId = string & { readonly __brand: "TaskId" }; +export type SessionId = string & { readonly __brand: "SessionId" }; +export type WorkspaceId = string & { readonly __brand: "WorkspaceId" }; +export type WorkflowId = string & { readonly __brand: "WorkflowId" }; +export type RepositoryId = string & { readonly __brand: "RepositoryId" }; +export type AgentProfileId = string & { readonly __brand: "AgentProfileId" }; + +// Escape-hatch constructors. Use these only at trust boundaries: +// - HTTP/WS payload parsing +// - URL/route param decoding +// - SSR hydration adapters +// - test fixtures +// Inside the app, prefer reading from already-branded fields (task.id, etc). +export const taskId = (s: string): TaskId => s as TaskId; +export const sessionId = (s: string): SessionId => s as SessionId; +export const workspaceId = (s: string): WorkspaceId => s as WorkspaceId; +export const workflowId = (s: string): WorkflowId => s as WorkflowId; +export const repositoryId = (s: string): RepositoryId => s as RepositoryId; +export const agentProfileId = (s: string): AgentProfileId => s as AgentProfileId; diff --git a/apps/web/lib/types/permission.ts b/apps/web/lib/types/permission.ts new file mode 100644 index 0000000000..b1ade77683 --- /dev/null +++ b/apps/web/lib/types/permission.ts @@ -0,0 +1,38 @@ +/** + * Permission request types mirrored from + * `apps/backend/internal/agentctl/types/streams/permission.go`. + * + * Keep these unions in sync with the backend constants + * (`PermissionActionType`, `PermissionOptionKind`). Stable wire-format strings + * shared across agentctl, the backend orchestrator, and the frontend. + */ + +/** + * Categorises the kind of action requiring approval. + * + * Mirrors `streams.PermissionActionType` constants: + * - command: shell command execution + * - file_write: file modification or creation + * - file_read: file read (for sensitive files) + * - network: network access + * - mcp_tool: MCP tool invocation + * - other: other / unknown action type + */ +export type PermissionActionType = + | "command" + | "file_write" + | "file_read" + | "network" + | "mcp_tool" + | "other"; + +/** + * Identifies the semantics of a permission option presented to the user. + * + * Mirrors `streams.PermissionOptionKind` constants: + * - allow_once: approves the current request only + * - allow_always: approves and remembers the decision + * - reject_once: rejects the current request only + * - reject_always: rejects and remembers the decision + */ +export type PermissionOptionKind = "allow_once" | "allow_always" | "reject_once" | "reject_always"; diff --git a/apps/web/lib/types/workflow-actions.ts b/apps/web/lib/types/workflow-actions.ts new file mode 100644 index 0000000000..dd998db663 --- /dev/null +++ b/apps/web/lib/types/workflow-actions.ts @@ -0,0 +1,95 @@ +/** + * Workflow step action types — mirrors the Go `workflow/models` package + * (`OnEnterActionType`, `OnTurnStartActionType`, `OnTurnCompleteActionType`, + * `OnExitActionType`). Each variant of the discriminated unions below carries + * its `config` shape so call sites stop reaching into `Record` + * to read e.g. `step_id`. + * + * Keep this file in sync with: + * - apps/backend/internal/workflow/models/models.go (action constants) + * - apps/backend/internal/workflow/engine/types.go (compiled action config readers) + */ + +// On Enter action types +export type OnEnterActionType = "enable_plan_mode" | "auto_start_agent" | "reset_agent_context"; + +// On Turn Start action types +export type OnTurnStartActionType = "move_to_next" | "move_to_previous" | "move_to_step"; + +// On Turn Complete action types +export type OnTurnCompleteActionType = + | "move_to_next" + | "move_to_previous" + | "move_to_step" + | "disable_plan_mode"; + +// On Exit action types +export type OnExitActionType = "disable_plan_mode"; + +/** + * Optional config flags shared by transition actions (move_to_next / + * move_to_previous / move_to_step). The Go engine reads these via + * `ConfigRequiresApproval` and `ConfigTransitionGuard` on every transition, + * so they are valid on any move_to_* action across the on_turn_start and + * on_turn_complete triggers. + * + * See `apps/backend/internal/workflow/engine/types.go`. + */ +export type TransitionConfig = { + /** Gate the transition on manual approval before it fires. */ + requires_approval?: boolean; + /** + * Optional guard clause that gates the transition on quorum / decision + * state. Today only `wait_for_quorum` is supported by the engine. + */ + if?: { + wait_for_quorum?: { + /** Participant role to count decisions for (e.g. "reviewer", "approver"). */ + role: string; + /** + * Threshold expression: "all_approve" | "all_decide" | "any_reject" | + * "majority_approve" | "n_approve:". + */ + threshold: string; + }; + }; +}; + +/** Config for `move_to_step` actions. Carries the target step id. */ +export type MoveToStepConfig = TransitionConfig & { + step_id: string; +}; + +// Discriminated union of on_enter actions. Today only `auto_start_agent` +// carries optional config (`queue_if_busy` + `prompt_override`), but kanban +// templates never set those so config is optional everywhere. +export type OnEnterAction = + | { type: "enable_plan_mode" } + | { + type: "auto_start_agent"; + config?: { + prompt_override?: string; + queue_if_busy?: boolean; + }; + } + | { type: "reset_agent_context" }; + +export type OnTurnStartAction = + | { type: "move_to_next"; config?: TransitionConfig } + | { type: "move_to_previous"; config?: TransitionConfig } + | { type: "move_to_step"; config: MoveToStepConfig }; + +export type OnTurnCompleteAction = + | { type: "move_to_next"; config?: TransitionConfig } + | { type: "move_to_previous"; config?: TransitionConfig } + | { type: "move_to_step"; config: MoveToStepConfig } + | { type: "disable_plan_mode" }; + +export type OnExitAction = { type: "disable_plan_mode" }; + +export type StepEvents = { + on_enter?: OnEnterAction[]; + on_turn_start?: OnTurnStartAction[]; + on_turn_complete?: OnTurnCompleteAction[]; + on_exit?: OnExitAction[]; +}; diff --git a/apps/web/lib/utils/pending-clarification.test.ts b/apps/web/lib/utils/pending-clarification.test.ts index 423c457969..73c279cb2e 100644 --- a/apps/web/lib/utils/pending-clarification.test.ts +++ b/apps/web/lib/utils/pending-clarification.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { Message } from "@/lib/types/http"; +import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http"; import { findPendingClarificationGroup, hasPendingClarification, @@ -9,8 +9,8 @@ import { function message(overrides: Partial): Message { return { id: "msg-1", - session_id: "session-1", - task_id: "task-1", + session_id: toSessionId("session-1"), + task_id: toTaskId("task-1"), author_type: "agent", content: "", type: "message", diff --git a/apps/web/lib/utils/session-info.test.ts b/apps/web/lib/utils/session-info.test.ts index 74e7eba204..d69bddb763 100644 --- a/apps/web/lib/utils/session-info.test.ts +++ b/apps/web/lib/utils/session-info.test.ts @@ -1,17 +1,23 @@ import { describe, it, expect } from "vitest"; import { getSessionInfoForTask } from "./session-info"; -import type { TaskSession } from "@/lib/types/http"; +import { sessionId as toSessionId, taskId as toTaskId, type TaskSession } from "@/lib/types/http"; -function session(overrides: Partial): TaskSession { +type SessionOverrides = Partial> & { + id?: string; + task_id?: string; +}; + +function session(overrides: SessionOverrides): TaskSession { + const { id, task_id, ...rest } = overrides; return { - id: overrides.id ?? "s1", - task_id: overrides.task_id ?? "t1", + id: toSessionId(id ?? "s1"), + task_id: toTaskId(task_id ?? "t1"), state: overrides.state ?? "WAITING_FOR_INPUT", started_at: overrides.started_at ?? "", updated_at: overrides.updated_at ?? "", is_primary: overrides.is_primary ?? false, - ...overrides, + ...rest, } as TaskSession; } diff --git a/apps/web/lib/ws/client.ts b/apps/web/lib/ws/client.ts index cad61497d1..07bccb4cd6 100644 --- a/apps/web/lib/ws/client.ts +++ b/apps/web/lib/ws/client.ts @@ -1,9 +1,13 @@ import type { BackendMessageMap, BackendMessageType } from "@/lib/types/backend"; +import type { ConnectionStatus } from "@/lib/types/connection"; import { generateUUID } from "@/lib/utils"; type MessageHandler = (message: BackendMessageMap[T]) => void; -type WebSocketStatus = "idle" | "connecting" | "open" | "closed" | "error" | "reconnecting"; +// Internal alias kept for readability — the WS client emits the same vocabulary +// the UI consumes. `disconnected` covers both "never connected" (formerly +// `idle`) and "socket closed" (formerly `closed`); `connected` replaces `open`. +type WebSocketStatus = ConnectionStatus; export interface ReconnectOptions { enabled?: boolean; @@ -23,7 +27,7 @@ const DEFAULT_RECONNECT_OPTIONS: Required = { export class WebSocketClient { private socket: WebSocket | null = null; - private status: WebSocketStatus = "idle"; + private status: WebSocketStatus = "disconnected"; private handlers = new Map>>(); private pendingRequests = new Map< string, @@ -69,7 +73,7 @@ export class WebSocketClient { this.socket.onopen = () => { this.reconnectAttempts = 0; - this.setStatus("open"); + this.setStatus("connected"); this.flushQueue(); this.resubscribe(); }; @@ -105,13 +109,13 @@ export class WebSocketClient { this.socket.close(); this.socket = null; } - this.setStatus("closed"); + this.setStatus("disconnected"); this.cleanupPendingRequests(); } send(payload: unknown) { const data = JSON.stringify(payload); - if (this.status !== "open" || !this.socket) { + if (this.status !== "connected" || !this.socket) { this.pendingQueue.push(data); return; } @@ -138,7 +142,7 @@ export class WebSocketClient { const currentCount = this.subscriptions.get(taskId) ?? 0; const nextCount = currentCount + 1; this.subscriptions.set(taskId, nextCount); - if (this.status === "open" && nextCount === 1) { + if (this.status === "connected" && nextCount === 1) { this.send({ id: generateUUID(), type: "request", @@ -153,7 +157,7 @@ export class WebSocketClient { const currentCount = this.sessionSubscriptions.get(sessionId) ?? 0; const nextCount = currentCount + 1; this.sessionSubscriptions.set(sessionId, nextCount); - if (this.status === "open" && nextCount === 1) { + if (this.status === "connected" && nextCount === 1) { this.send({ id: generateUUID(), type: "request", @@ -168,7 +172,7 @@ export class WebSocketClient { const currentCount = this.sessionFocusCounts.get(sessionId) ?? 0; const nextCount = currentCount + 1; this.sessionFocusCounts.set(sessionId, nextCount); - if (this.status === "open" && nextCount === 1) { + if (this.status === "connected" && nextCount === 1) { this.send({ id: generateUUID(), type: "request", @@ -185,7 +189,7 @@ export class WebSocketClient { const nextCount = currentCount - 1; if (nextCount <= 0) { this.sessionFocusCounts.delete(sessionId); - if (this.status === "open") { + if (this.status === "connected") { this.send({ id: generateUUID(), type: "request", @@ -200,7 +204,7 @@ export class WebSocketClient { subscribeUser() { this.userSubscriptionCount += 1; - if (this.status === "open" && this.userSubscriptionCount === 1) { + if (this.status === "connected" && this.userSubscriptionCount === 1) { this.send({ id: generateUUID(), type: "request", @@ -216,7 +220,7 @@ export class WebSocketClient { const nextCount = currentCount - 1; if (nextCount <= 0) { this.subscriptions.delete(taskId); - if (this.status === "open") { + if (this.status === "connected") { this.send({ id: generateUUID(), type: "request", @@ -238,7 +242,7 @@ export class WebSocketClient { if (nextCount <= 0) { this.sessionSubscriptions.delete(sessionId); - if (this.status === "open") { + if (this.status === "connected") { this.send({ id: generateUUID(), type: "request", @@ -262,7 +266,7 @@ export class WebSocketClient { const currentCount = this.runSubscriptions.get(runId) ?? 0; const nextCount = currentCount + 1; this.runSubscriptions.set(runId, nextCount); - if (this.status === "open" && nextCount === 1) { + if (this.status === "connected" && nextCount === 1) { this.send({ id: generateUUID(), type: "request", @@ -279,7 +283,7 @@ export class WebSocketClient { const nextCount = currentCount - 1; if (nextCount <= 0) { this.runSubscriptions.delete(runId); - if (this.status === "open") { + if (this.status === "connected") { this.send({ id: generateUUID(), type: "request", @@ -294,7 +298,7 @@ export class WebSocketClient { unsubscribeUser() { this.userSubscriptionCount = Math.max(0, this.userSubscriptionCount - 1); - if (this.status === "open" && this.userSubscriptionCount === 0) { + if (this.status === "connected" && this.userSubscriptionCount === 0) { this.send({ id: generateUUID(), type: "request", @@ -362,7 +366,7 @@ export class WebSocketClient { } private handleDisconnect(event: CloseEvent) { - this.setStatus("closed"); + this.setStatus("disconnected"); // Don't reconnect if this was an intentional close if (this.intentionalClose) { @@ -465,7 +469,7 @@ export class WebSocketClient { } private flushQueue() { - if (!this.socket || this.status !== "open") return; + if (!this.socket || this.status !== "connected") return; this.pendingQueue.forEach((data) => this.socket?.send(data)); this.pendingQueue = []; } diff --git a/apps/web/lib/ws/handlers/agent-session.ts b/apps/web/lib/ws/handlers/agent-session.ts index fca2de435d..92da42d2f1 100644 --- a/apps/web/lib/ws/handlers/agent-session.ts +++ b/apps/web/lib/ws/handlers/agent-session.ts @@ -1,7 +1,13 @@ import type { StoreApi } from "zustand"; import type { AppState } from "@/lib/state/store"; import type { WsHandlers } from "@/lib/ws/handlers/types"; -import type { TaskSessionState } from "@/lib/types/http"; +import { + sessionId as toSessionId, + taskId as toTaskId, + type SessionId, + type TaskId, + type TaskSessionState, +} from "@/lib/types/http"; import type { QueuedMessage } from "@/lib/state/slices/session/types"; const TERMINAL_SESSION_STATES: ReadonlySet = new Set([ @@ -105,8 +111,8 @@ function buildSessionUpdate(payload: any): Record { * fills in fields like agent_profile_id / repository_id / worktree_path. */ function upsertTaskSessionList( store: StoreApi, - taskId: string, - sessionId: string, + taskId: TaskId, + sessionId: SessionId, // eslint-disable-next-line @typescript-eslint/no-explicit-any payload: any, sessionUpdate: Record, @@ -224,10 +230,12 @@ function syncEnvFromAgentctlPayload( // eslint-disable-next-line @typescript-eslint/no-explicit-any payload: any, ): void { - const taskId = payload?.task_id; - const sessionId = payload?.session_id; + const rawTaskId = payload?.task_id; + const rawSessionId = payload?.session_id; const envId = payload?.task_environment_id; - if (!taskId || !sessionId || !envId) return; + if (!rawTaskId || !rawSessionId || !envId) return; + const taskId = toTaskId(rawTaskId); + const sessionId = toSessionId(rawSessionId); const existing = store.getState().taskSessions.items[sessionId]; store.getState().upsertTaskSessionFromEvent(taskId, { id: sessionId, @@ -271,8 +279,8 @@ function handleAgentctlReady(store: StoreApi, payload: any): void { } interface SessionFailureContext { - taskId: string; - sessionId: string; + taskId: TaskId; + sessionId: SessionId; newState: TaskSessionState | undefined; // eslint-disable-next-line @typescript-eslint/no-explicit-any payload: any; @@ -320,10 +328,12 @@ export function registerTaskSessionHandlers(store: StoreApi): WsHandle "session.state_changed": (message) => { const payload = message.payload; if (!payload?.task_id) return; - const { task_id: taskId, session_id: sessionId } = payload; + const { task_id: rawTaskId, session_id: rawSessionId } = payload; const newState = payload.new_state as TaskSessionState | undefined; - if (!sessionId) return; + if (!rawSessionId) return; + const taskId = toTaskId(rawTaskId); + const sessionId = toSessionId(rawSessionId); const sessionUpdate = buildSessionUpdate(payload); const existingSession = store.getState().taskSessions.items[sessionId]; diff --git a/apps/web/lib/ws/handlers/messages.ts b/apps/web/lib/ws/handlers/messages.ts index 561382ebfe..9981c56fca 100644 --- a/apps/web/lib/ws/handlers/messages.ts +++ b/apps/web/lib/ws/handlers/messages.ts @@ -1,7 +1,7 @@ import type { StoreApi } from "zustand"; import type { AppState } from "@/lib/state/store"; import type { WsHandlers } from "@/lib/ws/handlers/types"; -import type { MessageType } from "@/lib/types/http"; +import { sessionId, taskId, type MessageType } from "@/lib/types/http"; export function registerMessagesHandlers(store: StoreApi): WsHandlers { return { @@ -12,8 +12,8 @@ export function registerMessagesHandlers(store: StoreApi): WsHandlers } store.getState().addMessage({ id: payload.message_id, - session_id: payload.session_id, - task_id: payload.task_id, + session_id: sessionId(payload.session_id), + task_id: taskId(payload.task_id), turn_id: payload.turn_id, author_type: payload.author_type, author_id: payload.author_id, @@ -32,8 +32,8 @@ export function registerMessagesHandlers(store: StoreApi): WsHandlers } store.getState().updateMessage({ id: payload.message_id, - session_id: payload.session_id, - task_id: payload.task_id, + session_id: sessionId(payload.session_id), + task_id: taskId(payload.task_id), turn_id: payload.turn_id, author_type: payload.author_type, author_id: payload.author_id, diff --git a/apps/web/lib/ws/handlers/tasks.ts b/apps/web/lib/ws/handlers/tasks.ts index 021fbae6ed..a0e76d56c6 100644 --- a/apps/web/lib/ws/handlers/tasks.ts +++ b/apps/web/lib/ws/handlers/tasks.ts @@ -6,6 +6,7 @@ import { cleanupTaskStorage } from "@/lib/local-storage"; import { removeRecentTask } from "@/lib/recent-tasks"; import { useContextFilesStore } from "@/lib/state/context-files-store"; import { toKanbanTask, type TaskLike } from "@/lib/kanban/map-task"; +import { sessionId as toSessionId } from "@/lib/types/http"; type KanbanTask = KanbanState["tasks"][number]; @@ -168,8 +169,11 @@ export function registerTasksHandlers(store: StoreApi): WsHandlers { (s) => s.id, ); const task = currentState.kanban.tasks.find((t) => t.id === deletedId); - if (task?.primarySessionId && !sessionIds.includes(task.primarySessionId)) { - sessionIds.push(task.primarySessionId); + if (task?.primarySessionId) { + const primaryId = toSessionId(task.primarySessionId); + if (!sessionIds.includes(primaryId)) { + sessionIds.push(primaryId); + } } const envIds = Array.from( new Set( diff --git a/apps/web/lib/ws/handlers/turns.ts b/apps/web/lib/ws/handlers/turns.ts index 042bf75f41..b0002e28b8 100644 --- a/apps/web/lib/ws/handlers/turns.ts +++ b/apps/web/lib/ws/handlers/turns.ts @@ -1,6 +1,7 @@ import type { StoreApi } from "zustand"; import type { AppState } from "@/lib/state/store"; import type { WsHandlers } from "@/lib/ws/handlers/types"; +import { sessionId, taskId } from "@/lib/types/http"; export function registerTurnsHandlers(store: StoreApi): WsHandlers { return { @@ -11,8 +12,8 @@ export function registerTurnsHandlers(store: StoreApi): WsHandlers { } store.getState().addTurn({ id: payload.id, - session_id: payload.session_id, - task_id: payload.task_id, + session_id: sessionId(payload.session_id), + task_id: taskId(payload.task_id), started_at: payload.started_at, completed_at: payload.completed_at, metadata: payload.metadata, diff --git a/apps/web/lib/ws/use-websocket.tsx b/apps/web/lib/ws/use-websocket.tsx index f4e368b03c..3580587e48 100644 --- a/apps/web/lib/ws/use-websocket.tsx +++ b/apps/web/lib/ws/use-websocket.tsx @@ -15,26 +15,13 @@ export function useWebSocket(store: StoreApi, url: string) { url, (status) => { const setConnectionStatus = store.getState().setConnectionStatus; - switch (status) { - case "connecting": - setConnectionStatus("connecting", null); - break; - case "open": - setConnectionStatus("connected", null); - client.subscribeUser(); - break; - case "reconnecting": - setConnectionStatus("reconnecting", null); - break; - case "error": - setConnectionStatus("error", "WebSocket connection failed"); - break; - case "closed": - case "idle": - default: - setConnectionStatus("disconnected", null); - break; + // WS client and ConnectionState share one ConnectionStatus vocabulary, + // so this is a 1:1 forward with an `error` message attached and a + // `subscribeUser()` side-effect on first connect. + if (status === "connected") { + client.subscribeUser(); } + setConnectionStatus(status, status === "error" ? "WebSocket connection failed" : null); }, { enabled: true,