diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go b/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go index b3c7715086..78a9489854 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_execution.go @@ -617,6 +617,7 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work } return nil, fmt.Errorf("failed to register execution: %w", addErr) } + m.setRuntimeInterest(execution.SessionID, true) // Persist executors_running row in lockstep with the in-memory Add so the // DB never holds an execution_id the store doesn't know about. This is the diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go b/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go index 64c0576021..e05f2e20a1 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go @@ -1243,6 +1243,7 @@ func (m *Manager) registerAndPublishExecution( } return fmt.Errorf("failed to register execution: %w", addErr) } + m.setRuntimeInterest(execution.SessionID, true) m.persistRuntimeSecrets(ctx, execInstance, execution) diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_lifecycle.go b/apps/backend/internal/agent/runtime/lifecycle/manager_lifecycle.go index ef71fbaa92..43d620f0dd 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_lifecycle.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_lifecycle.go @@ -94,6 +94,7 @@ func (m *Manager) Start(ctx context.Context) error { initSpan.End() continue } + m.setRuntimeInterest(execution.SessionID, true) // Reconcile the persistence row to match the recovered in-memory ID. // If executors_running.agent_execution_id had drifted (e.g. from a @@ -312,6 +313,7 @@ func (m *Manager) RemoveExecution(executionID string) { m.releaseActivity(executionActivityKey(executionID)) if execution, ok := m.executionStore.Get(executionID); ok { m.cleanupPassthroughMCPConfig(execution) + m.setRuntimeInterest(execution.SessionID, false) } m.executionStore.Remove(executionID) m.logger.Debug("removed execution from tracking", diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_subscription.go b/apps/backend/internal/agent/runtime/lifecycle/manager_subscription.go index 4c8d0d9639..77837f7dee 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_subscription.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_subscription.go @@ -63,6 +63,16 @@ type workspacePollAggregator struct { // known to belong to that workspace. Lets recordAndCompute iterate only // sessions in the affected workspace instead of scanning all sessionModes. workspaceSessions map[string]map[string]bool + // runtimeSessions tracks executions independently of browser UI state. An + // active execution contributes the slow polling baseline so task summaries + // continue to receive Git/status updates when no task page is open. + runtimeSessions map[string]bool + // workspaceRuntimeSessions is the runtime-interest reverse index used when + // computing the workspace-level maximum without scanning all executions. + workspaceRuntimeSessions map[string]map[string]bool + // runtimeWorkspaceBySession lets a replacement execution move a session's + // runtime contribution without leaving an entry in its old workspace. + runtimeWorkspaceBySession map[string]string // Last-write-wins queue: pendingPush + pushInFlight serialize per-workspace HTTP pushes so order matches enqueue. pendingPush map[string]workspacePushTarget pushInFlight map[string]bool @@ -77,12 +87,15 @@ type workspacePushTarget struct { // newWorkspacePollAggregator wires an aggregator to the lifecycle manager. func newWorkspacePollAggregator(mgr *Manager) *workspacePollAggregator { return &workspacePollAggregator{ - mgr: mgr, - sessionModes: make(map[string]WorkspacePollMode), - lastPushed: make(map[string]WorkspacePollMode), - workspaceSessions: make(map[string]map[string]bool), - pendingPush: make(map[string]workspacePushTarget), - pushInFlight: make(map[string]bool), + mgr: mgr, + sessionModes: make(map[string]WorkspacePollMode), + lastPushed: make(map[string]WorkspacePollMode), + workspaceSessions: make(map[string]map[string]bool), + runtimeSessions: make(map[string]bool), + workspaceRuntimeSessions: make(map[string]map[string]bool), + runtimeWorkspaceBySession: make(map[string]string), + pendingPush: make(map[string]workspacePushTarget), + pushInFlight: make(map[string]bool), } } @@ -125,6 +138,24 @@ func (a *workspacePollAggregator) HandleSessionMode(sessionID string, mode Works a.pushAsync(execution, workspacePath, effective) } +// HandleRuntimeInterest records whether an execution is active for polling +// purposes. Runtime interest is deliberately separate from UI session mode: +// a browser may unsubscribe or lose focus while the execution still needs Git +// and status updates for the task-level summary. +func (a *workspacePollAggregator) HandleRuntimeInterest(sessionID string, active bool) { + execution, exists := a.mgr.GetExecutionBySessionID(sessionID) + if !exists || execution.WorkspacePath == "" { + return + } + + workspacePath, effective, changed := a.recordRuntimeAndCompute(sessionID, active, execution.WorkspacePath) + if !changed { + return + } + + a.pushAsync(execution, workspacePath, effective) +} + // setSessionModeLocked updates sessionModes and the workspaceSessions reverse // index for a single session. Caller must hold a.mu. func (a *workspacePollAggregator) setSessionModeLocked(sessionID string, mode WorkspacePollMode, workspacePath string) { @@ -153,6 +184,75 @@ func (a *workspacePollAggregator) removeFromWorkspaceIndex(sessionID, workspaceP } } +// removeRuntimeFromWorkspaceIndex drops a runtime contribution from its +// reverse index, cleaning up the workspace key if empty. Caller must hold +// a.mu. +func (a *workspacePollAggregator) removeRuntimeFromWorkspaceIndex(sessionID, workspacePath string) { + sessions := a.workspaceRuntimeSessions[workspacePath] + if sessions == nil { + return + } + delete(sessions, sessionID) + if len(sessions) == 0 { + delete(a.workspaceRuntimeSessions, workspacePath) + } +} + +// setRuntimeInterestLocked updates runtime interest and its workspace index. +// Caller must hold a.mu. +func (a *workspacePollAggregator) setRuntimeInterestLocked(sessionID string, active bool, workspacePath string) { + if !active { + delete(a.runtimeSessions, sessionID) + if previousWorkspace := a.runtimeWorkspaceBySession[sessionID]; previousWorkspace != "" { + a.removeRuntimeFromWorkspaceIndex(sessionID, previousWorkspace) + } + delete(a.runtimeWorkspaceBySession, sessionID) + return + } + + if previousWorkspace := a.runtimeWorkspaceBySession[sessionID]; previousWorkspace != "" && previousWorkspace != workspacePath { + a.removeRuntimeFromWorkspaceIndex(sessionID, previousWorkspace) + } + a.runtimeSessions[sessionID] = true + a.runtimeWorkspaceBySession[sessionID] = workspacePath + if a.workspaceRuntimeSessions[workspacePath] == nil { + a.workspaceRuntimeSessions[workspacePath] = make(map[string]bool) + } + a.workspaceRuntimeSessions[workspacePath][sessionID] = true +} + +// effectiveModeLocked computes the maximum of browser UI contributions and +// runtime-interest contributions for a workspace. Caller must hold a.mu. +func (a *workspacePollAggregator) effectiveModeLocked(workspacePath string) WorkspacePollMode { + effective := WorkspacePollModePaused + for sid := range a.workspaceSessions[workspacePath] { + if mode, ok := a.sessionModes[sid]; ok && mode.rank() > effective.rank() { + effective = mode + } + } + if len(a.workspaceRuntimeSessions[workspacePath]) > 0 && WorkspacePollModeSlow.rank() > effective.rank() { + effective = WorkspacePollModeSlow + } + return effective +} + +// applyEffectiveModeLocked records the workspace mode and reports whether a +// push is needed. Caller must hold a.mu. force is used by the ready-time flush +// to retry a mode that may have been sent before agentctl accepted requests. +func (a *workspacePollAggregator) applyEffectiveModeLocked(workspacePath string, effective WorkspacePollMode, force bool) bool { + prev, hadPrev := a.lastPushed[workspacePath] + shouldPush := force || !hadPrev || prev != effective + if !force && !hadPrev && effective == WorkspacePollModePaused { + return false + } + if effective == WorkspacePollModePaused { + delete(a.lastPushed, workspacePath) + } else { + a.lastPushed[workspacePath] = effective + } + return shouldPush && effective != WorkspacePollModePaused +} + // recordAndCompute updates the per-session mode for the given workspace and // returns the new workspace-effective mode, plus whether it changed since the // last push. We compute this under a single lock so concurrent transitions in @@ -167,32 +267,23 @@ func (a *workspacePollAggregator) recordAndCompute(sessionID string, mode Worksp a.setSessionModeLocked(sessionID, mode, workspacePath) - // Compute effective mode using only sessions in this workspace (O(k) + // Compute effective mode using only contributions in this workspace (O(k) // where k = sessions in workspace, not O(N) total sessions). - effective := WorkspacePollModePaused - for sid := range a.workspaceSessions[workspacePath] { - if m, ok := a.sessionModes[sid]; ok && m.rank() > effective.rank() { - effective = m - } - } + effective := a.effectiveModeLocked(workspacePath) - prev, hadPrev := a.lastPushed[workspacePath] - if hadPrev && prev == effective { - return workspacePath, effective, false - } - // Skip pushing paused when there's no prior entry — agentctl defaults to - // slow, so sending paused to a workspace we've never pushed to is a no-op - // RPC (and slightly misleading: agentctl would drop from slow to paused - // even though the gateway never told it to go slow in the first place). - if !hadPrev && effective == WorkspacePollModePaused { - return workspacePath, effective, false - } - if effective == WorkspacePollModePaused { - delete(a.lastPushed, workspacePath) - } else { - a.lastPushed[workspacePath] = effective - } - return workspacePath, effective, true + return workspacePath, effective, a.applyEffectiveModeLocked(workspacePath, effective, false) +} + +// recordRuntimeAndCompute updates runtime interest and returns the resulting +// workspace-effective mode plus whether it changed since the last push. +func (a *workspacePollAggregator) recordRuntimeAndCompute(sessionID string, active bool, workspacePath string) (string, WorkspacePollMode, bool) { + a.mu.Lock() + defer a.mu.Unlock() + + a.setRuntimeInterestLocked(sessionID, active, workspacePath) + effective := a.effectiveModeLocked(workspacePath) + + return workspacePath, effective, a.applyEffectiveModeLocked(workspacePath, effective, false) } // pushAsync queues the latest mode and ensures exactly one pusher goroutine per workspace drains it (last-write-wins). @@ -249,8 +340,8 @@ func (a *workspacePollAggregator) pushLoop(workspacePath string) { // // This is called from the lifecycle manager's waitForAgentctlReady success // path — once we know agentctl is accepting RPCs, force-resend whatever -// workspace-effective mode we currently believe is correct. No-op if nothing -// was cached (no gateway events reached us before flush). +// workspace-effective mode we currently believe is correct. A workspace with +// an active execution is flushed even when no gateway UI event was cached. func (a *workspacePollAggregator) FlushSessionMode(sessionID string) { execution, exists := a.mgr.GetExecutionBySessionID(sessionID) if !exists || execution.WorkspacePath == "" { @@ -270,40 +361,37 @@ func (a *workspacePollAggregator) FlushSessionMode(sessionID string) { qry := a.hubQry a.mu.Unlock() - var sessionMode WorkspacePollMode + var ( + sessionMode WorkspacePollMode + hasSessionMode bool + ) if qry != nil { sessionMode = qry.GetSessionMode(sessionID) + hasSessionMode = true } else { // Fall back to cached value if no hub wired (e.g., tests). a.mu.Lock() cached, hasCached := a.sessionModes[sessionID] a.mu.Unlock() - if !hasCached { - return + if hasCached { + sessionMode = cached + hasSessionMode = true } - sessionMode = cached } a.mu.Lock() - // Merge the queried mode with whatever we had cached, then recompute - // the workspace-level effective mode across all sessions in this - // workspace. + // Merge the queried mode with whatever we had cached when the hub has an + // authoritative answer. Runtime interest is always included, even when no + // UI subscription exists for this session. wp := execution.WorkspacePath - a.setSessionModeLocked(sessionID, sessionMode, wp) - effective := WorkspacePollModePaused - for sid := range a.workspaceSessions[wp] { - if m, ok := a.sessionModes[sid]; ok && m.rank() > effective.rank() { - effective = m - } - } - if effective == WorkspacePollModePaused { - delete(a.lastPushed, wp) - } else { - a.lastPushed[wp] = effective + if hasSessionMode { + a.setSessionModeLocked(sessionID, sessionMode, wp) } + effective := a.effectiveModeLocked(wp) + shouldPush := a.applyEffectiveModeLocked(wp, effective, true) a.mu.Unlock() - if effective != WorkspacePollModePaused { + if shouldPush { a.pushAsync(execution, execution.WorkspacePath, effective) } } @@ -317,3 +405,11 @@ func (m *Manager) SetSessionModeQuerier(q SessionModeQuerier) { m.pollAggregator.mu.Unlock() } } + +// setRuntimeInterest keeps workspace polling alive for active executions even +// when no browser is subscribed to the session stream. +func (m *Manager) setRuntimeInterest(sessionID string, active bool) { + if m.pollAggregator != nil { + m.pollAggregator.HandleRuntimeInterest(sessionID, active) + } +} diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_subscription_test.go b/apps/backend/internal/agent/runtime/lifecycle/manager_subscription_test.go index 91813d2e92..0fd6047e90 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_subscription_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_subscription_test.go @@ -136,6 +136,93 @@ func TestAggregator_NoExecutionIsNoOp(t *testing.T) { } } +func TestAggregator_RuntimeInterestKeepsSlowModeWithoutUISubscription(t *testing.T) { + mgr := newTestManagerForAggregator(t) + addExecution(mgr, "s1", "/tmp/ws1") + + // An active execution must keep workspace polling alive even when the + // browser has no session subscription for it. + mgr.pollAggregator.HandleRuntimeInterest("s1", true) + mgr.pollAggregator.HandleSessionMode("s1", WorkspacePollModePaused) + + mgr.pollAggregator.mu.Lock() + got := mgr.pollAggregator.lastPushed["/tmp/ws1"] + runtimeEntries := len(mgr.pollAggregator.runtimeSessions) + mgr.pollAggregator.mu.Unlock() + + if got != WorkspacePollModeSlow { + t.Errorf("active execution without UI subscription = %q, want slow", got) + } + if runtimeEntries != 1 { + t.Errorf("runtime interest entries = %d, want 1", runtimeEntries) + } +} + +func TestAggregator_RuntimeInterestDoesNotOverrideFocusedSession(t *testing.T) { + mgr := newTestManagerForAggregator(t) + addExecution(mgr, "s1", "/tmp/ws1") + + mgr.pollAggregator.HandleRuntimeInterest("s1", true) + mgr.pollAggregator.HandleSessionMode("s1", WorkspacePollModeFast) + + mgr.pollAggregator.mu.Lock() + focused := mgr.pollAggregator.lastPushed["/tmp/ws1"] + mgr.pollAggregator.mu.Unlock() + if focused != WorkspacePollModeFast { + t.Errorf("focused active execution = %q, want fast", focused) + } + + // Losing focus must fall back to the runtime baseline, not to paused. + mgr.pollAggregator.HandleSessionMode("s1", WorkspacePollModePaused) + mgr.pollAggregator.mu.Lock() + unfocused := mgr.pollAggregator.lastPushed["/tmp/ws1"] + mgr.pollAggregator.mu.Unlock() + if unfocused != WorkspacePollModeSlow { + t.Errorf("unfocused active execution = %q, want slow", unfocused) + } +} + +func TestAggregator_RuntimeInterestRemovalYieldsPaused(t *testing.T) { + mgr := newTestManagerForAggregator(t) + addExecution(mgr, "s1", "/tmp/ws1") + + mgr.pollAggregator.HandleRuntimeInterest("s1", true) + mgr.pollAggregator.HandleRuntimeInterest("s1", false) + + mgr.pollAggregator.mu.Lock() + _, hasLastPushed := mgr.pollAggregator.lastPushed["/tmp/ws1"] + runtimeEntries := len(mgr.pollAggregator.runtimeSessions) + workspaceEntries := len(mgr.pollAggregator.workspaceRuntimeSessions) + mgr.pollAggregator.mu.Unlock() + + if hasLastPushed { + t.Error("expected lastPushed entry to be removed after runtime interest ends") + } + if runtimeEntries != 0 || workspaceEntries != 0 { + t.Errorf("runtime indexes not cleaned up: sessions=%d workspaces=%d", runtimeEntries, workspaceEntries) + } +} + +func TestAggregator_FlushSessionMode_PushesRuntimeBaselineWithoutCachedUIState(t *testing.T) { + mgr := newTestManagerForAggregator(t) + addExecution(mgr, "s1", "/tmp/ws1") + mgr.pollAggregator.HandleRuntimeInterest("s1", true) + + // Simulate the first push being lost before agentctl was ready. Flush must + // still force the runtime baseline even though no UI mode was cached. + mgr.pollAggregator.mu.Lock() + delete(mgr.pollAggregator.lastPushed, "/tmp/ws1") + mgr.pollAggregator.mu.Unlock() + mgr.pollAggregator.FlushSessionMode("s1") + + mgr.pollAggregator.mu.Lock() + got := mgr.pollAggregator.lastPushed["/tmp/ws1"] + mgr.pollAggregator.mu.Unlock() + if got != WorkspacePollModeSlow { + t.Errorf("flushed runtime baseline = %q, want slow", got) + } +} + func TestAggregator_DifferentWorkspacesAreIndependent(t *testing.T) { mgr := newTestManagerForAggregator(t) addExecution(mgr, "s1", "/tmp/ws1") diff --git a/apps/backend/internal/backendapp/boot_state.go b/apps/backend/internal/backendapp/boot_state.go index 1cc588c068..85585e2372 100644 --- a/apps/backend/internal/backendapp/boot_state.go +++ b/apps/backend/internal/backendapp/boot_state.go @@ -11,6 +11,7 @@ import ( taskdto "github.com/kandev/kandev/internal/task/dto" taskmodels "github.com/kandev/kandev/internal/task/models" taskservice "github.com/kandev/kandev/internal/task/service" + "github.com/kandev/kandev/internal/task/statussummary" userdto "github.com/kandev/kandev/internal/user/dto" "github.com/kandev/kandev/internal/webapp" v1 "github.com/kandev/kandev/pkg/api/v1" @@ -611,21 +612,34 @@ func (b bootStateBuilder) taskDTOsWithSessionInfo(ctx context.Context, tasks []* taskIDs = append(taskIDs, task.ID) } } + statusSummaries, summaryErr := b.p.taskSvc.GetTaskStatusSummaries(ctx, taskIDs) + if summaryErr != nil { + b.logBootError("batch task status summaries", summaryErr) + statusSummaries = map[string]*statussummary.TaskStatusSummary{} + } sessionsByTask, err := b.p.taskSvc.BatchGetSessionsForTasks(ctx, taskIDs) if err != nil { b.logBootError("batch task detail sessions", err) - return taskDTOs(tasks) + return taskDTOsWithStatusSummaries(tasks, statusSummaries) } primaryInfoByTask, err := b.p.taskSvc.GetPrimarySessionInfoForTasks(ctx, taskIDs) if err != nil { b.logBootError("get task detail primary session info", err) - return taskDTOs(tasks) + return taskDTOsWithStatusSummaries(tasks, statusSummaries) } - pendingActionsBySession, err := b.bootPendingActionsForInputCapableSessions(ctx, sessionsByTask) - if err != nil { - b.logBootError("get task detail pending actions", err) + pendingActionsBySession, pendingErr := b.bootPendingActionsForInputCapableSessions(ctx, sessionsByTask) + if pendingErr != nil { + b.logBootError("get task detail pending actions", pendingErr) pendingActionsBySession = map[string]taskmodels.TaskPendingAction{} } + if summaryErr == nil && pendingErr == nil { + statusSummaries, err = b.p.taskSvc.HydrateMissingTaskStatusSummaries( + ctx, tasks, sessionsByTask, pendingActionsBySession, statusSummaries, + ) + if err != nil { + b.logBootError("repair missing task status summaries", err) + } + } result := make([]taskdto.TaskDTO, 0, len(tasks)) for _, task := range tasks { if task == nil { @@ -667,6 +681,20 @@ func (b bootStateBuilder) taskDTOsWithSessionInfo(ctx context.Context, tasks []* if b.p.orchestratorSvc != nil { taskdto.EnrichTaskForegroundActivity(&dto, sessions, b.p.orchestratorSvc) } + dto.StatusSummary = statusSummaries[task.ID] + result = append(result, dto) + } + return result +} + +func taskDTOsWithStatusSummaries(tasks []*taskmodels.Task, summaries map[string]*statussummary.TaskStatusSummary) []taskdto.TaskDTO { + result := make([]taskdto.TaskDTO, 0, len(tasks)) + for _, task := range tasks { + if task == nil { + continue + } + dto := taskdto.FromTask(task) + dto.StatusSummary = summaries[task.ID] result = append(result, dto) } return result diff --git a/apps/backend/internal/backendapp/boot_state_routes.go b/apps/backend/internal/backendapp/boot_state_routes.go index b2e3a79ae5..55e35d3e83 100644 --- a/apps/backend/internal/backendapp/boot_state_routes.go +++ b/apps/backend/internal/backendapp/boot_state_routes.go @@ -570,6 +570,7 @@ func mapKanbanTaskState(task taskdto.TaskDTO) map[string]any { "primarySessionState": task.PrimarySessionState, "primarySessionPendingAction": task.PrimarySessionPendingAction, "taskPendingAction": task.TaskPendingAction, + "statusSummary": task.StatusSummary, "sessionCount": task.SessionCount, "reviewStatus": nullString(string(task.ReviewStatus)), "parentTaskId": nullString(task.ParentID), diff --git a/apps/backend/internal/backendapp/gateway.go b/apps/backend/internal/backendapp/gateway.go index 5267b1272d..1930c3797d 100644 --- a/apps/backend/internal/backendapp/gateway.go +++ b/apps/backend/internal/backendapp/gateway.go @@ -2,6 +2,7 @@ package backendapp import ( "context" + "encoding/json" "fmt" "time" @@ -25,8 +26,10 @@ import ( notificationstore "github.com/kandev/kandev/internal/notifications/store" "github.com/kandev/kandev/internal/orchestrator" orchestratorhandlers "github.com/kandev/kandev/internal/orchestrator/handlers" + "github.com/kandev/kandev/internal/task/models" sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite" taskservice "github.com/kandev/kandev/internal/task/service" + "github.com/kandev/kandev/internal/task/statussummary" terminalrepo "github.com/kandev/kandev/internal/terminal/repository" terminalservice "github.com/kandev/kandev/internal/terminal/service" userservice "github.com/kandev/kandev/internal/user/service" @@ -273,6 +276,29 @@ func provideGateway( go gateway.Hub.Run(ctx) gateways.RegisterTaskNotifications(ctx, eventBus, gateway.Hub, log) + if taskRepo != nil && eventBus != nil { + projector := statussummary.NewProjector(statussummary.ProjectorConfig{ + Store: taskRepo, + EventBus: eventBus, + LoadGitObservations: func(ctx context.Context, taskID string) ([]statussummary.GitObservation, error) { + return loadTaskGitObservations(ctx, taskRepo, taskID) + }, + ResolveWorkspace: func(ctx context.Context, taskID string) (string, error) { + task, err := taskRepo.GetTask(ctx, taskID) + if err != nil { + return "", err + } + if task == nil { + return "", fmt.Errorf("task %q not found", taskID) + } + return task.WorkspaceID, nil + }, + Logger: log, + }) + if err := projector.Start(ctx); err != nil { + log.Error("failed to start task status summary projector", zap.Error(err)) + } + } gateways.RegisterUserNotifications(ctx, eventBus, gateway.Hub, log) gateways.RegisterOfficeNotifications(ctx, eventBus, gateway.Hub, taskWorkspaceResolver(taskRepo), log) gateways.RegisterRunNotifications(ctx, eventBus, gateway.Hub, log) @@ -370,6 +396,85 @@ func provideGateway( return gateway, notificationSvc, notificationCtrl, terminalSvc, nil } +func loadTaskGitObservations( + ctx context.Context, + taskRepo *sqliterepo.Repository, + taskID string, +) ([]statussummary.GitObservation, error) { + sessions, err := taskRepo.ListTaskSessions(ctx, taskID) + if err != nil { + return nil, err + } + sessionIDs := make([]string, 0, len(sessions)) + for _, session := range sessions { + if session != nil && session.ID != "" { + sessionIDs = append(sessionIDs, session.ID) + } + } + snapshots, err := taskRepo.GetLatestGitSnapshotsBySessionIDs(ctx, sessionIDs) + if err != nil { + return nil, err + } + observations := make([]statussummary.GitObservation, 0, len(snapshots)) + for _, session := range sessions { + observation, ok := taskGitObservation(session, snapshots[session.ID]) + if ok { + observations = append(observations, observation) + } + } + return observations, nil +} + +func taskGitObservation( + session *models.TaskSession, + snapshot *models.GitSnapshot, +) (statussummary.GitObservation, bool) { + if session == nil || snapshot == nil { + return statussummary.GitObservation{}, false + } + repository := session.ID + if name, ok := snapshot.Metadata["repository_name"].(string); ok && name != "" { + repository = name + } + return statussummary.GitObservation{ + Repository: repository, + Summary: statussummary.GitSummary{ + Additions: nonNegativeMetadataInt(snapshot.Metadata, "branch_additions"), + Deletions: nonNegativeMetadataInt(snapshot.Metadata, "branch_deletions"), + ChangedFiles: len(snapshot.Files), + Ahead: maxNonNegative(snapshot.Ahead), + Behind: maxNonNegative(snapshot.Behind), + }, + }, true +} + +func nonNegativeMetadataInt(metadata map[string]interface{}, key string) int { + if metadata == nil { + return 0 + } + switch value := metadata[key].(type) { + case int: + return maxNonNegative(value) + case int64: + return maxNonNegative(int(value)) + case float64: + return maxNonNegative(int(value)) + case json.Number: + parsed, err := value.Int64() + if err == nil { + return maxNonNegative(int(parsed)) + } + } + return 0 +} + +func maxNonNegative(value int) int { + if value < 0 { + return 0 + } + return value +} + func isAbandonedTurnCompletion(data map[string]interface{}) bool { startedAt, started := data["started_at"].(time.Time) completedAt, completed := data["completed_at"].(*time.Time) diff --git a/apps/backend/internal/backendapp/gateway_git_observations_test.go b/apps/backend/internal/backendapp/gateway_git_observations_test.go new file mode 100644 index 0000000000..f45c0b5f11 --- /dev/null +++ b/apps/backend/internal/backendapp/gateway_git_observations_test.go @@ -0,0 +1,111 @@ +package backendapp + +import ( + "context" + "encoding/json" + "testing" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/service" +) + +func TestTaskGitObservationConvertsSnapshotFields(t *testing.T) { + session := &models.TaskSession{ID: "session-1"} + snapshot := &models.GitSnapshot{ + SessionID: "session-1", + Files: map[string]interface{}{"one.go": true, "two.go": true}, + Ahead: -2, + Behind: -3, + Metadata: map[string]interface{}{ + "repository_name": "org/repo", + "branch_additions": json.Number("-7"), + "branch_deletions": -4, + }, + } + + observation, ok := taskGitObservation(session, snapshot) + if !ok { + t.Fatal("taskGitObservation returned ok=false") + } + if observation.Repository != "org/repo" { + t.Fatalf("repository = %q, want org/repo", observation.Repository) + } + if observation.Summary.Additions != 0 || observation.Summary.Deletions != 0 { + t.Fatalf("negative branch counts = %+v, want zero", observation.Summary) + } + if observation.Summary.Ahead != 0 || observation.Summary.Behind != 0 { + t.Fatalf("negative ahead/behind = %+v, want zero", observation.Summary) + } + if observation.Summary.ChangedFiles != 2 { + t.Fatalf("changed files = %d, want 2", observation.Summary.ChangedFiles) + } + + fallback, ok := taskGitObservation(session, &models.GitSnapshot{}) + if !ok || fallback.Repository != session.ID { + t.Fatalf("missing repository metadata fallback = %+v, ok=%v", fallback, ok) + } + if _, ok := taskGitObservation(session, nil); ok { + t.Fatal("nil snapshot should be skipped") + } +} + +func TestNonNegativeMetadataIntParsesAndNormalizesValues(t *testing.T) { + metadata := map[string]interface{}{ + "number": json.Number("7"), + "negative": -3, + "invalid": "not-a-number", + } + for name, want := range map[string]int{"number": 7, "negative": 0, "invalid": 0, "missing": 0} { + if got := nonNegativeMetadataInt(metadata, name); got != want { + t.Errorf("nonNegativeMetadataInt(%q) = %d, want %d", name, got, want) + } + } +} + +func TestLoadTaskGitObservationsSkipsSessionsWithoutSnapshots(t *testing.T) { + harness := newBootStateTestHarness(t) + ctx := context.Background() + workspaces, err := harness.taskSvc.ListWorkspaces(ctx) + if err != nil { + t.Fatalf("list workspaces: %v", err) + } + workflows, err := harness.taskSvc.ListWorkflows(ctx, workspaces[0].ID, true) + if err != nil { + t.Fatalf("list workflows: %v", err) + } + steps, err := harness.workflowSvc.ListStepsByWorkflow(ctx, workflows[0].ID) + if err != nil { + t.Fatalf("list workflow steps: %v", err) + } + task, err := harness.taskSvc.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: workspaces[0].ID, + WorkflowID: workflows[0].ID, + WorkflowStepID: steps[0].ID, + Title: "Git observation hydration", + }) + if err != nil { + t.Fatalf("create task: %v", err) + } + for _, sessionID := range []string{"session-with-snapshot", "session-without-snapshot"} { + if err := harness.taskRepo.CreateTaskSession(ctx, &models.TaskSession{ID: sessionID, TaskID: task.ID}); err != nil { + t.Fatalf("create session %s: %v", sessionID, err) + } + } + if err := harness.taskRepo.CreateGitSnapshot(ctx, &models.GitSnapshot{ + ID: "snapshot-1", + SessionID: "session-with-snapshot", + Files: map[string]interface{}{"main.go": true}, + Metadata: map[string]interface{}{"repository_name": "org/repo"}, + TriggeredBy: "agent_completed", + }); err != nil { + t.Fatalf("create snapshot: %v", err) + } + + observations, err := loadTaskGitObservations(ctx, harness.taskRepo, task.ID) + if err != nil { + t.Fatalf("load observations: %v", err) + } + if len(observations) != 1 || observations[0].Repository != "org/repo" { + t.Fatalf("observations = %+v, want one org/repo observation", observations) + } +} diff --git a/apps/backend/internal/backendapp/helpers.go b/apps/backend/internal/backendapp/helpers.go index 32a7b80f73..7e4f37dd8d 100644 --- a/apps/backend/internal/backendapp/helpers.go +++ b/apps/backend/internal/backendapp/helpers.go @@ -124,6 +124,19 @@ func buildSessionDataProvider(taskRepo *sqliterepo.Repository, lifecycleMgr *lif } } +// buildSessionGitDataProvider constructs the narrow provider used by the diff +// panel's explicit refresh request. It intentionally does not hydrate session +// state, agent readiness, commands, mode, models, or context-window data. +func buildSessionGitDataProvider(taskRepo *sqliterepo.Repository, lifecycleMgr *lifecycle.Manager, log *logger.Logger) func(context.Context, string) ([]*ws.Message, error) { + return func(ctx context.Context, sessionID string) ([]*ws.Message, error) { + session, err := taskRepo.GetTaskSession(ctx, sessionID) + if err != nil { + return nil, nil + } + return appendLiveGitStatusMessage(ctx, taskRepo, lifecycleMgr, sessionID, session, nil, log), nil + } +} + const sessionIDPayloadKey = "session_id" const taskIDPayloadKey = "task_id" const newStatePayloadKey = "new_state" diff --git a/apps/backend/internal/backendapp/helpers_test.go b/apps/backend/internal/backendapp/helpers_test.go index d324829be9..b8440e6429 100644 --- a/apps/backend/internal/backendapp/helpers_test.go +++ b/apps/backend/internal/backendapp/helpers_test.go @@ -1681,6 +1681,7 @@ func newBootStateTestHarness(t *testing.T) bootStateTestHarness { Environments: taskRepo, TaskEnvironments: taskRepo, Reviews: taskRepo, + StatusSummaries: taskRepo, }, eventBus, log, diff --git a/apps/backend/internal/backendapp/main.go b/apps/backend/internal/backendapp/main.go index 3b52827d1e..fdede3e541 100644 --- a/apps/backend/internal/backendapp/main.go +++ b/apps/backend/internal/backendapp/main.go @@ -697,6 +697,7 @@ func startGatewayAndServe( gateways.RegisterSessionStreamNotifications(ctx, eventBus, gateway.Hub, log) gateway.Hub.SetSessionDataProvider(buildSessionDataProvider(repos.Task, lifecycleMgr, log)) + gateway.Hub.SetSessionGitDataProvider(buildSessionGitDataProvider(repos.Task, lifecycleMgr, log)) log.Info("Session data provider configured for session subscriptions (git status from snapshots)") // WS gateway per-user scoping (opt-in auth): connection auth on upgrade diff --git a/apps/backend/internal/backendapp/services.go b/apps/backend/internal/backendapp/services.go index 642373d835..7df0cb17b3 100644 --- a/apps/backend/internal/backendapp/services.go +++ b/apps/backend/internal/backendapp/services.go @@ -80,6 +80,7 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories TaskEnvironments: repos.Task, Reviews: repos.Task, ResourceCleanups: repos.Task, + StatusSummaries: repos.Task, }, eventBus, log, @@ -113,6 +114,7 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories githubSvc := initGitHubService(cfg, dbPool, eventBus, repos.Secrets, log) if githubSvc != nil { + taskSvc.SetTaskStatusSummaryPRReader(&githubTaskStatusSummaryPRReader{gh: githubSvc}) githubSvc.SetPromptResolver(promptSvc) if brokerErr := githubSvc.ConfigureCredentialBroker(&githubBrokerScopeAuthorizer{repo: repos.Task}); brokerErr != nil { log.Warn("GitHub credential broker initialization failed", zap.Error(brokerErr)) diff --git a/apps/backend/internal/backendapp/status_summary_adapter.go b/apps/backend/internal/backendapp/status_summary_adapter.go new file mode 100644 index 0000000000..1f7fcfd084 --- /dev/null +++ b/apps/backend/internal/backendapp/status_summary_adapter.go @@ -0,0 +1,59 @@ +package backendapp + +import ( + "context" + "strconv" + + "github.com/kandev/kandev/internal/github" + "github.com/kandev/kandev/internal/task/statussummary" +) + +// githubTaskStatusSummaryPRReader keeps task-service summary hydration +// independent from the GitHub package's storage model. +type githubTaskStatusSummaryPRReader struct { + gh *github.Service +} + +func (r *githubTaskStatusSummaryPRReader) ListTaskStatusSummaryPullRequests( + ctx context.Context, + taskIDs []string, +) (map[string][]statussummary.PullRequestInput, error) { + result := make(map[string][]statussummary.PullRequestInput) + if r == nil || r.gh == nil || len(taskIDs) == 0 { + return result, nil + } + prsByTask, err := r.gh.ListTaskPRsByTaskIDs(ctx, taskIDs) + if err != nil { + return nil, err + } + for taskID, prs := range prsByTask { + for _, pr := range prs { + if pr == nil { + continue + } + key := pr.ID + if key == "" { + key = pr.RepositoryID + ":" + strconv.Itoa(pr.PRNumber) + } + requiredReviews := 0 + if pr.RequiredReviews != nil { + requiredReviews = *pr.RequiredReviews + } + result[taskID] = append(result[taskID], statussummary.PullRequestInput{ + Key: key, + State: pr.State, + Number: pr.PRNumber, + URL: pr.PRURL, + ReviewState: pr.ReviewState, + ChecksState: pr.ChecksState, + MergeableState: pr.MergeableState, + UnresolvedReviewCount: pr.UnresolvedReviewThreads, + PendingReviewCount: pr.PendingReviewCount, + RequiredReviews: requiredReviews, + ChecksTotal: pr.ChecksTotal, + ChecksPassing: pr.ChecksPassing, + }) + } + } + return result, nil +} diff --git a/apps/backend/internal/backendapp/status_summary_boot_test.go b/apps/backend/internal/backendapp/status_summary_boot_test.go new file mode 100644 index 0000000000..079492ac01 --- /dev/null +++ b/apps/backend/internal/backendapp/status_summary_boot_test.go @@ -0,0 +1,82 @@ +package backendapp + +import ( + "context" + "encoding/json" + "testing" + + "github.com/kandev/kandev/internal/task/service" + "github.com/kandev/kandev/internal/task/statussummary" + "github.com/kandev/kandev/internal/webapp" +) + +func TestBootKanbanSnapshotHydratesTaskStatusSummaryInBatch(t *testing.T) { + harness := newBootStateTestHarness(t) + ctx := context.Background() + workspaces, err := harness.taskSvc.ListWorkspaces(ctx) + if err != nil { + t.Fatalf("list workspaces: %v", err) + } + workflows, err := harness.taskSvc.ListWorkflows(ctx, workspaces[0].ID, true) + if err != nil { + t.Fatalf("list workflows: %v", err) + } + steps, err := harness.workflowSvc.ListStepsByWorkflow(ctx, workflows[0].ID) + if err != nil { + t.Fatalf("list workflow steps: %v", err) + } + task, err := harness.taskSvc.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: workspaces[0].ID, + WorkflowID: workflows[0].ID, + WorkflowStepID: steps[0].ID, + Title: "Summary hydration task", + }) + if err != nil { + t.Fatalf("create task: %v", err) + } + changed, err := harness.taskRepo.CompareAndUpdateTaskStatusSummary(ctx, &statussummary.StoredTaskStatusSummary{ + TaskID: task.ID, + WorkspaceID: workspaces[0].ID, + Summary: statussummary.TaskStatusSummary{ + Revision: 7, + ForegroundActivity: "background", + PendingAction: "clarification", + }, + }) + if err != nil || !changed { + t.Fatalf("persist task summary: changed=%v err=%v", changed, err) + } + + state := bootInitialState(ctx, nil, routeParams{ + taskSvc: harness.taskSvc, + services: &Services{Workflow: harness.workflowSvc}, + }, webapp.ClassifyRoute("/")) + raw, err := json.Marshal(state) + if err != nil { + t.Fatalf("marshal boot state: %v", err) + } + var decoded struct { + KanbanMulti struct { + Snapshots map[string]struct { + Tasks []struct { + ID string `json:"id"` + StatusSummary *statussummary.TaskStatusSummary `json:"statusSummary"` + } `json:"tasks"` + } `json:"snapshots"` + } `json:"kanbanMulti"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatalf("decode boot state: %v", err) + } + snapshot := decoded.KanbanMulti.Snapshots[workflows[0].ID] + for _, item := range snapshot.Tasks { + if item.ID != task.ID { + continue + } + if item.StatusSummary == nil || item.StatusSummary.Revision != 7 || item.StatusSummary.PendingAction != "clarification" { + t.Fatalf("boot status summary = %#v", item.StatusSummary) + } + return + } + t.Fatalf("task %q missing from boot snapshot: %s", task.ID, raw) +} diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index 4da62af70e..4563d07248 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -68,8 +68,18 @@ const ( // operator-facing composer and status indicator can distinguish // "generating" from "waiting on spawned background work". TaskSessionActivityChanged = "task_session.activity_changed" + // TaskSessionErrorChanged is emitted when a recoverable agent error is + // created, replaced, or dismissed. It is a bounded status source; the + // error message itself is projected into the task summary rather than + // streamed to task-list subscribers. + TaskSessionErrorChanged = "task_session.error_changed" ) +// TaskStatusSummaryUpdated is a complete replacement projection for one +// task. Consumers should subscribe to this event instead of session streams +// when they only need sidebar/task-switcher status. +const TaskStatusSummaryUpdated = "task.status_summary.updated" + // Event types for task plans const ( TaskPlanCreated = "task_plan.created" diff --git a/apps/backend/internal/gateway/websocket/access_test.go b/apps/backend/internal/gateway/websocket/access_test.go index e81663b4ac..e84b211428 100644 --- a/apps/backend/internal/gateway/websocket/access_test.go +++ b/apps/backend/internal/gateway/websocket/access_test.go @@ -65,6 +65,11 @@ func receivedActions(client *Client) []string { actions := []string{} for { select { + case raw := <-client.controlSend: + var msg ws.Message + if err := json.Unmarshal(raw, &msg); err == nil { + actions = append(actions, msg.Action) + } case raw := <-client.send: var msg ws.Message if err := json.Unmarshal(raw, &msg); err == nil { @@ -204,6 +209,14 @@ func TestUserSubscribeScopedToOwnUser(t *testing.T) { func assertErrorResponse(t *testing.T, client *Client, label string) { t.Helper() select { + case raw := <-client.controlSend: + var msg ws.Message + if err := json.Unmarshal(raw, &msg); err != nil { + t.Fatalf("%s: bad frame: %v", label, err) + } + if msg.Type != ws.MessageTypeError { + t.Fatalf("%s: got %s frame, want error", label, msg.Type) + } case raw := <-client.send: var msg ws.Message if err := json.Unmarshal(raw, &msg); err != nil { @@ -220,6 +233,14 @@ func assertErrorResponse(t *testing.T, client *Client, label string) { func assertSuccessResponse(t *testing.T, client *Client, label string) { t.Helper() select { + case raw := <-client.controlSend: + var msg ws.Message + if err := json.Unmarshal(raw, &msg); err != nil { + t.Fatalf("%s: bad frame: %v", label, err) + } + if msg.Type == ws.MessageTypeError { + t.Fatalf("%s: got error frame: %s", label, string(raw)) + } case raw := <-client.send: var msg ws.Message if err := json.Unmarshal(raw, &msg); err != nil { diff --git a/apps/backend/internal/gateway/websocket/client.go b/apps/backend/internal/gateway/websocket/client.go index b97591e163..44c5ac4953 100644 --- a/apps/backend/internal/gateway/websocket/client.go +++ b/apps/backend/internal/gateway/websocket/client.go @@ -28,6 +28,11 @@ const ( // Maximum message size allowed from peer // Increased to support image attachments (base64 encoded images are ~33% larger) maxMessageSize = 32 * 1024 * 1024 // 32MB + + // Control frames (RPC responses and errors) use a separate bounded queue so + // high-volume session notifications cannot fill the queue and make a user + // action appear to time out. + controlSendBufferSize = 256 ) // Client represents a single WebSocket connection @@ -41,6 +46,7 @@ type Client struct { conn *websocket.Conn hub *Hub send chan []byte + controlSend chan []byte subscriptions map[string]bool // Task IDs this client is subscribed to sessionSubscriptions map[string]bool // Session IDs this client is subscribed to sessionFocus map[string]bool // Session IDs this client has focused (a strict subset of subscriptions, conceptually — see hub_session_mode.go) @@ -60,6 +66,7 @@ func NewClient(id string, identity authn.Identity, conn *websocket.Conn, hub *Hu conn: conn, hub: hub, send: make(chan []byte, 256), + controlSend: make(chan []byte, controlSendBufferSize), subscriptions: make(map[string]bool), sessionSubscriptions: make(map[string]bool), sessionFocus: make(map[string]bool), @@ -163,6 +170,12 @@ func (c *Client) handleMessage(msg *ws.Message) { case ws.ActionSessionFocus: c.handleSessionFocus(msg) return + case ws.ActionSessionGitRefresh: + c.handleSessionGitRefresh(msg) + return + case ws.ActionSessionDataRefresh: + c.handleSessionDataRefresh(msg) + return case ws.ActionSessionUnfocus: c.handleSessionUnfocus(msg) return @@ -317,15 +330,18 @@ func (c *Client) handleSessionSubscribe(msg *ws.Message) { return } - c.hub.SubscribeToSession(c, req.SessionID) + newMembership := c.hub.SubscribeToSession(c, req.SessionID) resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ "success": true, "session_id": req.SessionID, }) c.sendMessage(resp) - // Send initial session data (e.g., git status) if available - c.sendSessionData(req.SessionID) + // Send initial session data only when this client newly joins. Duplicate + // subscribe requests are acknowledgements, not snapshot replay commands. + if newMembership { + c.sendSessionData(req.SessionID) + } } // maySubscribeSession applies the per-user session scoping check, emitting the @@ -383,9 +399,40 @@ func (c *Client) sendSessionData(sessionID string) { zap.String("session_id", sessionID), zap.Int("count", len(data))) - // Send each piece of session data as a notification + // Send each piece of session data as a notification. Snapshots are data + // traffic, not control traffic, so they must not consume the response queue. for _, msg := range data { - c.sendMessage(msg) + payload, err := json.Marshal(msg) + if err != nil { + c.logger.Error("Failed to marshal session data", zap.Error(err)) + continue + } + c.sendBytes(payload) + } +} + +// sendSessionGitData sends the bounded git snapshot used by the diff detail +// surface. The compatibility fallback may return the full legacy provider; +// filter it at the transport boundary so this action remains git-only. +func (c *Client) sendSessionGitData(sessionID string) { + ctx := context.Background() + data, err := c.hub.GetSessionGitData(ctx, sessionID) + if err != nil { + c.logger.Error("Failed to get session git data", + zap.String("session_id", sessionID), + zap.Error(err)) + return + } + for _, msg := range data { + if msg == nil || msg.Action != ws.ActionSessionGitEvent { + continue + } + payload, err := json.Marshal(msg) + if err != nil { + c.logger.Error("Failed to marshal session git data", zap.Error(err)) + continue + } + c.sendBytes(payload) } } @@ -498,12 +545,9 @@ func (c *Client) handleSessionUnsubscribe(msg *ws.Message) { // handleSessionFocus handles session.focus — marks the session as actively // viewed by this client, lifting backend polling to fast mode for the workspace. -// -// Also pushes a fresh session data snapshot (git status, etc.) because the -// session.subscribe frame is often absorbed by the sidebar's bulk subscribe -// (ref-counted on the client) before the task-page hook can ask for it — so -// without this, switching tasks leaves the Changes panel showing stale/empty -// state until the next poll broadcast arrives. +// It intentionally sends only the control acknowledgement. Snapshot/data +// refreshes belong to explicit detail-surface requests and must not be replayed +// on every focus transition. func (c *Client) handleSessionFocus(msg *ws.Message) { var req SessionSubscribeRequest if err := msg.ParsePayload(&req); err != nil { @@ -524,10 +568,59 @@ func (c *Client) handleSessionFocus(msg *ws.Message) { "session_id": req.SessionID, }) c.sendMessage(resp) +} +// handleSessionDataRefresh explicitly requests a fresh detail snapshot without +// changing subscription or focus state. Keeping this separate from focus +// makes repeated tab activation cheap and keeps focus acknowledgements small. +func (c *Client) handleSessionDataRefresh(msg *ws.Message) { + var req SessionSubscribeRequest + if err := msg.ParsePayload(&req); err != nil { + c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + return + } + if req.SessionID == "" { + c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) + return + } + if !c.maySubscribeSession(msg, req.SessionID) { + return + } + + resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ + "success": true, + "session_id": req.SessionID, + }) + c.sendMessage(resp) c.sendSessionData(req.SessionID) } +// handleSessionGitRefresh explicitly requests only a fresh git-status +// snapshot for an already-focused session. Unlike the legacy generic data +// refresh, this does not replay session state, models, commands, or other +// detail-independent data. +func (c *Client) handleSessionGitRefresh(msg *ws.Message) { + var req SessionSubscribeRequest + if err := msg.ParsePayload(&req); err != nil { + c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + return + } + if req.SessionID == "" { + c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) + return + } + if !c.maySubscribeSession(msg, req.SessionID) { + return + } + + resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ + "success": true, + "session_id": req.SessionID, + }) + c.sendMessage(resp) + c.sendSessionGitData(req.SessionID) +} + // handleSessionUnfocus handles session.unfocus — releases the focus mark for // this client. The session falls back to slow mode (still subscribed) or // paused (no subscribers), with a debounce to absorb tab churn. @@ -557,7 +650,7 @@ func (c *Client) sendMessage(msg *ws.Message) { c.logger.Error("Failed to marshal message", zap.Error(err)) return } - c.sendBytes(data) + c.sendControlBytes(data) } func (c *Client) sendBytes(data []byte) bool { @@ -576,6 +669,42 @@ func (c *Client) sendBytes(data []byte) bool { } } +// sendControlBytes queues a response/error separately from notifications. +// Keeping this queue independent is enough to prevent a burst of stream +// frames from dropping the ACK for a user action. It remains bounded so a +// stalled peer cannot grow memory without limit. +func (c *Client) sendControlBytes(data []byte) bool { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return false + } + if c.controlSend == nil { + // Keep zero-value/in-package test clients safe while all production + // clients use the dedicated control queue. + select { + case c.send <- data: + return true + default: + if c.logger != nil { + c.logger.Warn("Client control send buffer full; closing connection") + } + c.closeSendLocked() + return false + } + } + select { + case c.controlSend <- data: + return true + default: + if c.logger != nil { + c.logger.Warn("Client control send buffer full; closing connection") + } + c.closeSendLocked() + return false + } +} + // sendError sends an error message to the client func (c *Client) sendError(id, action, code, message string, details map[string]interface{}) { msg, err := ws.NewError(id, action, code, message, details) @@ -589,11 +718,20 @@ func (c *Client) sendError(id, action, code, message string, details map[string] func (c *Client) closeSend() { c.mu.Lock() defer c.mu.Unlock() + c.closeSendLocked() +} + +func (c *Client) closeSendLocked() { if c.closed { return } c.closed = true - close(c.send) + if c.send != nil { + close(c.send) + } + if c.controlSend != nil { + close(c.controlSend) + } } // WritePump pumps messages from the hub to the WebSocket connection @@ -607,33 +745,44 @@ func (c *Client) WritePump() { }() for { + // Prefer control frames whenever one is already queued. The second + // select still lets stream traffic make progress when no response is + // waiting, while preventing notifications from starving ACKs. + var message []byte + var ok bool select { - case message, ok := <-c.send: - if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { - c.logger.Debug("failed to set write deadline", zap.Error(err)) - } - if !ok { - // Hub closed the channel - if err := c.conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil { - c.logger.Debug("failed to write close message", zap.Error(err)) + case message, ok = <-c.controlSend: + default: + select { + case message, ok = <-c.controlSend: + case message, ok = <-c.send: + case <-ticker.C: + if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + c.logger.Debug("failed to set write deadline", zap.Error(err)) } - return + if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { + return + } + continue } + } - // Send each message in its own WebSocket frame - // (previously batched with newlines, but clients expect one JSON object per frame) - if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil { - c.logger.Debug("failed to write websocket message", zap.Error(err)) - return + if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + c.logger.Debug("failed to set write deadline", zap.Error(err)) + } + if !ok { + // Hub closed the channel. + if err := c.conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil { + c.logger.Debug("failed to write close message", zap.Error(err)) } + return + } - case <-ticker.C: - if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { - c.logger.Debug("failed to set write deadline", zap.Error(err)) - } - if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { - return - } + // Send each message in its own WebSocket frame + // (previously batched with newlines, but clients expect one JSON object per frame) + if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil { + c.logger.Debug("failed to write websocket message", zap.Error(err)) + return } } } diff --git a/apps/backend/internal/gateway/websocket/client_mcp_actions_test.go b/apps/backend/internal/gateway/websocket/client_mcp_actions_test.go index 7fd400cd7d..fd418eaa9f 100644 --- a/apps/backend/internal/gateway/websocket/client_mcp_actions_test.go +++ b/apps/backend/internal/gateway/websocket/client_mcp_actions_test.go @@ -116,6 +116,12 @@ func receiveClientMessage(t *testing.T, client *Client) *ws.Message { t.Helper() select { + case data := <-client.controlSend: + var message ws.Message + if err := json.Unmarshal(data, &message); err != nil { + t.Fatalf("decode client message: %v", err) + } + return &message case data := <-client.send: var message ws.Message if err := json.Unmarshal(data, &message); err != nil { diff --git a/apps/backend/internal/gateway/websocket/client_send_queue_test.go b/apps/backend/internal/gateway/websocket/client_send_queue_test.go new file mode 100644 index 0000000000..04696fc902 --- /dev/null +++ b/apps/backend/internal/gateway/websocket/client_send_queue_test.go @@ -0,0 +1,68 @@ +package websocket + +import ( + "encoding/json" + "testing" + + ws "github.com/kandev/kandev/pkg/websocket" +) + +func TestClient_ControlResponseIsNotBlockedByStreamBacklog(t *testing.T) { + c := newTestClient("control-priority") + c.controlSend = make(chan []byte, controlSendBufferSize) + + for index := 0; index < cap(c.send); index++ { + if !c.sendBytes([]byte("stream")) { + t.Fatalf("stream frame %d was not queued", index) + } + } + + response, err := ws.NewResponse("request-1", "message.add", map[string]any{"accepted": true}) + if err != nil { + t.Fatalf("build response: %v", err) + } + c.sendMessage(response) + + select { + case data := <-c.controlSend: + var got ws.Message + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("decode control frame: %v", err) + } + if got.ID != "request-1" || got.Type != ws.MessageTypeResponse { + t.Fatalf("unexpected control frame: %+v", got) + } + default: + t.Fatal("control response was not queued while stream queue was full") + } +} + +func TestClient_ControlOverflowClosesConnection(t *testing.T) { + c := newTestClient("control-overflow") + c.controlSend = make(chan []byte, 1) + + first, err := ws.NewResponse("request-1", "message.add", map[string]any{"accepted": true}) + if err != nil { + t.Fatalf("build first response: %v", err) + } + second, err := ws.NewResponse("request-2", "message.add", map[string]any{"accepted": true}) + if err != nil { + t.Fatalf("build second response: %v", err) + } + c.sendMessage(first) + c.sendMessage(second) + + if !c.closed { + t.Fatal("control overflow should close the client") + } + if _, ok := <-c.send; ok { + t.Fatal("stream queue should be closed after control overflow") + } + if _, ok := <-c.controlSend; ok { + // The first response is still drainable, but the queue must close after + // its buffered frame is consumed. + if _, stillOpen := <-c.controlSend; stillOpen { + t.Fatal("control queue remained open after overflow") + } + } +} diff --git a/apps/backend/internal/gateway/websocket/client_session_focus_test.go b/apps/backend/internal/gateway/websocket/client_session_focus_test.go index d63732f1de..92ff28199c 100644 --- a/apps/backend/internal/gateway/websocket/client_session_focus_test.go +++ b/apps/backend/internal/gateway/websocket/client_session_focus_test.go @@ -8,29 +8,21 @@ import ( ws "github.com/kandev/kandev/pkg/websocket" ) -// TestHandleSessionFocus_PushesSessionDataSnapshot verifies that session.focus -// pushes a fresh session-data snapshot to the focusing client, not just -// session.subscribe. This closes the "sidebar bulk-subscribe absorbs the -// task-page subscribe" gap — when the ref-counted client-side subscribe skips -// the frame, focus is the only signal the backend still receives on task open. -func TestHandleSessionFocus_PushesSessionDataSnapshot(t *testing.T) { +// TestHandleSessionFocus_IsAckOnly verifies that session.focus only changes +// polling interest and acknowledges the request. Detail surfaces fetch their +// snapshot explicitly; replaying the full session stream on every focus event +// made task switching compete with control responses on the same connection. +func TestHandleSessionFocus_IsAckOnly(t *testing.T) { h := newTestHub(t) const sessionID = "sess-focus-1" - snapshot, err := ws.NewNotification("session.git.event", map[string]any{ - "session_id": sessionID, - "type": "status_update", - }) - if err != nil { - t.Fatalf("build snapshot: %v", err) - } var provided bool h.SetSessionDataProvider(func(_ context.Context, sid string) ([]*ws.Message, error) { if sid != sessionID { t.Errorf("provider called with sid=%q, want %q", sid, sessionID) } provided = true - return []*ws.Message{snapshot}, nil + return nil, nil }) c := newTestClient("c-focus") @@ -41,31 +33,27 @@ func TestHandleSessionFocus_PushesSessionDataSnapshot(t *testing.T) { c.handleSessionFocus(msg) - if !provided { - t.Fatal("session data provider was not invoked on focus") + if provided { + t.Fatal("session data provider should not be invoked on focus") } - // handleSessionFocus is synchronous and sendMessage writes to the buffered - // send channel without blocking, so both frames are already queued by the - // time we get here. A non-blocking select fails fast if the invariant - // breaks in the future. - var sawSnapshot bool - for i := range 2 { - select { - case data := <-c.send: - var m ws.Message - if err := json.Unmarshal(data, &m); err != nil { - t.Fatalf("decode frame: %v", err) - } - if m.Type == ws.MessageTypeNotification && m.Action == "session.git.event" { - sawSnapshot = true - } - default: - t.Fatalf("expected focus frame %d, none in buffer", i+1) + // The ACK is a control frame, not a replayed session notification. + select { + case data := <-c.send: + var response ws.Message + if err := json.Unmarshal(data, &response); err != nil { + t.Fatalf("decode ACK: %v", err) } + if response.Type != ws.MessageTypeResponse || response.Action != "session.focus" { + t.Fatalf("unexpected focus response: %+v", response) + } + default: + t.Fatal("expected focus ACK in control queue") } - if !sawSnapshot { - t.Error("expected a session.git.event notification after focus, got none") + select { + case <-c.send: + t.Fatal("unexpected session-data replay after focus") + default: } } @@ -94,3 +82,162 @@ func TestHandleSessionFocus_NoProviderDoesNotCrash(t *testing.T) { default: } } + +func TestHandleSessionDataRefresh_ReplaysExplicitSnapshot(t *testing.T) { + h := newTestHub(t) + const sessionID = "sess-refresh-1" + provided := false + h.SetSessionDataProvider(func(_ context.Context, sid string) ([]*ws.Message, error) { + if sid != sessionID { + t.Errorf("provider called with sid=%q, want %q", sid, sessionID) + } + provided = true + return []*ws.Message{{ + Type: ws.MessageTypeNotification, + Action: "session.git.event", + Payload: json.RawMessage(`{"session_id":"sess-refresh-1"}`), + }}, nil + }) + + c := newTestClient("c-refresh") + c.hub = h + c.controlSend = make(chan []byte, 16) + + payload, _ := json.Marshal(SessionSubscribeRequest{SessionID: sessionID}) + msg := &ws.Message{ID: "req-refresh", Type: ws.MessageTypeRequest, Action: ws.ActionSessionDataRefresh, Payload: payload} + c.handleSessionDataRefresh(msg) + + if !provided { + t.Fatal("session data provider should be invoked by explicit refresh") + } + select { + case data := <-c.controlSend: + var response ws.Message + if err := json.Unmarshal(data, &response); err != nil { + t.Fatalf("decode refresh ACK: %v", err) + } + if response.Type != ws.MessageTypeResponse || response.Action != ws.ActionSessionDataRefresh { + t.Fatalf("unexpected refresh response: %+v", response) + } + default: + t.Fatal("expected refresh ACK in control queue") + } + select { + case data := <-c.send: + var notification ws.Message + if err := json.Unmarshal(data, ¬ification); err != nil { + t.Fatalf("decode refreshed session data: %v", err) + } + if notification.Action != "session.git.event" { + t.Fatalf("unexpected refreshed data: %+v", notification) + } + default: + t.Fatal("expected explicit session-data notification") + } +} + +func TestHandleSessionGitRefresh_SendsOnlyGitData(t *testing.T) { + h := newTestHub(t) + const sessionID = "sess-git-refresh-1" + h.SetSessionGitDataProvider(func(_ context.Context, sid string) ([]*ws.Message, error) { + if sid != sessionID { + t.Errorf("provider called with sid=%q, want %q", sid, sessionID) + } + return []*ws.Message{ + {Type: ws.MessageTypeNotification, Action: ws.ActionSessionStateChanged}, + {Type: ws.MessageTypeNotification, Action: ws.ActionSessionGitEvent}, + }, nil + }) + + c := newTestClient("c-git-refresh") + c.hub = h + c.controlSend = make(chan []byte, 16) + payload, _ := json.Marshal(SessionSubscribeRequest{SessionID: sessionID}) + c.handleSessionGitRefresh(&ws.Message{ + ID: "req-git-refresh", + Type: ws.MessageTypeRequest, + Action: ws.ActionSessionGitRefresh, + Payload: payload, + }) + + select { + case data := <-c.controlSend: + var response ws.Message + if err := json.Unmarshal(data, &response); err != nil { + t.Fatalf("decode refresh ACK: %v", err) + } + if response.Action != ws.ActionSessionGitRefresh { + t.Fatalf("unexpected refresh response: %+v", response) + } + default: + t.Fatal("expected refresh ACK") + } + select { + case data := <-c.send: + var notification ws.Message + if err := json.Unmarshal(data, ¬ification); err != nil { + t.Fatalf("decode git notification: %v", err) + } + if notification.Action != ws.ActionSessionGitEvent { + t.Fatalf("unexpected refresh data: %+v", notification) + } + default: + t.Fatal("expected git notification") + } + select { + case data := <-c.send: + t.Fatalf("unexpected non-git refresh data: %s", data) + default: + } +} + +func TestHandleSessionSubscribe_DuplicateDoesNotReplaySnapshot(t *testing.T) { + h := newTestHub(t) + const sessionID = "sess-subscribe-1" + providerCalls := 0 + h.SetSessionDataProvider(func(_ context.Context, sid string) ([]*ws.Message, error) { + if sid != sessionID { + t.Errorf("provider called with sid=%q, want %q", sid, sessionID) + } + providerCalls++ + return []*ws.Message{{ + Type: ws.MessageTypeNotification, + Action: "session.git.event", + Payload: json.RawMessage(`{"session_id":"sess-subscribe-1"}`), + }}, nil + }) + + c := newTestClient("c-subscribe") + c.hub = h + c.controlSend = make(chan []byte, 16) + payload, _ := json.Marshal(SessionSubscribeRequest{SessionID: sessionID}) + + for index := 1; index <= 2; index++ { + c.handleSessionSubscribe(&ws.Message{ + ID: "req-subscribe-" + string(rune('0'+index)), + Type: ws.MessageTypeRequest, + Action: ws.ActionSessionSubscribe, + Payload: payload, + }) + } + if providerCalls != 1 { + t.Fatalf("session data provider calls = %d, want 1", providerCalls) + } + for index := 0; index < 2; index++ { + select { + case <-c.controlSend: + default: + t.Fatal("expected subscribe acknowledgement") + } + } + select { + case <-c.send: + default: + t.Fatal("expected one initial session snapshot") + } + select { + case <-c.send: + t.Fatal("duplicate subscribe replayed session snapshot") + default: + } +} diff --git a/apps/backend/internal/gateway/websocket/client_zero_value_test.go b/apps/backend/internal/gateway/websocket/client_zero_value_test.go new file mode 100644 index 0000000000..d4039e016e --- /dev/null +++ b/apps/backend/internal/gateway/websocket/client_zero_value_test.go @@ -0,0 +1,10 @@ +package websocket + +import "testing" + +func TestZeroValueClientSendControlBytesReturnsFalseWithoutPanic(t *testing.T) { + var client Client + if client.sendControlBytes([]byte("response")) { + t.Fatal("zero-value client must not report a queued response") + } +} diff --git a/apps/backend/internal/gateway/websocket/hub.go b/apps/backend/internal/gateway/websocket/hub.go index 5b0ffc91a1..dc59b2c827 100644 --- a/apps/backend/internal/gateway/websocket/hub.go +++ b/apps/backend/internal/gateway/websocket/hub.go @@ -14,6 +14,11 @@ import ( // SessionDataProvider is a function that retrieves initial data for a session subscription (e.g., git status) type SessionDataProvider func(ctx context.Context, sessionID string) ([]*ws.Message, error) +// SessionGitDataProvider retrieves only the current git-status snapshot needed +// by a detail surface. It is separate from SessionDataProvider so a refresh +// does not replay unrelated session state, models, commands, or control data. +type SessionGitDataProvider func(ctx context.Context, sessionID string) ([]*ws.Message, error) + // Hub manages all WebSocket client connections type Hub struct { // All registered clients @@ -46,6 +51,7 @@ type Hub struct { // Optional provider for session data on subscription (e.g., git status) sessionDataProvider SessionDataProvider + sessionGitDataProvider SessionGitDataProvider userSubscriptionListeners []func(userID string) // sessionMode tracks per-session focus state and fires listeners when @@ -469,9 +475,12 @@ func (h *Hub) SubscribeToTask(client *Client, taskID string) { zap.String("task_id", taskID)) } -// SubscribeToSession subscribes a client to session notifications -func (h *Hub) SubscribeToSession(client *Client, sessionID string) { +// SubscribeToSession subscribes a client to session notifications and reports +// whether this call created new membership. Callers use the transition to +// decide whether an initial detail snapshot is needed. +func (h *Hub) SubscribeToSession(client *Client, sessionID string) bool { h.mu.Lock() + wasSubscribed := client.sessionSubscriptions[sessionID] if _, ok := h.sessionSubscribers[sessionID]; !ok { h.sessionSubscribers[sessionID] = make(map[*Client]bool) } @@ -484,6 +493,7 @@ func (h *Hub) SubscribeToSession(client *Client, sessionID string) { zap.String("session_id", sessionID)) h.recomputeSessionMode(sessionID) + return !wasSubscribed } // UnsubscribeFromSession unsubscribes a client from session notifications @@ -687,6 +697,12 @@ func (h *Hub) SetSessionDataProvider(provider SessionDataProvider) { h.sessionDataProvider = provider } +// SetSessionGitDataProvider sets the narrow provider used by explicit git +// refresh requests. Subscription hydration continues to use the full provider. +func (h *Hub) SetSessionGitDataProvider(provider SessionGitDataProvider) { + h.sessionGitDataProvider = provider +} + // GetSessionData retrieves session data (e.g., git status) if a provider is set func (h *Hub) GetSessionData(ctx context.Context, sessionID string) ([]*ws.Message, error) { if h.sessionDataProvider == nil { @@ -694,3 +710,13 @@ func (h *Hub) GetSessionData(ctx context.Context, sessionID string) ([]*ws.Messa } return h.sessionDataProvider(ctx, sessionID) } + +// GetSessionGitData retrieves only git data for an explicit detail refresh. +// Fall back to the full provider for compatibility with lightweight/test +// configurations that have not installed the dedicated provider yet. +func (h *Hub) GetSessionGitData(ctx context.Context, sessionID string) ([]*ws.Message, error) { + if h.sessionGitDataProvider != nil { + return h.sessionGitDataProvider(ctx, sessionID) + } + return h.GetSessionData(ctx, sessionID) +} diff --git a/apps/backend/internal/gateway/websocket/metrics_subscription_test.go b/apps/backend/internal/gateway/websocket/metrics_subscription_test.go index 49be7a501d..2d4e9f11df 100644 --- a/apps/backend/internal/gateway/websocket/metrics_subscription_test.go +++ b/apps/backend/internal/gateway/websocket/metrics_subscription_test.go @@ -92,6 +92,14 @@ func TestHandleSystemMetricsSubscribe(t *testing.T) { t.Fatalf("subscribe calls=%d, want 1", len(rec.subs)) } select { + case data := <-c.controlSend: + var got ws.Message + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("decode response: %v", err) + } + if got.Type != ws.MessageTypeResponse || got.Action != ws.ActionSystemMetricsSubscribe { + t.Fatalf("unexpected response type/action: %s %s", got.Type, got.Action) + } case data := <-c.send: var got ws.Message if err := json.Unmarshal(data, &got); err != nil { diff --git a/apps/backend/internal/gateway/websocket/task_notifications.go b/apps/backend/internal/gateway/websocket/task_notifications.go index e03c827fd3..d7e0d0c89e 100644 --- a/apps/backend/internal/gateway/websocket/task_notifications.go +++ b/apps/backend/internal/gateway/websocket/task_notifications.go @@ -72,6 +72,7 @@ func RegisterTaskNotifications(ctx context.Context, eventBus bus.EventBus, hub * b.subscribe(eventBus, events.EnvironmentUpdated, ws.ActionEnvironmentUpdated) b.subscribe(eventBus, events.EnvironmentDeleted, ws.ActionEnvironmentDeleted) b.subscribe(eventBus, events.TaskSessionActivityChanged, ws.ActionSessionActivityChanged) + b.subscribe(eventBus, events.TaskStatusSummaryUpdated, ws.ActionTaskStatusSummaryUpdated) b.subscribe(eventBus, events.MessageAdded, ws.ActionSessionMessageAdded) b.subscribe(eventBus, events.MessageUpdated, ws.ActionSessionMessageUpdated) b.subscribe(eventBus, events.MessageDeleted, ws.ActionSessionMessageDeleted) diff --git a/apps/backend/internal/gateway/websocket/task_notifications_test.go b/apps/backend/internal/gateway/websocket/task_notifications_test.go index 9499bb0dda..eb01f6dcb7 100644 --- a/apps/backend/internal/gateway/websocket/task_notifications_test.go +++ b/apps/backend/internal/gateway/websocket/task_notifications_test.go @@ -107,7 +107,7 @@ func TestTaskEventBroadcaster_NoDuplicateSubscriptions(t *testing.T) { // // Update this number when adding or removing event subscriptions in // RegisterTaskNotifications — it is intentionally exact. - const wantSubscriptions = 60 + const wantSubscriptions = 61 if got := len(b.subscriptions); got != wantSubscriptions { t.Errorf("RegisterTaskNotifications created %d subscriptions, want %d — "+ "did an event get subscribed twice?", got, wantSubscriptions) diff --git a/apps/backend/internal/integration/simulated_agent_manager_test.go b/apps/backend/internal/integration/simulated_agent_manager_test.go index 1125ade129..6d614b3e4b 100644 --- a/apps/backend/internal/integration/simulated_agent_manager_test.go +++ b/apps/backend/internal/integration/simulated_agent_manager_test.go @@ -253,11 +253,12 @@ func (s *SimulatedAgentManagerClient) publishACPMessages(instance *simulatedInst sessionID = instance.sessionID } msgData := map[string]interface{}{ - "type": msg.Type, - "task_id": msg.TaskID, - "session_id": sessionID, - "timestamp": msg.Timestamp, - "data": msg.Data, + "type": msg.Type, + "task_id": msg.TaskID, + "session_id": sessionID, + "execution_id": instance.id, + "timestamp": msg.Timestamp, + "data": msg.Data, } event := bus.NewEvent(events.AgentStream, "simulated-agent", msgData) diff --git a/apps/backend/internal/orchestrator/event_handlers_agent.go b/apps/backend/internal/orchestrator/event_handlers_agent.go index 75c46cd50b..4d218f28b7 100644 --- a/apps/backend/internal/orchestrator/event_handlers_agent.go +++ b/apps/backend/internal/orchestrator/event_handlers_agent.go @@ -1293,6 +1293,28 @@ func (s *Service) persistLastAgentError(ctx context.Context, data watcher.AgentE zap.String("task_id", data.TaskID), zap.String("session_id", data.SessionID), zap.Error(err)) + return + } + if s.eventBus != nil { + eventData := map[string]interface{}{ + "task_id": data.TaskID, + "session_id": data.SessionID, + "active": true, + "message": lastErr.Message, + "occurred_at": lastErr.OccurredAt.Format(time.RFC3339Nano), + "stamp": lastErr.Stamp(), + "agent_execution_id": lastErr.AgentExecutionID, + } + if err := s.eventBus.Publish(ctx, events.TaskSessionErrorChanged, bus.NewEvent( + events.TaskSessionErrorChanged, + "orchestrator", + eventData, + )); err != nil { + s.logger.Warn("failed to publish task session error event", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID), + zap.Error(err)) + } } } diff --git a/apps/backend/internal/orchestrator/event_handlers_streaming.go b/apps/backend/internal/orchestrator/event_handlers_streaming.go index 4541085306..0b5720ecdc 100644 --- a/apps/backend/internal/orchestrator/event_handlers_streaming.go +++ b/apps/backend/internal/orchestrator/event_handlers_streaming.go @@ -1113,6 +1113,7 @@ func (s *Service) publishTaskSessionStateChanged( metaKeyAgentProfileID: agentProfileID, "agent_profile_snapshot": session.AgentProfileSnapshot, "is_passthrough": session.IsPassthrough, + "is_primary": session.IsPrimary, // Carry activity only while the durable session is RUNNING. Every other // state gets an explicit null so partial client-store merges clear a // previously-live busy signal during settlement or teardown. diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index 18f45f0c8b..f6471bbf89 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -206,9 +206,13 @@ func (e *Executor) stopStartedExecutionIfSessionTerminal( return terminalState, true } -// startAgentProcessAsync starts the agent subprocess and transitions the task to IN_PROGRESS on success. +// startAgentProcessAsync starts the agent subprocess and transitions its session +// to RUNNING before reconciling the owning task to IN_PROGRESS on success. func (e *Executor) startAgentProcessAsync(ctx context.Context, taskID, sessionID, agentExecutionID string) { e.runAgentProcessAsync(ctx, taskID, sessionID, agentExecutionID, func(updCtx context.Context) { + if !e.markSessionRunningAfterProcessStart(updCtx, taskID, sessionID) { + return + } if updateErr := e.writeTaskInProgressForRuntime(updCtx, taskID, sessionID); updateErr != nil { e.logger.Warn("failed to update task state to IN_PROGRESS after agent start", zap.String("task_id", taskID), @@ -218,6 +222,45 @@ func (e *Executor) startAgentProcessAsync(ctx context.Context, taskID, sessionID }, true, false) } +// markSessionRunningAfterProcessStart records that a successfully started +// process is active. Agent stream events may settle a fast turn before this +// callback runs, so only a still-STARTING session may move to RUNNING. +func (e *Executor) markSessionRunningAfterProcessStart(ctx context.Context, taskID, sessionID string) bool { + session, err := e.repo.GetTaskSession(ctx, sessionID) + if err != nil { + e.logger.Warn("failed to load session after agent start", + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.Error(err)) + return false + } + if session == nil { + e.logger.Warn("session missing after agent start", + zap.String("task_id", taskID), + zap.String("session_id", sessionID)) + return false + } + + switch session.State { + case models.TaskSessionStateRunning: + return true + case models.TaskSessionStateStarting: + changed, finalState, transitionErr := e.transitionSessionState( + ctx, taskID, sessionID, models.TaskSessionStateRunning, "", + ) + if transitionErr != nil { + e.logger.Warn("failed to mark session running after agent start", + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.Error(transitionErr)) + return false + } + return changed || finalState == models.TaskSessionStateRunning + default: + return false + } +} + func (e *Executor) stopUnstartedExecution(ctx context.Context, sessionID, agentExecutionID string) { if agentExecutionID == "" { return diff --git a/apps/backend/internal/orchestrator/executor/executor_office.go b/apps/backend/internal/orchestrator/executor/executor_office.go index 5deeb7e798..852ed9abce 100644 --- a/apps/backend/internal/orchestrator/executor/executor_office.go +++ b/apps/backend/internal/orchestrator/executor/executor_office.go @@ -36,29 +36,42 @@ type officeSessionMetadataUpdater interface { func (e *Executor) EnsureSessionForAgent( ctx context.Context, task *v1.Task, agentInstanceID, agentProfileID, executorID, executorProfileID string, ) (*models.TaskSession, error) { + session, _, err := e.EnsureSessionForAgentWithCreation( + ctx, task, agentInstanceID, agentProfileID, executorID, executorProfileID, + ) + return session, err +} + +// EnsureSessionForAgentWithCreation is the same office-session lookup as +// EnsureSessionForAgent, but also reports whether the returned row was +// inserted by this call. Reused rows already have a CREATED lifecycle event; +// callers must not publish another one for every office turn. +func (e *Executor) EnsureSessionForAgentWithCreation( + ctx context.Context, task *v1.Task, agentInstanceID, agentProfileID, executorID, executorProfileID string, +) (*models.TaskSession, bool, error) { if task == nil || task.ID == "" { - return nil, errors.New("EnsureSessionForAgent: task is required") + return nil, false, errors.New("EnsureSessionForAgent: task is required") } if agentInstanceID == "" { - return nil, errors.New("EnsureSessionForAgent: agent_profile_id is required") + return nil, false, errors.New("EnsureSessionForAgent: agent_profile_id is required") } if agentProfileID == "" { - return nil, ErrNoAgentProfileID + return nil, false, ErrNoAgentProfileID } existing, err := e.repo.GetTaskSessionByTaskAndAgent(ctx, task.ID, agentInstanceID) if err != nil { - return nil, fmt.Errorf("lookup (task,agent) session: %w", err) + return nil, false, fmt.Errorf("lookup (task,agent) session: %w", err) } if existing != nil { if err := e.rebindOfficeSessionExecutionProfile(ctx, existing, agentProfileID); err != nil { - return nil, err + return nil, false, err } reused, decision := e.tryReuseExistingSession(ctx, existing) if decision == reuseDecisionTerminal { // Fall through to create a new row below. } else { - return reused, nil + return reused, false, nil } } @@ -68,15 +81,15 @@ func (e *Executor) EnsureSessionForAgent( raced, lookupErr := e.repo.GetTaskSessionByTaskAndAgent(ctx, task.ID, agentInstanceID) if lookupErr == nil && raced != nil { if rebindErr := e.rebindOfficeSessionExecutionProfile(ctx, raced, agentProfileID); rebindErr != nil { - return nil, rebindErr + return nil, false, rebindErr } reused, _ := e.tryReuseExistingSession(ctx, raced) if reused != nil { - return reused, nil + return reused, false, nil } } } - return created, err + return created, err == nil, err } func (e *Executor) rebindOfficeSessionExecutionProfile( diff --git a/apps/backend/internal/orchestrator/executor/executor_test.go b/apps/backend/internal/orchestrator/executor/executor_test.go index b9faf80c71..0d754d3533 100644 --- a/apps/backend/internal/orchestrator/executor/executor_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_test.go @@ -1812,6 +1812,60 @@ func TestCleanupUnstartedExecutionAfterPersistError_CancelledWithTeardownSkipsEx } } +func TestStartAgentProcessAsync_MarksStartingSessionRunning(t *testing.T) { + repo := newMockRepository() + repo.sessions["session-123"] = &models.TaskSession{ + ID: "session-123", TaskID: "task-123", State: models.TaskSessionStateStarting, + } + repo.tasks["task-123"] = &models.Task{ID: "task-123", State: v1.TaskStateScheduling} + + agentManager := &mockAgentManager{ + startAgentProcessFunc: func(context.Context, string) error { return nil }, + } + exec := newTestExecutor(t, agentManager, repo) + exec.SetOnSessionStateChange(func( + ctx context.Context, + _ string, + sessionID string, + state models.TaskSessionState, + errorMessage string, + ) error { + return repo.UpdateTaskSessionState(ctx, sessionID, state, errorMessage) + }) + reconciled := make(chan struct{}) + exec.SetOnTaskRuntimeStateReconcile(func( + ctx context.Context, + taskID, _ string, + state v1.TaskState, + ) error { + defer close(reconciled) + _, _, err := repo.UpdateTaskStateIfNotArchived(ctx, taskID, state) + return err + }) + + exec.startAgentProcessAsync(context.Background(), "task-123", "session-123", "exec-456") + select { + case <-reconciled: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for runtime state reconciliation") + } + + session, err := repo.GetTaskSession(context.Background(), "session-123") + if err != nil { + t.Fatalf("get session: %v", err) + } + if session.State != models.TaskSessionStateRunning { + t.Fatalf("session state = %q, want RUNNING", session.State) + } + task, err := repo.GetTask(context.Background(), "task-123") + if err != nil { + t.Fatalf("get task: %v", err) + } + if task.State != v1.TaskStateInProgress { + t.Fatalf("task state = %q, want IN_PROGRESS", task.State) + } +} + func TestStartAgentProcessAsync_StopWinningStartRacePreservesReview(t *testing.T) { repo := newMockRepository() repo.sessions["session-123"] = &models.TaskSession{ diff --git a/apps/backend/internal/orchestrator/handoff_inheritance_test.go b/apps/backend/internal/orchestrator/handoff_inheritance_test.go index b50e57702e..36120c6825 100644 --- a/apps/backend/internal/orchestrator/handoff_inheritance_test.go +++ b/apps/backend/internal/orchestrator/handoff_inheritance_test.go @@ -96,7 +96,7 @@ func TestPrepareSessionForStart_PropagatesInheritedEnvironment(t *testing.T) { ParentID: "parent", Metadata: map[string]interface{}{"workspace": map[string]interface{}{"mode": "inherit_parent"}}, } - sessionID, err := svc.prepareSessionForStart(ctx, childTask, "profile-1", "exec-1", "", "") + sessionID, _, err := svc.prepareSessionForStart(ctx, childTask, "profile-1", "exec-1", "", "") if err != nil { t.Fatalf("prepareSessionForStart: %v", err) } diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index 7cb3c5611f..c23a9245bd 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -270,7 +270,7 @@ func (s *Service) PrepareTaskSession(ctx context.Context, taskID string, agentPr // EnsureSessionForAgent so runs + advanced-mode reuse one row. // prepareSessionForStart also propagates any inherited workspace // environment (inherit_parent / shared_group) onto the new session. - sessionID, err := s.prepareSessionForStart(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) + sessionID, sessionCreated, err := s.prepareSessionForStart(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) if err != nil { s.logger.Error("failed to prepare session", zap.String("task_id", taskID), @@ -282,7 +282,9 @@ func (s *Service) PrepareTaskSession(ctx context.Context, taskID string, agentPr // transitions through updateTaskSessionState which broadcasts; the prepare // path writes the row directly, so without this the per-task session list // stays empty until a manual reload. - s.publishSessionCreatedEvent(ctx, taskID, sessionID, workflowStepID) + if sessionCreated { + s.publishSessionCreatedEvent(ctx, taskID, sessionID, workflowStepID) + } if launchWorkspace { // Launch workspace infrastructure (agentctl) in the background so the WS response @@ -856,10 +858,17 @@ func (s *Service) startTask(ctx context.Context, taskID string, agentProfileID s // Prepare session first so we have the sessionID for config context injection. // For office tasks, replace the per-launch PrepareSession with the per-(task, // agent) EnsureSessionForAgent so runs reuse one row across turns. - sessionID, err := s.prepareSessionForStart(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) + sessionID, sessionCreated, err := s.prepareSessionForStart(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) if err != nil { return nil, err } + // Surface the newly created session before LaunchPreparedSession performs + // potentially slow environment setup (for example, a Docker health check). + // The frontend adopts this CREATED session and can render + // executor.prepare.progress events while the launch request is still pending. + if sessionCreated { + s.publishSessionCreatedEvent(ctx, taskID, sessionID, workflowStepID) + } // When the workflow step overrode the caller's profile, tag the session // for provenance: the profile came from workflow routing rather than @@ -1121,13 +1130,13 @@ func validateOfficeLaunchEnv(taskID string, env map[string]string) error { func (s *Service) prepareSessionForStart( ctx context.Context, task *v1.Task, agentProfileID, executorID, executorProfileID, workflowStepID string, -) (string, error) { - sessionID, err := s.createStartSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) +) (string, bool, error) { + sessionID, created, err := s.createStartSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) if err != nil { - return "", err + return "", false, err } s.propagateInheritedEnvironment(ctx, task, sessionID) - return sessionID, nil + return sessionID, created, nil } // resolveIsPassthroughForLaunch reloads the session snapshot to decide @@ -1154,18 +1163,19 @@ func (s *Service) resolveIsPassthroughForLaunch(ctx context.Context, sessionID s func (s *Service) createStartSession( ctx context.Context, task *v1.Task, agentProfileID, executorID, executorProfileID, workflowStepID string, -) (string, error) { +) (string, bool, error) { dbTask, err := s.repo.GetTask(ctx, task.ID) if err == nil && dbTask != nil && dbTask.IsFromOffice && dbTask.AssigneeAgentProfileID != "" { - session, ensureErr := s.executor.EnsureSessionForAgent( + session, created, ensureErr := s.executor.EnsureSessionForAgentWithCreation( ctx, task, dbTask.AssigneeAgentProfileID, agentProfileID, executorID, executorProfileID, ) if ensureErr != nil { - return "", ensureErr + return "", false, ensureErr } - return session.ID, nil + return session.ID, created, nil } - return s.executor.PrepareSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) + sessionID, err := s.executor.PrepareSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) + return sessionID, err == nil, err } // moveTaskToWorkflowStep moves a task to the target workflow step if provided and different from current. @@ -2482,6 +2492,12 @@ func (s *Service) stopTaskSessionForCoordinatorLocked( if err != nil { return result, false, fmt.Errorf("coordinator stop: session %q: %w", sessionID, err) } + if result.Changed { + // Cancellation takes effect before detached runtime teardown. Tombstone + // the execution immediately so buffered agent frames cannot recreate + // session output after the coordinator has acknowledged the stop. + s.markExecutionFailed(sessionID, result.ExecutionID) + } teardownClaimed := result.Changed && s.claimExecutionTeardown( sessionID, result.ExecutionID, diff --git a/apps/backend/internal/orchestrator/task_operations_test.go b/apps/backend/internal/orchestrator/task_operations_test.go index 98b64b4d07..3d1964eada 100644 --- a/apps/backend/internal/orchestrator/task_operations_test.go +++ b/apps/backend/internal/orchestrator/task_operations_test.go @@ -143,7 +143,7 @@ func TestCreateStartSession_KanbanRunnerCreatesDistinctSession(t *testing.T) { if isOffice { t.Fatal("kanban task with a runner was classified as office-owned") } - sessionID, err := svc.createStartSession(ctx, task.ToAPI(), "copilot-runner", "", "", "") + sessionID, _, err := svc.createStartSession(ctx, task.ToAPI(), "copilot-runner", "", "", "") if err != nil { t.Fatalf("create start session: %v", err) } @@ -196,10 +196,13 @@ func TestCreateStartSession_OfficeRunnerReusesPersistentSession(t *testing.T) { if !isOffice { t.Fatal("office-owned assigned task was not classified as office") } - sessionID, err := svc.createStartSession(ctx, task.ToAPI(), "copilot-runner", "", "", "") + sessionID, created, err := svc.createStartSession(ctx, task.ToAPI(), "copilot-runner", "", "", "") if err != nil { t.Fatalf("create start session: %v", err) } + if created { + t.Fatal("office launch reuse must not report a newly created session") + } if sessionID != "existing-office-session" { t.Fatalf("office launch session = %q, want existing-office-session", sessionID) } @@ -3846,6 +3849,49 @@ func TestStartTask_OfficeWithoutRuntimeEnvFailsClosed(t *testing.T) { assert.False(t, launchCalled) } +func TestStartTaskPublishesCreatedSessionBeforeLaunch(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedTaskAndSession(t, repo, "task1", "existing-session", models.TaskSessionStateCompleted) + + taskRepo := newMockTaskRepo() + taskRepo.tasks["task1"] = &v1.Task{ + ID: "task1", + Title: "Task", + Description: "Do the work", + State: v1.TaskStateInProgress, + } + eventBus := &mockEventBus{} + publishedBeforeLaunch := false + agentMgr := &mockAgentManager{ + launchAgentFunc: func(_ context.Context, req *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + for _, published := range eventBus.published() { + if published.Subject != events.TaskSessionStateChanged { + continue + } + data, ok := published.Event.Data.(map[string]any) + if !ok { + continue + } + if data[metaKeySessionID] == req.SessionID && + data[metaKeyNewState] == string(models.TaskSessionStateCreated) { + publishedBeforeLaunch = true + } + } + return &executor.LaunchAgentResponse{AgentExecutionID: "exec-1"}, nil + }, + } + svc := createTestServiceWithScheduler(repo, newMockStepGetter(), taskRepo, agentMgr) + svc.eventBus = eventBus + + _, err := svc.StartTask( + ctx, "task1", "profile1", "", "", "", "Do the work", + "", false, false, nil, + ) + require.NoError(t, err) + assert.True(t, publishedBeforeLaunch, "created session event must arrive before the runtime starts") +} + func TestStartTask_PreservesOnlyResolvedWorkflowPromptExpansion(t *testing.T) { for _, tc := range []struct { name string diff --git a/apps/backend/internal/task/dto/dto.go b/apps/backend/internal/task/dto/dto.go index e94de6bb6b..45e726fd08 100644 --- a/apps/backend/internal/task/dto/dto.go +++ b/apps/backend/internal/task/dto/dto.go @@ -5,6 +5,7 @@ import ( "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/task/service" + "github.com/kandev/kandev/internal/task/statussummary" v1 "github.com/kandev/kandev/pkg/api/v1" ) @@ -194,6 +195,11 @@ type TaskDTO struct { // task-listing MCP tools so agents can reason about PR status (e.g. find // tasks whose PRs are merged). Omitted when empty. PRs []v1.TaskPRSummary `json:"prs,omitempty"` + + // StatusSummary is the bounded task-level projection consumed by task rows. + // It is loaded in batches and is absent when no projection exists yet; the + // existing coarse fields above remain the compatibility fallback. + StatusSummary *statussummary.TaskStatusSummary `json:"status_summary,omitempty"` } type TaskRepositoryDTO struct { diff --git a/apps/backend/internal/task/dto/status_summary_test.go b/apps/backend/internal/task/dto/status_summary_test.go new file mode 100644 index 0000000000..d770841c8f --- /dev/null +++ b/apps/backend/internal/task/dto/status_summary_test.go @@ -0,0 +1,45 @@ +package dto + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/statussummary" +) + +func TestTaskDTOStatusSummaryIsBoundedAndOptional(t *testing.T) { + without := FromTask(&models.Task{ID: "task-without-summary"}) + withoutJSON, err := json.Marshal(without) + if err != nil { + t.Fatalf("marshal task without summary: %v", err) + } + if strings.Contains(string(withoutJSON), "status_summary") { + t.Fatalf("missing summary should remain omitted: %s", withoutJSON) + } + + with := FromTask(&models.Task{ID: "task-with-summary"}) + with.StatusSummary = &statussummary.TaskStatusSummary{ + Revision: 1, + ActiveError: &statussummary.ActiveErrorSummary{ + SessionID: "session-1", + Stamp: "error-1", + Preview: "safe preview", + }, + } + withJSON, err := json.Marshal(with) + if err != nil { + t.Fatalf("marshal task with summary: %v", err) + } + var decoded map[string]json.RawMessage + if err := json.Unmarshal(withJSON, &decoded); err != nil { + t.Fatalf("decode task JSON: %v", err) + } + if _, ok := decoded["status_summary"]; !ok { + t.Fatalf("task JSON missing status_summary: %s", withJSON) + } + if _, ok := decoded["messages"]; ok { + t.Fatal("task status summary must not carry transcript data") + } +} diff --git a/apps/backend/internal/task/handlers/message_handlers.go b/apps/backend/internal/task/handlers/message_handlers.go index 33cf760b00..eb88d7a70d 100644 --- a/apps/backend/internal/task/handlers/message_handlers.go +++ b/apps/backend/internal/task/handlers/message_handlers.go @@ -7,6 +7,7 @@ import ( "net/http" "strconv" "strings" + "sync" "unicode" "github.com/gin-gonic/gin" @@ -44,6 +45,13 @@ type MessageHandlers struct { orchestrator OrchestratorService logger *logger.Logger referenceValidator entityrefs.SubmissionValidator + messageIDMu sync.Mutex + messageIDGates map[string]*messageIDGate +} + +type messageIDGate struct { + mu sync.Mutex + refs int } // NewMessageHandlers creates a new MessageHandlers instance @@ -236,6 +244,8 @@ func (h *MessageHandlers) httpListMessages(c *gin.Context) { type wsAddMessageRequest struct { TaskID string `json:"task_id"` TaskSessionID string `json:"session_id"` + MessageID string `json:"message_id,omitempty"` + ClientMessageID string `json:"client_message_id,omitempty"` Content string `json:"content"` AuthorID string `json:"author_id,omitempty"` Model string `json:"model,omitempty"` @@ -252,10 +262,44 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) } req.Content = strings.TrimSpace(req.Content) + req.MessageID = strings.TrimSpace(req.MessageID) + req.ClientMessageID = strings.TrimSpace(req.ClientMessageID) + if req.ClientMessageID == "" { + req.ClientMessageID = req.MessageID + } if errMsg := validateAddMessageRequest(req); errMsg != "" { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, errMsg, nil) } + unlockMessageID := h.lockMessageID(req.ClientMessageID) + defer unlockMessageID() + + // A response can be lost after the message is committed. Resolve a replay + // before checking the live session state or running turn-start hooks so a + // retry is a read, not a second prompt. + if req.ClientMessageID != "" { + existing, err := h.service.GetMessage(ctx, req.ClientMessageID) + switch { + case err == nil && existing != nil: + // The turn-start hook may switch the task's primary session before + // the message is persisted. A retried request still belongs to the + // same authorized task even when its original session_id is no + // longer the persisted message's session. + if (existing.TaskID != "" && existing.TaskID != req.TaskID) || + existing.AuthorType != models.MessageAuthorUser { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "client_message_id is already used", nil) + } + apiMsg := existing.ToAPI() + response, responseErr := ws.NewResponse(msg.ID, msg.Action, apiMsg) + if responseErr != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to encode response", nil) + } + return response, nil + case err != nil && !errors.Is(err, sql.ErrNoRows): + h.logger.Error("failed to check idempotent message", zap.String("message_id", req.ClientMessageID), zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to check message", nil) + } + } // Check session state — may block the message or flag it as a create-start sessionResp, wsErr := h.checkSessionStateForMessage(ctx, msg, req.TaskSessionID) @@ -359,14 +403,21 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w } req.Content = storedContent - message, err := h.service.CreateMessage(ctx, &service.CreateMessageRequest{ + createRequest := &service.CreateMessageRequest{ TaskSessionID: req.TaskSessionID, TaskID: req.TaskID, Content: storedContent, AuthorType: "user", AuthorID: req.AuthorID, Metadata: meta.ToMap(), - }) + } + var message *models.Message + var err error + if req.ClientMessageID != "" { + message, err = h.service.CreateMessageIdempotent(ctx, req.ClientMessageID, createRequest) + } else { + message, err = h.service.CreateMessage(ctx, createRequest) + } if err != nil { h.logger.Error("failed to create message", zap.Error(err)) return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create message", nil) @@ -388,6 +439,39 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w return response, nil } +// lockMessageID serializes acceptance for one caller-owned message ID. The +// database primary key still closes races across process boundaries, but this +// gate keeps same-process retries from running mutable session hooks twice +// before the first insert commits. +func (h *MessageHandlers) lockMessageID(id string) func() { + if id == "" { + return func() {} + } + + h.messageIDMu.Lock() + if h.messageIDGates == nil { + h.messageIDGates = make(map[string]*messageIDGate) + } + gate := h.messageIDGates[id] + if gate == nil { + gate = &messageIDGate{} + h.messageIDGates[id] = gate + } + gate.refs++ + h.messageIDMu.Unlock() + + gate.mu.Lock() + return func() { + gate.mu.Unlock() + h.messageIDMu.Lock() + gate.refs-- + if gate.refs == 0 && h.messageIDGates[id] == gate { + delete(h.messageIDGates, id) + } + h.messageIDMu.Unlock() + } +} + func (h *MessageHandlers) resolveSessionAfterTurnStart( ctx context.Context, taskID, submittedSessionID string, @@ -452,6 +536,9 @@ func validateAddMessageRequest(req wsAddMessageRequest) string { if req.Content == "" && len(req.Attachments) == 0 { return "content or attachments are required" } + if len(req.ClientMessageID) > 128 { + return "client_message_id is too long" + } if err := validateAttachments(req.Attachments); err != nil { return err.Error() } diff --git a/apps/backend/internal/task/handlers/message_handlers_blocked_test.go b/apps/backend/internal/task/handlers/message_handlers_blocked_test.go index e8cc7a0cc4..6ca9965a4a 100644 --- a/apps/backend/internal/task/handlers/message_handlers_blocked_test.go +++ b/apps/backend/internal/task/handlers/message_handlers_blocked_test.go @@ -30,14 +30,22 @@ import ( type messageAddSwitchRepo struct { mockRepository - tasks map[string]*models.Task - sessions map[string]*models.TaskSession - primaryID string - messages []*models.Message - turns []*models.Turn - getCalls map[string]int - failReload bool - taskGetCalls int + tasks map[string]*models.Task + sessions map[string]*models.TaskSession + primaryID string + messages []*models.Message + turns []*models.Turn + idempotentMessage *models.Message + getCalls map[string]int + failReload bool + taskGetCalls int +} + +func (r *messageAddSwitchRepo) GetMessage(_ context.Context, id string) (*models.Message, error) { + if r.idempotentMessage != nil && r.idempotentMessage.ID == id { + return r.idempotentMessage, nil + } + return nil, sql.ErrNoRows } func (r *messageAddSwitchRepo) GetTask(_ context.Context, id string) (*models.Task, error) { @@ -580,6 +588,51 @@ func TestWSAddMessageUsesSessionSelectedByOnTurnStart(t *testing.T) { assert.Empty(t, orch.getForwardedSession()) } +func TestWSAddMessageRetryAcceptsMessagePersistedAfterSessionSwitch(t *testing.T) { + now := time.Now().UTC() + repo := &messageAddSwitchRepo{ + tasks: map[string]*models.Task{ + "t1": {ID: "t1", State: v1.TaskStateReview, UpdatedAt: now}, + }, + sessions: map[string]*models.TaskSession{ + "s1": {ID: "s1", TaskID: "t1", State: models.TaskSessionStateWaitingForInput, UpdatedAt: now}, + "s2": {ID: "s2", TaskID: "t1", State: models.TaskSessionStateCreated, UpdatedAt: now}, + }, + primaryID: "s1", + idempotentMessage: &models.Message{ + ID: "client-1", + TaskID: "t1", + TaskSessionID: "s2", + AuthorType: models.MessageAuthorUser, + Content: "continue here", + CreatedAt: now, + }, + } + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + require.NoError(t, err) + svc := service.NewService(service.Repos{ + Workspaces: repo, Tasks: repo, TaskRepos: repo, + Workflows: repo, Messages: repo, Turns: repo, + Sessions: repo, GitSnapshots: repo, RepoEntities: repo, + Executors: repo, Environments: repo, TaskEnvironments: repo, + Reviews: repo, + }, nil, log, service.RepositoryDiscoveryConfig{}) + h := NewMessageHandlers(svc, &switchingTurnStartOrchestrator{repo: repo}, log) + + req, err := ws.NewRequest("req-retry", ws.ActionMessageAdd, map[string]interface{}{ + "task_id": "t1", + "session_id": "s1", + "client_message_id": "client-1", + "content": "continue here", + }) + require.NoError(t, err) + + resp, err := h.wsAddMessage(context.Background(), req) + require.NoError(t, err) + require.Equal(t, ws.MessageTypeResponse, resp.Type) + assert.Empty(t, repo.messages, "an idempotent retry must not create a second message") +} + func TestWSAddMessageFailsWhenOnTurnStartCompletesSessionWithoutReplacement(t *testing.T) { now := time.Now().UTC() repo := &messageAddSwitchRepo{ diff --git a/apps/backend/internal/task/handlers/process_handlers_test.go b/apps/backend/internal/task/handlers/process_handlers_test.go index 7745733c0a..4fc7e5764a 100644 --- a/apps/backend/internal/task/handlers/process_handlers_test.go +++ b/apps/backend/internal/task/handlers/process_handlers_test.go @@ -514,6 +514,9 @@ func (m *mockRepository) CreateGitSnapshot(ctx context.Context, snapshot *models func (m *mockRepository) GetLatestGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { return nil, nil } +func (m *mockRepository) GetLatestGitSnapshotsBySessionIDs(ctx context.Context, sessionIDs []string) (map[string]*models.GitSnapshot, error) { + return make(map[string]*models.GitSnapshot), nil +} func (m *mockRepository) GetFirstGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { return nil, nil } diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 962fb91c6d..ec586a9d56 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -20,6 +20,7 @@ import ( taskrepository "github.com/kandev/kandev/internal/task/repository" taskrepo "github.com/kandev/kandev/internal/task/repository/sqlite" "github.com/kandev/kandev/internal/task/service" + "github.com/kandev/kandev/internal/task/statussummary" usermodels "github.com/kandev/kandev/internal/user/models" "github.com/kandev/kandev/internal/worktree" v1 "github.com/kandev/kandev/pkg/api/v1" @@ -134,9 +135,11 @@ func (h *TaskHandlers) httpListTasks(c *gin.Context) { handleNotFound(c, h.logger, err, "tasks not found") return } - taskDTOs := make([]dto.TaskDTO, 0, len(tasks)) - for _, task := range tasks { - taskDTOs = append(taskDTOs, dto.FromTask(task)) + taskDTOs, err := h.toTaskDTOsWithSessionInfo(c.Request.Context(), tasks) + if err != nil { + h.logger.Error("failed to enrich tasks with status summaries", zap.Error(err)) + handleNotFound(c, h.logger, err, "tasks not found") + return } c.JSON(http.StatusOK, dto.ListTasksResponse{ Tasks: taskDTOs, @@ -190,13 +193,9 @@ func (h *TaskHandlers) httpListTasksByWorkspace(c *gin.Context) { } // buildTaskDTOsWithSessionInfo converts tasks to DTOs enriched with primary -// session IDs, session counts, and review status. Uses BatchGetSessionsForTasks -// to derive the primary session ID and session count in a single round trip, -// then calls GetPrimarySessionInfoForTasks for the executor type/name fields -// — those are populated by a LEFT JOIN to the executors table inside that -// method (the persisted ExecutorSnapshot JSON uses different keys), so the -// batch loader alone can't supply them without a regression. Two queries -// total, down from three pre-batch. +// session IDs, session counts, review status, and the bounded task status +// summary. Session and executor lookups remain batched; missing summary rows +// are repaired lazily from the same batch-loaded authoritative inputs. func buildTaskDTOsWithSessionInfo( ctx context.Context, svc *service.Service, @@ -219,11 +218,24 @@ func buildTaskDTOsWithSessionInfo( if err != nil { return nil, err } - pendingActionsBySession, err := pendingActionsForInputCapableSessions(ctx, svc, sessionsByTask) - if err != nil { - log.Warn("failed to load pending actions for task list, using empty map", zap.Error(err)) + pendingActionsBySession, pendingErr := pendingActionsForInputCapableSessions(ctx, svc, sessionsByTask) + if pendingErr != nil { + log.Warn("failed to load pending actions for task list, using empty map", zap.Error(pendingErr)) pendingActionsBySession = map[string]models.TaskPendingAction{} } + statusSummaries, summaryErr := svc.GetTaskStatusSummaries(ctx, taskIDs) + if summaryErr != nil { + log.Warn("failed to load task status summaries, using coarse task fields", zap.Error(summaryErr)) + statusSummaries = map[string]*statussummary.TaskStatusSummary{} + } + if summaryErr == nil && pendingErr == nil { + statusSummaries, err = svc.HydrateMissingTaskStatusSummaries( + ctx, tasks, sessionsByTask, pendingActionsBySession, statusSummaries, + ) + if err != nil { + log.Warn("failed to repair missing task status summaries", zap.Error(err)) + } + } result := make([]dto.TaskDTO, 0, len(tasks)) for _, task := range tasks { sessions := sessionsByTask[task.ID] @@ -255,6 +267,7 @@ func buildTaskDTOsWithSessionInfo( ) taskDTO.TaskPendingAction = taskPendingActionPtr(sessions, pendingActionsBySession) dto.EnrichTaskForegroundActivity(&taskDTO, sessions, activityProvider) + taskDTO.StatusSummary = statusSummaries[task.ID] result = append(result, taskDTO) } return result, nil diff --git a/apps/backend/internal/task/handlers/task_ws_handlers.go b/apps/backend/internal/task/handlers/task_ws_handlers.go index 8c194c3311..2cf86deef8 100644 --- a/apps/backend/internal/task/handlers/task_ws_handlers.go +++ b/apps/backend/internal/task/handlers/task_ws_handlers.go @@ -76,9 +76,10 @@ func (h *TaskHandlers) wsListTasks(ctx context.Context, msg *ws.Message) (*ws.Me h.logger.Error("failed to list tasks", zap.Error(err)) return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to list tasks", nil) } - taskDTOs := make([]dto.TaskDTO, 0, len(tasks)) - for _, task := range tasks { - taskDTOs = append(taskDTOs, dto.FromTask(task)) + taskDTOs, err := h.toTaskDTOsWithSessionInfo(ctx, tasks) + if err != nil { + h.logger.Error("failed to enrich tasks with status summaries", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to list tasks", nil) } resp := dto.ListTasksResponse{ Tasks: taskDTOs, diff --git a/apps/backend/internal/task/repository/interface.go b/apps/backend/internal/task/repository/interface.go index f6a6fe7d3c..ba60ce75ad 100644 --- a/apps/backend/internal/task/repository/interface.go +++ b/apps/backend/internal/task/repository/interface.go @@ -7,6 +7,7 @@ import ( agentdto "github.com/kandev/kandev/internal/agent/dto" "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/task/repository/repoerrors" + "github.com/kandev/kandev/internal/task/statussummary" wfmodels "github.com/kandev/kandev/internal/workflow/models" v1 "github.com/kandev/kandev/pkg/api/v1" ) @@ -126,6 +127,16 @@ type TaskRepository interface { GetWorkspaceTaskPrefix(ctx context.Context, workspaceID string) (prefix, officeWorkflowID string, err error) } +// TaskStatusSummaryRepository stores the bounded task-level projection used by +// list and switcher surfaces. Implementations must compare revisions and the +// semantic payload atomically so retries and concurrent source observations do +// not regress a task or create a revision for a no-op. +type TaskStatusSummaryRepository interface { + LoadTaskStatusSummaries(ctx context.Context, taskIDs []string) (map[string]*statussummary.TaskStatusSummary, error) + CompareAndUpdateTaskStatusSummary(ctx context.Context, stored *statussummary.StoredTaskStatusSummary) (bool, error) + DeleteTaskStatusSummary(ctx context.Context, taskID string) error +} + // TaskRepoRepository handles the task↔repository junction table (models.TaskRepository rows). // Named TaskRepoRepository to reduce reader confusion with the TaskRepository sub-interface above. type TaskRepoRepository interface { @@ -265,6 +276,7 @@ type TaskResourceCleanupRepository interface { type GitSnapshotRepository interface { CreateGitSnapshot(ctx context.Context, snapshot *models.GitSnapshot) error GetLatestGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) + GetLatestGitSnapshotsBySessionIDs(ctx context.Context, sessionIDs []string) (map[string]*models.GitSnapshot, error) GetFirstGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) GetGitSnapshotsBySession(ctx context.Context, sessionID string, limit int) ([]*models.GitSnapshot, error) CreateSessionCommit(ctx context.Context, commit *models.SessionCommit) error diff --git a/apps/backend/internal/task/repository/sqlite/base_migrations.go b/apps/backend/internal/task/repository/sqlite/base_migrations.go index 2fa554ed45..5b733621c4 100644 --- a/apps/backend/internal/task/repository/sqlite/base_migrations.go +++ b/apps/backend/internal/task/repository/sqlite/base_migrations.go @@ -199,6 +199,22 @@ func (r *Repository) runMigrations() error { // "New" divider (see models.TaskSession.LastReadMessageID). r.migrate.Apply("task_sessions.last_read_message_id", `ALTER TABLE task_sessions ADD COLUMN last_read_message_id TEXT DEFAULT ''`) + // Bounded task-level status projection. Keep this on the replay path as well + // as the fresh schema path so an existing installation gets the table + // without a destructive rebuild. + r.migrate.Apply("task_status_summaries.table", ` + CREATE TABLE IF NOT EXISTS task_status_summaries ( + task_id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + revision INTEGER NOT NULL DEFAULT 0, + summary TEXT NOT NULL DEFAULT '{}', + updated_at TIMESTAMP NOT NULL, + FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE + )`) + r.migrate.Apply("task_status_summaries.workspace", ` + CREATE INDEX IF NOT EXISTS idx_task_status_summaries_workspace + ON task_status_summaries(workspace_id)`) + return nil } diff --git a/apps/backend/internal/task/repository/sqlite/base_schema.go b/apps/backend/internal/task/repository/sqlite/base_schema.go index f8f1f1830c..e730f23e3b 100644 --- a/apps/backend/internal/task/repository/sqlite/base_schema.go +++ b/apps/backend/internal/task/repository/sqlite/base_schema.go @@ -159,9 +159,31 @@ func (r *Repository) initCoreSchema() error { if err := r.initTaskSchema(); err != nil { return err } + if err := r.initTaskStatusSummarySchema(); err != nil { + return err + } return r.initCoreIndexes() } +const taskStatusSummarySchemaDDL = ` + CREATE TABLE IF NOT EXISTS task_status_summaries ( + task_id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + revision INTEGER NOT NULL DEFAULT 0, + summary TEXT NOT NULL DEFAULT '{}', + updated_at TIMESTAMP NOT NULL, + FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_task_status_summaries_workspace + ON task_status_summaries(workspace_id); +` + +func (r *Repository) initTaskStatusSummarySchema() error { + _, err := r.db.Exec(taskStatusSummarySchemaDDL) + return err +} + // infraSchemaDDL is the concatenated CREATE TABLE block for infrastructure // tables (workspaces, executors, environments, workflows). Kept as a single // DDL string so the table layout reads top-to-bottom; lives in a const so the diff --git a/apps/backend/internal/task/repository/sqlite/git_snapshots.go b/apps/backend/internal/task/repository/sqlite/git_snapshots.go index ec4cdea04a..6ef466c5d1 100644 --- a/apps/backend/internal/task/repository/sqlite/git_snapshots.go +++ b/apps/backend/internal/task/repository/sqlite/git_snapshots.go @@ -168,11 +168,6 @@ func (r *Repository) getGitSnapshotByOrder(ctx context.Context, sessionID, order // no agent_completed snapshot exists. // Returns sql.ErrNoRows if no snapshot is found. func (r *Repository) GetLatestGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { - snapshot := &models.GitSnapshot{} - var snapshotType string - var filesJSON string - var metadataJSON string - query := ` SELECT id, session_id, snapshot_type, branch, remote_branch, head_commit, base_commit, ahead, behind, files, triggered_by, metadata, created_at @@ -183,16 +178,80 @@ func (r *Repository) GetLatestGitSnapshot(ctx context.Context, sessionID string) created_at DESC LIMIT 1 ` - err := r.ro.QueryRowContext(ctx, r.ro.Rebind(query), sessionID).Scan( + return scanGitSnapshot(r.ro.QueryRowContext(ctx, r.ro.Rebind(query), sessionID)) +} + +// GetLatestGitSnapshotsBySessionIDs loads one authoritative snapshot per +// session in one query per placeholder-sized chunk. It mirrors +// GetLatestGitSnapshot's agent_completed preference without introducing an +// N+1 read when task-list summaries repair historical rows. +func (r *Repository) GetLatestGitSnapshotsBySessionIDs( + ctx context.Context, + sessionIDs []string, +) (map[string]*models.GitSnapshot, error) { + result := make(map[string]*models.GitSnapshot, len(sessionIDs)) + if len(sessionIDs) == 0 { + return result, nil + } + for _, chunk := range chunkIDs(sessionIDs, sqliteMaxHostParams) { + placeholders, args := buildInPlaceholders(chunk) + query := ` + SELECT id, session_id, snapshot_type, branch, remote_branch, head_commit, base_commit, + ahead, behind, files, triggered_by, metadata, created_at + FROM ( + SELECT id, session_id, snapshot_type, branch, remote_branch, head_commit, base_commit, + ahead, behind, files, triggered_by, metadata, created_at, + ROW_NUMBER() OVER ( + PARTITION BY session_id + ORDER BY CASE WHEN triggered_by = 'agent_completed' THEN 0 ELSE 1 END, + created_at DESC + ) AS row_number + FROM task_session_git_snapshots + WHERE session_id IN (` + placeholders + `) + ) ranked + WHERE row_number = 1 + ORDER BY session_id + ` + rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(query), args...) + if err != nil { + return nil, err + } + for rows.Next() { + snapshot, scanErr := scanGitSnapshot(rows) + if scanErr != nil { + _ = rows.Close() + return nil, scanErr + } + if _, exists := result[snapshot.SessionID]; !exists { + result[snapshot.SessionID] = snapshot + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, err + } + _ = rows.Close() + } + return result, nil +} + +type gitSnapshotScanner interface { + Scan(dest ...interface{}) error +} + +func scanGitSnapshot(scanner gitSnapshotScanner) (*models.GitSnapshot, error) { + snapshot := &models.GitSnapshot{} + var snapshotType string + var filesJSON string + var metadataJSON string + if err := scanner.Scan( &snapshot.ID, &snapshot.SessionID, &snapshotType, &snapshot.Branch, &snapshot.RemoteBranch, &snapshot.HeadCommit, &snapshot.BaseCommit, &snapshot.Ahead, &snapshot.Behind, &filesJSON, &snapshot.TriggeredBy, &metadataJSON, &snapshot.CreatedAt, - ) - if err != nil { + ); err != nil { return nil, err } - snapshot.SnapshotType = models.SnapshotType(snapshotType) if filesJSON != "" && filesJSON != "{}" { if err := json.Unmarshal([]byte(filesJSON), &snapshot.Files); err != nil { @@ -204,7 +263,6 @@ func (r *Repository) GetLatestGitSnapshot(ctx context.Context, sessionID string) return nil, fmt.Errorf("failed to deserialize git snapshot metadata: %w", err) } } - return snapshot, nil } diff --git a/apps/backend/internal/task/repository/sqlite/task_status_summary.go b/apps/backend/internal/task/repository/sqlite/task_status_summary.go new file mode 100644 index 0000000000..cfef7a2103 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_status_summary.go @@ -0,0 +1,128 @@ +package sqlite + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/kandev/kandev/internal/task/statussummary" +) + +// LoadTaskStatusSummaries returns the rows present for taskIDs. Missing rows +// are intentionally omitted so callers can retain their coarse task fallback. +// The input is chunked to keep the query portable across SQLite builds. +func (r *Repository) LoadTaskStatusSummaries(ctx context.Context, taskIDs []string) (map[string]*statussummary.TaskStatusSummary, error) { + result := make(map[string]*statussummary.TaskStatusSummary, len(taskIDs)) + if len(taskIDs) == 0 { + return result, nil + } + + for _, chunk := range chunkIDs(taskIDs, sqliteMaxHostParams) { + placeholders, args := buildInPlaceholders(chunk) + query := ` + SELECT task_id, revision, summary, updated_at + FROM task_status_summaries + WHERE task_id IN (` + placeholders + `)` + rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(query), args...) + if err != nil { + return nil, fmt.Errorf("load task status summaries: %w", err) + } + + for rows.Next() { + var ( + taskID string + revision int64 + rawSummary string + updatedAt time.Time + ) + if err := rows.Scan(&taskID, &revision, &rawSummary, &updatedAt); err != nil { + _ = rows.Close() + return nil, fmt.Errorf("scan task status summary: %w", err) + } + if revision < 0 { + _ = rows.Close() + return nil, fmt.Errorf("task status summary %q has negative revision %d", taskID, revision) + } + + var summary statussummary.TaskStatusSummary + if err := json.Unmarshal([]byte(rawSummary), &summary); err != nil { + _ = rows.Close() + return nil, fmt.Errorf("decode task status summary %q: %w", taskID, err) + } + summary.Revision = uint64(revision) + summary.UpdatedAt = updatedAt + if err := summary.Validate(); err != nil { + _ = rows.Close() + return nil, fmt.Errorf("validate task status summary %q: %w", taskID, err) + } + result[taskID] = &summary + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, fmt.Errorf("read task status summaries: %w", err) + } + _ = rows.Close() + } + return result, nil +} + +// CompareAndUpdateTaskStatusSummary inserts a new row or replaces an older +// semantic value. The revision and semantic comparison live in the same SQL +// statement, so concurrent source observations cannot overwrite a newer row. +// RowsAffected is false for an older revision or a semantic no-op. +func (r *Repository) CompareAndUpdateTaskStatusSummary(ctx context.Context, stored *statussummary.StoredTaskStatusSummary) (bool, error) { + if stored == nil { + return false, fmt.Errorf("task status summary is nil") + } + if stored.TaskID == "" { + return false, fmt.Errorf("task status summary task_id is required") + } + if stored.WorkspaceID == "" { + return false, fmt.Errorf("task status summary workspace_id is required") + } + if stored.Summary.Revision == 0 { + return false, fmt.Errorf("task status summary revision must be positive") + } + + updatedAt := stored.Summary.UpdatedAt + if updatedAt.IsZero() { + updatedAt = time.Now().UTC() + } + semanticJSON, err := stored.Summary.SemanticJSON() + if err != nil { + return false, fmt.Errorf("serialize task status summary: %w", err) + } + + result, err := r.db.ExecContext(ctx, r.db.Rebind(` + INSERT INTO task_status_summaries ( + task_id, workspace_id, revision, summary, updated_at + ) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (task_id) DO UPDATE SET + workspace_id = excluded.workspace_id, + revision = excluded.revision, + summary = excluded.summary, + updated_at = excluded.updated_at + WHERE task_status_summaries.revision < excluded.revision + AND ( + task_status_summaries.workspace_id <> excluded.workspace_id + OR task_status_summaries.summary <> excluded.summary + ) + `), stored.TaskID, stored.WorkspaceID, stored.Summary.Revision, string(semanticJSON), updatedAt) + if err != nil { + return false, fmt.Errorf("compare and update task status summary: %w", err) + } + rows, err := result.RowsAffected() + if err != nil { + return false, err + } + return rows > 0, nil +} + +func (r *Repository) DeleteTaskStatusSummary(ctx context.Context, taskID string) error { + if taskID == "" { + return nil + } + _, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM task_status_summaries WHERE task_id = ?`), taskID) + return err +} diff --git a/apps/backend/internal/task/repository/sqlite/task_status_summary_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_status_summary_postgres_test.go new file mode 100644 index 0000000000..3486c11c2a --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_status_summary_postgres_test.go @@ -0,0 +1,55 @@ +package sqlite + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/statussummary" + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresTaskStatusSummarySchemaReplay(t *testing.T) { + db := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("initialize postgres schema: %v", err) + } + + ctx := context.Background() + now := time.Now().UTC() + if _, err := db.Exec(db.Rebind(` + INSERT INTO tasks (id, workspace_id, title, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + `), "task-summary-postgres", "workspace-summary-postgres", "Postgres summary", now, now); err != nil { + t.Fatalf("seed postgres task: %v", err) + } + if _, err := db.Exec(`DROP TABLE task_status_summaries`); err != nil { + t.Fatalf("drop summary table to simulate legacy schema: %v", err) + } + if err := repo.runMigrations(); err != nil { + t.Fatalf("replay postgres migrations: %v", err) + } + + changed, err := repo.CompareAndUpdateTaskStatusSummary(ctx, &statussummary.StoredTaskStatusSummary{ + TaskID: "task-summary-postgres", + WorkspaceID: "workspace-summary-postgres", + Summary: statussummary.TaskStatusSummary{ + Revision: 1, + ForegroundActivity: "background", + }, + }) + if err != nil { + t.Fatalf("insert postgres summary: %v", err) + } + if !changed { + t.Fatal("postgres summary insert reported no change") + } + loaded, err := repo.LoadTaskStatusSummaries(ctx, []string{"task-summary-postgres"}) + if err != nil { + t.Fatalf("load postgres summary: %v", err) + } + if loaded["task-summary-postgres"] == nil || loaded["task-summary-postgres"].Revision != 1 { + t.Fatalf("postgres summary = %#v", loaded["task-summary-postgres"]) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_status_summary_test.go b/apps/backend/internal/task/repository/sqlite/task_status_summary_test.go new file mode 100644 index 0000000000..9093c1175a --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_status_summary_test.go @@ -0,0 +1,225 @@ +package sqlite + +import ( + "context" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/jmoiron/sqlx" + + dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/task/statussummary" +) + +func TestTaskStatusSummarySchemaReplayAndCascade(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "task-status-summary.db") + dbConn, err := dbutil.OpenSQLite(dbPath) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + db := sqlx.NewDb(dbConn, "sqlite3") + t.Cleanup(func() { _ = db.Close() }) + + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("initialize schema: %v", err) + } + + var tableName string + if err := db.Get(&tableName, ` + SELECT name + FROM sqlite_master + WHERE type = 'table' AND name = 'task_status_summaries' + `); err != nil { + t.Fatalf("task status summary table is missing: %v", err) + } + if tableName != "task_status_summaries" { + t.Fatalf("summary table name = %q", tableName) + } + + now := time.Now().UTC() + if _, err := db.Exec(db.Rebind(` + INSERT INTO tasks (id, workspace_id, title, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + `), "task-summary-schema", "workspace-summary-schema", "Summary schema", now, now); err != nil { + t.Fatalf("seed task: %v", err) + } + if _, err := db.Exec(db.Rebind(` + INSERT INTO task_status_summaries (task_id, workspace_id, revision, summary, updated_at) + VALUES (?, ?, ?, ?, ?) + `), "task-summary-schema", "workspace-summary-schema", 1, `{"revision":1}`, now); err != nil { + t.Fatalf("insert summary: %v", err) + } + + if _, err := db.Exec(db.Rebind(`DELETE FROM tasks WHERE id = ?`), "task-summary-schema"); err != nil { + t.Fatalf("delete task: %v", err) + } + var count int + if err := db.Get(&count, db.Rebind(`SELECT COUNT(*) FROM task_status_summaries WHERE task_id = ?`), "task-summary-schema"); err != nil { + t.Fatalf("count cascade rows: %v", err) + } + if count != 0 { + t.Fatalf("summary rows after task deletion = %d, want 0", count) + } + + if err := repo.runMigrations(); err != nil { + t.Fatalf("replay migrations: %v", err) + } + if err := repo.runMigrations(); err != nil { + t.Fatalf("replay migrations twice: %v", err) + } +} + +func TestTaskStatusSummaryBatchCompareAndUpdate(t *testing.T) { + repo, db := newTaskStatusSummaryTestRepo(t) + ctx := context.Background() + seedTaskForStatusSummary(t, db, "task-summary-repository", "workspace-summary-repository") + + first := statussummary.StoredTaskStatusSummary{ + TaskID: "task-summary-repository", + WorkspaceID: "workspace-summary-repository", + Summary: statussummary.TaskStatusSummary{ + Revision: 1, + ForegroundActivity: "background", + Git: &statussummary.GitSummary{ChangedFiles: 3, Additions: 4}, + }, + } + changed, err := repo.CompareAndUpdateTaskStatusSummary(ctx, &first) + if err != nil { + t.Fatalf("insert summary: %v", err) + } + if !changed { + t.Fatal("first summary insert reported no change") + } + + loaded, err := repo.LoadTaskStatusSummaries(ctx, []string{"task-summary-repository", "missing-summary"}) + if err != nil { + t.Fatalf("batch load summaries: %v", err) + } + got := loaded["task-summary-repository"] + if got == nil || got.Revision != 1 || got.ForegroundActivity != "background" || got.Git == nil || got.Git.ChangedFiles != 3 { + t.Fatalf("loaded summary = %#v", got) + } + if _, ok := loaded["missing-summary"]; ok { + t.Fatal("missing summary should be omitted from the batch result") + } + + noOp := first + noOp.Summary.UpdatedAt = time.Now().UTC().Add(time.Hour) + changed, err = repo.CompareAndUpdateTaskStatusSummary(ctx, &noOp) + if err != nil { + t.Fatalf("semantic no-op update: %v", err) + } + if changed { + t.Fatal("semantic no-op created a new row revision") + } + + stale := first + stale.Summary.Revision = 0 + if _, err := repo.CompareAndUpdateTaskStatusSummary(ctx, &stale); err == nil { + t.Fatal("revision zero should be rejected") + } + + next := first + next.Summary.Revision = 2 + next.Summary.ForegroundActivity = "generating" + changed, err = repo.CompareAndUpdateTaskStatusSummary(ctx, &next) + if err != nil { + t.Fatalf("newer summary update: %v", err) + } + if !changed { + t.Fatal("newer semantic summary reported no change") + } + loaded, err = repo.LoadTaskStatusSummaries(ctx, []string{"task-summary-repository"}) + if err != nil { + t.Fatalf("reload summary: %v", err) + } + if loaded["task-summary-repository"].Revision != 2 || loaded["task-summary-repository"].ForegroundActivity != "generating" { + t.Fatalf("newer summary was not retained: %#v", loaded["task-summary-repository"]) + } +} + +func TestTaskStatusSummaryConcurrentUpdatesRemainMonotonic(t *testing.T) { + repo, db := newTaskStatusSummaryTestRepo(t) + ctx := context.Background() + seedTaskForStatusSummary(t, db, "task-summary-concurrent", "workspace-summary-concurrent") + + const updates = 8 + errs := make(chan error, updates) + var wg sync.WaitGroup + for revision := 1; revision <= updates; revision++ { + revision := revision + wg.Add(1) + go func() { + defer wg.Done() + _, err := repo.CompareAndUpdateTaskStatusSummary(ctx, &statussummary.StoredTaskStatusSummary{ + TaskID: "task-summary-concurrent", + WorkspaceID: "workspace-summary-concurrent", + Summary: statussummary.TaskStatusSummary{ + Revision: uint64(revision), + ForegroundActivity: "revision-" + string(rune('a'+revision)), + }, + }) + errs <- err + }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("concurrent update: %v", err) + } + } + + loaded, err := repo.LoadTaskStatusSummaries(ctx, []string{"task-summary-concurrent"}) + if err != nil { + t.Fatalf("load concurrent result: %v", err) + } + if got := loaded["task-summary-concurrent"]; got == nil || got.Revision != updates { + t.Fatalf("concurrent summary = %#v, want revision %d", got, updates) + } +} + +func TestTaskStatusSummaryRejectsMalformedStoredJSON(t *testing.T) { + repo, db := newTaskStatusSummaryTestRepo(t) + seedTaskForStatusSummary(t, db, "task-summary-malformed", "workspace-summary-malformed") + now := time.Now().UTC() + if _, err := db.Exec(db.Rebind(` + INSERT INTO task_status_summaries (task_id, workspace_id, revision, summary, updated_at) + VALUES (?, ?, ?, ?, ?) + `), "task-summary-malformed", "workspace-summary-malformed", 1, "{not-json", now); err != nil { + t.Fatalf("insert malformed summary: %v", err) + } + if _, err := repo.LoadTaskStatusSummaries(context.Background(), []string{"task-summary-malformed"}); err == nil { + t.Fatal("malformed summary should be observable to the caller") + } +} + +func newTaskStatusSummaryTestRepo(t *testing.T) (*Repository, *sqlx.DB) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "task-status-summary-repository.db") + dbConn, err := dbutil.OpenSQLite(dbPath) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + db := sqlx.NewDb(dbConn, "sqlite3") + t.Cleanup(func() { _ = db.Close() }) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("initialize schema: %v", err) + } + return repo, db +} + +func seedTaskForStatusSummary(t *testing.T, db *sqlx.DB, taskID, workspaceID string) { + t.Helper() + now := time.Now().UTC() + if _, err := db.Exec(db.Rebind(` + INSERT INTO tasks (id, workspace_id, title, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + `), taskID, workspaceID, "Status summary task", now, now); err != nil { + t.Fatalf("seed task %q: %v", taskID, err) + } +} diff --git a/apps/backend/internal/task/service/service.go b/apps/backend/internal/task/service/service.go index ea0a90803f..00885167da 100644 --- a/apps/backend/internal/task/service/service.go +++ b/apps/backend/internal/task/service/service.go @@ -215,6 +215,7 @@ type Repos struct { TaskEnvironments repository.TaskEnvironmentRepository Reviews repository.ReviewRepository ResourceCleanups repository.TaskResourceCleanupRepository + StatusSummaries repository.TaskStatusSummaryRepository } // Service provides task business logic @@ -235,6 +236,8 @@ type Service struct { taskEnvironments repository.TaskEnvironmentRepository reviews repository.ReviewRepository resourceCleanups repository.TaskResourceCleanupRepository + statusSummaries repository.TaskStatusSummaryRepository + statusSummaryPRs TaskStatusSummaryPRReader eventBus bus.EventBus logger *logger.Logger discoveryConfig RepositoryDiscoveryConfig @@ -316,6 +319,7 @@ func NewService(repos Repos, eventBus bus.EventBus, log *logger.Logger, discover taskEnvironments: repos.TaskEnvironments, reviews: repos.Reviews, resourceCleanups: repos.ResourceCleanups, + statusSummaries: repos.StatusSummaries, eventBus: eventBus, logger: log, discoveryConfig: discoveryConfig, diff --git a/apps/backend/internal/task/service/service_events.go b/apps/backend/internal/task/service/service_events.go index 8972f31c8f..bea68160bf 100644 --- a/apps/backend/internal/task/service/service_events.go +++ b/apps/backend/internal/task/service/service_events.go @@ -160,6 +160,7 @@ func (s *Service) publishSessionsCancelled( "agent_profile_id": sess.AgentProfileID, "agent_profile_snapshot": sess.AgentProfileSnapshot, "is_passthrough": sess.IsPassthrough, + "is_primary": sess.IsPrimary, sessionEventFieldUpdatedAt: sess.UpdatedAt.Format(time.RFC3339Nano), sessionEventFieldName: sess.Name, } diff --git a/apps/backend/internal/task/service/service_messages.go b/apps/backend/internal/task/service/service_messages.go index a0712e8e04..ad38efe86d 100644 --- a/apps/backend/internal/task/service/service_messages.go +++ b/apps/backend/internal/task/service/service_messages.go @@ -2,6 +2,8 @@ package service import ( "context" + "database/sql" + "errors" "fmt" "time" @@ -102,6 +104,39 @@ func (s *Service) CreateMessage(ctx context.Context, req *CreateMessageRequest) return message, nil } +// CreateMessageIdempotent persists a caller-owned message ID and returns the +// existing row when the request is replayed. A client can lose the response +// after the database commit, so retrying must not create a second user turn. +// The handler performs the fast preflight before session-state side effects; +// this method also closes the concurrent two-request race at the repository +// primary-key boundary. +func (s *Service) CreateMessageIdempotent(ctx context.Context, id string, req *CreateMessageRequest) (*models.Message, error) { + if id == "" { + return nil, errors.New("message id is required for idempotent creation") + } + + existing, err := s.messages.GetMessage(ctx, id) + if err == nil && existing != nil { + return existing, nil + } + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("check existing message: %w", err) + } + + message, err := s.CreateMessageWithID(ctx, id, req) + if err == nil { + return message, nil + } + + // Another request may have won the insert while this request was building + // its turn. Read the committed row and treat that duplicate as success. + existing, lookupErr := s.messages.GetMessage(ctx, id) + if lookupErr == nil && existing != nil { + return existing, nil + } + return nil, err +} + // CreateMessageWithID creates a new message with a pre-generated ID. // This is used for streaming messages where the ID is generated by the caller. // It includes retry logic to handle transient database errors and ensure diff --git a/apps/backend/internal/task/service/service_sessions.go b/apps/backend/internal/task/service/service_sessions.go index 796a5fd46d..9375c660f4 100644 --- a/apps/backend/internal/task/service/service_sessions.go +++ b/apps/backend/internal/task/service/service_sessions.go @@ -9,6 +9,8 @@ import ( "go.uber.org/zap" + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/events/bus" "github.com/kandev/kandev/internal/task/models" ) @@ -125,7 +127,27 @@ func (s *Service) DismissLastAgentError(ctx context.Context, sessionID, stamp st if !updated { return session, nil } - return s.sessions.GetTaskSession(ctx, sessionID) + if s.eventBus != nil { + eventCtx := context.WithoutCancel(ctx) + eventData := map[string]interface{}{ + "task_id": session.TaskID, + "session_id": sessionID, + "active": false, + "stamp": lastErr.Stamp(), + "dismissed_at": now.Format(time.RFC3339Nano), + } + if err := s.eventBus.Publish(eventCtx, events.TaskSessionErrorChanged, bus.NewEvent( + events.TaskSessionErrorChanged, + "task-service", + eventData, + )); err != nil { + s.logger.Warn("failed to publish task session error dismissal event", + zap.String("task_id", session.TaskID), + zap.String("session_id", sessionID), + zap.Error(err)) + } + } + return s.sessions.GetTaskSession(context.WithoutCancel(ctx), sessionID) } // MarkSessionRead advances sessionID's Slack-style read cursor to messageID. diff --git a/apps/backend/internal/task/service/service_status_summary.go b/apps/backend/internal/task/service/service_status_summary.go new file mode 100644 index 0000000000..115a127f81 --- /dev/null +++ b/apps/backend/internal/task/service/service_status_summary.go @@ -0,0 +1,17 @@ +package service + +import ( + "context" + + "github.com/kandev/kandev/internal/task/statussummary" +) + +// GetTaskStatusSummaries batch-loads the bounded task projections used by all +// list/snapshot DTO builders. A nil repository is a safe compatibility state +// for focused tests and installations that have not materialized projections. +func (s *Service) GetTaskStatusSummaries(ctx context.Context, taskIDs []string) (map[string]*statussummary.TaskStatusSummary, error) { + if s == nil || s.statusSummaries == nil { + return map[string]*statussummary.TaskStatusSummary{}, nil + } + return s.statusSummaries.LoadTaskStatusSummaries(ctx, taskIDs) +} diff --git a/apps/backend/internal/task/service/service_status_summary_rebuild.go b/apps/backend/internal/task/service/service_status_summary_rebuild.go new file mode 100644 index 0000000000..19c01e5c62 --- /dev/null +++ b/apps/backend/internal/task/service/service_status_summary_rebuild.go @@ -0,0 +1,323 @@ +package service + +import ( + "context" + "reflect" + "strings" + "time" + + "go.uber.org/zap" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/statussummary" + v1 "github.com/kandev/kandev/pkg/api/v1" +) + +// TaskStatusSummaryPRReader supplies already-persisted provider state for the +// one-time repair of a task whose summary row predates the projector. +type TaskStatusSummaryPRReader interface { + ListTaskStatusSummaryPullRequests( + context.Context, + []string, + ) (map[string][]statussummary.PullRequestInput, error) +} + +// SetTaskStatusSummaryPRReader wires the optional provider-backed PR reader. +// The task service keeps the interface narrow so it does not depend on the +// GitHub package. +func (s *Service) SetTaskStatusSummaryPRReader(reader TaskStatusSummaryPRReader) { + if s != nil { + s.statusSummaryPRs = reader + } +} + +// HydrateMissingTaskStatusSummaries repairs only absent rows. All durable +// inputs are batch-loaded by the caller or by optional batch readers; this is +// intentionally a lazy repair so startup does not scan every historical task. +// The returned map includes both existing and newly repaired summaries. +func (s *Service) HydrateMissingTaskStatusSummaries( + ctx context.Context, + tasks []*models.Task, + sessionsByTask map[string][]*models.TaskSession, + pendingBySession map[string]models.TaskPendingAction, + summaries map[string]*statussummary.TaskStatusSummary, +) (map[string]*statussummary.TaskStatusSummary, error) { + if summaries == nil { + summaries = make(map[string]*statussummary.TaskStatusSummary) + } + if s == nil || s.statusSummaries == nil || len(tasks) == 0 { + return summaries, nil + } + + missing := missingSummaryTasks(tasks, summaries) + if len(missing) == 0 { + return summaries, nil + } + prByTask, prObserved := s.loadSummaryPRs(ctx, taskIDs(missing)) + gitBySession, gitObserved := s.loadSummaryGit(ctx, sessionIDsForTasks(missing, sessionsByTask)) + now := time.Now().UTC() + for _, task := range missing { + if task == nil || task.ID == "" { + continue + } + input := s.rebuildInput( + sessionsByTask[task.ID], + pendingBySession, + gitBySession, + gitObserved, + prByTask[task.ID], + prObserved, + now, + ) + next := statussummary.BuildFromAuthoritative(input) + next.Revision = 1 + next.UpdatedAt = now + if err := next.Validate(); err != nil { + s.logSummaryRepairFailure(task.ID, "validate", err) + continue + } + accepted, err := s.statusSummaries.CompareAndUpdateTaskStatusSummary(ctx, &statussummary.StoredTaskStatusSummary{ + TaskID: task.ID, + WorkspaceID: task.WorkspaceID, + Summary: next, + }) + if err != nil { + s.logSummaryRepairFailure(task.ID, "persist", err) + continue + } + if accepted { + summaries[task.ID] = &next + continue + } + // A projector event may have won the race while this repair was running. + // Return that authoritative row instead of exposing a stale repair. + rows, err := s.statusSummaries.LoadTaskStatusSummaries(ctx, []string{task.ID}) + if err != nil { + s.logSummaryRepairFailure(task.ID, "reload", err) + continue + } + if stored := rows[task.ID]; stored != nil { + summaries[task.ID] = stored + } + } + return summaries, nil +} + +func (s *Service) logSummaryRepairFailure(taskID, stage string, err error) { + if s.logger != nil { + s.logger.Warn("failed to repair task status summary; continuing task list hydration", + zap.String("task_id", taskID), zap.String("stage", stage), zap.Error(err)) + } +} + +func missingSummaryTasks(tasks []*models.Task, summaries map[string]*statussummary.TaskStatusSummary) []*models.Task { + missing := make([]*models.Task, 0, len(tasks)) + for _, task := range tasks { + if task != nil && task.ID != "" && summaries[task.ID] == nil { + missing = append(missing, task) + } + } + return missing +} + +func taskIDs(tasks []*models.Task) []string { + ids := make([]string, 0, len(tasks)) + for _, task := range tasks { + if task != nil && task.ID != "" { + ids = append(ids, task.ID) + } + } + return ids +} + +func sessionIDsForTasks(tasks []*models.Task, sessionsByTask map[string][]*models.TaskSession) []string { + seen := make(map[string]struct{}) + ids := make([]string, 0) + for _, task := range tasks { + if task == nil { + continue + } + for _, session := range sessionsByTask[task.ID] { + if session == nil || session.ID == "" { + continue + } + if _, ok := seen[session.ID]; ok { + continue + } + seen[session.ID] = struct{}{} + ids = append(ids, session.ID) + } + } + return ids +} + +func (s *Service) loadSummaryPRs( + ctx context.Context, + taskIDs []string, +) (map[string][]statussummary.PullRequestInput, bool) { + if s.statusSummaryPRs == nil || len(taskIDs) == 0 { + return nil, false + } + prs, err := s.statusSummaryPRs.ListTaskStatusSummaryPullRequests(ctx, taskIDs) + if err != nil { + if s.logger != nil { + s.logger.Warn("failed to load task PR state for status summary repair", zap.Error(err)) + } + return nil, false + } + return prs, true +} + +func (s *Service) loadSummaryGit( + ctx context.Context, + sessionIDs []string, +) (map[string]*models.GitSnapshot, bool) { + if s.gitSnapshots == nil || len(sessionIDs) == 0 { + return nil, false + } + snapshots, err := s.gitSnapshots.GetLatestGitSnapshotsBySessionIDs(ctx, sessionIDs) + if err != nil { + if s.logger != nil { + s.logger.Warn("failed to load Git state for status summary repair", zap.Error(err)) + } + return nil, false + } + return snapshots, true +} + +func (s *Service) rebuildInput( + sessions []*models.TaskSession, + pendingBySession map[string]models.TaskPendingAction, + gitBySession map[string]*models.GitSnapshot, + gitObserved bool, + prs []statussummary.PullRequestInput, + prObserved bool, + now time.Time, +) statussummary.RebuildInput { + input := statussummary.RebuildInput{ + Sessions: make([]statussummary.RebuildSession, 0, len(sessions)), + PendingActions: make(map[string]string), + ActivityObserved: s.foregroundActivity != nil, + PullRequests: prs, + PRObserved: prObserved, + GitObserved: gitObserved, + Now: now, + } + countProvider, hasCountProvider := s.foregroundActivity.(activeSubagentCountProvider) + for _, session := range sessions { + if session == nil || session.ID == "" { + continue + } + activity := "" + activeSubagentCount := 0 + if s.foregroundActivity != nil { + value := s.foregroundActivity.ForegroundActivity(session.ID) + if session.State == models.TaskSessionStateRunning || value == v1.ForegroundActivityBackground { + activity = string(value) + } + if hasCountProvider { + activeSubagentCount = countProvider.ActiveSubagentCount(session.ID) + } + } + var activeError *statussummary.ActiveErrorSummary + if lastError, ok := models.LoadLastAgentError(session.Metadata); ok && !lastError.IsDismissed() { + activeError = &statussummary.ActiveErrorSummary{ + SessionID: session.ID, + Stamp: lastError.Stamp(), + OccurredAt: lastError.OccurredAt, + Preview: lastError.Message, + } + } + input.Sessions = append(input.Sessions, statussummary.RebuildSession{ + ID: session.ID, + State: string(session.State), + IsPrimary: session.IsPrimary, + ForegroundActivity: activity, + ActiveSubagentCount: activeSubagentCount, + ActiveError: activeError, + }) + if action := string(pendingBySession[session.ID]); strings.TrimSpace(action) != "" { + input.PendingActions[session.ID] = action + } + if snapshot := gitBySession[session.ID]; snapshot != nil { + input.Git = append(input.Git, statussummary.RebuildGit{ + Repository: snapshotRepositoryKey(snapshot, session.ID), + Summary: gitSummaryFromSnapshot(snapshot), + }) + } + } + return input +} + +func snapshotRepositoryKey(snapshot *models.GitSnapshot, fallback string) string { + if snapshot != nil && snapshot.Metadata != nil { + if repository, ok := snapshot.Metadata["repository_name"].(string); ok && strings.TrimSpace(repository) != "" { + return repository + } + } + return fallback +} + +func gitSummaryFromSnapshot(snapshot *models.GitSnapshot) statussummary.GitSummary { + if snapshot == nil { + return statussummary.GitSummary{} + } + return statussummary.GitSummary{ + Additions: nonNegative(snapshot.Metadata, "branch_additions"), + Deletions: nonNegative(snapshot.Metadata, "branch_deletions"), + ChangedFiles: changedFilesFromSnapshot(snapshot), + Ahead: maxInt(snapshot.Ahead, 0), + Behind: maxInt(snapshot.Behind, 0), + } +} + +func changedFilesFromSnapshot(snapshot *models.GitSnapshot) int { + if snapshot == nil { + return 0 + } + count := 0 + for _, key := range []string{"modified", "added", "deleted", "untracked", "renamed"} { + count += collectionLength(snapshot.Metadata[key]) + } + if count == 0 { + count = len(snapshot.Files) + } + return count +} + +func nonNegative(values map[string]interface{}, key string) int { + if values == nil { + return 0 + } + value := values[key] + switch number := value.(type) { + case int: + return maxInt(number, 0) + case int64: + return maxInt(int(number), 0) + case float64: + return maxInt(int(number), 0) + default: + return 0 + } +} + +func collectionLength(value interface{}) int { + if value == nil { + return 0 + } + reflected := reflect.ValueOf(value) + switch reflected.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return reflected.Len() + default: + return 0 + } +} + +func maxInt(value, minimum int) int { + if value < minimum { + return minimum + } + return value +} diff --git a/apps/backend/internal/task/service/service_status_summary_rebuild_test.go b/apps/backend/internal/task/service/service_status_summary_rebuild_test.go new file mode 100644 index 0000000000..c403993ca9 --- /dev/null +++ b/apps/backend/internal/task/service/service_status_summary_rebuild_test.go @@ -0,0 +1,137 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/statussummary" + v1 "github.com/kandev/kandev/pkg/api/v1" +) + +type statusSummaryRebuildPRReader struct { + calls int +} + +func (r *statusSummaryRebuildPRReader) ListTaskStatusSummaryPullRequests( + context.Context, + []string, +) (map[string][]statussummary.PullRequestInput, error) { + r.calls++ + return map[string][]statussummary.PullRequestInput{ + "task-1": {{ + Key: "repo-pr-1", + State: "open", + Number: 42, + URL: "https://github.test/pr/42", + ReviewState: "approved", + ChecksState: "success", + }}, + }, nil +} + +type statusSummaryRebuildActivityProvider struct{} + +func (statusSummaryRebuildActivityProvider) ForegroundActivity(string) v1.ForegroundActivity { + return v1.ForegroundActivityGenerating +} + +func (statusSummaryRebuildActivityProvider) ActiveSubagentCount(string) int { return 3 } + +func TestHydrateMissingTaskStatusSummariesRepairsExistingTaskOnce(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + createTaskWithoutRepositories(t, ctx, repo) + + now := time.Date(2026, 8, 1, 18, 0, 0, 0, time.UTC) + session := &models.TaskSession{ + ID: "session-1", + TaskID: "task-1", + State: models.TaskSessionStateRunning, + IsPrimary: true, + Metadata: map[string]interface{}{ + models.SessionMetaKeyLastAgentError: map[string]interface{}{ + "message": "agent failed to complete the turn", + "occurred_at": now.Add(-time.Minute).Format(time.RFC3339Nano), + }, + }, + } + if err := repo.CreateTaskSession(ctx, session); err != nil { + t.Fatalf("CreateTaskSession: %v", err) + } + if err := repo.CreateGitSnapshot(ctx, &models.GitSnapshot{ + ID: "snapshot-1", + SessionID: session.ID, + SnapshotType: models.SnapshotTypeStatusUpdate, + Ahead: 2, + Behind: 1, + Files: map[string]interface{}{"a.go": map[string]interface{}{}, "b.go": map[string]interface{}{}}, + TriggeredBy: "agent_completed", + Metadata: map[string]interface{}{ + "repository_name": "kandev", + "branch_additions": 5, + "branch_deletions": 2, + }, + CreatedAt: now, + }); err != nil { + t.Fatalf("CreateGitSnapshot: %v", err) + } + + // createTestService predates the status-summary repository field, so wire + // it explicitly here while keeping the shared fixture unchanged. + svc.statusSummaries = repo + svc.SetForegroundActivityProvider(statusSummaryRebuildActivityProvider{}) + prReader := &statusSummaryRebuildPRReader{} + svc.SetTaskStatusSummaryPRReader(prReader) + task := &models.Task{ID: "task-1", WorkspaceID: "ws-1"} + sessions := map[string][]*models.TaskSession{task.ID: {session}} + pending := map[string]models.TaskPendingAction{session.ID: models.TaskPendingActionPermission} + + got, err := svc.HydrateMissingTaskStatusSummaries( + ctx, []*models.Task{task}, sessions, pending, map[string]*statussummary.TaskStatusSummary{}, + ) + if err != nil { + t.Fatalf("HydrateMissingTaskStatusSummaries: %v", err) + } + summary := got[task.ID] + if summary == nil { + t.Fatal("repaired summary missing from returned map") + } + if summary.Revision != 1 || summary.PrimarySession == nil || summary.PrimarySession.ID != session.ID { + t.Fatalf("repaired summary identity = %+v", summary) + } + if summary.PendingAction != string(models.TaskPendingActionPermission) { + t.Fatalf("pending action = %q", summary.PendingAction) + } + if summary.ForegroundActivity != "generating" || summary.ActiveSubagentCount != 3 { + t.Fatalf("activity summary = %+v", summary) + } + if summary.ActiveError == nil || summary.ActiveError.Preview != "agent failed to complete the turn" { + t.Fatalf("active error = %+v", summary.ActiveError) + } + if summary.Git == nil || summary.Git.Additions != 5 || summary.Git.Deletions != 2 || summary.Git.ChangedFiles != 2 { + t.Fatalf("Git summary = %+v", summary.Git) + } + if summary.PullRequest == nil || summary.PullRequest.Number != 42 || summary.PullRequest.AggregateState != "ready" { + t.Fatalf("pull request summary = %+v", summary.PullRequest) + } + if prReader.calls != 1 { + t.Fatalf("PR reader calls = %d, want one batch read", prReader.calls) + } + + persisted, err := repo.LoadTaskStatusSummaries(ctx, []string{task.ID}) + if err != nil { + t.Fatalf("LoadTaskStatusSummaries: %v", err) + } + if persisted[task.ID] == nil || persisted[task.ID].Revision != 1 { + t.Fatalf("persisted summary = %+v", persisted[task.ID]) + } + + if _, err := svc.HydrateMissingTaskStatusSummaries(ctx, []*models.Task{task}, sessions, pending, got); err != nil { + t.Fatalf("second HydrateMissingTaskStatusSummaries: %v", err) + } + if prReader.calls != 1 { + t.Fatalf("PR reader calls after existing summary = %d, want one", prReader.calls) + } +} diff --git a/apps/backend/internal/task/service/service_test.go b/apps/backend/internal/task/service/service_test.go index be0e6a0957..3a7b949ab2 100644 --- a/apps/backend/internal/task/service/service_test.go +++ b/apps/backend/internal/task/service/service_test.go @@ -3150,6 +3150,48 @@ func TestService_CreateMessage(t *testing.T) { } } +func TestService_CreateMessageIdempotentReturnsCommittedMessage(t *testing.T) { + svc, eventBus, repo := createTestService(t) + ctx := context.Background() + + setupTestTask(t, repo) + sessionID := setupTestSession(t, repo) + turnID := setupTestTurn(t, repo, sessionID, "task-123", "turn-idempotent") + request := &CreateMessageRequest{ + TaskSessionID: sessionID, + TaskID: "task-123", + TurnID: turnID, + Content: "the original prompt", + AuthorType: "user", + } + + first, err := svc.CreateMessageIdempotent(ctx, "client-message-1", request) + if err != nil { + t.Fatalf("first create: %v", err) + } + + retry := *request + retry.Content = "the retry should not be stored" + second, err := svc.CreateMessageIdempotent(ctx, "client-message-1", &retry) + if err != nil { + t.Fatalf("retry create: %v", err) + } + if second.ID != first.ID || second.Content != first.Content { + t.Fatalf("retry returned %+v, want original %+v", second, first) + } + if events := eventBus.GetPublishedEvents(); len(events) != 1 { + t.Fatalf("published events = %d, want 1", len(events)) + } + + messages, err := repo.ListMessages(ctx, sessionID) + if err != nil { + t.Fatalf("list messages: %v", err) + } + if len(messages) != 1 { + t.Fatalf("stored messages = %d, want 1", len(messages)) + } +} + func TestService_CreateAgentMessage(t *testing.T) { svc, _, repo := createTestService(t) ctx := context.Background() diff --git a/apps/backend/internal/task/statussummary/constants.go b/apps/backend/internal/task/statussummary/constants.go new file mode 100644 index 0000000000..f7ec677e24 --- /dev/null +++ b/apps/backend/internal/task/statussummary/constants.go @@ -0,0 +1,27 @@ +package statussummary + +const ( + statusPending = "pending" + + pendingPermission = "permission" + pendingClarification = "clarification" + + activityBackground = "background" + activityGenerating = "generating" + + prStateMerged = "merged" + prStateClosed = "closed" + prStateDraft = "draft" + prStateBlocked = "blocked" + prStateFailure = "failure" + prStatePending = "pending" + prStateAwaiting = "awaiting_review" + prStateReady = "ready" + prStatePassing = "passing" + prStateNeutral = "neutral" + prStateOpen = "open" + prStateSuccess = "success" + prStateApproved = "approved" + prStateChanges = "changes_requested" + prStateDirty = "dirty" +) diff --git a/apps/backend/internal/task/statussummary/model.go b/apps/backend/internal/task/statussummary/model.go new file mode 100644 index 0000000000..11e939fbaa --- /dev/null +++ b/apps/backend/internal/task/statussummary/model.go @@ -0,0 +1,199 @@ +// Package statussummary contains the bounded, task-level status projection +// used by task lists and switchers. It deliberately contains no transcript, +// Git file, or provider payload data. +package statussummary + +import ( + "encoding/json" + "fmt" + "reflect" + "time" + "unicode/utf8" +) + +const ( + // MaxActiveErrorPreviewBytes keeps an error decoration safe to send with + // every task row without turning it into a message-stream transport. + MaxActiveErrorPreviewBytes = 512 + maxSessionIDBytes = 256 + maxPendingActionBytes = 128 + maxActiveErrorStampBytes = 64 + maxPullRequestStateBytes = 64 + maxPullRequestURLBytes = 2048 +) + +// TaskStatusSummary is the complete replacement value delivered to task-list +// consumers. Revision and UpdatedAt are transport metadata and are ignored by +// SemanticEqual when deciding whether a projection actually changed. +type TaskStatusSummary struct { + Revision uint64 `json:"revision"` + UpdatedAt time.Time `json:"updated_at"` + PrimarySession *PrimarySessionSummary `json:"primary_session,omitempty"` + ForegroundActivity string `json:"foreground_activity,omitempty"` + ActiveSubagentCount int `json:"active_subagent_count,omitempty"` + PendingAction string `json:"pending_action,omitempty"` + ActiveError *ActiveErrorSummary `json:"active_error,omitempty"` + Git *GitSummary `json:"git,omitempty"` + PullRequest *PullRequestSummary `json:"pull_request,omitempty"` +} + +type PrimarySessionSummary struct { + ID string `json:"id"` + State string `json:"state"` +} + +type ActiveErrorSummary struct { + SessionID string `json:"session_id"` + Stamp string `json:"stamp"` + OccurredAt time.Time `json:"occurred_at"` + Preview string `json:"preview"` +} + +type GitSummary struct { + Additions int `json:"additions,omitempty"` + Deletions int `json:"deletions,omitempty"` + ChangedFiles int `json:"changed_files,omitempty"` + Ahead int `json:"ahead,omitempty"` + Behind int `json:"behind,omitempty"` +} + +// PullRequestSummary is intentionally an aggregate plus one representative +// identity. It is not a list of PR records. +type PullRequestSummary struct { + Count int `json:"count,omitempty"` + OpenCount int `json:"open_count,omitempty"` + Attention bool `json:"attention,omitempty"` + AggregateState string `json:"aggregate_state,omitempty"` + State string `json:"state,omitempty"` + Number int `json:"number,omitempty"` + URL string `json:"url,omitempty"` +} + +// StoredTaskStatusSummary is the persistence boundary for one task. The +// workspace ID is kept beside the payload so future event routing can verify +// ownership without decoding arbitrary summary data. +type StoredTaskStatusSummary struct { + TaskID string + WorkspaceID string + Summary TaskStatusSummary +} + +// SemanticEqual compares only fields that task consumers observe as status. +func (s TaskStatusSummary) SemanticEqual(other TaskStatusSummary) bool { + s.Revision = 0 + s.UpdatedAt = time.Time{} + other.Revision = 0 + other.UpdatedAt = time.Time{} + return reflect.DeepEqual(s, other) +} + +// Validate enforces the bounded fields at the persistence boundary. Other +// source-specific limits belong to the projector that derives this model. +func (s TaskStatusSummary) Validate() error { + if s.ActiveSubagentCount < 0 { + return fmt.Errorf("active subagent count cannot be negative") + } + if err := validatePrimarySession(s.PrimarySession); err != nil { + return err + } + if err := validateUTF8Bytes("pending action", s.PendingAction, maxPendingActionBytes); err != nil { + return err + } + if err := validateActiveError(s.ActiveError); err != nil { + return err + } + return validatePullRequest(s.PullRequest) +} + +func validatePrimarySession(session *PrimarySessionSummary) error { + if session == nil { + return nil + } + if err := validateUTF8Bytes("primary session id", session.ID, maxSessionIDBytes); err != nil { + return err + } + return validateUTF8Bytes("primary session state", session.State, maxPendingActionBytes) +} + +func validateActiveError(activeError *ActiveErrorSummary) error { + if activeError == nil { + return nil + } + fields := []struct { + name string + value string + limit int + }{ + {"active error session id", activeError.SessionID, maxSessionIDBytes}, + {"active error stamp", activeError.Stamp, maxSessionIDBytes}, + {"active error preview", activeError.Preview, MaxActiveErrorPreviewBytes}, + } + for _, field := range fields { + if err := validateUTF8Bytes(field.name, field.value, field.limit); err != nil { + return err + } + } + return nil +} + +func validatePullRequest(pr *PullRequestSummary) error { + if pr == nil { + return nil + } + if pr.Count < 0 || pr.OpenCount < 0 || pr.Number < 0 { + return fmt.Errorf("pull request counts and number cannot be negative") + } + fields := []struct { + name string + value string + limit int + }{ + {"pull request state", pr.State, maxPullRequestStateBytes}, + {"pull request aggregate state", pr.AggregateState, maxPullRequestStateBytes}, + {"pull request URL", pr.URL, maxPullRequestURLBytes}, + } + for _, field := range fields { + if err := validateUTF8Bytes(field.name, field.value, field.limit); err != nil { + return err + } + } + return nil +} + +func validateUTF8Bytes(field, value string, maxBytes int) error { + if !utf8.ValidString(value) { + return fmt.Errorf("%s must be valid UTF-8", field) + } + if len(value) > maxBytes { + return fmt.Errorf("%s exceeds %d bytes", field, maxBytes) + } + return nil +} + +// SemanticJSON returns the canonical payload stored in SQLite/Postgres. The +// revision and timestamp are columns so retries with a newer revision can be +// compared without making timestamps part of semantic equality. +func (s TaskStatusSummary) SemanticJSON() ([]byte, error) { + if err := s.Validate(); err != nil { + return nil, err + } + return json.Marshal(semanticPayload{ + PrimarySession: s.PrimarySession, + ForegroundActivity: s.ForegroundActivity, + ActiveSubagentCount: s.ActiveSubagentCount, + PendingAction: s.PendingAction, + ActiveError: s.ActiveError, + Git: s.Git, + PullRequest: s.PullRequest, + }) +} + +type semanticPayload struct { + PrimarySession *PrimarySessionSummary `json:"primary_session,omitempty"` + ForegroundActivity string `json:"foreground_activity,omitempty"` + ActiveSubagentCount int `json:"active_subagent_count,omitempty"` + PendingAction string `json:"pending_action,omitempty"` + ActiveError *ActiveErrorSummary `json:"active_error,omitempty"` + Git *GitSummary `json:"git,omitempty"` + PullRequest *PullRequestSummary `json:"pull_request,omitempty"` +} diff --git a/apps/backend/internal/task/statussummary/model_test.go b/apps/backend/internal/task/statussummary/model_test.go new file mode 100644 index 0000000000..e2f26e512a --- /dev/null +++ b/apps/backend/internal/task/statussummary/model_test.go @@ -0,0 +1,75 @@ +package statussummary + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestTaskStatusSummarySemanticEqualityIgnoresTransportMetadata(t *testing.T) { + first := TaskStatusSummary{ + Revision: 1, + UpdatedAt: time.Now().UTC(), + PrimarySession: &PrimarySessionSummary{ + ID: "session-1", State: "WAITING_FOR_INPUT", + }, + ActiveError: &ActiveErrorSummary{SessionID: "session-1", Stamp: "error-1", Preview: "failed"}, + } + second := first + second.Revision = 9 + second.UpdatedAt = first.UpdatedAt.Add(time.Hour) + if !first.SemanticEqual(second) { + t.Fatal("revision and updated_at should not affect semantic equality") + } + + second.PrimarySession = &PrimarySessionSummary{ID: "session-1", State: "RUNNING"} + if first.SemanticEqual(second) { + t.Fatal("observed status changes must not compare equal") + } +} + +func TestTaskStatusSummarySemanticJSONIsBoundedAndOmitsTransportMetadata(t *testing.T) { + summary := TaskStatusSummary{ + Revision: 4, + UpdatedAt: time.Now().UTC(), + ActiveError: &ActiveErrorSummary{ + SessionID: "session-1", + Stamp: "error-1", + Preview: "safe preview", + }, + Git: &GitSummary{ChangedFiles: 2, Additions: 3}, + } + payload, err := summary.SemanticJSON() + if err != nil { + t.Fatalf("semantic JSON: %v", err) + } + if strings.Contains(string(payload), `"revision"`) || strings.Contains(string(payload), `"updated_at"`) { + t.Fatalf("semantic payload contains transport metadata: %s", payload) + } + var decoded TaskStatusSummary + if err := json.Unmarshal(payload, &decoded); err != nil { + t.Fatalf("decode semantic JSON: %v", err) + } + if !summary.SemanticEqual(decoded) { + t.Fatalf("semantic round trip changed value: %#v", decoded) + } +} + +func TestTaskStatusSummaryValidateBoundsErrorPreview(t *testing.T) { + valid := TaskStatusSummary{ActiveError: &ActiveErrorSummary{Preview: strings.Repeat("é", MaxActiveErrorPreviewBytes/2)}} + if err := valid.Validate(); err != nil { + t.Fatalf("valid UTF-8 preview rejected: %v", err) + } + + tooLarge := valid + tooLarge.ActiveError = &ActiveErrorSummary{Preview: strings.Repeat("x", MaxActiveErrorPreviewBytes+1)} + if err := tooLarge.Validate(); err == nil { + t.Fatal("oversized preview should be rejected") + } + + invalidUTF8 := TaskStatusSummary{ActiveError: &ActiveErrorSummary{Preview: string([]byte{0xff})}} + if err := invalidUTF8.Validate(); err == nil { + t.Fatal("invalid UTF-8 preview should be rejected") + } +} diff --git a/apps/backend/internal/task/statussummary/projector.go b/apps/backend/internal/task/statussummary/projector.go new file mode 100644 index 0000000000..c5900767c6 --- /dev/null +++ b/apps/backend/internal/task/statussummary/projector.go @@ -0,0 +1,883 @@ +package statussummary + +import ( + "context" + "fmt" + "strings" + "sync" + "time" + + "go.uber.org/zap" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/events/bus" +) + +// SummaryStore is the small persistence boundary needed by the live +// projector. Keeping it local to this package avoids making the projector +// depend on the task repository package, which already imports this model. +type SummaryStore interface { + LoadTaskStatusSummaries(ctx context.Context, taskIDs []string) (map[string]*TaskStatusSummary, error) + CompareAndUpdateTaskStatusSummary(ctx context.Context, stored *StoredTaskStatusSummary) (bool, error) +} + +// WorkspaceResolver fills in workspace ownership for source events that only +// carry task_id (session, message, and Git observations historically do not +// include workspace_id in their payloads). +type WorkspaceResolver func(context.Context, string) (string, error) + +// GitObservation is the bounded source state for one repository. It is kept +// internal to the projector and never serialized into the task summary. +type GitObservation struct { + Repository string + Summary GitSummary +} + +// GitObservationLoader rehydrates the keyed repository observations that are +// needed when a projector is recreated after a process restart. +type GitObservationLoader func(context.Context, string) ([]GitObservation, error) + +// SummaryUpdated is the complete replacement payload sent to workspace +// subscribers. It intentionally contains no transcript, file list, or source +// event payload. +type SummaryUpdated struct { + TaskID string `json:"task_id"` + WorkspaceID string `json:"workspace_id"` + Summary TaskStatusSummary `json:"status_summary"` +} + +// GetWorkspaceID lets the WebSocket broadcaster route the event without +// reflecting into the replacement payload. +func (e SummaryUpdated) GetWorkspaceID() string { return e.WorkspaceID } + +type ProjectorConfig struct { + Store SummaryStore + EventBus bus.EventBus + ResolveWorkspace WorkspaceResolver + LoadGitObservations GitObservationLoader + Logger *logger.Logger + Now func() time.Time +} + +// Projector converts authoritative, bounded occurrences into one complete +// task summary. It serializes source application and persistence per task so +// independent tasks do not block one another during a burst. Raw stream events +// are never subscribed to here. +type Projector struct { + store SummaryStore + eventBus bus.EventBus + resolveWorkspace WorkspaceResolver + loadGitObservations GitObservationLoader + logger *logger.Logger + now func() time.Time + + mu sync.Mutex + state map[string]*projectionState + taskLockMu sync.Mutex + taskLocks map[string]*taskProjectionLock + subs []bus.Subscription +} + +type taskProjectionLock struct { + mu sync.Mutex + refs int +} + +type projectionState struct { + workspaceID string + revision uint64 + current *TaskStatusSummary + sessions map[string]sessionObservation + pending map[string]string + taskPending string + pendingObserved bool + activityObserved bool + errors map[string]*ActiveErrorSummary + errorsObserved bool + git map[string]GitSummary + gitBaseline *GitSummary + gitObserved bool + prs map[string]pullRequestObservation + prBaseline *PullRequestSummary + prObserved bool +} + +type sessionObservation struct { + id string + state string + isPrimary bool + foregroundActivity string + activeSubagentCount int +} + +type pullRequestObservation struct { + state string + number int + url string + reviewState string + checksState string + mergeableState string + unresolvedReviewCount int + pendingReviewCount int + requiredReviews int + checksTotal int + checksPassing int +} + +func NewProjector(cfg ProjectorConfig) *Projector { + log := cfg.Logger + if log == nil { + log = logger.Default() + } + now := cfg.Now + if now == nil { + now = func() time.Time { return time.Now().UTC() } + } + return &Projector{ + store: cfg.Store, + eventBus: cfg.EventBus, + resolveWorkspace: cfg.ResolveWorkspace, + loadGitObservations: cfg.LoadGitObservations, + logger: log.WithFields(zap.String("component", "task-status-summary-projector")), + now: now, + state: make(map[string]*projectionState), + taskLocks: make(map[string]*taskProjectionLock), + } +} + +// Start subscribes only to source occurrences that can affect a summary. +// In particular, it does not subscribe to agent.stream, shell, process, +// model, MCP, or per-message streaming subjects. +func (p *Projector) Start(ctx context.Context) error { + if p == nil || p.eventBus == nil { + return nil + } + patterns := []string{ + events.TaskUpdated, + events.TaskSessionStateChanged, + events.TaskSessionActivityChanged, + events.TaskSessionErrorChanged, + events.MessageAdded, + events.MessageUpdated, + events.MessageDeleted, + events.ClarificationAnswered, + events.ClarificationPrimaryAnswered, + events.ClarificationCancelled, + events.ClarificationStaleDismissed, + events.BuildPermissionRequestWildcardSubject(), + events.BuildGitEventWildcardSubject(), + events.GitHubTaskPRUpdated, + } + for _, pattern := range patterns { + sub, err := p.eventBus.Subscribe(pattern, p.handleEvent) + if err != nil { + p.Close() + return fmt.Errorf("subscribe task status summary source %q: %w", pattern, err) + } + p.subs = append(p.subs, sub) + } + go func() { + <-ctx.Done() + p.Close() + }() + return nil +} + +func (p *Projector) Close() { + if p == nil { + return + } + p.mu.Lock() + subs := p.subs + p.subs = nil + p.mu.Unlock() + for _, sub := range subs { + if sub != nil && sub.IsValid() { + _ = sub.Unsubscribe() + } + } +} + +// HandleEvent is exported for focused tests and for callers that already +// multiplex event-bus subscriptions. Start normally installs it directly. +func (p *Projector) HandleEvent(ctx context.Context, event *bus.Event) error { + return p.handleEvent(ctx, event) +} + +func (p *Projector) handleEvent(ctx context.Context, event *bus.Event) error { + if event == nil { + return nil + } + data, err := eventDataMap(event.Data) + if err != nil { + return err + } + taskID := stringField(data, "task_id") + if taskID == "" { + return nil + } + + unlockTask := p.lockTask(taskID) + defer unlockTask() + + state, err := p.ensureState(ctx, taskID) + if err != nil { + return err + } + if workspaceID := stringField(data, "workspace_id"); workspaceID != "" { + state.workspaceID = workspaceID + } + if state.workspaceID == "" && p.resolveWorkspace != nil { + state.workspaceID, err = p.resolveWorkspace(ctx, taskID) + if err != nil { + return fmt.Errorf("resolve task workspace %q: %w", taskID, err) + } + } + if state.workspaceID == "" { + return fmt.Errorf("task status summary %q has no workspace", taskID) + } + + changed := p.applySourceEventLocked(state, event.Type, data) + if !changed { + return nil + } + return p.persistAndPublishLocked(ctx, taskID, state) +} + +func (p *Projector) applySourceEventLocked(state *projectionState, eventType string, data map[string]interface{}) bool { + switch eventType { + case events.TaskUpdated: + return p.applyTaskUpdatedEventLocked(state, data) + case events.TaskSessionStateChanged: + return p.applySessionEventLocked(state, data) + case events.TaskSessionActivityChanged: + return p.applyActivityEventLocked(state, data) + case events.TaskSessionErrorChanged: + return p.applyErrorEventLocked(state, data) + case events.MessageAdded, events.MessageUpdated, events.MessageDeleted: + return p.applyMessageEventLocked(state, eventType, data) + case events.ClarificationAnswered, events.ClarificationPrimaryAnswered, + events.ClarificationCancelled, events.ClarificationStaleDismissed: + return p.clearPendingLocked(state, stringField(data, "session_id")) + case events.PermissionRequestReceived: + return applyPermissionEventLocked(state, data) + case events.GitEvent: + return p.applyGitEventLocked(state, data) + case events.GitHubTaskPRUpdated: + return p.applyPREventLocked(state, data) + default: + return false + } +} + +func applyPermissionEventLocked(state *projectionState, data map[string]interface{}) bool { + sessionID := stringField(data, "session_id") + if sessionID == "" || state.pending[sessionID] == pendingPermission { + return false + } + state.pendingObserved = true + state.pending[sessionID] = pendingPermission + return true +} + +func (p *Projector) lockTask(taskID string) func() { + p.taskLockMu.Lock() + lock := p.taskLocks[taskID] + if lock == nil { + lock = &taskProjectionLock{} + p.taskLocks[taskID] = lock + } + lock.refs++ + p.taskLockMu.Unlock() + + lock.mu.Lock() + return func() { + lock.mu.Unlock() + p.taskLockMu.Lock() + lock.refs-- + if lock.refs == 0 && p.taskLocks[taskID] == lock { + delete(p.taskLocks, taskID) + } + p.taskLockMu.Unlock() + } +} + +func (p *Projector) applyTaskUpdatedEventLocked(state *projectionState, data map[string]interface{}) bool { + primarySessionID, primaryChanged := p.applyTaskPrimaryUpdateLocked(state, data) + pendingChanged := applyTaskPendingUpdateLocked(state, data, primarySessionID) + return primaryChanged || pendingChanged +} + +func (p *Projector) applyTaskPrimaryUpdateLocked(state *projectionState, data map[string]interface{}) (string, bool) { + if _, ok := data["foreground_activity"]; ok { + state.activityObserved = true + } + if _, ok := data["active_subagent_count"]; ok { + state.activityObserved = true + } + primaryValue, primaryPresent := data["primary_session_id"] + if !primaryPresent { + return "", false + } + primarySessionID := stringFromNullable(primaryValue) + changed := updatePrimaryFlagsLocked(state, primarySessionID) + if primarySessionID == "" { + return primarySessionID, changed + } + observation := state.sessions[primarySessionID] + observation.id = primarySessionID + observation.isPrimary = true + changed = updatePrimaryObservation(&observation, data) || changed + state.sessions[primarySessionID] = observation + return primarySessionID, changed +} + +func updatePrimaryFlagsLocked(state *projectionState, primarySessionID string) bool { + changed := false + for sessionID, observation := range state.sessions { + wantPrimary := primarySessionID != "" && sessionID == primarySessionID + if observation.isPrimary == wantPrimary { + continue + } + observation.isPrimary = wantPrimary + state.sessions[sessionID] = observation + changed = true + } + return changed +} + +func updatePrimaryObservation(observation *sessionObservation, data map[string]interface{}) bool { + changed := false + if stateValue := stringFromNullable(data["primary_session_state"]); stateValue != "" && observation.state != stateValue { + observation.state = stateValue + changed = true + } + if activity, ok := data["foreground_activity"]; ok { + value := stringFromNullable(activity) + if observation.foregroundActivity != value { + observation.foregroundActivity = value + changed = true + } + } + if count, ok := intValue(data["active_subagent_count"]); ok { + count = maxInt(count, 0) + if observation.activeSubagentCount != count { + observation.activeSubagentCount = count + changed = true + } + } + return changed +} + +func applyTaskPendingUpdateLocked(state *projectionState, data map[string]interface{}, primarySessionID string) bool { + changed := false + if pending, ok := data["task_pending_action"]; ok { + state.pendingObserved = true + value := stringFromNullable(pending) + if len(state.pending) > 0 { + state.pending = make(map[string]string) + changed = true + } + if state.taskPending != value { + state.taskPending = value + changed = true + } + } + if pending, ok := data["primary_session_pending_action"]; ok && primarySessionID != "" { + state.pendingObserved = true + changed = updateSessionPendingLocked(state, primarySessionID, stringFromNullable(pending)) || changed + } + return changed +} + +func updateSessionPendingLocked(state *projectionState, sessionID, action string) bool { + if action == "" { + if _, exists := state.pending[sessionID]; exists { + delete(state.pending, sessionID) + return true + } + return false + } + if state.pending[sessionID] == action { + return false + } + state.pending[sessionID] = action + return true +} + +func newProjectionState() *projectionState { + return &projectionState{ + sessions: make(map[string]sessionObservation), + pending: make(map[string]string), + errors: make(map[string]*ActiveErrorSummary), + git: make(map[string]GitSummary), + prs: make(map[string]pullRequestObservation), + } +} + +// ensureState performs persistence and source rehydration outside the global +// projector mutex. The per-task lock held by handleEvent still serializes all +// updates for this task, while unrelated tasks remain responsive during I/O. +func (p *Projector) ensureState(ctx context.Context, taskID string) (*projectionState, error) { + p.mu.Lock() + if state := p.state[taskID]; state != nil { + p.mu.Unlock() + return state, nil + } + p.mu.Unlock() + + state := newProjectionState() + if err := p.restorePersistedState(ctx, taskID, state); err != nil { + return nil, err + } + + p.mu.Lock() + defer p.mu.Unlock() + if existing := p.state[taskID]; existing != nil { + return existing, nil + } + p.state[taskID] = state + return state, nil +} + +func (p *Projector) restorePersistedState(ctx context.Context, taskID string, state *projectionState) error { + if p.store == nil { + return nil + } + rows, err := p.store.LoadTaskStatusSummaries(ctx, []string{taskID}) + if err != nil { + return fmt.Errorf("load task status summary %q: %w", taskID, err) + } + summary := rows[taskID] + if summary == nil { + return nil + } + state.current = cloneSummary(summary) + state.revision = summary.Revision + state.taskPending = summary.PendingAction + if summary.PrimarySession != nil && summary.PrimarySession.ID != "" { + state.sessions[summary.PrimarySession.ID] = sessionObservation{ + id: summary.PrimarySession.ID, + state: summary.PrimarySession.State, + isPrimary: true, + } + } + if summary.ActiveError != nil && summary.ActiveError.SessionID != "" { + copy := *summary.ActiveError + state.errors[summary.ActiveError.SessionID] = © + } + if summary.Git != nil { + copy := *summary.Git + state.gitBaseline = © + if err := p.restoreGitObservations(ctx, taskID, state); err != nil { + return err + } + } + if summary.PullRequest != nil { + copy := *summary.PullRequest + state.prBaseline = © + } + return nil +} + +func (p *Projector) restoreGitObservations(ctx context.Context, taskID string, state *projectionState) error { + if p.loadGitObservations == nil { + return nil + } + observations, err := p.loadGitObservations(ctx, taskID) + if err != nil { + return fmt.Errorf("load Git observations for task status summary %q: %w", taskID, err) + } + for _, observation := range observations { + if strings.TrimSpace(observation.Repository) == "" { + continue + } + state.git[observation.Repository] = observation.Summary + } + state.gitObserved = true + return nil +} + +func (p *Projector) applySessionEventLocked(state *projectionState, data map[string]interface{}) bool { + sessionID := firstString(data, "session_id", "primary_session_id") + if sessionID == "" { + return false + } + observation := state.sessions[sessionID] + observation.id = sessionID + if value := firstString(data, "new_state", "state", "primary_session_state"); value != "" { + observation.state = value + } + if value, ok := data["is_primary"].(bool); ok { + observation.isPrimary = value + if value { + for otherID, other := range state.sessions { + if otherID == sessionID || !other.isPrimary { + continue + } + other.isPrimary = false + state.sessions[otherID] = other + } + } + } else if stringField(data, "primary_session_id") == sessionID { + observation.isPrimary = true + } + if value, ok := data["foreground_activity"]; ok { + state.activityObserved = true + observation.foregroundActivity = stringFromNullable(value) + } + if value, ok := intValue(data["active_subagent_count"]); ok { + state.activityObserved = true + observation.activeSubagentCount = maxInt(value, 0) + } + state.sessions[sessionID] = observation + + changed := true + if metadata, ok := data["session_metadata"].(map[string]interface{}); ok { + if errSummary, present := errorFromMetadata(p.now().UTC(), sessionID, metadata); present { + state.errorsObserved = true + changed = !errorEqual(state.errors[sessionID], errSummary) || changed + state.errors[sessionID] = errSummary + } + } + return changed +} + +func (p *Projector) applyActivityEventLocked(state *projectionState, data map[string]interface{}) bool { + sessionID := stringField(data, "session_id") + if sessionID == "" { + return false + } + observation := state.sessions[sessionID] + observation.id = sessionID + if value, ok := data["foreground_activity"]; ok { + state.activityObserved = true + observation.foregroundActivity = stringFromNullable(value) + } + if value, ok := intValue(data["active_subagent_count"]); ok { + state.activityObserved = true + observation.activeSubagentCount = maxInt(value, 0) + } + state.sessions[sessionID] = observation + return true +} + +func (p *Projector) applyErrorEventLocked(state *projectionState, data map[string]interface{}) bool { + sessionID := stringField(data, "session_id") + if sessionID == "" { + return false + } + state.errorsObserved = true + if active, ok := data["active"].(bool); ok && !active { + return p.clearErrorLocked(state, sessionID) + } + errSummary, ok := errorFromMap(p.now().UTC(), sessionID, data) + if !ok { + return false + } + if errorEqual(state.errors[sessionID], errSummary) { + return false + } + state.errors[sessionID] = errSummary + return true +} + +func (p *Projector) applyMessageEventLocked(state *projectionState, eventType string, data map[string]interface{}) bool { + sessionID := stringField(data, "session_id") + if sessionID == "" { + return false + } + changed := p.clearSupersededErrorFromMessageLocked(state, eventType, sessionID, data) + pendingChanged := p.applyPendingMessageLocked(state, eventType, data, sessionID) + return changed || pendingChanged +} + +func (p *Projector) clearSupersededErrorFromMessageLocked( + state *projectionState, + eventType, sessionID string, + data map[string]interface{}, +) bool { + if eventType != events.MessageAdded || stringField(data, "author_type") != "agent" { + return false + } + messageType := strings.ToLower(stringField(data, "type")) + metadata, _ := data["metadata"].(map[string]interface{}) + if messageType == "error" || messageType == "status" || stringField(metadata, "variant") == "error" { + return false + } + return p.clearErrorLocked(state, sessionID) +} + +func (p *Projector) applyPendingMessageLocked(state *projectionState, eventType string, data map[string]interface{}, sessionID string) bool { + messageType := strings.ToLower(stringField(data, "type")) + metadata, _ := data["metadata"].(map[string]interface{}) + status := strings.ToLower(stringField(metadata, "status")) + isPendingMessage := boolValue(data["requests_input"]) || + messageType == "clarification_request" || messageType == "permission_request" + isTrackedMessage := isPendingMessage || stringField(metadata, "pending_id") != "" || status != "" + if !isTrackedMessage { + return false + } + state.pendingObserved = true + if eventType == events.MessageDeleted || (!isPendingMessage && status != "" && status != statusPending) { + return p.clearPendingLocked(state, sessionID) + } + action := pendingPermission + if messageType == "clarification_request" || boolValue(data["requests_input"]) { + action = pendingClarification + } + if state.pending[sessionID] == action { + return false + } + state.pending[sessionID] = action + return true +} + +func (p *Projector) applyGitEventLocked(state *projectionState, data map[string]interface{}) bool { + if stringField(data, "type") != "status_update" { + return false + } + status, _ := data["status"].(map[string]interface{}) + if status == nil { + return false + } + repository := firstString(status, "repository_name", "repository") + if repository == "" { + repository = stringField(data, "session_id") + } + if repository == "" { + return false + } + if !state.gitObserved { + state.git = make(map[string]GitSummary) + state.gitBaseline = nil + state.gitObserved = true + } + observation := GitSummary{ + Additions: nonNegativeInt(status, "branch_additions", "additions"), + Deletions: nonNegativeInt(status, "branch_deletions", "deletions"), + ChangedFiles: changedFileCount(status), + Ahead: nonNegativeInt(status, "ahead"), + Behind: nonNegativeInt(status, "behind"), + } + if equalGitSummary(state.git[repository], observation) { + return false + } + state.git[repository] = observation + return true +} + +func (p *Projector) applyPREventLocked(state *projectionState, data map[string]interface{}) bool { + key := pullRequestObservationKey(data) + if key == "" { + return false + } + if !state.prObserved { + state.prs = make(map[string]pullRequestObservation) + state.prBaseline = nil + state.prObserved = true + } + observation := pullRequestObservation{ + state: stringField(data, "state"), + number: intValueOrZero(data["pr_number"]), + url: stringField(data, "pr_url"), + reviewState: stringField(data, "review_state"), + checksState: stringField(data, "checks_state"), + mergeableState: stringField(data, "mergeable_state"), + unresolvedReviewCount: intValueOrZero(data["unresolved_review_threads"]), + pendingReviewCount: intValueOrZero(data["pending_review_count"]), + checksTotal: intValueOrZero(data["checks_total"]), + checksPassing: intValueOrZero(data["checks_passing"]), + } + if value, ok := intValue(data["required_reviews"]); ok { + observation.requiredReviews = maxInt(value, 0) + } + if existing, ok := state.prs[key]; ok && existing == observation { + return false + } + state.prs[key] = observation + return true +} + +func pullRequestObservationKey(data map[string]interface{}) string { + repository := firstString(data, "repository_id", "repository") + number := intValueOrZero(data["pr_number"]) + url := firstString(data, "pr_url", "url") + if repository != "" && number > 0 { + return fmt.Sprintf("%s#%d", repository, number) + } + if url != "" { + return url + } + if repository != "" { + return repository + } + if number > 0 { + return fmt.Sprintf("#%d", number) + } + return "" +} + +func (p *Projector) persistAndPublishLocked(ctx context.Context, taskID string, state *projectionState) error { + next := deriveSummary(state) + if state.current != nil && state.current.SemanticEqual(next) { + return nil + } + if state.revision == ^uint64(0) { + return fmt.Errorf("task status summary %q revision overflow", taskID) + } + next.Revision = state.revision + 1 + next.UpdatedAt = p.now().UTC() + if err := next.Validate(); err != nil { + return fmt.Errorf("validate projected task status summary %q: %w", taskID, err) + } + if p.store == nil { + return fmt.Errorf("task status summary store is unavailable") + } + accepted, err := p.store.CompareAndUpdateTaskStatusSummary(ctx, &StoredTaskStatusSummary{ + TaskID: taskID, + WorkspaceID: state.workspaceID, + Summary: next, + }) + if err != nil { + return fmt.Errorf("persist projected task status summary %q: %w", taskID, err) + } + if !accepted { + rows, loadErr := p.store.LoadTaskStatusSummaries(ctx, []string{taskID}) + if loadErr != nil { + return fmt.Errorf("reload projected task status summary %q: %w", taskID, loadErr) + } + if stored := rows[taskID]; stored != nil { + state.current = cloneSummary(stored) + state.revision = stored.Revision + } + return nil + } + state.current = cloneSummary(&next) + state.revision = next.Revision + if p.eventBus != nil { + payload := SummaryUpdated{TaskID: taskID, WorkspaceID: state.workspaceID, Summary: next} + if err := p.eventBus.Publish(ctx, events.TaskStatusSummaryUpdated, + bus.NewEvent(events.TaskStatusSummaryUpdated, "task-status-summary", payload)); err != nil { + return fmt.Errorf("publish task status summary %q: %w", taskID, err) + } + } + return nil +} + +func deriveSummary(state *projectionState) TaskStatusSummary { + primary, foregroundActivity, activeSubagentCount := deriveSessionFields(state) + return TaskStatusSummary{ + PrimarySession: primary, + ForegroundActivity: foregroundActivity, + ActiveSubagentCount: activeSubagentCount, + PendingAction: derivePendingAction(state), + ActiveError: deriveActiveError(state), + Git: deriveGitSummary(state), + PullRequest: derivePullRequestSummary(state), + } +} + +func deriveSessionFields(state *projectionState) (*PrimarySessionSummary, string, int) { + var primary *sessionObservation + activities := make([]string, 0, len(state.sessions)) + activeSubagentCount := 0 + for _, session := range state.sessions { + if session.isPrimary && (primary == nil || session.id < primary.id) { + copy := session + primary = © + } + if state.activityObserved { + if session.state == "RUNNING" || session.foregroundActivity == activityBackground { + activities = append(activities, session.foregroundActivity) + } + if isActiveSessionState(session.state) { + activeSubagentCount += maxInt(session.activeSubagentCount, 0) + } + } + } + var primarySummary *PrimarySessionSummary + if primary != nil { + primarySummary = &PrimarySessionSummary{ID: primary.id, State: primary.state} + } + foregroundActivity := "" + if state.activityObserved { + foregroundActivity = deriveForegroundActivity(activities) + } else if state.current != nil { + foregroundActivity = state.current.ForegroundActivity + activeSubagentCount = state.current.ActiveSubagentCount + } + return primarySummary, foregroundActivity, activeSubagentCount +} + +func isActiveSessionState(state string) bool { + return state == "STARTING" || state == "RUNNING" || state == "WAITING_FOR_INPUT" +} + +func deriveForegroundActivity(activities []string) string { + hasBackground := false + for _, activity := range activities { + if activity == activityGenerating { + return activityGenerating + } + if activity == activityBackground { + hasBackground = true + } + } + if hasBackground { + return activityBackground + } + return "" +} + +func derivePendingAction(state *projectionState) string { + if !state.pendingObserved && state.current != nil { + return state.current.PendingAction + } + action := state.taskPending + for _, candidate := range state.pending { + if candidate == pendingPermission { + return candidate + } + if candidate == pendingClarification && action == "" { + action = candidate + } + } + return action +} + +func deriveActiveError(state *projectionState) *ActiveErrorSummary { + if !state.errorsObserved && state.current != nil && state.current.ActiveError != nil { + copy := *state.current.ActiveError + return © + } + var active *ActiveErrorSummary + for _, candidate := range state.errors { + if candidate == nil || (active != nil && !candidate.OccurredAt.After(active.OccurredAt)) { + continue + } + copy := *candidate + active = © + } + return active +} + +func deriveGitSummary(state *projectionState) *GitSummary { + if !state.gitObserved && state.gitBaseline != nil { + copy := *state.gitBaseline + return © + } + var git GitSummary + for _, observation := range state.git { + git.Additions += observation.Additions + git.Deletions += observation.Deletions + git.ChangedFiles += observation.ChangedFiles + git.Ahead += observation.Ahead + git.Behind += observation.Behind + } + if git == (GitSummary{}) { + return nil + } + return &git +} diff --git a/apps/backend/internal/task/statussummary/projector_helpers.go b/apps/backend/internal/task/statussummary/projector_helpers.go new file mode 100644 index 0000000000..e609932104 --- /dev/null +++ b/apps/backend/internal/task/statussummary/projector_helpers.go @@ -0,0 +1,233 @@ +package statussummary + +import ( + "encoding/json" + "fmt" + "strconv" + "time" + "unicode/utf8" +) + +func (p *Projector) clearPendingLocked(state *projectionState, sessionID string) bool { + if sessionID == "" { + return false + } + state.pendingObserved = true + _, existed := state.pending[sessionID] + if existed { + delete(state.pending, sessionID) + } + previousTaskPending := state.taskPending + recomputeTaskPending(state) + return existed || previousTaskPending != state.taskPending +} + +func recomputeTaskPending(state *projectionState) { + state.taskPending = "" + for _, action := range state.pending { + if action == pendingPermission { + state.taskPending = action + return + } + if action == pendingClarification { + state.taskPending = action + } + } +} + +func (p *Projector) clearErrorLocked(state *projectionState, sessionID string) bool { + state.errorsObserved = true + if _, ok := state.errors[sessionID]; !ok { + return false + } + delete(state.errors, sessionID) + return true +} + +func errorFromMetadata(now time.Time, sessionID string, metadata map[string]interface{}) (*ActiveErrorSummary, bool) { + raw, ok := metadata["last_agent_error"].(map[string]interface{}) + if !ok { + return nil, false + } + return errorFromMap(now, sessionID, raw) +} + +func errorFromMap(now time.Time, sessionID string, data map[string]interface{}) (*ActiveErrorSummary, bool) { + message := firstString(data, "preview", "message", "error_message") + if message == "" { + return nil, false + } + if dismissed := stringField(data, "dismissed_at"); dismissed != "" || boolValue(data["dismissed"]) { + return nil, false + } + occurredAt := timeValue(data["occurred_at"]) + if occurredAt.IsZero() { + occurredAt = timeValue(data["updated_at"]) + } + if occurredAt.IsZero() { + occurredAt = now.UTC() + } + preview := truncateString(message, MaxActiveErrorPreviewBytes) + stamp := stringField(data, "stamp") + if stamp == "" { + stamp = occurredAt.UTC().Format(time.RFC3339Nano) + ":" + preview + } + return &ActiveErrorSummary{ + SessionID: truncateString(sessionID, maxSessionIDBytes), + Stamp: truncateString(stamp, maxActiveErrorStampBytes), + OccurredAt: occurredAt.UTC(), + Preview: preview, + }, true +} + +func errorEqual(a, b *ActiveErrorSummary) bool { + if a == nil || b == nil { + return a == b + } + return a.SessionID == b.SessionID && a.Stamp == b.Stamp && + a.OccurredAt.Equal(b.OccurredAt) && a.Preview == b.Preview +} + +func eventDataMap(data interface{}) (map[string]interface{}, error) { + if data == nil { + return nil, nil + } + if mapped, ok := data.(map[string]interface{}); ok { + return mapped, nil + } + encoded, err := json.Marshal(data) + if err != nil { + return nil, fmt.Errorf("decode status source payload: %w", err) + } + var mapped map[string]interface{} + if err := json.Unmarshal(encoded, &mapped); err != nil { + return nil, fmt.Errorf("decode status source payload: %w", err) + } + return mapped, nil +} + +func stringField(data map[string]interface{}, key string) string { + if data == nil { + return "" + } + value, _ := data[key].(string) + return value +} + +func firstString(data map[string]interface{}, keys ...string) string { + for _, key := range keys { + if value := stringField(data, key); value != "" { + return value + } + } + return "" +} + +func stringFromNullable(value interface{}) string { + if value == nil { + return "" + } + out, _ := value.(string) + return out +} + +func boolValue(value interface{}) bool { + out, _ := value.(bool) + return out +} + +func intValue(value interface{}) (int, bool) { + switch number := value.(type) { + case int: + return number, true + case int64: + return int(number), true + case float64: + return int(number), true + case json.Number: + parsed, err := number.Int64() + return int(parsed), err == nil + case string: + parsed, err := strconv.Atoi(number) + return parsed, err == nil + default: + return 0, false + } +} + +func intValueOrZero(value interface{}) int { + parsed, _ := intValue(value) + return parsed +} + +func nonNegativeInt(data map[string]interface{}, keys ...string) int { + for _, key := range keys { + if value, ok := intValue(data[key]); ok { + return maxInt(value, 0) + } + } + return 0 +} + +func changedFileCount(data map[string]interface{}) int { + if value, ok := intValue(data["changed_files"]); ok { + return maxInt(value, 0) + } + count := 0 + for _, key := range []string{"modified", "added", "deleted", "untracked", "renamed"} { + if values, ok := data[key].([]interface{}); ok { + count += len(values) + } + } + return count +} + +func timeValue(value interface{}) time.Time { + switch value := value.(type) { + case time.Time: + return value + case string: + parsed, err := time.Parse(time.RFC3339Nano, value) + if err == nil { + return parsed + } + } + return time.Time{} +} + +func maxInt(value, minimum int) int { + if value < minimum { + return minimum + } + return value +} + +func equalGitSummary(a, b GitSummary) bool { return a == b } + +func cloneSummary(summary *TaskStatusSummary) *TaskStatusSummary { + if summary == nil { + return nil + } + encoded, err := json.Marshal(summary) + if err != nil { + copy := *summary + return © + } + var clone TaskStatusSummary + if err := json.Unmarshal(encoded, &clone); err != nil { + copy := *summary + return © + } + return &clone +} + +func truncateString(value string, maxBytes int) string { + if len(value) <= maxBytes { + return value + } + value = value[:maxBytes] + for len(value) > 0 && !utf8.ValidString(value) { + value = value[:len(value)-1] + } + return value +} diff --git a/apps/backend/internal/task/statussummary/projector_pr.go b/apps/backend/internal/task/statussummary/projector_pr.go new file mode 100644 index 0000000000..98f075fab8 --- /dev/null +++ b/apps/backend/internal/task/statussummary/projector_pr.go @@ -0,0 +1,171 @@ +package statussummary + +import ( + "sort" + "strings" +) + +func derivePullRequestSummary(state *projectionState) *PullRequestSummary { + if !state.prObserved && state.prBaseline != nil { + copy := *state.prBaseline + return © + } + var summary PullRequestSummary + var representative *pullRequestObservation + keys := make([]string, 0, len(state.prs)) + for key := range state.prs { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + observation := state.prs[key] + summary.Count++ + if strings.EqualFold(observation.state, prStateOpen) { + summary.OpenCount++ + } + if pullRequestNeedsAttention(observation) { + summary.Attention = true + } + if representative == nil || betterPRRepresentative(observation, *representative) { + copy := observation + representative = © + } + } + if representative == nil { + return nil + } + summary.State = representative.state + summary.Number = representative.number + summary.URL = truncateString(representative.url, maxPullRequestURLBytes) + summary.AggregateState = aggregatePullRequestState(state.prs) + return &summary +} + +func pullRequestNeedsAttention(pr pullRequestObservation) bool { + if strings.EqualFold(pr.reviewState, prStateChanges) || + strings.EqualFold(pr.checksState, prStateFailure) || + strings.EqualFold(pr.mergeableState, prStateBlocked) || + strings.EqualFold(pr.mergeableState, prStateDirty) || + pr.unresolvedReviewCount > 0 { + return true + } + if pr.requiredReviews > 0 && pr.pendingReviewCount > 0 { + return true + } + return strings.EqualFold(pr.checksState, prStatePending) || + (pr.checksTotal > 0 && pr.checksPassing < pr.checksTotal) +} + +func betterPRRepresentative(candidate, current pullRequestObservation) bool { + candidateOpen := strings.EqualFold(candidate.state, prStateOpen) + currentOpen := strings.EqualFold(current.state, prStateOpen) + if candidateOpen != currentOpen { + return candidateOpen + } + candidateAttention := pullRequestNeedsAttention(candidate) + currentAttention := pullRequestNeedsAttention(current) + if candidateAttention != currentAttention { + return candidateAttention + } + if candidate.number != current.number { + return candidate.number < current.number + } + return candidate.url < current.url +} + +func aggregatePullRequestState(prs map[string]pullRequestObservation) string { + best := prStateNeutral + bestRank := 0 + for _, pr := range prs { + state := pullRequestAggregateState(pr) + rank := pullRequestStateRank(state) + if rank > bestRank { + best = state + bestRank = rank + } + } + return best +} + +func pullRequestAggregateState(pr pullRequestObservation) string { + state := strings.ToLower(strings.TrimSpace(pr.state)) + mergeable := strings.ToLower(strings.TrimSpace(pr.mergeableState)) + checks := strings.ToLower(strings.TrimSpace(pr.checksState)) + review := strings.ToLower(strings.TrimSpace(pr.reviewState)) + if lifecycle := pullRequestLifecycleState(state, mergeable); lifecycle != "" { + return lifecycle + } + if mergeable == prStateBlocked || mergeable == prStateDirty { + return prStateBlocked + } + if pullRequestHasFailure(pr, review, checks) { + return prStateFailure + } + if pullRequestHasPendingChecks(pr, checks) { + return prStatePending + } + if pullRequestAwaitsReview(pr, review) { + return prStateAwaiting + } + if review == prStateApproved && (checks == "" || checks == prStateSuccess) { + return prStateReady + } + if checks == prStateSuccess { + return prStatePassing + } + if state == prStateOpen { + return prStateReady + } + return prStateNeutral +} + +func pullRequestLifecycleState(state, mergeable string) string { + switch { + case state == prStateMerged: + return prStateMerged + case state == prStateClosed: + return prStateClosed + case state == prStateDraft || mergeable == prStateDraft: + return prStateDraft + default: + return "" + } +} + +func pullRequestHasFailure(pr pullRequestObservation, review, checks string) bool { + return review == prStateChanges || checks == prStateFailure || pr.unresolvedReviewCount > 0 +} + +func pullRequestHasPendingChecks(pr pullRequestObservation, checks string) bool { + return checks == prStatePending || + (pr.checksTotal > 0 && pr.checksPassing < pr.checksTotal && checks != prStateSuccess) +} + +func pullRequestAwaitsReview(pr pullRequestObservation, review string) bool { + return pr.pendingReviewCount > 0 || (pr.requiredReviews > 0 && review == prStatePending) +} + +func pullRequestStateRank(state string) int { + switch state { + case prStateFailure: + return 100 + case prStateBlocked: + return 90 + case prStatePending: + return 80 + case prStateAwaiting: + return 70 + case prStateReady: + return 60 + case prStatePassing: + return 50 + case prStateDraft: + return 40 + case prStateMerged: + return 20 + case prStateClosed: + return 10 + default: + return 0 + } +} diff --git a/apps/backend/internal/task/statussummary/projector_test.go b/apps/backend/internal/task/statussummary/projector_test.go new file mode 100644 index 0000000000..b338aae665 --- /dev/null +++ b/apps/backend/internal/task/statussummary/projector_test.go @@ -0,0 +1,454 @@ +package statussummary + +import ( + "context" + "fmt" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + "unicode/utf8" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/events/bus" +) + +type projectorTestStore struct { + mu sync.Mutex + rows map[string]*StoredTaskStatusSummary +} + +func newProjectorTestStore() *projectorTestStore { + return &projectorTestStore{rows: make(map[string]*StoredTaskStatusSummary)} +} + +func (s *projectorTestStore) LoadTaskStatusSummaries(_ context.Context, taskIDs []string) (map[string]*TaskStatusSummary, error) { + s.mu.Lock() + defer s.mu.Unlock() + rows := make(map[string]*TaskStatusSummary, len(taskIDs)) + for _, taskID := range taskIDs { + if row := s.rows[taskID]; row != nil { + rows[taskID] = cloneSummary(&row.Summary) + } + } + return rows, nil +} + +func (s *projectorTestStore) CompareAndUpdateTaskStatusSummary(_ context.Context, stored *StoredTaskStatusSummary) (bool, error) { + if stored == nil { + return false, fmt.Errorf("nil summary") + } + s.mu.Lock() + defer s.mu.Unlock() + if previous := s.rows[stored.TaskID]; previous != nil && previous.Summary.Revision >= stored.Summary.Revision { + return false, nil + } + copy := *stored + copy.Summary = *cloneSummary(&stored.Summary) + s.rows[stored.TaskID] = © + return true, nil +} + +func (s *projectorTestStore) summary(taskID string) *TaskStatusSummary { + s.mu.Lock() + defer s.mu.Unlock() + row := s.rows[taskID] + if row == nil { + return nil + } + return cloneSummary(&row.Summary) +} + +func newProjectorTest(t *testing.T) (*Projector, *projectorTestStore, *bus.MemoryEventBus, *atomic.Int64, context.CancelFunc) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + store := newProjectorTestStore() + eventBus := bus.NewMemoryEventBus(logger.Default()) + updates := new(atomic.Int64) + if _, err := eventBus.Subscribe(events.TaskStatusSummaryUpdated, func(_ context.Context, event *bus.Event) error { + updates.Add(1) + if _, ok := event.Data.(SummaryUpdated); !ok { + t.Errorf("summary event data type = %T, want SummaryUpdated", event.Data) + } + return nil + }); err != nil { + t.Fatal(err) + } + projector := NewProjector(ProjectorConfig{ + Store: store, + EventBus: eventBus, + ResolveWorkspace: func(context.Context, string) (string, error) { + return "workspace-1", nil + }, + Now: func() time.Time { return time.Date(2026, 8, 1, 18, 0, 0, 0, time.UTC) }, + }) + if err := projector.Start(ctx); err != nil { + cancel() + eventBus.Close() + t.Fatal(err) + } + t.Cleanup(func() { + cancel() + projector.Close() + eventBus.Close() + }) + return projector, store, eventBus, updates, cancel +} + +func publishProjectorEvent(t *testing.T, eventBus *bus.MemoryEventBus, eventType, subject string, data map[string]interface{}) { + t.Helper() + if err := eventBus.Publish(context.Background(), subject, bus.NewEvent(eventType, "test", data)); err != nil { + t.Fatal(err) + } +} + +func publishSessionState(t *testing.T, eventBus *bus.MemoryEventBus, taskID, sessionID string, extra map[string]interface{}) { + t.Helper() + data := map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "workspace_id": "workspace-1", + "new_state": "RUNNING", + "is_primary": true, + "foreground_activity": "generating", + "active_subagent_count": 2, + } + for key, value := range extra { + data[key] = value + } + publishProjectorEvent(t, eventBus, events.TaskSessionStateChanged, events.TaskSessionStateChanged, data) +} + +func TestProjectorDoesNotSubscribeToRawStreamsOrStreamingMessageAppends(t *testing.T) { + _, store, eventBus, updates, _ := newProjectorTest(t) + ctx := context.Background() + const taskID = "task-stream-boundary" + + publishProjectorEvent(t, eventBus, events.AgentStream, events.BuildAgentStreamSubject("session-1"), map[string]interface{}{ + "task_id": taskID, + "session_id": "session-1", + "delta": "a very large stream frame", + }) + publishProjectorEvent(t, eventBus, events.MessageUpdated, events.MessageUpdated, map[string]interface{}{ + "task_id": taskID, + "session_id": "session-1", + "author_type": "agent", + "type": "text", + "content": "partial assistant output", + }) + if got := store.summary(taskID); got != nil { + t.Fatalf("unrelated streaming events created summary: %+v", got) + } + if updates.Load() != 0 { + t.Fatalf("summary updates after unrelated streaming events = %d, want 0", updates.Load()) + } + + publishSessionState(t, eventBus, taskID, "session-1", nil) + got := store.summary(taskID) + if got == nil || got.PrimarySession == nil { + t.Fatalf("summary after authoritative session state = %+v", got) + } + if got.PrimarySession.ID != "session-1" || got.PrimarySession.State != "RUNNING" { + t.Fatalf("primary session = %+v", got.PrimarySession) + } + if got.ForegroundActivity != "generating" || got.ActiveSubagentCount != 2 { + t.Fatalf("activity summary = %+v", got) + } + if updates.Load() != 1 { + t.Fatalf("summary updates after authoritative state = %d, want 1", updates.Load()) + } + + // Replayed lifecycle state and assistant append updates are both no-ops at + // the semantic projection boundary. + publishSessionState(t, eventBus, taskID, "session-1", nil) + publishProjectorEvent(t, eventBus, events.MessageUpdated, events.MessageUpdated, map[string]interface{}{ + "task_id": taskID, + "session_id": "session-1", + "author_type": "agent", + "type": "text", + "content": "more partial output", + }) + if updates.Load() != 1 { + t.Fatalf("summary updates after replay/append = %d, want 1", updates.Load()) + } + _ = ctx +} + +func TestProjectorDerivesBoundedStatusAcrossSources(t *testing.T) { + _, store, eventBus, updates, _ := newProjectorTest(t) + const taskID = "task-status-sources" + const sessionID = "session-status" + + publishSessionState(t, eventBus, taskID, sessionID, nil) + occurredAt := "2026-08-01T18:01:00.000000000Z" + longError := strings.Repeat("ошибка ", 200) + publishProjectorEvent(t, eventBus, events.TaskSessionErrorChanged, events.TaskSessionErrorChanged, map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "active": true, + "message": longError, + "occurred_at": occurredAt, + "stamp": "error-stamp-1", + }) + publishProjectorEvent(t, eventBus, events.MessageAdded, events.MessageAdded, map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "author_type": "user", + "type": "clarification_request", + "requests_input": true, + }) + publishProjectorEvent(t, eventBus, events.GitEvent, events.BuildGitEventSubject(sessionID), map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "type": "status_update", + "status": map[string]interface{}{ + "repository_name": "repo-a", + "branch_additions": 4, + "branch_deletions": 1, + "modified": []interface{}{"a.go"}, + "added": []interface{}{"b.go"}, + "ahead": 2, + "behind": 1, + }, + }) + publishProjectorEvent(t, eventBus, events.GitEvent, events.BuildGitEventSubject(sessionID), map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "type": "status_update", + "status": map[string]interface{}{ + "repository_name": "repo-b", + "changed_files": 3, + "branch_additions": 6, + "branch_deletions": 2, + "ahead": 1, + "behind": 4, + }, + }) + publishProjectorEvent(t, eventBus, events.GitHubTaskPRUpdated, events.GitHubTaskPRUpdated, map[string]interface{}{ + "task_id": taskID, + "workspace_id": "workspace-1", + "repository_id": "repo-a", + "state": "open", + "pr_number": 42, + "pr_url": "https://example.test/pr/42", + "review_state": "changes_requested", + "checks_state": "success", + "required_reviews": 1, + "pending_review_count": 0, + }) + + got := store.summary(taskID) + if got == nil { + t.Fatal("missing projected summary") + } + if got.ActiveError == nil || got.ActiveError.Preview == "" { + t.Fatalf("active error = %+v", got.ActiveError) + } + if len(got.ActiveError.Preview) > MaxActiveErrorPreviewBytes || !utf8.ValidString(got.ActiveError.Preview) { + t.Fatalf("error preview is not bounded valid UTF-8: bytes=%d", len(got.ActiveError.Preview)) + } + if got.PendingAction != "clarification" { + t.Fatalf("pending action = %q, want clarification", got.PendingAction) + } + if got.Git == nil || got.Git.Additions != 10 || got.Git.Deletions != 3 || got.Git.ChangedFiles != 5 || got.Git.Ahead != 3 || got.Git.Behind != 5 { + t.Fatalf("git summary = %+v", got.Git) + } + if got.PullRequest == nil || got.PullRequest.Count != 1 || !got.PullRequest.Attention || got.PullRequest.Number != 42 || got.PullRequest.AggregateState != "failure" { + t.Fatalf("pull request summary = %+v", got.PullRequest) + } + + publishProjectorEvent(t, eventBus, events.ClarificationAnswered, events.ClarificationAnswered, map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + }) + publishProjectorEvent(t, eventBus, events.MessageAdded, events.MessageAdded, map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "author_type": "agent", + "type": "text", + "content": "recovered", + }) + got = store.summary(taskID) + if got.PendingAction != "" || got.ActiveError != nil { + t.Fatalf("cleared status = %+v", got) + } + if updates.Load() < 7 { + t.Fatalf("summary updates = %d, want one for each semantic source change", updates.Load()) + } +} + +func TestProjectorConvergesConcurrentGitObservations(t *testing.T) { + projector, store, _, _, _ := newProjectorTest(t) + const taskID = "task-concurrent-git" + const sessionID = "session-concurrent-git" + + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func(index int) { + defer wg.Done() + data := map[string]interface{}{ + "task_id": taskID, + "session_id": sessionID, + "workspace_id": "workspace-1", + "type": "status_update", + "status": map[string]interface{}{ + "repository_name": fmt.Sprintf("repo-%d", index), + "changed_files": 1, + "branch_additions": 2, + }, + } + if err := projector.HandleEvent(context.Background(), bus.NewEvent(events.GitEvent, "test", data)); err != nil { + t.Errorf("project concurrent Git event %d: %v", index, err) + } + }(i) + } + wg.Wait() + + got := store.summary(taskID) + if got == nil || got.Git == nil { + t.Fatalf("concurrent summary = %+v", got) + } + if got.Git.ChangedFiles != 8 || got.Git.Additions != 16 { + t.Fatalf("concurrent Git aggregate = %+v, want 8 files and 16 additions", got.Git) + } + if got.Revision != 8 { + t.Fatalf("concurrent revision = %d, want 8", got.Revision) + } +} + +func TestProjectorRetainsStoredDomainsUntilTheirFirstObservation(t *testing.T) { + store := newProjectorTestStore() + storedAt := time.Date(2026, 8, 1, 17, 59, 0, 0, time.UTC) + store.rows["task-restart"] = &StoredTaskStatusSummary{ + TaskID: "task-restart", + WorkspaceID: "workspace-1", + Summary: TaskStatusSummary{ + Revision: 8, + UpdatedAt: storedAt, + PrimarySession: &PrimarySessionSummary{ID: "primary-restart", State: "RUNNING"}, + ForegroundActivity: "generating", + ActiveSubagentCount: 3, + PendingAction: "permission", + ActiveError: &ActiveErrorSummary{ + SessionID: "primary-restart", + Stamp: "error-restart", + OccurredAt: storedAt, + Preview: "stored error", + }, + Git: &GitSummary{Additions: 4, Deletions: 2, ChangedFiles: 3, Ahead: 1, Behind: 2}, + PullRequest: &PullRequestSummary{Count: 1, OpenCount: 1, Attention: true, State: "open", Number: 12, URL: "https://example.test/12"}, + }, + } + + projector := NewProjector(ProjectorConfig{ + Store: store, + ResolveWorkspace: func(context.Context, string) (string, error) { + return "workspace-1", nil + }, + Now: func() time.Time { return storedAt.Add(time.Minute) }, + }) + + if err := projector.HandleEvent(context.Background(), bus.NewEvent(events.TaskSessionStateChanged, "test", map[string]interface{}{ + "task_id": "task-restart", + "workspace_id": "workspace-1", + "session_id": "background-restart", + "new_state": "WAITING_FOR_INPUT", + "is_primary": false, + })); err != nil { + t.Fatalf("replay lifecycle event: %v", err) + } + + got := store.summary("task-restart") + if got == nil { + t.Fatal("stored summary disappeared after projector restart") + } + if got.Revision != 8 { + t.Fatalf("revision after unrelated replay = %d, want 8", got.Revision) + } + if got.PrimarySession == nil || got.PrimarySession.ID != "primary-restart" || got.PrimarySession.State != "RUNNING" { + t.Fatalf("primary session after replay = %+v", got.PrimarySession) + } + if got.ForegroundActivity != "generating" || got.ActiveSubagentCount != 3 || got.PendingAction != "permission" { + t.Fatalf("stored task status after replay = %+v", got) + } + if got.ActiveError == nil || got.ActiveError.Stamp != "error-restart" { + t.Fatalf("stored error after replay = %+v", got.ActiveError) + } + if got.Git == nil || got.Git.ChangedFiles != 3 || got.PullRequest == nil || got.PullRequest.Number != 12 { + t.Fatalf("stored source domains after replay = git=%+v pr=%+v", got.Git, got.PullRequest) + } +} + +func TestProjectorKeepsPRsWithTheSameRepositoryDistinct(t *testing.T) { + _, store, eventBus, _, _ := newProjectorTest(t) + const taskID = "task-pr-identity" + + for _, number := range []int{41, 42} { + publishProjectorEvent(t, eventBus, events.GitHubTaskPRUpdated, events.GitHubTaskPRUpdated, map[string]interface{}{ + "task_id": taskID, + "workspace_id": "workspace-1", + "repository_id": "repo-a", + "state": "open", + "pr_number": number, + "pr_url": fmt.Sprintf("https://example.test/pr/%d", number), + }) + } + + got := store.summary(taskID) + if got == nil || got.PullRequest == nil { + t.Fatalf("PR summary = %+v", got) + } + if got.PullRequest.Count != 2 { + t.Fatalf("PR count = %d, want 2 for two PR numbers in one repository", got.PullRequest.Count) + } +} + +func TestProjectorRehydratesSiblingGitObservationsAfterRestart(t *testing.T) { + store := newProjectorTestStore() + store.rows["task-git-restart"] = &StoredTaskStatusSummary{ + TaskID: "task-git-restart", + WorkspaceID: "workspace-1", + Summary: TaskStatusSummary{ + Revision: 1, + Git: &GitSummary{Additions: 7, ChangedFiles: 3}, + }, + } + projector := NewProjector(ProjectorConfig{ + Store: store, + ResolveWorkspace: func(context.Context, string) (string, error) { + return "workspace-1", nil + }, + LoadGitObservations: func(context.Context, string) ([]GitObservation, error) { + return []GitObservation{ + {Repository: "repo-a", Summary: GitSummary{Additions: 5, ChangedFiles: 2}}, + {Repository: "repo-b", Summary: GitSummary{Additions: 2, ChangedFiles: 1}}, + }, nil + }, + Now: func() time.Time { return time.Date(2026, 8, 1, 18, 0, 0, 0, time.UTC) }, + }) + + if err := projector.HandleEvent(context.Background(), bus.NewEvent(events.GitEvent, "test", map[string]interface{}{ + "task_id": "task-git-restart", + "workspace_id": "workspace-1", + "session_id": "session-1", + "type": "status_update", + "status": map[string]interface{}{ + "repository_name": "repo-a", + "branch_additions": 6, + "changed_files": 2, + }, + })); err != nil { + t.Fatalf("replay Git event: %v", err) + } + + got := store.summary("task-git-restart") + if got == nil || got.Git == nil { + t.Fatalf("Git summary = %+v", got) + } + if got.Git.Additions != 8 || got.Git.ChangedFiles != 3 { + t.Fatalf("Git summary after sibling rehydration = %+v, want additions=8 changed_files=3", got.Git) + } +} diff --git a/apps/backend/internal/task/statussummary/rebuild.go b/apps/backend/internal/task/statussummary/rebuild.go new file mode 100644 index 0000000000..eec231ee36 --- /dev/null +++ b/apps/backend/internal/task/statussummary/rebuild.go @@ -0,0 +1,151 @@ +package statussummary + +import ( + "strconv" + "strings" + "time" +) + +// RebuildSession is the durable/session-backed portion of a task summary. +// Callers may add live activity values when an in-memory activity provider is +// available; the rest of the fields come from task_sessions and metadata. +type RebuildSession struct { + ID string + State string + IsPrimary bool + ForegroundActivity string + ActiveSubagentCount int + ActiveError *ActiveErrorSummary +} + +// RebuildGit is one authoritative Git snapshot. Repository is empty for the +// single-repository shape and is otherwise the stable repository key. +type RebuildGit struct { + Repository string + Summary GitSummary +} + +// PullRequestInput is the bounded GitHub state needed to rebuild a task row. +// It deliberately does not expose the full provider record to the summary +// package or to the WebSocket payload. +type PullRequestInput struct { + Key string + State string + Number int + URL string + ReviewState string + ChecksState string + MergeableState string + UnresolvedReviewCount int + PendingReviewCount int + RequiredReviews int + ChecksTotal int + ChecksPassing int +} + +// RebuildInput contains the authoritative bounded facts available from +// durable stores and optional live providers. Every source is marked as +// observed by its corresponding boolean so an unavailable optional provider +// does not masquerade as an authoritative empty value. +type RebuildInput struct { + Sessions []RebuildSession + PendingActions map[string]string + ActivityObserved bool + Git []RebuildGit + GitObserved bool + PullRequests []PullRequestInput + PRObserved bool + Now time.Time +} + +// BuildFromAuthoritative derives the same summary semantics used by the live +// projector, but starts from a batch-loaded snapshot. It is used to repair +// rows created before the projector existed, without subscribing to or +// replaying any session stream. +func BuildFromAuthoritative(input RebuildInput) TaskStatusSummary { + state := &projectionState{ + sessions: make(map[string]sessionObservation, len(input.Sessions)), + pending: make(map[string]string, len(input.PendingActions)), + errors: make(map[string]*ActiveErrorSummary), + git: make(map[string]GitSummary, len(input.Git)), + prs: make(map[string]pullRequestObservation, len(input.PullRequests)), + pendingObserved: true, + activityObserved: input.ActivityObserved, + errorsObserved: true, + gitObserved: input.GitObserved, + prObserved: input.PRObserved, + } + for _, inputSession := range input.Sessions { + if strings.TrimSpace(inputSession.ID) == "" { + continue + } + state.sessions[inputSession.ID] = sessionObservation{ + id: inputSession.ID, + state: inputSession.State, + isPrimary: inputSession.IsPrimary, + foregroundActivity: inputSession.ForegroundActivity, + activeSubagentCount: maxInt(inputSession.ActiveSubagentCount, 0), + } + if inputSession.ActiveError != nil { + if activeError := normalizeRebuildError(inputSession.ActiveError, input.Now); activeError != nil { + state.errors[inputSession.ID] = activeError + } + } + } + for sessionID, action := range input.PendingActions { + if strings.TrimSpace(sessionID) == "" || strings.TrimSpace(action) == "" { + continue + } + state.pending[sessionID] = action + } + recomputeTaskPending(state) + for _, git := range input.Git { + repository := strings.TrimSpace(git.Repository) + if repository == "" { + repository = "default" + } + state.git[repository] = git.Summary + } + for index, pullRequest := range input.PullRequests { + key := strings.TrimSpace(pullRequest.Key) + if key == "" { + key = strings.TrimSpace(pullRequest.URL) + } + if key == "" && pullRequest.Number > 0 { + key = strconv.Itoa(pullRequest.Number) + } + if key == "" { + key = strconv.Itoa(index) + } + state.prs[key] = pullRequestObservation{ + state: pullRequest.State, + number: maxInt(pullRequest.Number, 0), + url: pullRequest.URL, + reviewState: pullRequest.ReviewState, + checksState: pullRequest.ChecksState, + mergeableState: pullRequest.MergeableState, + unresolvedReviewCount: maxInt(pullRequest.UnresolvedReviewCount, 0), + pendingReviewCount: maxInt(pullRequest.PendingReviewCount, 0), + requiredReviews: maxInt(pullRequest.RequiredReviews, 0), + checksTotal: maxInt(pullRequest.ChecksTotal, 0), + checksPassing: maxInt(pullRequest.ChecksPassing, 0), + } + } + return deriveSummary(state) +} + +func normalizeRebuildError(input *ActiveErrorSummary, now time.Time) *ActiveErrorSummary { + if input == nil { + return nil + } + copy := *input + if copy.OccurredAt.IsZero() { + copy.OccurredAt = now.UTC() + } + copy.Preview = truncateString(copy.Preview, MaxActiveErrorPreviewBytes) + if copy.Stamp == "" { + copy.Stamp = copy.OccurredAt.UTC().Format(time.RFC3339Nano) + ":" + copy.Preview + } + copy.Stamp = truncateString(copy.Stamp, maxActiveErrorStampBytes) + return © +} diff --git a/apps/backend/internal/task/statussummary/rebuild_test.go b/apps/backend/internal/task/statussummary/rebuild_test.go new file mode 100644 index 0000000000..1b7e3788cb --- /dev/null +++ b/apps/backend/internal/task/statussummary/rebuild_test.go @@ -0,0 +1,128 @@ +package statussummary + +import ( + "testing" + "time" +) + +func TestBuildFromAuthoritativeAggregatesDurableSources(t *testing.T) { + now := time.Date(2026, 8, 1, 18, 0, 0, 0, time.UTC) + got := BuildFromAuthoritative(RebuildInput{ + Sessions: []RebuildSession{ + { + ID: "primary", + State: "RUNNING", + IsPrimary: true, + ForegroundActivity: activityGenerating, + ActiveSubagentCount: 2, + }, + { + ID: "worker", + State: "WAITING_FOR_INPUT", + ForegroundActivity: activityBackground, + ActiveSubagentCount: 1, + ActiveError: &ActiveErrorSummary{ + SessionID: "worker", + Stamp: "worker-error", + OccurredAt: now.Add(-time.Minute), + Preview: "the worker failed", + }, + }, + }, + PendingActions: map[string]string{ + "worker": string(pendingClarification), + "primary": string(pendingPermission), + }, + ActivityObserved: true, + GitObserved: true, + Git: []RebuildGit{ + {Repository: "repo-a", Summary: GitSummary{Additions: 3, Deletions: 1, ChangedFiles: 2, Ahead: 2}}, + {Repository: "repo-b", Summary: GitSummary{Additions: 4, Deletions: 2, ChangedFiles: 1, Behind: 5}}, + }, + PRObserved: true, + PullRequests: []PullRequestInput{ + { + Key: "pr-open", + State: prStateOpen, + Number: 12, + URL: "https://github.test/pr/12", + ReviewState: prStateChanges, + ChecksState: prStateFailure, + ChecksTotal: 3, + ChecksPassing: 1, + RequiredReviews: 1, + }, + {Key: "pr-merged", State: prStateMerged, Number: 7, ReviewState: prStateApproved}, + }, + Now: now, + }) + + if got.PrimarySession == nil || got.PrimarySession.ID != "primary" || got.PrimarySession.State != "RUNNING" { + t.Fatalf("primary session = %+v", got.PrimarySession) + } + if got.ForegroundActivity != activityGenerating || got.ActiveSubagentCount != 3 { + t.Fatalf("activity summary = %+v", got) + } + if got.PendingAction != pendingPermission { + t.Fatalf("pending action = %q, want %q", got.PendingAction, pendingPermission) + } + if got.ActiveError == nil || got.ActiveError.SessionID != "worker" || got.ActiveError.Preview != "the worker failed" { + t.Fatalf("active error = %+v", got.ActiveError) + } + if got.Git == nil { + t.Fatal("Git summary is nil") + } + if want := (GitSummary{Additions: 7, Deletions: 3, ChangedFiles: 3, Ahead: 2, Behind: 5}); *got.Git != want { + t.Fatalf("Git summary = %+v, want %+v", *got.Git, want) + } + if got.PullRequest == nil { + t.Fatal("pull request summary is nil") + } + if got.PullRequest.Count != 2 || got.PullRequest.OpenCount != 1 || !got.PullRequest.Attention { + t.Fatalf("pull request aggregate = %+v", *got.PullRequest) + } + if got.PullRequest.State != prStateOpen || got.PullRequest.Number != 12 || got.PullRequest.AggregateState != prStateFailure { + t.Fatalf("pull request representative = %+v", *got.PullRequest) + } +} + +func TestDeriveForegroundActivityPrefersGeneratingOverBackground(t *testing.T) { + got := deriveForegroundActivity([]string{activityBackground, activityGenerating}) + if got != activityGenerating { + t.Fatalf("foreground activity = %q, want %q", got, activityGenerating) + } +} + +func TestBuildFromAuthoritativeLeavesUnavailableOptionalSourcesEmpty(t *testing.T) { + got := BuildFromAuthoritative(RebuildInput{ + Sessions: []RebuildSession{{ID: "session-1", State: "COMPLETED", IsPrimary: true}}, + }) + + if got.PrimarySession == nil || got.PrimarySession.ID != "session-1" { + t.Fatalf("primary session = %+v", got.PrimarySession) + } + if got.Git != nil { + t.Fatalf("Git summary = %+v, want nil when source was not observed", got.Git) + } + if got.PullRequest != nil { + t.Fatalf("pull request summary = %+v, want nil when source was not observed", got.PullRequest) + } +} + +func TestPullRequestChecksWithAnIncompleteUnknownRollupArePending(t *testing.T) { + got := BuildFromAuthoritative(RebuildInput{ + PRObserved: true, + PullRequests: []PullRequestInput{{ + Key: "repo-a#42", + State: prStateOpen, + Number: 42, + ChecksTotal: 3, + ChecksPassing: 1, + ChecksState: "", + }}, + }) + + if got.PullRequest == nil || got.PullRequest.AggregateState != prStatePending { + t.Fatalf("pull request summary = %+v, want pending while checks are incomplete", got.PullRequest) + } +} diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index 751a2a29ad..2fa55d0f4f 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -208,6 +208,7 @@ const ( ActionSessionMessageDeleted = "session.message.deleted" ActionSessionStateChanged = "session.state_changed" ActionSessionActivityChanged = "session.activity_changed" + ActionTaskStatusSummaryUpdated = "task.status_summary.updated" ActionSessionAgentctlStarting = "session.agentctl_starting" ActionSessionAgentctlReady = "session.agentctl_ready" ActionSessionAgentctlError = "session.agentctl_error" @@ -293,6 +294,12 @@ const ( // Session git event (unified notification) ActionSessionGitEvent = "session.git.event" // Notification: unified git event + // Session git refresh (explicit detail-surface git snapshot request) + ActionSessionGitRefresh = "session.git.refresh" + // Retained for older clients. New detail surfaces should use the narrower + // ActionSessionGitRefresh request instead. + ActionSessionDataRefresh = "session.data.refresh" + // Process runner actions ActionSessionProcessOutput = "session.process.output" ActionSessionProcessStatus = "session.process.status" diff --git a/apps/web/app/office/tasks/[id]/advanced-panels/chat-panel.tsx b/apps/web/app/office/tasks/[id]/advanced-panels/chat-panel.tsx index 4f83fdc8c3..c66276c7fb 100644 --- a/apps/web/app/office/tasks/[id]/advanced-panels/chat-panel.tsx +++ b/apps/web/app/office/tasks/[id]/advanced-panels/chat-panel.tsx @@ -16,6 +16,7 @@ import { buildStartRequest } from "@/lib/services/session-launch-helpers"; import { MessageRenderer } from "@/components/task/chat/message-renderer"; import type { Message } from "@/lib/types/http"; import { getSessionWorkspacePath } from "@/lib/session-workspace-path"; +import { generateUUID } from "@/lib/utils"; type AdvancedChatPanelProps = { taskId: string; @@ -130,7 +131,12 @@ function useChatActions( if (!client || !sessionId) return; await client.request( "message.add", - { task_id: taskId, session_id: sessionId, content: text }, + { + task_id: taskId, + session_id: sessionId, + client_message_id: generateUUID(), + content: text, + }, 10_000, ); }, diff --git a/apps/web/components/github/pr-task-icon.test.ts b/apps/web/components/github/pr-task-icon.test.ts index f7f78b570e..592cf20099 100644 --- a/apps/web/components/github/pr-task-icon.test.ts +++ b/apps/web/components/github/pr-task-icon.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from "vitest"; import { aggregatePRStatusColor, + getPRAggregateStatusColor, areAllOpenPRsReadyToMerge, getPRStatusColor, getPRTooltip, @@ -12,6 +13,14 @@ import { } from "./pr-task-icon"; import type { TaskPR } from "@/lib/types/github"; +const SKY_400 = "text-sky-400"; +const RED_500 = "text-red-500"; +const YELLOW_500 = "text-yellow-500"; +const EMERALD_400 = "text-emerald-400"; +const GREEN_500 = "text-green-500"; +const PURPLE_500 = "text-purple-500"; +const MUTED_FOREGROUND = "text-muted-foreground"; + function makePR(overrides: Partial = {}): TaskPR { return { id: "id", @@ -45,10 +54,19 @@ function makePR(overrides: Partial = {}): TaskPR { }; } -const SKY_400 = "text-sky-400"; -const RED_500 = "text-red-500"; -const YELLOW_500 = "text-yellow-500"; -const MUTED_FOREGROUND = "text-muted-foreground"; +describe("getPRAggregateStatusColor", () => { + it.each([ + ["failure", RED_500], + ["pending", YELLOW_500], + ["awaiting_review", SKY_400], + ["ready", EMERALD_400], + ["passing", GREEN_500], + ["merged", PURPLE_500], + ["open", MUTED_FOREGROUND], + ])("maps %s to %s", (state, color) => { + expect(getPRAggregateStatusColor(state)).toBe(color); + }); +}); describe("isPRReadyToMerge", () => { it("is true when open + approved + success + clean", () => { @@ -241,7 +259,7 @@ describe("getPRStatusColor", () => { checks_state: "success", mergeable_state: "clean", }); - expect(getPRStatusColor(pr)).toBe("text-emerald-400"); + expect(getPRStatusColor(pr)).toBe(EMERALD_400); }); it("returns muted for approved+success but mergeable_state blocked (branch protection)", () => { @@ -293,7 +311,7 @@ describe("getPRStatusColor", () => { checks_state: "success", mergeable_state: "", }); - expect(getPRStatusColor(pr)).toBe("text-green-500"); + expect(getPRStatusColor(pr)).toBe(GREEN_500); }); it("returns sky-400 when CI passed but review is pending", () => { @@ -326,7 +344,7 @@ describe("getPRStatusColor", () => { mergeable_state: "clean", pending_review_count: 0, }); - expect(getPRStatusColor(pr)).toBe("text-emerald-400"); + expect(getPRStatusColor(pr)).toBe(EMERALD_400); }); it("returns red for changes_requested regardless of mergeable_state", () => { @@ -345,7 +363,7 @@ describe("getPRStatusColor", () => { }); it("returns purple for merged", () => { - expect(getPRStatusColor(makePR({ state: "merged" }))).toBe("text-purple-500"); + expect(getPRStatusColor(makePR({ state: "merged" }))).toBe(PURPLE_500); }); }); @@ -359,7 +377,7 @@ describe("getPRStatusColor — aggregate checks", () => { checks_passing: 5, mergeable_state: "", }); - expect(getPRStatusColor(pr)).toBe("text-green-500"); + expect(getPRStatusColor(pr)).toBe(GREEN_500); }); it("treats aggregate all-green counts as passed when no reviews are required", () => { @@ -372,7 +390,7 @@ describe("getPRStatusColor — aggregate checks", () => { checks_passing: 5, mergeable_state: "", }); - expect(getPRStatusColor(pr)).toBe("text-green-500"); + expect(getPRStatusColor(pr)).toBe(GREEN_500); }); }); @@ -402,7 +420,7 @@ describe("getPRStatusColor — mergeability", () => { it("ignores dirty/behind mergeable_state on terminal (merged) PRs", () => { expect(getPRStatusColor(makePR({ state: "merged", mergeable_state: "dirty" }))).toBe( - "text-purple-500", + PURPLE_500, ); }); }); @@ -514,7 +532,7 @@ describe("aggregatePRStatusColor", () => { checks_state: "success", mergeable_state: "clean", }); - expect(aggregatePRStatusColor([ready, ready])).toBe("text-emerald-400"); + expect(aggregatePRStatusColor([ready, ready])).toBe(EMERALD_400); }); it("yellow CI pending beats merged purple", () => { @@ -546,7 +564,7 @@ describe("aggregatePRStatusColor", () => { // so the result depends on which terminal state is present. Merged ranks // 0 (purple), closed ranks 5 (red) — both paths need a guard. const merged = makePR({ state: "merged" }); - expect(aggregatePRStatusColor([merged, merged])).toBe("text-purple-500"); + expect(aggregatePRStatusColor([merged, merged])).toBe(PURPLE_500); const closed = makePR({ state: "closed" }); expect(aggregatePRStatusColor([closed, closed])).toBe(RED_500); }); diff --git a/apps/web/components/github/pr-task-icon.tsx b/apps/web/components/github/pr-task-icon.tsx index ad851aac5b..0780ffa29b 100644 --- a/apps/web/components/github/pr-task-icon.tsx +++ b/apps/web/components/github/pr-task-icon.tsx @@ -7,16 +7,47 @@ import { useAppStore } from "@/components/state-provider"; import type { TaskPR } from "@/lib/types/github"; const MUTED_FOREGROUND = "text-muted-foreground"; +const PURPLE_500 = "text-purple-500"; +const RED_500 = "text-red-500"; +const YELLOW_500 = "text-yellow-500"; +const SKY_400 = "text-sky-400"; +const EMERALD_400 = "text-emerald-400"; +const GREEN_500 = "text-green-500"; + +/** Maps the task-level PR projection to the same visual language as live PRs. */ +export function getPRAggregateStatusColor(state: string | null | undefined): string { + switch (state?.toLowerCase()) { + case "merged": + return PURPLE_500; + case "closed": + case "failure": + return RED_500; + case "pending": + return YELLOW_500; + case "awaiting_review": + return SKY_400; + case "ready": + return EMERALD_400; + case "passing": + return GREEN_500; + case "draft": + case "blocked": + case "neutral": + case "open": + default: + return MUTED_FOREGROUND; + } +} const STATUS_RANK: Record = { // Higher = more attention-worthy. Drives the aggregated icon color when a // task has multiple PRs (we surface the worst state). - "text-red-500": 5, - "text-yellow-500": 4, - "text-sky-400": 3, - "text-emerald-400": 2, - "text-green-500": 1, - "text-purple-500": 0, + [RED_500]: 5, + [YELLOW_500]: 4, + [SKY_400]: 3, + [EMERALD_400]: 2, + [GREEN_500]: 1, + [PURPLE_500]: 0, [MUTED_FOREGROUND]: 0, }; @@ -97,16 +128,16 @@ export function isPRWaitingOnBranchProtection(pr: TaskPR): boolean { // awaiting-review, so an outstanding review still reads as sky.) function openMergeBlockerColor(pr: TaskPR): string | null { if (pr.state !== "open") return null; - if (pr.mergeable_state === "dirty") return "text-red-500"; - if (pr.mergeable_state === "behind") return "text-yellow-500"; + if (pr.mergeable_state === "dirty") return RED_500; + if (pr.mergeable_state === "behind") return YELLOW_500; return null; } export function getPRStatusColor(pr: TaskPR): string { - if (pr.state === "merged") return "text-purple-500"; - if (pr.state === "closed") return "text-red-500"; + if (pr.state === "merged") return PURPLE_500; + if (pr.state === "closed") return RED_500; if (pr.review_state === "changes_requested" || pr.checks_state === "failure") { - return "text-red-500"; + return RED_500; } if (isPRDraft(pr)) { return MUTED_FOREGROUND; @@ -114,12 +145,12 @@ export function getPRStatusColor(pr: TaskPR): string { const blockerColor = openMergeBlockerColor(pr); if (blockerColor) return blockerColor; if (isPRReadyToMerge(pr)) { - return "text-emerald-400"; + return EMERALD_400; } // Check awaiting-review before the plain-green fallback so an approved PR // with pending reviewers (1 of N required) doesn't read as fully approved. if (isPRAwaitingReview(pr)) { - return "text-sky-400"; + return SKY_400; } // Branch protection can be a normal repository-rule wait after CI has passed. // Keep it muted so it doesn't read like a failure. @@ -127,10 +158,10 @@ export function getPRStatusColor(pr: TaskPR): string { return MUTED_FOREGROUND; } if (hasPRChecksPassedWithoutReviewWaitForDisplay(pr)) { - return "text-green-500"; + return GREEN_500; } if (hasPRChecksInProgressForDisplay(pr) || pr.review_state === "pending") { - return "text-yellow-500"; + return YELLOW_500; } return MUTED_FOREGROUND; } diff --git a/apps/web/components/task/dockview-shared.tsx b/apps/web/components/task/dockview-shared.tsx index 1bf3a6450c..d85f7204a9 100644 --- a/apps/web/components/task/dockview-shared.tsx +++ b/apps/web/components/task/dockview-shared.tsx @@ -226,10 +226,10 @@ function ChatContent({ panelId, params }: { panelId: string; params: Record { diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.test.ts b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.test.ts index 9dc0285f40..19ca13e29c 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.test.ts +++ b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.test.ts @@ -1,27 +1,16 @@ import { describe, expect, it } from "vitest"; import { toSheetItem } from "./session-task-switcher-sheet-hooks"; -import { - sessionId as toSessionId, - taskId as toTaskId, - type Message, - type TaskSession, -} from "@/lib/types/http"; type SheetTask = Parameters[0]; type SheetCtx = Parameters[1]; +const UPDATED_AT = "2026-07-22T00:00:00Z"; +const ERROR_PREVIEW = "Agent failed"; function emptyCtx(): SheetCtx { return { repositoryPathsById: new Map(), workflowNameById: new Map(), stepTitleById: new Map(), - sessionsById: {}, - sessionsByTaskId: {}, - gitStatusByEnvId: {}, - envIdBySessionId: {}, - messagesBySession: {}, - dismissedAgentErrors: {}, - acknowledgedAgentErrors: {}, }; } @@ -36,29 +25,6 @@ function task(overrides: Partial = {}): SheetTask { } as SheetTask; } -function session(id: string, state: TaskSession["state"]): TaskSession { - return { - id: toSessionId(id), - task_id: toTaskId("t1"), - state, - started_at: "2026-07-22T00:00:00Z", - updated_at: "2026-07-22T00:00:00Z", - }; -} - -function pendingPermission(id: string, sessionId: string): Message { - return { - id, - session_id: toSessionId(sessionId), - task_id: toTaskId("t1"), - author_type: "agent", - content: "Allow?", - type: "permission_request", - metadata: { status: "pending" }, - created_at: "2026-07-22T00:00:00Z", - }; -} - describe("toSheetItem", () => { // The mobile task-switcher row must read the same task-level most-active-wins // aggregate the desktop sidebar and board card read, so a background-running @@ -78,29 +44,89 @@ describe("toSheetItem", () => { expect(item.foregroundActivity).toBeUndefined(); }); - it("finds pending permission in a secondary waiting session", () => { - const ctx = emptyCtx(); - ctx.sessionsByTaskId.t1 = [ - session("primary", "STARTING"), - session("secondary", "WAITING_FOR_INPUT"), - ]; - ctx.messagesBySession.primary = []; - ctx.messagesBySession.secondary = [pendingPermission("permission", "secondary")]; - - const item = toSheetItem(task({ primarySessionId: "primary" }), ctx); - + it("reads pending permission from the task status summary", () => { + const item = toSheetItem( + task({ + statusSummary: { + revision: 2, + updated_at: UPDATED_AT, + pending_action: "permission", + }, + }), + emptyCtx(), + ); expect(item.hasPendingPermission).toBe(true); expect(item.hasPendingClarification).toBe(false); }); - it("excludes stale pending permission from a starting session", () => { - const ctx = emptyCtx(); - ctx.sessionsByTaskId.t1 = [session("starting", "STARTING")]; - ctx.messagesBySession.starting = [pendingPermission("stale-permission", "starting")]; + it("reads an active error from the task status summary", () => { + const item = toSheetItem( + task({ + statusSummary: { + revision: 3, + updated_at: UPDATED_AT, + active_error: { + session_id: "session-1", + stamp: "error-3", + occurred_at: UPDATED_AT, + preview: ERROR_PREVIEW, + }, + }, + }), + emptyCtx(), + ); - const item = toSheetItem(task({ primarySessionId: "starting" }), ctx); + expect(item.agentErrorMessage).toBe(ERROR_PREVIEW); + }); + + it("does not resurrect legacy status when a summary explicitly clears it", () => { + const item = toSheetItem( + task({ + taskPendingAction: "permission", + primarySessionState: "RUNNING", + primarySessionId: "legacy-session", + foregroundActivity: "background", + updatedAt: "legacy-update", + statusSummary: { + revision: 4, + updated_at: UPDATED_AT, + }, + }), + emptyCtx(), + ); expect(item.hasPendingPermission).toBe(false); - expect(item.hasPendingClarification).toBe(false); + expect(item.sessionState).toBeUndefined(); + expect(item.primarySessionId).toBeNull(); + expect(item.foregroundActivity).toBeUndefined(); + expect(item.updatedAt).toBe(UPDATED_AT); + }); + + it("hides only the acknowledged error stamp and shows a newer one", () => { + const base = task({ + statusSummary: { + revision: 5, + updated_at: UPDATED_AT, + active_error: { + session_id: "session-1", + stamp: "error-5", + occurred_at: UPDATED_AT, + preview: ERROR_PREVIEW, + }, + }, + }); + + expect( + toSheetItem(base, { + ...emptyCtx(), + acknowledgedAgentErrors: { "session-1": "error-5" }, + }).agentErrorMessage, + ).toBeNull(); + expect( + toSheetItem(base, { + ...emptyCtx(), + dismissedAgentErrors: { "session-1": "older-error" }, + }).agentErrorMessage, + ).toBe(ERROR_PREVIEW); }); }); 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 83a234a4dc..219bee170f 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 @@ -10,63 +10,85 @@ import { useWorkspaceSidebarTasks } from "@/hooks/domains/kanban/use-workspace-s import { useTaskActions, useArchiveAndSwitchTask } from "@/hooks/use-task-actions"; import { useTaskDetachDialog } from "@/hooks/use-detach-task"; import { useTaskRemoval } from "@/hooks/use-task-removal"; -import { getSessionInfoForTask } from "@/lib/utils/session-info"; -import { - hasPendingClarification, - hasPendingPermissionRequest, -} from "@/lib/utils/pending-clarification"; -import { aggregateTaskPendingInput } from "@/lib/utils/task-pending-input"; import { workspaceModeFromMetadata } from "@/lib/kanban/map-task"; import { repositoryId as toRepositoryId, type TaskState, - type TaskSession, type TaskSessionState, type Repository, type Task, - type Message, } from "@/lib/types/http"; import type { KanbanState } from "@/lib/state/slices"; import { findTaskInSnapshots } from "@/lib/kanban/find-task"; import { repositorySlug } from "@/lib/repository-slug"; +import { statusSummaryActiveErrorPreview } from "@/lib/task-status-summary"; import { resolvePreferredSessionId } from "../task-select-helpers"; -import { agentErrorMessageForTask } from "@/lib/task-agent-error"; -import { - agentErrorAcknowledgementSessionIds, - usePersistResolvedAgentErrorAcknowledgements, -} from "../use-agent-error-acknowledgements"; import { mapSnapshotToKanban, sortByUpdatedAtDesc } from "./session-task-switcher-sheet-helpers"; type SheetItemCtx = { repositoryPathsById: Map; workflowNameById: Map; stepTitleById: Map; - sessionsById: Record; - sessionsByTaskId: Parameters[1]; - gitStatusByEnvId: Parameters[2]; - envIdBySessionId: Parameters[3]; - messagesBySession: Record; - dismissedAgentErrors: Record; - acknowledgedAgentErrors: Record; + acknowledgedAgentErrors?: Record; + dismissedAgentErrors?: Record; }; +function sheetDiffStats(summary: KanbanState["tasks"][number]["statusSummary"]) { + const git = summary?.git; + if (!git || ((git.additions ?? 0) <= 0 && (git.deletions ?? 0) <= 0)) return undefined; + return { additions: git.additions ?? 0, deletions: git.deletions ?? 0 }; +} + +function sheetRepositoryPath( + task: KanbanState["tasks"][number], + ctx: SheetItemCtx, +): string | undefined { + return task.repositoryId + ? ctx.repositoryPathsById.get(toRepositoryId(task.repositoryId)) + : undefined; +} + +function sheetPendingFlags( + summary: KanbanState["tasks"][number]["statusSummary"], + fallback?: string | null, +) { + const action = summary != null ? summary.pending_action : fallback; + return { + clarification: action === "clarification", + permission: action === "permission", + }; +} + +function sheetStatus(task: KanbanState["tasks"][number], ctx: SheetItemCtx) { + const summary = task.statusSummary; + const hasSummary = summary != null; + const pending = sheetPendingFlags(hasSummary ? summary : undefined, task.taskPendingAction); + return { + sessionState: hasSummary + ? summary?.primary_session?.state + : (task.primarySessionState as TaskSessionState | undefined), + foregroundActivity: hasSummary ? summary?.foreground_activity : task.foregroundActivity, + repositoryPath: sheetRepositoryPath(task, ctx), + diffStats: sheetDiffStats(summary), + updatedAt: hasSummary ? summary?.updated_at : task.updatedAt, + primarySessionId: hasSummary + ? (summary?.primary_session?.id ?? null) + : (task.primarySessionId ?? null), + hasPendingClarification: pending.clarification, + hasPendingPermission: pending.permission, + agentErrorMessage: statusSummaryActiveErrorPreview( + summary, + ctx.acknowledgedAgentErrors, + ctx.dismissedAgentErrors, + ), + }; +} + export function toSheetItem( task: KanbanState["tasks"][number] & { _workflowId: string }, ctx: SheetItemCtx, ) { - const sessionInfo = getSessionInfoForTask( - task.id, - ctx.sessionsByTaskId, - ctx.gitStatusByEnvId, - ctx.envIdBySessionId, - ); - const resolvedSessionState = - sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined); - const pending = pendingFlagsForTask( - task, - ctx.sessionsByTaskId[task.id] ?? [], - ctx.messagesBySession, - ); + const status = sheetStatus(task, ctx); return { id: task.id, title: task.title, @@ -75,62 +97,24 @@ export function toSheetItem( parentTaskId: task.parentTaskId ?? undefined, workspaceMode: task.workspaceMode, state: task.state as TaskState | undefined, - sessionState: resolvedSessionState, + ...status, // Task-level most-active-wins busy aggregate from the task record — the same // authoritative value the desktop sidebar (toSidebarItem) and board read, so the // mobile task-switcher row shows background-running and agrees with the board for // multi-session tasks instead of missing it. - foregroundActivity: task.foregroundActivity, description: task.description, workflowId: task._workflowId, workflowName: ctx.workflowNameById.get(task._workflowId), workflowStepId: task.workflowStepId, workflowStepTitle: ctx.stepTitleById.get(task.workflowStepId), - repositoryPath: task.repositoryId - ? ctx.repositoryPathsById.get(toRepositoryId(task.repositoryId)) - : undefined, - diffStats: sessionInfo.diffStats, - updatedAt: sessionInfo.updatedAt ?? task.updatedAt, isRemoteExecutor: task.isRemoteExecutor, remoteExecutorType: task.primaryExecutorType ?? undefined, remoteExecutorName: task.primaryExecutorName ?? undefined, - primarySessionId: task.primarySessionId ?? null, - hasPendingClarification: pending.clarification, - hasPendingPermission: pending.permission, - agentErrorMessage: agentErrorMessageForTask(task, ctx.sessionsById, ctx.sessionsByTaskId, ctx), }; } -function pendingFlagsForTask( - task: Pick, - sessions: TaskSession[], - messagesBySession: Record, -): { clarification: boolean; permission: boolean } { - const { clarification, permission } = aggregateTaskPendingInput( - sessions, - (session) => { - const messages = messagesBySession[session.id]; - if (messages === undefined) return undefined; - return { - clarification: hasPendingClarification(messages), - permission: hasPendingPermissionRequest(messages), - }; - }, - task.taskPendingAction, - ); - return { clarification, permission }; -} - export function useSheetData(workspaceId: string | null) { const activeTaskId = useAppStore((state) => state.tasks.activeTaskId); - const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); - const sessionsById = useAppStore((state) => state.taskSessions.items); - const sessionsByTaskId = useAppStore((state) => state.taskSessionsByTask.itemsByTaskId); - const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId); - const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId); - const messagesBySession = useAppStore((state) => state.messages.bySession); - const dismissedAgentErrors = useAppStore((state) => state.dismissedAgentErrors); - const acknowledgedAgentErrors = useAppStore((state) => state.acknowledgedAgentErrors); const { allTasks, allSteps, @@ -141,22 +125,10 @@ export function useSheetData(workspaceId: string | null) { const steps = useAppStore((state) => state.kanban.steps); const workspaces = useAppStore((state) => state.workspaces.items); const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId); + const acknowledgedAgentErrors = useAppStore((state) => state.acknowledgedAgentErrors); + const dismissedAgentErrors = useAppStore((state) => state.dismissedAgentErrors); - const selectedTaskId = useMemo(() => { - if (activeSessionId) return sessionsById[activeSessionId]?.task_id ?? activeTaskId; - return activeTaskId; - }, [activeSessionId, activeTaskId, sessionsById]); - - const acknowledgementSessionIds = useMemo( - () => agentErrorAcknowledgementSessionIds(allTasks, sessionsByTaskId), - [allTasks, sessionsByTaskId], - ); - usePersistResolvedAgentErrorAcknowledgements({ - sessionsById, - sessionIds: acknowledgementSessionIds, - messagesBySession, - dismissedAgentErrors, - }); + const selectedTaskId = activeTaskId; const tasksWithRepositories = useMemo(() => { const repositories = workspaceId ? (repositoriesByWorkspace[workspaceId] ?? []) : []; @@ -166,13 +138,8 @@ export function useSheetData(workspaceId: string | null) { ), workflowNameById: new Map(workflows.map((w) => [w.id, w.name])), stepTitleById: new Map(allSteps.map((s) => [s.id, s.title])), - sessionsById, - sessionsByTaskId, - gitStatusByEnvId, - envIdBySessionId, - messagesBySession, - dismissedAgentErrors, acknowledgedAgentErrors, + dismissedAgentErrors, }; return allTasks.map((task) => toSheetItem(task, ctx)); }, [ @@ -181,13 +148,8 @@ export function useSheetData(workspaceId: string | null) { allSteps, workflows, workspaceId, - sessionsById, - sessionsByTaskId, - gitStatusByEnvId, - envIdBySessionId, - messagesBySession, - dismissedAgentErrors, acknowledgedAgentErrors, + dismissedAgentErrors, ]); const dialogSteps = useMemo( diff --git a/apps/web/components/task/passthrough-chat-composer.tsx b/apps/web/components/task/passthrough-chat-composer.tsx index dec42a97f7..043d170afb 100644 --- a/apps/web/components/task/passthrough-chat-composer.tsx +++ b/apps/web/components/task/passthrough-chat-composer.tsx @@ -21,6 +21,7 @@ import { buildContextFilesContext, buildTaskMentionsContext } from "@/hooks/use- import { getWebSocketClient } from "@/lib/ws/connection"; import { getTaskPlan } from "@/lib/api/domains/plan-api"; import type { AppState } from "@/lib/state/store"; +import { generateUUID } from "@/lib/utils"; const PLAN_CONTEXT_PATH = "plan:context"; @@ -243,6 +244,7 @@ async function requestPassthroughMessage({ { task_id: taskId, session_id: sessionId, + client_message_id: generateUUID(), content: message.content, ...(hasAttachments && { attachments }), ...(message.contextFilesMeta && { context_files: message.contextFilesMeta }), diff --git a/apps/web/components/task/preview-session-tabs.test.tsx b/apps/web/components/task/preview-session-tabs.test.tsx index ced8e2588d..037938751e 100644 --- a/apps/web/components/task/preview-session-tabs.test.tsx +++ b/apps/web/components/task/preview-session-tabs.test.tsx @@ -82,6 +82,7 @@ describe("PreviewSessionBody send failures", () => { { task_id: "task-1", session_id: "session-1", + client_message_id: expect.any(String), content: "reference", attachments: [{ type: "image", data: "base64", mime_type: "image/png" }], entity_references: [reference], diff --git a/apps/web/components/task/task-changes-panel.tsx b/apps/web/components/task/task-changes-panel.tsx index 6f9b1977bb..8f0cb7d9b2 100644 --- a/apps/web/components/task/task-changes-panel.tsx +++ b/apps/web/components/task/task-changes-panel.tsx @@ -10,6 +10,7 @@ import { useGitOperations } from "@/hooks/use-git-operations"; import { useSessionFileReviews } from "@/hooks/use-session-file-reviews"; import { useCommentsStore, isDiffComment } from "@/lib/state/slices/comments"; import { getWebSocketClient } from "@/lib/ws/connection"; +import { generateUUID } from "@/lib/utils"; import { updateUserSettings } from "@/lib/api"; import { formatReviewCommentsAsMarkdown } from "@/lib/state/slices/comments/format"; import { ReviewDiffList } from "@/components/review/review-diff-list"; @@ -299,17 +300,15 @@ function useChangesActions( const markdown = formatReviewCommentsAsMarkdown(comments); if (!markdown) return; const client = getWebSocketClient(); - if (client) { + if (client) client .request("message.add", { task_id: activeTaskId, session_id: activeSessionId, + client_message_id: generateUUID(), content: markdown, }) - .catch(() => { - toast({ title: "Failed to send comments", variant: "error" }); - }); - } + .catch(() => toast({ title: "Failed to send comments", variant: "error" })); markCommentsSent(comments.map((c) => c.id)); }, [activeSessionId, activeTaskId, getPendingComments, markCommentsSent, toast]); diff --git a/apps/web/components/task/task-item.tsx b/apps/web/components/task/task-item.tsx index 9128b9b46a..15e10f54c7 100644 --- a/apps/web/components/task/task-item.tsx +++ b/apps/web/components/task/task-item.tsx @@ -13,7 +13,7 @@ import { IconPinFilled, IconShieldQuestion, } from "@tabler/icons-react"; -import { PRTaskIcon } from "@/components/github/pr-task-icon"; +import { getPRAggregateStatusColor, PRTaskIcon } from "@/components/github/pr-task-icon"; import { IssueTaskIcon } from "@/components/github/issue-task-icon"; import { useAppStore } from "@/components/state-provider"; import { cn, formatRelativeTime } from "@/lib/utils"; @@ -84,7 +84,7 @@ type TaskItemProps = { /** Toggles subtask visibility when the chevron is clicked. */ onToggleSubtasks?: () => void; repositories?: string[]; - prInfo?: { number: number; state: string }; + prInfo?: { number: number; state: string; aggregateState?: string }; issueInfo?: { url: string; number: number }; isPinned?: boolean; agentErrorMessage?: string | null; @@ -284,7 +284,7 @@ function TaskItemStatsRow({ primarySessionId, }: { updatedAt?: string; - prInfo?: { number: number; state: string }; + prInfo?: { number: number; state: string; aggregateState?: string }; primarySessionId?: string | null; }) { const pollMode = useAppStore((s) => @@ -342,17 +342,18 @@ function TaskPRIcon({ prInfo, }: { taskId?: string; - prInfo?: { number: number; state: string }; + prInfo?: { number: number; state: string; aggregateState?: string }; }) { const hasStorePR = useAppStore((s) => !!taskId && (s.taskPRs.byTaskId[taskId]?.length ?? 0) > 0); if (hasStorePR) return ; if (!prInfo) return null; - const state = prInfo.state.toLowerCase(); - let color = "text-muted-foreground"; - if (state === "merged") color = "text-purple-500"; - else if (state === "closed") color = "text-red-500"; + const color = getPRAggregateStatusColor(prInfo.aggregateState ?? prInfo.state); return ( - + ); @@ -383,7 +384,7 @@ function TaskItemContent({ isPinned?: boolean; repositories?: string[]; updatedAt?: string; - prInfo?: { number: number; state: string }; + prInfo?: { number: number; state: string; aggregateState?: string }; issueInfo?: { url: string; number: number }; agentErrorMessage?: string | null; }) { diff --git a/apps/web/components/task/task-session-sidebar-item.test.ts b/apps/web/components/task/task-session-sidebar-item.test.ts new file mode 100644 index 0000000000..3590b7a165 --- /dev/null +++ b/apps/web/components/task/task-session-sidebar-item.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from "vitest"; +import { buildSidebarItem } from "./task-session-sidebar-item"; + +type SidebarTask = Parameters[0]; +type SidebarContext = Parameters[1]; +const UPDATED_AT = "2026-07-22T00:00:00Z"; + +function emptyContext(): SidebarContext { + return { + repositorySlugById: new Map(), + titleById: new Map(), + workflowNameById: new Map(), + stepTitleById: new Map(), + }; +} + +function task(overrides: Partial = {}): SidebarTask { + return { + id: "t1", + _workflowId: "wf1", + title: "Task", + workflowStepId: "step-1", + ...overrides, + } as SidebarTask; +} + +describe("buildSidebarItem", () => { + it("keeps the PR aggregate state for the row icon", () => { + const item = buildSidebarItem( + task({ + statusSummary: { + revision: 1, + updated_at: UPDATED_AT, + pull_request: { + number: 42, + state: "open", + aggregate_state: "pending", + }, + }, + }), + emptyContext(), + ); + + expect(item.prInfo).toEqual({ number: 42, state: "Open", aggregateState: "pending" }); + }); + + it("uses summary presence as the authority for cleared session and pending fields", () => { + const item = buildSidebarItem( + task({ + taskPendingAction: "clarification", + primarySessionState: "RUNNING", + primarySessionId: "legacy-session", + foregroundActivity: "background", + updatedAt: "legacy-update", + statusSummary: { revision: 2, updated_at: UPDATED_AT }, + }), + emptyContext(), + ); + + expect(item.hasPendingClarification).toBe(false); + expect(item.sessionState).toBeUndefined(); + expect(item.primarySessionId).toBeNull(); + expect(item.foregroundActivity).toBeUndefined(); + expect(item.updatedAt).toBe(UPDATED_AT); + }); + + it("honors the summary error acknowledgement stamp", () => { + const item = buildSidebarItem( + task({ + statusSummary: { + revision: 3, + updated_at: UPDATED_AT, + active_error: { + session_id: "session-1", + stamp: "error-3", + occurred_at: UPDATED_AT, + preview: "Agent failed", + }, + }, + }), + { + ...emptyContext(), + acknowledgedAgentErrors: { "session-1": "error-3" }, + }, + ); + + expect(item.agentErrorMessage).toBeNull(); + }); +}); diff --git a/apps/web/components/task/task-session-sidebar-item.ts b/apps/web/components/task/task-session-sidebar-item.ts index 552cf06e54..b67ebf99e9 100644 --- a/apps/web/components/task/task-session-sidebar-item.ts +++ b/apps/web/components/task/task-session-sidebar-item.ts @@ -1,115 +1,138 @@ -import type { TaskPR } from "@/lib/types/github"; import type { KanbanState } from "@/lib/state/slices"; -import type { GitStatusEntry } from "@/lib/state/slices/session-runtime/types"; -import type { TaskSession, TaskSessionState, TaskState } from "@/lib/types/http"; -import { getSessionInfoForTask } from "@/lib/utils/session-info"; -import { type AgentErrorOptions, agentErrorMessageForTask } from "@/lib/task-agent-error"; -import { readTaskPendingFlags, workflowStepTitle } from "./task-session-sidebar-aggregate"; +import type { TaskSessionState, TaskState } from "@/lib/types/http"; +import type { TaskStatusSummary } from "@/lib/types/task-status-summary"; +import { statusSummaryActiveErrorPreview } from "@/lib/task-status-summary"; +import { workflowStepTitle } from "./task-session-sidebar-aggregate"; -type SidebarItemContext = AgentErrorOptions & { - sessionsById: Record; - sessionsByTaskId: Record; - gitStatusByEnvId: Record; - envIdBySessionId: Record; +type SidebarItemContext = { repositorySlugById: Map; - taskPRsByTaskId: Record; - pendingFlags: Record; titleById: Map; workflowNameById: Map; stepTitleById: Map; + acknowledgedAgentErrors?: Record; + dismissedAgentErrors?: Record; }; -function resolveDiffStats( - sessionDiffStats: { additions: number; deletions: number } | undefined, - task: { primarySessionId?: string | null }, - envIdBySessionId: Record, - gitStatusByEnvId: Record, +function summaryDiffStats( + summary: TaskStatusSummary | null | undefined, ): { additions: number; deletions: number } | undefined { - if (sessionDiffStats || !task.primarySessionId) return sessionDiffStats; - const envKey = envIdBySessionId[task.primarySessionId] ?? task.primarySessionId; - const gitStatus = gitStatusByEnvId[envKey]; - if (!gitStatus) return undefined; - const additions = gitStatus.branch_additions ?? 0; - const deletions = gitStatus.branch_deletions ?? 0; + const git = summary?.git; + if (!git) return undefined; + const additions = git.additions ?? 0; + const deletions = git.deletions ?? 0; return additions > 0 || deletions > 0 ? { additions, deletions } : undefined; } -function toPrInfo(pr: TaskPR | undefined): { number: number; state: string } | undefined { - if (!pr?.state) return undefined; - return { number: pr.pr_number, state: pr.state[0].toUpperCase() + pr.state.slice(1) }; +function capitalize(value: string): string { + return value.length > 0 ? value[0].toUpperCase() + value.slice(1) : value; } -function toIssueInfo( +function summaryPRInfo( + summary: TaskStatusSummary | null | undefined, +): { number: number; state: string; aggregateState?: string } | undefined { + const pullRequest = summary?.pull_request; + if (!pullRequest?.number) return undefined; + return { + number: pullRequest.number, + state: capitalize(pullRequest.state ?? pullRequest.aggregate_state ?? "open"), + aggregateState: pullRequest.aggregate_state, + }; +} + +function repositoryPathFromSummary( + summary: TaskStatusSummary | null | undefined, +): string | undefined { + const url = summary?.pull_request?.url; + if (!url) return undefined; + try { + const path = new URL(url).pathname.split("/").filter(Boolean); + if (path.length >= 2) return `${path[0]}/${path[1]}`; + } catch { + // A malformed provider URL must not make the task switcher disappear. + } + return undefined; +} + +function pendingFlags(summary: TaskStatusSummary | null | undefined, fallback?: string | null) { + const action = summary != null ? summary.pending_action : fallback; + return { + clarification: action === "clarification", + permission: action === "permission", + }; +} + +function issueInfoForTask(task: KanbanState["tasks"][number]) { + if (!task.issueUrl || !task.issueNumber) return undefined; + return { url: task.issueUrl, number: task.issueNumber }; +} + +function sidebarSessionStatus( + summary: TaskStatusSummary | null | undefined, task: KanbanState["tasks"][number], -): { url: string; number: number } | undefined { - return task.issueUrl && task.issueNumber - ? { url: task.issueUrl, number: task.issueNumber } - : undefined; +) { + const primarySession = summary?.primary_session; + const hasSummary = summary != null; + return { + sessionState: (hasSummary ? primarySession?.state : task.primarySessionState) as + | TaskSessionState + | undefined, + foregroundActivity: hasSummary ? summary?.foreground_activity : task.foregroundActivity, + primarySessionId: hasSummary ? (primarySession?.id ?? null) : (task.primarySessionId ?? null), + updatedAt: hasSummary ? summary?.updated_at : (task.updatedAt ?? task.createdAt), + }; } -/** Map a kanban task to a sidebar item with session info and repository metadata. */ +function sidebarStatus( + task: KanbanState["tasks"][number] & { _workflowId: string }, + context: SidebarItemContext, +) { + const summary = task.statusSummary; + const pending = pendingFlags(summary, task.taskPendingAction); + const sessionStatus = sidebarSessionStatus(summary, task); + return { + ...sessionStatus, + agentErrorMessage: statusSummaryActiveErrorPreview( + summary, + context.acknowledgedAgentErrors, + context.dismissedAgentErrors, + ), + repositoryPath: + repositoryPathFromSummary(summary) ?? + (task.repositoryId ? context.repositorySlugById.get(task.repositoryId) : undefined), + diffStats: summaryDiffStats(summary), + hasPendingClarification: pending.clarification, + hasPendingPermission: pending.permission, + prInfo: summaryPRInfo(summary), + issueInfo: issueInfoForTask(task), + }; +} + +/** Map a task-level status projection to a sidebar item without session streams. */ export function buildSidebarItem( task: KanbanState["tasks"][number] & { _workflowId: string }, context: SidebarItemContext, ) { - const sessionInfo = getSessionInfoForTask( - task.id, - context.sessionsByTaskId, - context.gitStatusByEnvId, - context.envIdBySessionId, - ); - const sessionState = - sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined); - const repositoryPath = task.repositoryId - ? context.repositorySlugById.get(task.repositoryId) - : undefined; - const pr = context.taskPRsByTaskId[task.id]?.[0]; - const pending = readTaskPendingFlags( - context.pendingFlags, - context.sessionsByTaskId[task.id] ?? [], - task.taskPendingAction, - ); + const status = sidebarStatus(task, context); return { id: task.id, title: task.title, state: task.state as TaskState | undefined, - sessionState, - // Use the task-level aggregate so multi-session and off-screen rows match other task views. - foregroundActivity: task.foregroundActivity, + ...status, description: task.description, workflowId: task._workflowId, workflowName: context.workflowNameById.get(task._workflowId), workflowStepId: task.workflowStepId as string | undefined, workflowStepTitle: workflowStepTitle(task, context.stepTitleById), - repositoryPath: pr ? `${pr.owner}/${pr.repo}` : repositoryPath, - diffStats: resolveDiffStats( - sessionInfo.diffStats, - task, - context.envIdBySessionId, - context.gitStatusByEnvId, - ), isRemoteExecutor: task.isRemoteExecutor, remoteExecutorType: task.primaryExecutorType ?? undefined, remoteExecutorName: task.primaryExecutorName ?? undefined, - primarySessionId: task.primarySessionId ?? null, - hasPendingClarification: pending.clarification, - hasPendingPermission: pending.permission, - updatedAt: sessionInfo.updatedAt ?? task.updatedAt ?? task.createdAt, createdAt: task.createdAt, isArchived: false as boolean, parentTaskTitle: task.parentTaskId ? context.titleById.get(task.parentTaskId) : undefined, parentTaskId: task.parentTaskId ?? undefined, workspaceMode: task.workspaceMode, - prInfo: toPrInfo(pr), isPRReview: task.isPRReview ?? false, isIssueWatch: task.isIssueWatch ?? false, - issueInfo: toIssueInfo(task), - agentErrorMessage: agentErrorMessageForTask( - task, - context.sessionsById, - context.sessionsByTaskId, - context, - ), }; } diff --git a/apps/web/components/task/task-session-sidebar.tsx b/apps/web/components/task/task-session-sidebar.tsx index 1409302bd6..9a36fe5650 100644 --- a/apps/web/components/task/task-session-sidebar.tsx +++ b/apps/web/components/task/task-session-sidebar.tsx @@ -1,9 +1,9 @@ "use client"; -import { useCallback, useEffect, useMemo, useState, memo } from "react"; +import { useCallback, useMemo, useState, memo } from "react"; import { usePathname, useRouter } from "@/lib/routing/client-router"; import { linkToTask } from "@/lib/links"; -import type { Repository, TaskSession, TaskSessionState } from "@/lib/types/http"; +import type { Repository, TaskSessionState } from "@/lib/types/http"; import { PluginSlot } from "@/components/plugins/plugin-slot"; import { TaskSwitcher, type TaskSwitcherItem } from "./task-switcher"; import { buildTaskSwitcherProps } from "./task-session-sidebar-switcher-props"; @@ -21,27 +21,13 @@ import { useTaskRemoval } from "@/hooks/use-task-removal"; import { findTaskInSnapshots } from "@/lib/kanban/find-task"; import { repositorySlug } from "@/lib/repository-slug"; import { buildSwitchToSession, selectTaskWithLayout } from "./task-select-helpers"; -import { getWebSocketClient } from "@/lib/ws/connection"; import { useArchivedTaskState } from "./task-archived-context"; import { useRepositories } from "@/hooks/domains/workspace/use-repositories"; -import { useWorkspacePRs } from "@/hooks/domains/github/use-task-pr"; -import { buildPendingFlags } from "./task-session-sidebar-aggregate"; import { useGroupedSidebarView } from "./task-session-sidebar-grouped-view"; import { useSidebarLinkActions } from "./task-session-sidebar-link-actions"; import { buildArchivedSidebarItem } from "./task-session-sidebar-archived-item"; import { useSidebarTaskLinking } from "./task-session-sidebar-task-linking"; -import { useShallow } from "zustand/react/shallow"; import { buildSidebarItem } from "./task-session-sidebar-item"; -import { - agentErrorAcknowledgementSessionIds, - stablePrimarySessionIdsKey, - usePersistResolvedAgentErrorAcknowledgements, -} from "./use-agent-error-acknowledgements"; - -function useStablePrimarySessionIds(allTasks: Array<{ primarySessionId?: string | null }>) { - const key = useMemo(() => stablePrimarySessionIdsKey(allTasks), [allTasks]); - return useMemo(() => (key ? key.split("\0") : []), [key]); -} type TaskSessionSidebarProps = { workspaceId: string | null; @@ -50,36 +36,13 @@ type TaskSessionSidebarProps = { hideFilterBar?: boolean; }; -function usePendingSessionIds( - primarySessionIds: string[], - sessionsByTaskId: Record, -) { - return useMemo( - () => - Array.from( - new Set([ - ...primarySessionIds, - ...Object.values(sessionsByTaskId) - .flat() - .map((session) => session.id), - ]), - ), - [primarySessionIds, sessionsByTaskId], - ); -} - function useSidebarData(workspaceId: string | null) { const activeTaskId = useAppStore((state) => state.tasks.activeTaskId); const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); const sessionsById = useAppStore((state) => state.taskSessions.items); - const sessionsByTaskId = useAppStore((state) => state.taskSessionsByTask.itemsByTaskId); - const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId); - const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId); - const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId); - const taskPRsByTaskId = useAppStore((state) => state.taskPRs.byTaskId); - const messagesBySession = useAppStore((state) => state.messages.bySession); - const dismissedAgentErrors = useAppStore((state) => state.dismissedAgentErrors); const acknowledgedAgentErrors = useAppStore((state) => state.acknowledgedAgentErrors); + const dismissedAgentErrors = useAppStore((state) => state.dismissedAgentErrors); + const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId); const archivedState = useArchivedTaskState(); const selectedTaskId = useMemo(() => { @@ -95,22 +58,6 @@ function useSidebarData(workspaceId: string | null) { isLoading: isLoadingWorkflow, } = useWorkspaceSidebarTasks(workspaceId); - const primarySessionIds = useStablePrimarySessionIds(allTasks); - const pendingSessionIds = usePendingSessionIds(primarySessionIds, sessionsByTaskId); - const acknowledgementSessionIds = useMemo( - () => agentErrorAcknowledgementSessionIds(allTasks, sessionsByTaskId), - [allTasks, sessionsByTaskId], - ); - usePersistResolvedAgentErrorAcknowledgements({ - sessionsById, - sessionIds: acknowledgementSessionIds, - messagesBySession, - dismissedAgentErrors, - }); - const pendingFlags = useAppStore( - useShallow((state) => buildPendingFlags(state.messages.bySession, pendingSessionIds)), - ); - const tasksWithRepositories = useMemo(() => { const repositories = workspaceId ? (repositoriesByWorkspace[workspaceId] ?? []) : []; const repositorySlugById = new Map( @@ -120,19 +67,12 @@ function useSidebarData(workspaceId: string | null) { const workflowNameById = new Map(workflows.map((w) => [w.id, w.name])); const stepTitleById = new Map(allSteps.map((s) => [s.id, s.title])); const mapCtx = { - sessionsById, - sessionsByTaskId, - gitStatusByEnvId, - envIdBySessionId, repositorySlugById, - taskPRsByTaskId, - pendingFlags, titleById, workflowNameById, stepTitleById, - dismissedAgentErrors, acknowledgedAgentErrors, - messagesBySession, + dismissedAgentErrors, }; const items: TaskSwitcherItem[] = allTasks.map((task) => buildSidebarItem(task, mapCtx)); if ( @@ -149,16 +89,9 @@ function useSidebarData(workspaceId: string | null) { allSteps, workflows, workspaceId, - sessionsByTaskId, - sessionsById, - gitStatusByEnvId, - envIdBySessionId, - taskPRsByTaskId, - pendingFlags, - dismissedAgentErrors, - acknowledgedAgentErrors, - messagesBySession, archivedState, + acknowledgedAgentErrors, + dismissedAgentErrors, ]); return { @@ -168,7 +101,6 @@ function useSidebarData(workspaceId: string | null) { stepsByWorkflowId, isLoadingWorkflow, tasksWithRepositories, - primarySessionIds, workflows, }; } @@ -437,28 +369,12 @@ export function useSidebarActions(store: StoreApi) { }; } -function useBulkGitStatusSubscription(primarySessionIds: string[]) { - const connectionStatus = useAppStore((state) => state.connection.status); - const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); - useEffect(() => { - if (connectionStatus !== "connected" || primarySessionIds.length === 0) return; - const client = getWebSocketClient(); - if (!client) return; - const backgroundIds = activeSessionId - ? primarySessionIds.filter((id) => id !== activeSessionId) - : primarySessionIds; - const unsubscribes = backgroundIds.map((id) => client.subscribeSession(id)); - return () => unsubscribes.forEach((u) => u()); - }, [primarySessionIds, connectionStatus, activeSessionId]); -} - export const TaskSessionSidebar = memo(function TaskSessionSidebar({ workspaceId, hideFilterBar, }: TaskSessionSidebarProps) { const store = useAppStoreApi(); useRepositories(workspaceId); - useWorkspacePRs(workspaceId); const pathname = usePathname(); const { @@ -468,7 +384,6 @@ export const TaskSessionSidebar = memo(function TaskSessionSidebar({ workflows, isLoadingWorkflow, tasksWithRepositories, - primarySessionIds, } = useSidebarData(workspaceId); // Only highlight while viewing a task route; AppSidebar is global and activeTaskId lingers. @@ -477,8 +392,6 @@ export const TaskSessionSidebar = memo(function TaskSessionSidebar({ const highlightedTaskId = onTaskRoute ? activeTaskId : null; const highlightedSelectedTaskId = onTaskRoute ? selectedTaskId : null; - useBulkGitStatusSubscription(primarySessionIds); - const sidebarActions = useSidebarActions(store); const { preparingTaskId } = sidebarActions; const taskLinkHandlers = useSidebarTaskLinking(workspaceId, sidebarActions); diff --git a/apps/web/components/task/task-switcher.tsx b/apps/web/components/task/task-switcher.tsx index 3e302ff6ab..3b3e22e452 100644 --- a/apps/web/components/task/task-switcher.tsx +++ b/apps/web/components/task/task-switcher.tsx @@ -40,7 +40,7 @@ export type TaskSwitcherItem = { parentTaskTitle?: string; parentTaskId?: string; workspaceMode?: "inherit_parent" | "new_workspace" | "shared_group"; - prInfo?: { number: number; state: string }; + prInfo?: { number: number; state: string; aggregateState?: string }; isPRReview?: boolean; isIssueWatch?: boolean; issueInfo?: { url: string; number: number }; diff --git a/apps/web/components/task/use-review-dialog.ts b/apps/web/components/task/use-review-dialog.ts index 896b959d07..94130b769e 100644 --- a/apps/web/components/task/use-review-dialog.ts +++ b/apps/web/components/task/use-review-dialog.ts @@ -15,6 +15,7 @@ import { useTaskRepositories } from "@/hooks/domains/kanban/use-task-repositorie import { formatReviewCommentsAsMarkdown } from "@/components/task/chat/messages/review-comments-attachment"; import { getCumulativeReviewRepositoryNames, isReviewMultiRepo } from "@/components/review/types"; import { getWebSocketClient } from "@/lib/ws/connection"; +import { generateUUID } from "@/lib/utils"; import { useToast } from "@/components/toast-provider"; import type { DiffComment } from "@/lib/diff/types"; import type { FileInfo, GitStatusEntry } from "@/lib/state/slices/session-runtime/types"; @@ -134,7 +135,12 @@ export function useReviewDialog(effectiveSessionId: string | null) { client .request( "message.add", - { task_id: activeTaskId, session_id: effectiveSessionId, content: markdown }, + { + task_id: activeTaskId, + session_id: effectiveSessionId, + client_message_id: generateUUID(), + content: markdown, + }, 10000, ) .catch(() => { diff --git a/apps/web/e2e/helpers/ws-drop.ts b/apps/web/e2e/helpers/ws-drop.ts index 2d7f2eb541..a568885822 100644 --- a/apps/web/e2e/helpers/ws-drop.ts +++ b/apps/web/e2e/helpers/ws-drop.ts @@ -10,10 +10,30 @@ type PromptDropController = { droppedCount: () => number; }; +type MessageAddResponseDropController = { + dropNextMessageAddResponse: () => void; + droppedCount: () => number; +}; + function asRecord(value: unknown): Record | null { return typeof value === "object" && value !== null ? (value as Record) : null; } +function parseJSONFrames(message: string | Buffer): Array> { + if (typeof message !== "string") return []; + const frames: Array> = []; + for (const part of message.split("\n")) { + if (!part.trim()) continue; + try { + const parsed = asRecord(JSON.parse(part)); + if (parsed) frames.push(parsed); + } catch { + // Preserve non-JSON frames; the app's WS client handles parse failures too. + } + } + return frames; +} + function isTargetUserMessageAdded( message: unknown, prompt: string, @@ -81,3 +101,93 @@ export async function routeMainWebSocketWithPromptDrop(page: Page): Promise dropped.length, }; } + +function filterMessageAddResponses( + message: string | Buffer, + requestIDs: Set, + armed: { value: boolean }, + dropped: { value: number }, +): string | Buffer | null { + if (typeof message !== "string" || !armed.value) return message; + + const kept: string[] = []; + let didDrop = false; + for (const part of message.split("\n")) { + const trimmed = part.trim(); + if (!trimmed) { + kept.push(part); + continue; + } + + let responseID: string | undefined; + try { + const frame = asRecord(JSON.parse(trimmed)); + if ( + frame?.type === "response" && + frame.action === "message.add" && + typeof frame.id === "string" && + requestIDs.has(frame.id) + ) { + responseID = frame.id; + } + } catch { + // Preserve non-JSON frames. + } + + if (responseID) { + requestIDs.delete(responseID); + armed.value = false; + dropped.value += 1; + didDrop = true; + continue; + } + kept.push(part); + } + + if (!didDrop) return message; + const filtered = kept.join("\n"); + return filtered.trim() ? filtered : null; +} + +/** + * Drops one correlated `message.add` response while preserving the request, + * notification, and every unrelated frame. This exercises the UI's + * stable-ID reconciliation path without disconnecting the whole socket. + */ +export async function routeMainWebSocketWithMessageAddResponseDrop( + page: Page, +): Promise { + const requestIDs = new Set(); + const armed = { value: false }; + const dropped = { value: 0 }; + + await page.routeWebSocket(/\/ws$/, (ws) => { + const server = ws.connectToServer(); + ws.onMessage((message) => { + for (const frame of parseJSONFrames(message)) { + if ( + armed.value && + frame.type === "request" && + frame.action === "message.add" && + typeof frame.id === "string" + ) { + requestIDs.add(frame.id); + } + } + server.send(message); + }); + server.onMessage((message) => { + const filtered = filterMessageAddResponses(message, requestIDs, armed, dropped); + if (filtered !== null) ws.send(filtered); + }); + }); + + return { + dropNextMessageAddResponse: () => { + requestIDs.clear(); + armed.value = true; + dropped.value = 0; + }, + droppedCount: () => dropped.value, + }; +} diff --git a/apps/web/e2e/helpers/ws-traffic.ts b/apps/web/e2e/helpers/ws-traffic.ts new file mode 100644 index 0000000000..1d0892dd00 --- /dev/null +++ b/apps/web/e2e/helpers/ws-traffic.ts @@ -0,0 +1,142 @@ +import type { Page } from "@playwright/test"; + +export type GatewayTrafficFrame = { + direction: "sent" | "received"; + action?: string; + type?: string; + sessionId?: string; + taskId?: string; + bytes: number; + timestamp: number; +}; + +export type GatewayTrafficSummary = { + frameCount: number; + byteCount: number; + sentFrameCount: number; + sentByteCount: number; + receivedFrameCount: number; + receivedByteCount: number; + byAction: Record< + string, + { + sent: number; + received: number; + bytes: number; + } + >; +}; + +type WireMessage = { + action?: unknown; + type?: unknown; + payload?: unknown; +}; + +function decodePayload(payload: string | Buffer | Uint8Array): string | null { + if (typeof payload === "string") return payload; + try { + return new TextDecoder("utf-8", { fatal: false }).decode(payload); + } catch { + return null; + } +} + +function payloadBytes(payload: string | Buffer | Uint8Array): number { + return typeof payload === "string" ? Buffer.byteLength(payload, "utf8") : payload.byteLength; +} + +function parseMessage(payload: string | Buffer | Uint8Array): WireMessage | null { + const decoded = decodePayload(payload); + if (!decoded) return null; + try { + const parsed = JSON.parse(decoded) as WireMessage; + return parsed && typeof parsed === "object" ? parsed : null; + } catch { + return null; + } +} + +function stringField(value: unknown): string | undefined { + return typeof value === "string" && value.length > 0 ? value : undefined; +} + +function frameFromPayload( + direction: GatewayTrafficFrame["direction"], + payload: string | Buffer | Uint8Array, +): GatewayTrafficFrame { + const message = parseMessage(payload); + const messagePayload = + message?.payload && typeof message.payload === "object" + ? (message.payload as Record) + : undefined; + + return { + direction, + action: stringField(message?.action), + type: stringField(message?.type), + sessionId: + stringField(messagePayload?.session_id) ?? + stringField((message as Record | null)?.session_id), + taskId: + stringField(messagePayload?.task_id) ?? + stringField((message as Record | null)?.task_id), + bytes: payloadBytes(payload), + timestamp: Date.now(), + }; +} + +/** + * Capture only the gateway WebSocket. Terminal/preview sockets are deliberately + * excluded so the result measures task/session traffic rather than transport + * noise from other panels. + */ +export function attachGatewayTrafficCapture(page: Page): { frames: GatewayTrafficFrame[] } { + const frames: GatewayTrafficFrame[] = []; + page.on("websocket", (webSocket) => { + if (!webSocket.url().endsWith("/ws")) return; + webSocket.on("framesent", (event) => { + frames.push(frameFromPayload("sent", event.payload)); + }); + webSocket.on("framereceived", (event) => { + frames.push(frameFromPayload("received", event.payload)); + }); + }); + return { frames }; +} + +export function summarizeGatewayTraffic( + frames: readonly GatewayTrafficFrame[], +): GatewayTrafficSummary { + const summary: GatewayTrafficSummary = { + frameCount: frames.length, + byteCount: 0, + sentFrameCount: 0, + sentByteCount: 0, + receivedFrameCount: 0, + receivedByteCount: 0, + byAction: {}, + }; + + for (const frame of frames) { + summary.byteCount += frame.bytes; + if (frame.direction === "sent") { + summary.sentFrameCount += 1; + summary.sentByteCount += frame.bytes; + } else { + summary.receivedFrameCount += 1; + summary.receivedByteCount += frame.bytes; + } + + const action = frame.action ?? ""; + const actionSummary = (summary.byAction[action] ??= { + sent: 0, + received: 0, + bytes: 0, + }); + actionSummary[frame.direction] += 1; + actionSummary.bytes += frame.bytes; + } + + return summary; +} diff --git a/apps/web/e2e/tests/chat/message-send-pressure.spec.ts b/apps/web/e2e/tests/chat/message-send-pressure.spec.ts new file mode 100644 index 0000000000..62d711f9f4 --- /dev/null +++ b/apps/web/e2e/tests/chat/message-send-pressure.spec.ts @@ -0,0 +1,77 @@ +import { expect } from "@playwright/test"; +import { test } from "../../fixtures/test-base"; +import { routeMainWebSocketWithMessageAddResponseDrop } from "../../helpers/ws-drop"; +import { openTaskSession } from "../../helpers/session"; + +test.describe("Message send under notification pressure", () => { + test("reconciles a lost response without duplicating the prompt or turn", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + + const wsDrop = await routeMainWebSocketWithMessageAddResponseDrop(testPage); + const task = await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Message send pressure", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id"); + + const session = await openTaskSession(testPage, task.id); + await session.waitForChatIdle({ timeout: 45_000 }); + + const modelSelector = testPage.getByRole("button", { name: "Session model settings" }); + await expect(modelSelector).toBeVisible({ timeout: 15_000 }); + + const beforeMessages = await apiClient.listSessionMessages(task.session_id); + const beforeTurns = await apiClient.listSessionTurns(task.session_id); + + // These events are deliberately irrelevant to the task summary, but they + // exercise the selected session's stream while the task-level sidebar + // remains bounded. + await apiClient.seedToolCallMessages(task.session_id, 80); + const pressuredMessages = await apiClient.listSessionMessages(task.session_id); + expect( + pressuredMessages.messages.filter((message) => + message.content.startsWith("synthetic tool call "), + ), + ).toHaveLength(80); + await expect(modelSelector).toBeVisible(); + + const prompt = "/slow 8s"; + wsDrop.dropNextMessageAddResponse(); + await session.sendMessageViaButton(prompt); + + await expect + .poll(wsDrop.droppedCount, { + message: "expected the test proxy to drop the correlated message.add response", + timeout: 20_000, + }) + .toBeGreaterThan(0); + await expect( + session.chat.locator(".chat-message-list:visible").getByText(prompt, { exact: false }), + ).toBeVisible({ timeout: 20_000 }); + await session.waitForChatIdle({ timeout: 45_000 }); + await expect(modelSelector).toBeVisible(); + + const afterMessages = await apiClient.listSessionMessages(task.session_id); + const afterTurns = await apiClient.listSessionTurns(task.session_id); + expect( + afterMessages.messages.filter( + (message) => message.author_type === "user" && message.content === prompt, + ), + ).toHaveLength(1); + expect(afterMessages.messages.length).toBeGreaterThanOrEqual( + beforeMessages.messages.length + 1, + ); + expect(afterTurns.turns).toHaveLength(beforeTurns.turns.length + 1); + }); +}); diff --git a/apps/web/e2e/tests/session/session-stream-budget.spec.ts b/apps/web/e2e/tests/session/session-stream-budget.spec.ts new file mode 100644 index 0000000000..9214005b08 --- /dev/null +++ b/apps/web/e2e/tests/session/session-stream-budget.spec.ts @@ -0,0 +1,165 @@ +import { expect } from "@playwright/test"; +import { test } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; +import { + attachGatewayTrafficCapture, + summarizeGatewayTraffic, + type GatewayTrafficFrame, +} from "../../helpers/ws-traffic"; + +const TASK_COUNT = 27; +const SWITCH_COUNT = 5; +const MAX_SUBSCRIPTION_OPERATIONS = SWITCH_COUNT * 3; + +const SESSION_DETAIL_ACTIONS = new Set([ + "session.message.added", + "session.message.updated", + "session.message.deleted", + "session.git.event", + "session.shell.output", + "session.process.output", + "session.process.status", + "session.available_commands", + "session.mode_changed", + "session.agent_capabilities", + "session.models_updated", + "session.mcp_status_updated", + "session.info_updated", + "session.todos_updated", + "session.prompt_usage", + "session.workspace_sources.updated", + "workspace.file.changes", +]); + +type SeededTask = { + id: string; + title: string; + sessionId: string; +}; + +function trafficTaskTitle(index: number): string { + return `Traffic Task ${String(index + 1).padStart(2, "0")}`; +} + +function sessionIdFromFrame(frame: GatewayTrafficFrame): string | undefined { + return frame.sessionId; +} + +test.describe("Session stream budget", () => { + test("keeps task-switcher traffic bounded with 27 task sessions", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(180_000); + + const capture = attachGatewayTrafficCapture(testPage); + const trafficStep = await apiClient.createWorkflowStep( + seedData.workflowId, + "Traffic measurement", + 1, + ); + const tasks = await Promise.all( + Array.from({ length: TASK_COUNT }, (_, index) => + apiClient.createTask(seedData.workspaceId, trafficTaskTitle(index), { + workflow_id: seedData.workflowId, + workflow_step_id: trafficStep.id, + }), + ), + ); + + const seededTasks: SeededTask[] = await Promise.all( + tasks.map(async (task, index) => { + const { session_id: sessionId } = await apiClient.seedTaskSession(task.id, { + state: "WAITING_FOR_INPUT", + agentProfileId: seedData.agentProfileId, + repositoryId: seedData.repositoryId, + }); + return { id: task.id, title: trafficTaskTitle(index), sessionId }; + }), + ); + const switchTasks = seededTasks.slice(0, SWITCH_COUNT); + const switchSessionIds = new Set(switchTasks.map((task) => task.sessionId)); + + await testPage.goto(`/t/${switchTasks[0].id}`); + const session = new SessionPage(testPage); + await session.waitForLoad(); + await expect(session.sidebarTaskItem(switchTasks[0].title)).toHaveAttribute( + "aria-current", + "true", + { timeout: 30_000 }, + ); + + await expect + .poll(() => session.sidebar.getByTestId("sidebar-task-item").count(), { + timeout: 30_000, + message: `expected all ${TASK_COUNT} task rows in the sidebar`, + }) + .toBeGreaterThanOrEqual(TASK_COUNT); + + // Exercise the inactive-session message path while only the selected task + // is subscribed. Under the old sidebar implementation these writes also + // produced message detail frames in the browser for every inactive row. + await Promise.all( + seededTasks.slice(SWITCH_COUNT).map((task, index) => + apiClient.seedSessionMessage(task.sessionId, { + type: "message", + content: `inactive traffic probe ${index + 1}`, + }), + ), + ); + + for (const task of switchTasks.slice(1)) { + await session.sidebarTaskItem(task.title).click(); + await expect(session.sidebarTaskItem(task.title)).toHaveAttribute("aria-current", "true", { + timeout: 15_000, + }); + } + + // Leave a deliberate five-second observation window after the five task + // switches. This is a diagnostic total, not a compression-dependent + // correctness threshold. + await testPage.waitForTimeout(5_000); + + const summary = summarizeGatewayTraffic(capture.frames); + await test.info().attach("gateway-traffic.json", { + body: JSON.stringify(summary, null, 2), + contentType: "application/json", + }); + test.info().annotations.push({ + type: "gateway-traffic", + description: JSON.stringify(summary), + }); + console.log(`[gateway-traffic] ${JSON.stringify(summary)}`); + + const sentSubscribes = capture.frames.filter( + (frame) => frame.direction === "sent" && frame.action === "session.subscribe", + ); + const sentUnsubscribes = capture.frames.filter( + (frame) => frame.direction === "sent" && frame.action === "session.unsubscribe", + ); + + expect(sentSubscribes.length).toBeLessThanOrEqual(MAX_SUBSCRIPTION_OPERATIONS); + expect(sentUnsubscribes.length).toBeLessThanOrEqual(MAX_SUBSCRIPTION_OPERATIONS); + expect( + sentSubscribes.filter((frame) => !switchSessionIds.has(frame.sessionId ?? "")), + "inactive task sessions must not be subscribed by the task switcher", + ).toEqual([]); + expect( + sentUnsubscribes.filter((frame) => !switchSessionIds.has(frame.sessionId ?? "")), + "inactive task sessions must not be unsubscribed by the task switcher", + ).toEqual([]); + + const inactiveDetailFrames = capture.frames.filter( + (frame) => + frame.direction === "received" && + SESSION_DETAIL_ACTIONS.has(frame.action ?? "") && + frame.sessionId != null && + !switchSessionIds.has(sessionIdFromFrame(frame) ?? ""), + ); + expect( + inactiveDetailFrames, + "inactive task rows must not receive session detail streams", + ).toEqual([]); + }); +}); diff --git a/apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts b/apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts new file mode 100644 index 0000000000..a088aec414 --- /dev/null +++ b/apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts @@ -0,0 +1,98 @@ +import { expect } from "@playwright/test"; +import { test } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; + +const TARGET_TITLE = "Mobile inactive summary target"; + +test.describe("Mobile task status summary", () => { + test("updates the native task switcher from bounded status revisions", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(90_000); + + const stepOptions = { + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + }; + const navTask = await apiClient.seedTask( + seedData.workspaceId, + "Mobile summary navigation", + stepOptions, + ); + const targetTask = await apiClient.seedTask(seedData.workspaceId, TARGET_TITLE, stepOptions); + await apiClient.seedTaskSession(navTask.task_id, { + state: "WAITING_FOR_INPUT", + agentProfileId: seedData.agentProfileId, + }); + const targetSession = await apiClient.seedTaskSession(targetTask.task_id, { + state: "WAITING_FOR_INPUT", + agentProfileId: seedData.agentProfileId, + }); + + await testPage.goto(`/t/${navTask.task_id}`); + const session = new SessionPage(testPage); + await session.waitForLoad(); + await testPage.getByTestId("mobile-session-menu").click(); + const sheet = testPage.getByRole("dialog"); + const targetRow = sheet.getByTestId("sidebar-task-item").filter({ + hasText: TARGET_TITLE, + }); + await expect(targetRow).toBeVisible({ timeout: 15_000 }); + + await apiClient.seedSessionMessage(targetSession.session_id, { + type: "clarification_request", + content: "Choose a mobile-safe approach", + }); + await expect(targetRow.getByTestId("task-state-waiting-for-input")).toBeVisible({ + timeout: 15_000, + }); + + await apiClient.seedTaskSession(targetTask.task_id, { + sessionId: targetSession.session_id, + state: "WAITING_FOR_INPUT", + metadata: { + last_agent_error: { + message: "Mobile inactive agent failed", + occurred_at: new Date().toISOString(), + }, + }, + }); + await expect(targetRow.getByTestId("task-agent-error-icon")).toBeVisible({ timeout: 15_000 }); + + await apiClient.mockGitHubAssociateTaskPR({ + workspace_id: seedData.workspaceId, + task_id: targetTask.task_id, + owner: "kandev-e2e", + repo: "mobile-summary-fixtures", + pr_number: 43, + pr_url: "https://github.test/kandev-e2e/mobile-summary-fixtures/pull/43", + pr_title: "Mobile bounded summary fixture", + head_branch: "feature/mobile-summary", + base_branch: "main", + author_login: "e2e", + state: "open", + review_state: "approved", + checks_state: "success", + mergeable_state: "clean", + required_reviews: 1, + checks_total: 1, + checks_passing: 1, + }); + await expect(targetRow.getByTestId(`pr-task-icon-${targetTask.task_id}`)).toHaveAttribute( + "data-pr-state", + "open", + { timeout: 15_000 }, + ); + + const viewport = testPage.viewportSize(); + expect(viewport).not.toBeNull(); + expect( + await testPage.evaluate( + () => document.documentElement.scrollWidth <= document.documentElement.clientWidth, + ), + ).toBe(true); + expect(viewport!.width).toBeGreaterThan(0); + }); +}); diff --git a/apps/web/e2e/tests/task/sidebar-diff-stats.spec.ts b/apps/web/e2e/tests/task/sidebar-diff-stats.spec.ts index 7e7349e0a1..67c9f3a47a 100644 --- a/apps/web/e2e/tests/task/sidebar-diff-stats.spec.ts +++ b/apps/web/e2e/tests/task/sidebar-diff-stats.spec.ts @@ -4,8 +4,7 @@ import { SessionPage } from "../../pages/session-page"; /** * Regression test for the task sidebar diff badge bug. * - * The sidebar bulk-subscribes to every task's primary session on connect and - * expects an initial git status snapshot per session, including the global + * The sidebar consumes the task status summary, including the global * branch_additions/branch_deletions diff against the merge-base. Before the * fix, the backend's `tryGetLiveGitStatus` only returned data when an * agentctl execution was actively running for that session. For any task @@ -18,8 +17,8 @@ import { SessionPage } from "../../pages/session-page"; * keeping the DB-snapshot fallback fresh across restarts and unavailability. * * This test creates two tasks that produce diffs, restarts the backend - * (which kills all running executors), then asserts the sidebar still shows - * +N/-N badges for BOTH tasks — not just an active one. + * (which kills all running executors), then asserts the inactive sidebar row + * still shows its +N/-N badge from the persisted task summary. */ test.describe("Task sidebar diff stats", () => { test("badges survive backend restart for non-active tasks", async ({ diff --git a/apps/web/e2e/tests/task/task-status-summary.spec.ts b/apps/web/e2e/tests/task/task-status-summary.spec.ts new file mode 100644 index 0000000000..1160a663da --- /dev/null +++ b/apps/web/e2e/tests/task/task-status-summary.spec.ts @@ -0,0 +1,93 @@ +import { expect } from "@playwright/test"; +import { test } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; + +const TARGET_TITLE = "Inactive summary target"; + +test.describe("Task status summary", () => { + test("updates an inactive row from bounded clarification, error, and PR state", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(90_000); + + const stepOptions = { + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + }; + const navTask = await apiClient.seedTask( + seedData.workspaceId, + "Summary navigation", + stepOptions, + ); + const targetTask = await apiClient.seedTask(seedData.workspaceId, TARGET_TITLE, stepOptions); + const navSession = await apiClient.seedTaskSession(navTask.task_id, { + state: "WAITING_FOR_INPUT", + agentProfileId: seedData.agentProfileId, + }); + const targetSession = await apiClient.seedTaskSession(targetTask.task_id, { + state: "WAITING_FOR_INPUT", + agentProfileId: seedData.agentProfileId, + }); + + await testPage.goto(`/t/${navTask.task_id}`); + const session = new SessionPage(testPage); + await session.waitForLoad(); + const targetRow = session.sidebarTaskItem(TARGET_TITLE); + await expect(targetRow).toBeVisible({ timeout: 15_000 }); + + await apiClient.seedSessionMessage(targetSession.session_id, { + type: "clarification_request", + content: "Which approach should I use?", + }); + await expect(targetRow.getByTestId("task-state-waiting-for-input")).toBeVisible({ + timeout: 15_000, + }); + + const occurredAt = new Date().toISOString(); + await apiClient.seedTaskSession(targetTask.task_id, { + sessionId: targetSession.session_id, + state: "WAITING_FOR_INPUT", + metadata: { + last_agent_error: { + message: "Inactive agent failed", + occurred_at: occurredAt, + }, + }, + }); + await expect(targetRow.getByTestId("task-agent-error-icon")).toBeVisible({ timeout: 15_000 }); + + await apiClient.mockGitHubAssociateTaskPR({ + workspace_id: seedData.workspaceId, + task_id: targetTask.task_id, + owner: "kandev-e2e", + repo: "summary-fixtures", + pr_number: 42, + pr_url: "https://github.test/kandev-e2e/summary-fixtures/pull/42", + pr_title: "Bounded summary fixture", + head_branch: "feature/summary", + base_branch: "main", + author_login: "e2e", + state: "open", + review_state: "changes_requested", + checks_state: "failure", + mergeable_state: "dirty", + required_reviews: 1, + checks_total: 1, + checks_passing: 0, + }); + await expect(targetRow.getByText("#42", { exact: true })).toBeVisible({ timeout: 15_000 }); + await expect(targetRow.getByTestId("task-agent-error-icon")).toBeVisible(); + await expect(targetRow.getByTestId("task-state-waiting-for-input")).toBeVisible(); + + // The navigation task is deliberately selected throughout: every update + // above must arrive through task.status_summary.updated, not an inactive + // session detail subscription. + await expect(session.activeSidebarTaskItem("Summary navigation")).toHaveAttribute( + "aria-current", + "true", + ); + expect(navSession.session_id).toBeTruthy(); + }); +}); diff --git a/apps/web/hooks/domains/comments/use-run-comment.ts b/apps/web/hooks/domains/comments/use-run-comment.ts index 2fe9c83230..fde457be7d 100644 --- a/apps/web/hooks/domains/comments/use-run-comment.ts +++ b/apps/web/hooks/domains/comments/use-run-comment.ts @@ -21,6 +21,7 @@ import type { } from "@/lib/state/slices/comments"; import type { Message } from "@/lib/types/http"; import { deriveSessionInputMode } from "@/hooks/domains/session/session-input-mode"; +import { generateUUID } from "@/lib/utils"; /** * Format a single comment into markdown suitable for sending to the agent. @@ -74,6 +75,7 @@ type QueuePayload = { type MessagePayload = { task_id: string; session_id: string; + client_message_id: string; content: string; plan_mode?: boolean; has_review_comments?: boolean; @@ -97,7 +99,12 @@ function buildMessagePayload( planModeEnabled: boolean, comment: Comment, ): MessagePayload { - const payload: MessagePayload = { task_id: taskId, session_id: sessionId, content }; + const payload: MessagePayload = { + task_id: taskId, + session_id: sessionId, + client_message_id: generateUUID(), + content, + }; if (planModeEnabled) payload.plan_mode = true; if (comment.source !== "plan") payload.has_review_comments = true; return payload; diff --git a/apps/web/hooks/domains/kanban/use-plan-actions.ts b/apps/web/hooks/domains/kanban/use-plan-actions.ts index bcc5d37755..0dcc819671 100644 --- a/apps/web/hooks/domains/kanban/use-plan-actions.ts +++ b/apps/web/hooks/domains/kanban/use-plan-actions.ts @@ -7,6 +7,7 @@ import { moveTask } from "@/lib/api/domains/kanban-api"; import { useContextFilesStore } from "@/lib/state/context-files-store"; import { useLayoutStore } from "@/lib/state/layout-store"; import { useDockviewStore } from "@/lib/state/dockview-store"; +import { generateUUID } from "@/lib/utils"; import { useImplementFresh } from "./use-implement-fresh"; import { markPlanImplementationStarted } from "@/lib/api/domains/plan-api"; import type { @@ -176,6 +177,7 @@ function useImplementPlan( { task_id: taskId, session_id: resolvedSessionId, + client_message_id: generateUUID(), content, plan_mode: false, ...(attachments.length > 0 && { attachments }), diff --git a/apps/web/hooks/domains/review/use-send-finding-to-agent.ts b/apps/web/hooks/domains/review/use-send-finding-to-agent.ts index c411254a06..0c88c4b901 100644 --- a/apps/web/hooks/domains/review/use-send-finding-to-agent.ts +++ b/apps/web/hooks/domains/review/use-send-finding-to-agent.ts @@ -8,6 +8,7 @@ import { formatFindingAsMarkdown } from "@/lib/review/format"; import type { TaskReviewFinding } from "@/lib/types/review"; import type { Message } from "@/lib/types/http"; import { getWebSocketClient } from "@/lib/ws/connection"; +import { generateUUID } from "@/lib/utils"; type Params = { taskId: string | null | undefined; @@ -55,6 +56,7 @@ export function useSendFindingToAgent({ taskId, sessionId }: Params) { { task_id: taskId, session_id: sessionId, + client_message_id: generateUUID(), content, has_review_comments: true, ...(planMode ? { plan_mode: true } : {}), diff --git a/apps/web/hooks/domains/session/use-request-changes-walkthrough.ts b/apps/web/hooks/domains/session/use-request-changes-walkthrough.ts index c030a6cd4d..d9e9614824 100644 --- a/apps/web/hooks/domains/session/use-request-changes-walkthrough.ts +++ b/apps/web/hooks/domains/session/use-request-changes-walkthrough.ts @@ -11,6 +11,7 @@ import { import type { Message } from "@/lib/types/http"; import type { AppState } from "@/lib/state/store"; import { deriveSessionInputMode } from "./session-input-mode"; +import { generateUUID } from "@/lib/utils"; const TERMINAL_SESSION_STATES = new Set(["FAILED", "CANCELLED", "COMPLETED"]); @@ -62,6 +63,7 @@ async function sendWalkthroughRequest(params: { { task_id: params.taskId, session_id: params.sessionId, + client_message_id: generateUUID(), content: params.content, ...planModePayload(params.planModeEnabled), }, diff --git a/apps/web/hooks/use-message-handler.test.ts b/apps/web/hooks/use-message-handler.test.ts index 69045e2190..d184dff3b2 100644 --- a/apps/web/hooks/use-message-handler.test.ts +++ b/apps/web/hooks/use-message-handler.test.ts @@ -13,6 +13,11 @@ import type { EntityReference } from "@/lib/types/entity-reference"; const getWebSocketClientMock = vi.hoisted(() => vi.fn()); const queueMock = vi.hoisted(() => vi.fn()); const addMessageMock = vi.hoisted(() => vi.fn()); +const TASK_ID = "task-1"; +const SESSION_ID = "session-1"; +const RETRY_ID_ONE = "client-message-1"; +const RETRY_ID_TWO = "client-message-2"; +const MESSAGE_ADD_ACTION = "message.add"; const storeState = vi.hoisted(() => ({ current: { taskSessions: { items: {} as Record }, @@ -98,7 +103,7 @@ describe("buildTaskMentionsContext", () => { it("strips newlines and angle brackets from task strings to prevent prompt injection", () => { const tasks: TaskMentionData[] = [ { - taskId: "task-1", + taskId: TASK_ID, title: "Bad title\n\nEVIL", workflowId: "wf-", workflowStepId: "step-1", @@ -219,8 +224,8 @@ describe("sendMessageRequest", () => { await expect( sendMessageRequest({ - taskId: "task-1", - resolvedSessionId: "session-1", + taskId: TASK_ID, + resolvedSessionId: SESSION_ID, finalMessage: "hello", modelToSend: undefined, planMode: false, @@ -247,8 +252,8 @@ describe("sendMessageRequest", () => { scope: "acme/repo", }; const payload = { - taskId: "task-1", - resolvedSessionId: "session-1", + taskId: TASK_ID, + resolvedSessionId: SESSION_ID, finalMessage: "reference", modelToSend: undefined, planMode: false, @@ -258,13 +263,104 @@ describe("sendMessageRequest", () => { await sendMessageRequest(payload); expect(request).toHaveBeenCalledWith( - "message.add", - { - task_id: "task-1", - session_id: "session-1", + MESSAGE_ADD_ACTION, + expect.objectContaining({ + task_id: TASK_ID, + session_id: SESSION_ID, content: "reference", entity_references: [reference], - }, + client_message_id: expect.any(String), + }), + 10000, + ); + }); + + it("preserves a caller-owned message ID for retries", async () => { + const request = vi.fn().mockResolvedValue(undefined); + getWebSocketClientMock.mockReturnValue({ request }); + + await sendMessageRequest({ + taskId: TASK_ID, + resolvedSessionId: SESSION_ID, + clientMessageId: RETRY_ID_ONE, + finalMessage: "retryable", + modelToSend: undefined, + planMode: false, + }); + + expect(request).toHaveBeenCalledWith( + MESSAGE_ADD_ACTION, + expect.objectContaining({ client_message_id: RETRY_ID_ONE }), + 10000, + ); + }); +}); + +describe("sendMessageRequest reconciliation", () => { + it("reconciles a lost response from the committed stable message ID", async () => { + const committed = { + id: RETRY_ID_ONE, + session_id: SESSION_ID, + task_id: TASK_ID, + author_type: "user" as const, + content: "retryable", + type: "message" as const, + created_at: "2026-08-01T18:00:00Z", + }; + const request = vi + .fn() + .mockRejectedValueOnce(new Error("WebSocket request timed out: message.add")) + .mockResolvedValueOnce({ messages: [committed] }); + getWebSocketClientMock.mockReturnValue({ request, getStatus: () => "connected" }); + + await expect( + sendMessageRequest({ + taskId: TASK_ID, + resolvedSessionId: SESSION_ID, + clientMessageId: RETRY_ID_ONE, + finalMessage: "retryable", + modelToSend: undefined, + planMode: false, + }), + ).resolves.toEqual(committed); + + expect(request).toHaveBeenNthCalledWith( + 1, + MESSAGE_ADD_ACTION, + expect.objectContaining({ client_message_id: RETRY_ID_ONE }), + 10000, + ); + expect(request).toHaveBeenNthCalledWith( + 2, + "message.list", + { session_id: SESSION_ID, limit: 100, sort: "desc" }, + 5000, + ); + }); + + it("retries the same stable ID when reconciliation finds no message", async () => { + const request = vi + .fn() + .mockRejectedValueOnce(new Error("WebSocket request timed out: message.add")) + .mockResolvedValueOnce({ messages: [] }) + .mockResolvedValueOnce({ id: RETRY_ID_TWO }); + getWebSocketClientMock.mockReturnValue({ request, getStatus: () => "connected" }); + + await expect( + sendMessageRequest({ + taskId: TASK_ID, + resolvedSessionId: SESSION_ID, + clientMessageId: RETRY_ID_TWO, + finalMessage: "retryable", + modelToSend: undefined, + planMode: false, + }), + ).resolves.toEqual({ id: RETRY_ID_TWO }); + + expect(request).toHaveBeenNthCalledWith( + 3, + MESSAGE_ADD_ACTION, + expect.objectContaining({ client_message_id: RETRY_ID_TWO }), 10000, ); }); @@ -277,8 +373,8 @@ describe("useMessageHandler", () => { selectedSession("WAITING_FOR_INPUT"); const { result } = renderHook(() => useMessageHandler({ - resolvedSessionId: "session-1", - taskId: "task-1", + resolvedSessionId: SESSION_ID, + taskId: TASK_ID, sessionModel: null, activeModel: null, hasPendingClarification: true, @@ -288,7 +384,7 @@ describe("useMessageHandler", () => { await result.current.handleSendMessage({ message: "Queue this after I answer" }); expect(queueMock).toHaveBeenCalledWith( - expect.objectContaining({ content: "Queue this after I answer", taskId: "task-1" }), + expect.objectContaining({ content: "Queue this after I answer", taskId: TASK_ID }), ); expect(request).not.toHaveBeenCalled(); }); @@ -296,7 +392,7 @@ describe("useMessageHandler", () => { function selectedSession(state: string, foregroundActivity?: string) { storeState.current.taskSessions.items = { - "session-1": { state, foreground_activity: foregroundActivity }, + [SESSION_ID]: { state, foreground_activity: foregroundActivity }, "other-session": { state: "RUNNING", foreground_activity: "generating" }, }; } @@ -304,8 +400,8 @@ function selectedSession(state: string, foregroundActivity?: string) { function renderMessageHandler() { return renderHook(() => useMessageHandler({ - resolvedSessionId: "session-1", - taskId: "task-1", + resolvedSessionId: SESSION_ID, + taskId: TASK_ID, sessionModel: null, activeModel: null, }), @@ -331,8 +427,8 @@ describe("useMessageHandler input routing", () => { }); expect(getWebSocketClientMock().request).toHaveBeenCalledWith( - "message.add", - expect.objectContaining({ session_id: "session-1", content: "follow up" }), + MESSAGE_ADD_ACTION, + expect.objectContaining({ session_id: SESSION_ID, content: "follow up" }), 10000, ); expect(queueMock).not.toHaveBeenCalled(); @@ -360,7 +456,7 @@ describe("useMessageHandler input routing", () => { }); expect(queueMock).toHaveBeenCalledWith({ - taskId: "task-1", + taskId: TASK_ID, content: "next", model: undefined, planMode: false, diff --git a/apps/web/hooks/use-message-handler.ts b/apps/web/hooks/use-message-handler.ts index 6cad20c09d..38a0a2f6dd 100644 --- a/apps/web/hooks/use-message-handler.ts +++ b/apps/web/hooks/use-message-handler.ts @@ -1,6 +1,7 @@ import { useCallback } from "react"; import { getWebSocketClient } from "@/lib/ws/connection"; import { MessageSendError } from "@/lib/chat/message-send-error"; +import { generateUUID } from "@/lib/utils"; import { useAppStoreApi } from "@/components/state-provider"; import { useQueue } from "./domains/session/use-queue"; import type { @@ -156,6 +157,7 @@ export interface UseMessageHandlerParams { type SendMessagePayload = { taskId: string; resolvedSessionId: string; + clientMessageId?: string; finalMessage: string; modelToSend: string | undefined; planMode: boolean; @@ -165,6 +167,65 @@ type SendMessagePayload = { entityReferences?: EntityReference[]; }; +type MessageListResponse = { messages?: Message[] }; + +function isUncertainMessageTransportError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + const message = error.message.toLowerCase(); + return ( + message.includes("websocket request timed out") || message === "websocket connection closed" + ); +} + +async function findMessageByID( + client: ReturnType, + sessionId: string, + messageId: string, +): Promise { + if (!client) return undefined; + try { + const response = await client.request( + "message.list", + { session_id: sessionId, limit: 100, sort: "desc" }, + 5000, + ); + return response.messages?.find((message) => message.id === messageId); + } catch { + return undefined; + } +} + +async function waitForConnected(client: NonNullable>) { + const getStatus = client.getStatus?.bind(client); + if (!getStatus || getStatus() === "connected") return true; + const deadline = Date.now() + 3000; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 100)); + if (getStatus() === "connected") return true; + } + return false; +} + +async function reconcileUncertainMessage( + client: NonNullable>, + sessionId: string, + messageId: string, + request: () => Promise, + originalError: unknown, +) { + const committed = await findMessageByID(client, sessionId, messageId); + if (committed) return committed; + if (!(await waitForConnected(client))) throw originalError; + + try { + return await request(); + } catch (retryError) { + const retriedMessage = await findMessageByID(client, sessionId, messageId); + if (retriedMessage) return retriedMessage; + throw retryError; + } +} + export async function sendMessageRequest( payload: SendMessagePayload, ): Promise { @@ -179,6 +240,7 @@ export async function sendMessageRequest( const { taskId, resolvedSessionId, + clientMessageId, finalMessage, modelToSend, planMode, @@ -188,22 +250,33 @@ export async function sendMessageRequest( entityReferences, } = payload; const hasAttachments = attachments && attachments.length > 0; + const stableMessageId = clientMessageId ?? generateUUID(); + const requestPayload = { + task_id: taskId, + session_id: resolvedSessionId, + client_message_id: stableMessageId, + content: finalMessage, + ...(modelToSend && { model: modelToSend }), + ...(planMode && { plan_mode: true }), + ...(hasReviewComments && { has_review_comments: true }), + ...(hasAttachments && { attachments }), + ...(contextFilesMeta && { context_files: contextFilesMeta }), + ...(entityReferences && { entity_references: entityReferences }), + }; - return client.request( - "message.add", - { - task_id: taskId, - session_id: resolvedSessionId, - content: finalMessage, - ...(modelToSend && { model: modelToSend }), - ...(planMode && { plan_mode: true }), - ...(hasReviewComments && { has_review_comments: true }), - ...(hasAttachments && { attachments }), - ...(contextFilesMeta && { context_files: contextFilesMeta }), - ...(entityReferences && { entity_references: entityReferences }), - }, - hasAttachments ? 30000 : 10000, - ); + const request = () => + client.request( + "message.add", + requestPayload, + hasAttachments ? 30000 : 10000, + ); + + try { + return await request(); + } catch (error) { + if (!isUncertainMessageTransportError(error)) throw error; + return reconcileUncertainMessage(client, resolvedSessionId, stableMessageId, request, error); + } } const TERMINAL_SESSION_STATES = new Set(["FAILED", "CANCELLED", "COMPLETED"]); @@ -304,6 +377,7 @@ export function useMessageHandler({ const created = await sendMessageRequest({ taskId, resolvedSessionId, + clientMessageId: generateUUID(), finalMessage, modelToSend, planMode: planModeEnabled, diff --git a/apps/web/lib/kanban/map-task.test.ts b/apps/web/lib/kanban/map-task.test.ts index 9a84bab7c9..8e221d0853 100644 --- a/apps/web/lib/kanban/map-task.test.ts +++ b/apps/web/lib/kanban/map-task.test.ts @@ -131,6 +131,22 @@ describe("toKanbanTask — HTTP DTO / WS payload parity", () => { expect(toKanbanTask(httpDTO(invalid)).taskPendingAction).toBeUndefined(); expect(toKanbanTask(wsPayload(invalid)).taskPendingAction).toBeUndefined(); }); + + it("maps the bounded status summary from HTTP and WS task shapes", () => { + const statusSummary = { + revision: 7, + updated_at: "2026-08-01T18:56:13.512Z", + pending_action: "permission" as const, + git: { additions: 4, deletions: 2, changed_files: 3 }, + pull_request: { count: 1, open_count: 1, attention: true, number: 42 }, + }; + const http = toKanbanTask(httpDTO({ status_summary: statusSummary })); + const ws = toKanbanTask(wsPayload({ status_summary: statusSummary })); + + expect(http.statusSummary).toEqual(statusSummary); + expect(ws.statusSummary).toEqual(statusSummary); + expect(http).toEqual(ws); + }); }); describe("toKanbanTask — state normalization", () => { diff --git a/apps/web/lib/kanban/map-task.ts b/apps/web/lib/kanban/map-task.ts index cd88c8b8c8..350de86875 100644 --- a/apps/web/lib/kanban/map-task.ts +++ b/apps/web/lib/kanban/map-task.ts @@ -10,6 +10,7 @@ import type { TaskState, TaskSessionState, } from "@/lib/types/http"; +import type { TaskStatusSummary } from "@/lib/types/task-status-summary"; type KanbanTask = KanbanState["tasks"][number]; @@ -63,6 +64,7 @@ export type TaskLike = { queued_for_step_id?: string | null; queued_at?: string | null; metadata?: Record | null; + status_summary?: TaskStatusSummary | null; }; export type WorkspaceMode = "inherit_parent" | "new_workspace" | "shared_group"; @@ -154,6 +156,7 @@ export function toKanbanTask(source: TaskLike): KanbanTask { wipAdmitted: source.wip_admitted, queuedForStepId: source.queued_for_step_id, queuedAt: source.queued_at, + statusSummary: source.status_summary, isPRReview: isPRReviewFromMetadata(source.metadata), isIssueWatch: isIssueWatchFromMetadata(source.metadata), ...issueFieldsFromMetadata(source.metadata), diff --git a/apps/web/lib/state/slices/kanban/types.ts b/apps/web/lib/state/slices/kanban/types.ts index 7e7a002c37..b8d48bf9dd 100644 --- a/apps/web/lib/state/slices/kanban/types.ts +++ b/apps/web/lib/state/slices/kanban/types.ts @@ -3,6 +3,7 @@ import type { TaskPendingAction, TaskState as TaskStatus, } from "@/lib/types/http"; +import type { TaskStatusSummary } from "@/lib/types/task-status-summary"; export type KanbanStepEvents = { on_enter?: Array<{ type: string; config?: Record }>; @@ -98,6 +99,7 @@ export type KanbanState = { isIssueWatch?: boolean; issueUrl?: string; issueNumber?: number; + statusSummary?: TaskStatusSummary | null; }>; isLoading?: boolean; }; diff --git a/apps/web/lib/task-status-summary.ts b/apps/web/lib/task-status-summary.ts new file mode 100644 index 0000000000..391de34798 --- /dev/null +++ b/apps/web/lib/task-status-summary.ts @@ -0,0 +1,21 @@ +import type { TaskStatusSummary } from "./types/task-status-summary"; + +/** + * Returns the current task-level error only when it has not already been + * acknowledged or dismissed for the same session and stamp. + */ +export function statusSummaryActiveErrorPreview( + summary: TaskStatusSummary | null | undefined, + acknowledgedAgentErrors?: Record, + dismissedAgentErrors?: Record, +): string | null { + const error = summary?.active_error; + if (!error) return null; + if ( + acknowledgedAgentErrors?.[error.session_id] === error.stamp || + dismissedAgentErrors?.[error.session_id] === error.stamp + ) { + return null; + } + return error.preview; +} diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index 336281ff39..9bbbdeed19 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -23,6 +23,7 @@ import type { SecretListItem } from "@/lib/types/http-secrets"; import type { GitEventPayload } from "@/lib/types/git-events"; import type { GitHubRateLimitUpdate, TaskCIAutomationOptions, TaskPR } from "@/lib/types/github"; import type { TaskMR } from "@/lib/types/gitlab"; +import type { TaskStatusSummary } from "@/lib/types/task-status-summary"; import type { SystemMetricsSnapshot } from "./system"; import type { FileChangeNotificationPayload } from "./workspace-files"; import type { @@ -107,6 +108,7 @@ export type TaskEventPayload = { metadata?: Record | null; /** Deletion reason on task.deleted (e.g. "pr_approved_by_user"). Absent otherwise. */ reason?: string; + status_summary?: TaskStatusSummary | null; }; export type AgentUpdatePayload = { @@ -475,6 +477,12 @@ export type QueueStatusChangedPayload = { max?: number; }; +export type TaskStatusSummaryUpdatedPayload = { + task_id: string; + workspace_id: string; + status_summary: TaskStatusSummary; +}; + export type BackendMessageMap = OfficeBackendMessageMap & import("@/lib/types/http").WalkthroughBackendMessageMap & import("@/lib/types/review").ReviewBackendMessageMap & { @@ -483,6 +491,10 @@ export type BackendMessageMap = OfficeBackendMessageMap & "task.updated": BackendMessage<"task.updated", TaskEventPayload>; "task.deleted": BackendMessage<"task.deleted", TaskEventPayload>; "task.state_changed": BackendMessage<"task.state_changed", TaskEventPayload>; + "task.status_summary.updated": BackendMessage< + "task.status_summary.updated", + TaskStatusSummaryUpdatedPayload + >; "task.plan.created": BackendMessage<"task.plan.created", TaskPlanEventPayload>; "task.plan.updated": BackendMessage<"task.plan.updated", TaskPlanEventPayload>; "task.plan.deleted": BackendMessage<"task.plan.deleted", TaskPlanEventPayload>; diff --git a/apps/web/lib/types/http.ts b/apps/web/lib/types/http.ts index 74b06edfb7..c1d3b20b57 100644 --- a/apps/web/lib/types/http.ts +++ b/apps/web/lib/types/http.ts @@ -14,6 +14,9 @@ import type { } from "./ids"; import type { OnEnterActionType, StepEvents } from "./workflow-actions"; import type { EntityReference } from "./entity-reference"; +import type { TaskStatusSummary } from "./task-status-summary"; + +export type { TaskStatusSummary } from "./task-status-summary"; export type { ExecutorType } from "./executor"; export type { ActiveSubagentCountFields, ForegroundActivity } from "./activity"; @@ -346,6 +349,7 @@ export type Task = ActiveSubagentCountFields & { // OR workflow_id matches the workspace's office_workflow_id. See // isFromOfficeProjection in the Go task repo for the canonical rule. is_from_office?: boolean; + status_summary?: TaskStatusSummary | null; }; // Task origin values mirror models.TaskOrigin* constants in the Go backend. diff --git a/apps/web/lib/types/task-status-summary.test.ts b/apps/web/lib/types/task-status-summary.test.ts new file mode 100644 index 0000000000..e50fb14a63 --- /dev/null +++ b/apps/web/lib/types/task-status-summary.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import type { TaskStatusSummary } from "./task-status-summary"; + +describe("TaskStatusSummary", () => { + it("models the bounded replacement payload without transcript fields", () => { + const summary: TaskStatusSummary = { + revision: 4, + updated_at: "2026-08-01T18:56:13.512Z", + primary_session: { id: "session-1", state: "WAITING_FOR_INPUT" }, + pending_action: "clarification", + active_error: { + session_id: "session-1", + stamp: "error-4", + occurred_at: "2026-08-01T18:56:13.512Z", + preview: "The agent needs attention", + }, + git: { additions: 3, deletions: 1, changed_files: 2 }, + pull_request: { count: 1, open_count: 1, attention: true, number: 42 }, + }; + + expect(summary).not.toHaveProperty("messages"); + expect(summary).not.toHaveProperty("files"); + }); +}); diff --git a/apps/web/lib/types/task-status-summary.ts b/apps/web/lib/types/task-status-summary.ts new file mode 100644 index 0000000000..41377c7f17 --- /dev/null +++ b/apps/web/lib/types/task-status-summary.ts @@ -0,0 +1,35 @@ +import type { ForegroundActivity, TaskPendingAction, TaskSessionState } from "./http"; + +export type TaskStatusSummary = { + revision: number; + updated_at: string; + primary_session?: { + id: string; + state: TaskSessionState; + } | null; + foreground_activity?: ForegroundActivity; + active_subagent_count?: number; + pending_action?: TaskPendingAction; + active_error?: { + session_id: string; + stamp: string; + occurred_at: string; + preview: string; + } | null; + git?: { + additions?: number; + deletions?: number; + changed_files?: number; + ahead?: number; + behind?: number; + } | null; + pull_request?: { + count?: number; + open_count?: number; + attention?: boolean; + aggregate_state?: string; + state?: string; + number?: number; + url?: string; + } | null; +}; diff --git a/apps/web/lib/utils.test.ts b/apps/web/lib/utils.test.ts index 3187964488..8ab2e1ea4e 100644 --- a/apps/web/lib/utils.test.ts +++ b/apps/web/lib/utils.test.ts @@ -128,7 +128,17 @@ describe("generateUUID", () => { expect(stub).toHaveBeenCalledOnce(); }); - it("falls back to Math.random UUID when crypto.randomUUID is undefined (HTTP/non-secure)", () => { + it("uses crypto.getRandomValues when randomUUID is unavailable", () => { + const getRandomValues = vi.fn((bytes: Uint8Array) => { + bytes.fill(0x11); + return bytes; + }); + vi.stubGlobal("crypto", { getRandomValues }); + expect(generateUUID()).toBe("11111111-1111-4111-9111-111111111111"); + expect(getRandomValues).toHaveBeenCalledOnce(); + }); + + it("falls back to a UUID-shaped value when Web Crypto is unavailable", () => { vi.stubGlobal("crypto", {}); const id = generateUUID(); expect(id).toMatch(UUID_V4_REGEX); diff --git a/apps/web/lib/utils.ts b/apps/web/lib/utils.ts index 6846300957..a658e1b4fa 100644 --- a/apps/web/lib/utils.ts +++ b/apps/web/lib/utils.ts @@ -20,20 +20,56 @@ export function formatDollars(subcents: number | null | undefined): string { return `$${(subcents / 10000).toFixed(2)}`; } +let uuidFallbackCounter = 0; +let uuidFallbackContextCounter = 0; + +function createUuidFallbackContext(): string { + const entropy = new Uint32Array(2); + if (typeof crypto !== "undefined" && crypto.getRandomValues) { + try { + crypto.getRandomValues(entropy); + return entropy[0].toString(16).padStart(8, "0"); + } catch { + // Fall through to the non-cryptographic legacy-environment fallback. + } + } + + const monotonic = typeof performance !== "undefined" ? Math.floor(performance.now() * 1000) : 0; + const counter = uuidFallbackContextCounter++; + return ((Date.now() ^ monotonic ^ counter) >>> 0).toString(16).padStart(8, "0"); +} + +// Keep a per-module component so two tabs generating IDs in the same +// millisecond do not share the timestamp/counter prefix. Prefer Web Crypto +// entropy when available; old environments get a monotonic best-effort ID. +const uuidFallbackContext = createUuidFallbackContext(); + /** - * Generate a UUID. Falls back to a custom implementation in non-secure contexts - * (e.g., HTTP on non-localhost where crypto.randomUUID is unavailable). + * Generate a UUID. Falls back to crypto.getRandomValues when randomUUID is + * unavailable (e.g., HTTP on non-localhost), then to a UUID-shaped fallback + * with a per-context component for legacy environments without any Web Crypto API. */ export function generateUUID(): string { if (typeof crypto !== "undefined" && crypto.randomUUID) { return crypto.randomUUID(); } - // Fallback implementation - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = (Math.random() * 16) | 0; - const v = c === "x" ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); + + if (typeof crypto !== "undefined" && crypto.getRandomValues) { + const bytes = crypto.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; + } + + const context = uuidFallbackContext; + const timestamp = Date.now().toString(16).padStart(12, "0").slice(-12); + const counter = (uuidFallbackCounter++ >>> 0).toString(16).padStart(8, "0"); + const chars = `${context}${timestamp}${counter}`.padEnd(32, "0").slice(0, 32).split(""); + chars[12] = "4"; + chars[16] = "8"; + const hex = chars.join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } /** diff --git a/apps/web/lib/ws/client.ts b/apps/web/lib/ws/client.ts index 20debeda44..0b2edebb8b 100644 --- a/apps/web/lib/ws/client.ts +++ b/apps/web/lib/ws/client.ts @@ -214,21 +214,10 @@ export class WebSocketClient { } /** - * Re-send a `session.focus` frame for an already-focused session WITHOUT - * touching the focus ref-count. The backend's focus handler pushes a fresh - * live git-status snapshot as a side effect (see `handleSessionFocus` → - * `sendSessionData` → `appendLiveGitStatusMessage`, which forces a - * `GetGitStatusMultiFresh` query that bypasses the workspace poll cache). - * - * This is the deterministic recovery for the focus-gated polling race: the - * agent edits a file, but if the workspace is still in slow poll mode (the - * focus→fast push lost a race with agentctl startup) the next - * `session.git.event` may be up to 30s away. Components that become visible - * and need fresh diff data (the diff panel becoming the active tab) call - * this to pull the latest git status immediately. - * - * No-op when the session isn't currently focused (the regular focus frame, - * sent on 0→1, already pushed fresh data). + * Request a fresh git snapshot for an already-focused session without + * changing its focus ref-count. Focus itself is intentionally ACK-only; + * explicit git refresh keeps tab activation from replaying session data during + * ordinary task switching. */ refreshSessionData(sessionId: string) { if (this.status !== "connected") return; @@ -236,7 +225,7 @@ export class WebSocketClient { this.send({ id: generateUUID(), type: "request", - action: "session.focus", + action: "session.git.refresh", payload: { session_id: sessionId }, }); } diff --git a/apps/web/lib/ws/handlers/tasks-status-summary.test.ts b/apps/web/lib/ws/handlers/tasks-status-summary.test.ts new file mode 100644 index 0000000000..7cebb2fbeb --- /dev/null +++ b/apps/web/lib/ws/handlers/tasks-status-summary.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from "vitest"; +import { registerTasksHandlers } from "./tasks"; +import { makeStore } from "./tasks.test-helpers"; + +const TASK_ID = "task-1"; +const WORKFLOW_ID = "workflow-1"; +const STEP_ID = "step-1"; +const UPDATED_AT = "2026-08-01T18:00:00Z"; + +function summaryMessage(summary: Record) { + return { + id: "summary-message", + type: "notification" as const, + action: "task.status_summary.updated" as const, + payload: { + task_id: TASK_ID, + workspace_id: "workspace-1", + status_summary: summary, + }, + } as Parameters< + NonNullable["task.status_summary.updated"]> + >[0]; +} + +describe("task.status_summary.updated cache replacement", () => { + it("replaces the summary in both single and multi-kanban task caches", () => { + const store = makeStore({ + kanban: { + workflowId: WORKFLOW_ID, + steps: [], + tasks: [{ id: TASK_ID, workflowStepId: STEP_ID, title: "Task" }], + }, + kanbanMulti: { + isLoading: false, + snapshots: { + [WORKFLOW_ID]: { + workflowId: WORKFLOW_ID, + workflowName: "Workflow", + steps: [], + tasks: [{ id: TASK_ID, workflowStepId: STEP_ID, title: "Task" }], + }, + }, + }, + } as never); + + registerTasksHandlers(store)["task.status_summary.updated"]!( + summaryMessage({ + revision: 2, + updated_at: UPDATED_AT, + git: { additions: 4 }, + }), + ); + + expect(store.getState().kanban.tasks[0].statusSummary).toMatchObject({ + revision: 2, + git: { additions: 4 }, + }); + expect( + store.getState().kanbanMulti.snapshots[WORKFLOW_ID]?.tasks[0].statusSummary, + ).toMatchObject({ revision: 2 }); + }); +}); + +describe("task.status_summary.updated monotonicity", () => { + it("ignores stale or same-revision replacements", () => { + const store = makeStore({ + kanban: { + workflowId: WORKFLOW_ID, + steps: [], + tasks: [ + { + id: TASK_ID, + workflowStepId: STEP_ID, + title: "Task", + statusSummary: { + revision: 3, + updated_at: UPDATED_AT, + git: { additions: 7 }, + }, + }, + ], + }, + kanbanMulti: { isLoading: false, snapshots: {} }, + } as never); + const handler = registerTasksHandlers(store)["task.status_summary.updated"]!; + + handler( + summaryMessage({ + revision: 2, + updated_at: "2026-08-01T17:00:00Z", + git: { additions: 1 }, + }), + ); + handler( + summaryMessage({ + revision: 3, + updated_at: UPDATED_AT, + git: { additions: 2 }, + }), + ); + + expect(store.getState().kanban.tasks[0].statusSummary).toMatchObject({ + revision: 3, + git: { additions: 7 }, + }); + }); +}); + +describe("task.updated summary preservation", () => { + it("keeps the cached summary when a lightweight task update omits it", () => { + const store = makeStore({ + kanban: { + workflowId: WORKFLOW_ID, + steps: [], + tasks: [ + { + id: TASK_ID, + workflowStepId: STEP_ID, + title: "Task", + statusSummary: { + revision: 4, + updated_at: UPDATED_AT, + pending_action: "clarification", + }, + }, + ], + }, + kanbanMulti: { isLoading: false, snapshots: {} }, + } as never); + + registerTasksHandlers(store)["task.updated"]!({ + id: "task-update", + type: "notification", + action: "task.updated", + payload: { + task_id: TASK_ID, + id: TASK_ID, + workflow_id: WORKFLOW_ID, + title: "Renamed task", + state: "IN_PROGRESS", + }, + } as never); + + expect(store.getState().kanban.tasks[0].title).toBe("Renamed task"); + expect(store.getState().kanban.tasks[0].statusSummary).toMatchObject({ + revision: 4, + pending_action: "clarification", + }); + }); +}); diff --git a/apps/web/lib/ws/handlers/tasks.ts b/apps/web/lib/ws/handlers/tasks.ts index af00f7cf70..b0af36efad 100644 --- a/apps/web/lib/ws/handlers/tasks.ts +++ b/apps/web/lib/ws/handlers/tasks.ts @@ -46,6 +46,17 @@ function preservePrimaryExecutorFields( } } +function preserveOmittedStatusSummary( + existing: KanbanTask, + merged: KanbanTask, + nextTask: KanbanTask, + payload: TaskEventPayload, +): void { + if (!hasPayloadField(payload, "status_summary") && nextTask.statusSummary === undefined) { + merged.statusSummary = existing.statusSummary; + } +} + function mergeTaskUpdate( existing: KanbanTask | undefined, nextTask: KanbanTask, @@ -93,6 +104,7 @@ function mergeTaskUpdate( ) { merged.activeSubagentCount = existing.activeSubagentCount; } + preserveOmittedStatusSummary(existing, merged, nextTask, payload); return merged; } @@ -341,9 +353,54 @@ function redirectAwayFromRemovedTask(taskId: string): void { type TaskUpdatedMessage = Parameters>[0]; type TaskCreatedMessage = Parameters>[0]; type TaskStateChangedMessage = Parameters>[0]; +type TaskStatusSummaryUpdatedMessage = Parameters< + NonNullable +>[0]; type TaskUpsertMessage = TaskCreatedMessage | TaskStateChangedMessage; type TaskUpsertAction = "task.created" | "task.state_changed"; +function updateTaskStatusSummaryInBothKanbans( + state: AppState, + message: TaskStatusSummaryUpdatedMessage, +): AppState { + const { task_id: taskId, status_summary: nextSummary } = message.payload; + const shouldReplace = (task: KanbanTask): boolean => { + const current = task.statusSummary; + return !current || nextSummary.revision > current.revision; + }; + const updateTask = (task: KanbanTask): KanbanTask => + shouldReplace(task) ? { ...task, statusSummary: nextSummary } : task; + + let next = state; + if (state.kanban.tasks.some((task) => task.id === taskId && shouldReplace(task))) { + next = { + ...next, + kanban: { + ...next.kanban, + tasks: next.kanban.tasks.map((task) => (task.id === taskId ? updateTask(task) : task)), + }, + }; + } + + const snapshots = Object.entries(next.kanbanMulti.snapshots); + const changedSnapshots = snapshots.filter(([, snapshot]) => + snapshot.tasks.some((task) => task.id === taskId && shouldReplace(task)), + ); + if (changedSnapshots.length === 0) return next; + + const nextSnapshots = { ...next.kanbanMulti.snapshots }; + for (const [workflowId, snapshot] of changedSnapshots) { + nextSnapshots[workflowId] = { + ...snapshot, + tasks: snapshot.tasks.map((task) => (task.id === taskId ? updateTask(task) : task)), + }; + } + return { + ...next, + kanbanMulti: { ...next.kanbanMulti, snapshots: nextSnapshots }, + }; +} + function handleTaskUpdated(store: StoreApi, message: TaskUpdatedMessage): void { // Ephemeral tasks never reach the Kanban board, but quick chats are shared // across devices — mirror them into the tab strip before bailing out. @@ -506,5 +563,8 @@ export function registerTasksHandlers(store: StoreApi): WsHandlers { "task.state_changed": (message) => { handleTaskUpsert("task.state_changed", store, message); }, + "task.status_summary.updated": (message) => { + store.setState((state) => updateTaskStatusSummaryInBothKanbans(state, message)); + }, }; } diff --git a/docs/decisions/2026-08-01-separate-task-summary-session-stream-traffic.md b/docs/decisions/2026-08-01-separate-task-summary-session-stream-traffic.md new file mode 100644 index 0000000000..c994d65587 --- /dev/null +++ b/docs/decisions/2026-08-01-separate-task-summary-session-stream-traffic.md @@ -0,0 +1,102 @@ +# ADR-2026-08-01-separate-task-summary-session-stream-traffic: Separate Task Summary and Session Stream Traffic + +**Status:** accepted +**Date:** 2026-08-01 +**Area:** backend, frontend, protocol + +## Context + +Task switchers need a small set of facts for every visible task: runtime state, +pending user input, recoverable agent errors, aggregate Git changes, and pull +request status. Those facts currently come from several stores. In particular, +the desktop sidebar subscribes to every task's primary session to obtain live +Git status, while desktop and mobile also inspect loaded session messages and +metadata to derive pending and error indicators. + +A captured reload with 27 sessions produced 700 WebSocket frames (3.23 MB) in +five seconds, including 74 `session.subscribe` and 47 `session.unsubscribe` +requests. Switching tasks rebuilds the subscription set. Each session +subscription can replay the full session snapshot and then carry messages, +shell activity, model configuration, MCP status, and other data that a task row +does not use. + +The WebSocket client currently puts correlated responses and unsolicited +notifications on one bounded FIFO queue. When that queue is full, a frame can +be dropped without closing the socket. This makes a fast, persisted +`message.add` operation appear to time out, and delayed model snapshots can +temporarily remove the model selector. Increasing the message timeout would +hide the symptom without removing the fan-out or the ambiguous response loss. + +## Decision + +Kandev will maintain a bounded, rebuildable `TaskStatusSummary` read model for +task-level surfaces. It is carried on task snapshots and updated through the +existing workspace-scoped task event path. The summary contains only the facts +needed to classify and decorate a task row; transcripts, file paths, diffs, +shell output, model configuration, and MCP payloads remain session-owned and +are never copied into it. + +Session, message, Git, and pull-request domains remain authoritative. The +summary projector consumes their semantic changes, persists the latest compact +projection with a monotonic per-task revision, and emits an update only when +the projected value changes. A missing projection is rebuilt from authoritative +state and never causes the browser to subscribe to background sessions. + +Task switchers consume task snapshots plus task-summary deltas. They do not +subscribe to session streams. Full session streams are limited to sessions +explicitly opened in an active detail surface. Repeated subscription and focus +requests are idempotent: only a new subscription receives a full initial +snapshot, and focus changes polling priority without replaying session data. +Targeted refresh operations use targeted actions rather than `session.focus`. + +Git-summary freshness is tied to runtime ownership rather than browser +interest. A live execution keeps a slow monitoring baseline, active focus may +upgrade it to fast monitoring, and settled tasks use the latest persisted +snapshot. Removing a browser's background subscriptions therefore cannot pause +the source that feeds task-level Git status. + +Correlated WebSocket responses and errors use a reserved, prioritized delivery +path separate from best-effort notifications. A response must be queued or the +connection must fail explicitly; it must not be silently discarded behind +session notification traffic. User message submission also carries a stable +client-generated message ID. Retrying that ID returns the accepted message +without rerunning turn-start hooks or dispatching the prompt twice. + +## Consequences + +Workspace traffic scales with task-summary changes and explicitly opened +sessions rather than with every task's full session activity. Switching tasks +has constant subscription work and no longer tears down and recreates an +all-task subscription fan-out. Desktop and mobile task switchers read the same +status contract and preserve their existing icon precedence. + +The summary is eventually consistent by design. Revisions prevent stale +deltas from overwriting newer task state, and reconnect/task-list hydration +repairs missed updates. Projection failures leave the last valid summary in +place and are observable; detailed domain data remains available on demand. + +The implementation adds a compact persistence model and projection wiring +across several domains. It also requires explicit queue semantics in the +WebSocket gateway and an idempotency contract for `message.add`. These are more +moving parts than a frontend-only optimization, but they remove the coupling +that caused the traffic amplification and protect every request type from the +same queue-pressure failure mode. + +## Alternatives Considered + +- **Keep all session subscriptions but reduce individual payloads.** Rejected + because task switching would still perform O(number of tasks) subscription + churn and task rows would remain coupled to session-internal events. +- **Derive one task aggregate entirely in the frontend.** Rejected because the + browser would still need every authoritative stream, every client would + duplicate precedence rules, and a suspended browser could not repair the + aggregate without replaying those streams. +- **Copy full session, Git, or PR records onto the task row.** Rejected because + it would create competing sources of truth and make a bounded list payload + grow with transcripts, repositories, or pull requests. +- **Poll task details from REST.** Rejected because polling introduces stale + badges and repeated full-list reads while the workspace task event channel + already provides an appropriate bounded delivery path. +- **Only enlarge the WebSocket queue or message timeout.** Rejected because + queue pressure would remain proportional to background sessions and a full + queue could still make accepted writes ambiguous. diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index 384ee4915b..a989f700f6 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -97,6 +97,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or | 2026-07-31-system-service-user-continuity | [Preserve System Service Identity Across Reinstallation](2026-07-31-system-service-user-continuity.md) | accepted | backend, cli, security, operations | 2026-07-31 | | 2026-08-01-repository-task-executor-defaults | [Resolve Task Executor Policy Before Last-Used Profile](2026-08-01-repository-task-executor-defaults.md) | accepted | frontend | 2026-08-01 | | 2026-08-01-validate-mcp-tool-arguments | [Validate MCP Tool Arguments at the Shared Server Boundary](2026-08-01-validate-mcp-tool-arguments.md) | accepted | backend, protocol | 2026-08-01 | +| 2026-08-01-separate-task-summary-session-stream-traffic | [Separate Task Summary and Session Stream Traffic](2026-08-01-separate-task-summary-session-stream-traffic.md) | accepted | backend, frontend, protocol | 2026-08-01 | | 2026-08-01-global-run-scheduler-ownership | [Separate Global Run Dispatch from Office Maintenance](2026-08-01-global-run-scheduler-ownership.md) | accepted | backend, workflow | 2026-08-01 | | 2026-08-01-release-toggle-gating-contract | [Release Toggles Are Install-Wide Fail-Closed Gates](2026-08-01-release-toggle-gating-contract.md) | proposed | backend, frontend, workflow | 2026-08-01 | | 2026-08-01-share-artifact-locale | [Shared-Task Artifacts Render in the Creator's Locale](2026-08-01-share-artifact-locale.md) | accepted | backend | 2026-08-01 | diff --git a/docs/plans/bounded-task-status-delivery/plan.md b/docs/plans/bounded-task-status-delivery/plan.md new file mode 100644 index 0000000000..5ffe3cf3e5 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/plan.md @@ -0,0 +1,285 @@ +--- +spec: docs/specs/platform/bounded-task-status-delivery.md +created: 2026-08-01 +status: implemented +--- + +# Implementation Plan: Bounded Task Status Delivery + +## Overview + +Replace task-switcher dependence on background session streams with one +backend-owned, bounded task-status projection. Hydrate that projection through +the existing boot/task snapshot paths, publish revisions on the workspace task +feed, and make both desktop and mobile rows consume it. Preserve full session +streams for selected detail surfaces, make subscribe/focus idempotent, decouple +Git monitoring from browser interest, and reserve WebSocket delivery capacity +for correlated responses. Finally, make message submission retry-safe so a +transport interruption cannot create a duplicate prompt. + +This is a staged migration. Existing task runtime fields remain as a coarse +fallback until all snapshot producers and consumers carry `status_summary`. +No task-row consumer may fall back to subscribing to an inactive session. + +## Architecture + +### Projection ownership + +Add a typed package under `apps/backend/internal/task/statussummary` with: + +- the bounded `TaskStatusSummary` model and aggregate enums; +- repository interfaces for batch load, compare/update, and delete; +- a keyed projector that rebuilds or applies source observations; +- provider interfaces for session/pending/error/Git/PR reads, wired by + `backendapp` to avoid package cycles; and +- semantic equality that excludes revision/update timestamps, so a no-op does + not write or publish. + +Persist one row per task in `task_status_summaries` with `task_id`, +`workspace_id`, `revision`, serialized summary, and `updated_at`. Use the +repository's portable schema/migration conventions and cover both SQLite and +Postgres replay. Serialize compare/update per task so concurrent source events +cannot lose a newer projection. Deleting a task cascades to the projection. + +The authoritative inputs remain unchanged: + +| Authoritative occurrence | Projected fields | Refresh rule | +| -------------------------------------------------------- | ---------------------------------------------- | --------------------------------------------------------------- | +| Task/session lifecycle and primary-session changes | `primary_session` | Rebuild on semantic lifecycle event | +| Foreground activity/subagent changes | `foreground_activity`, `active_subagent_count` | Rebuild only on published aggregate change | +| Pending permission/clarification | `pending_action` | Read the existing task-level pending aggregate | +| Recoverable agent error, dismissal, newer agent response | `active_error` | Explicit error-change signal plus relevant agent-message events | +| Per-repository Git observation | `git` | Coalesce by task/repository, then aggregate latest observations | +| GitHub task-PR update | `pull_request` | Recompute bounded attention state and representative identity | + +Filter message events before scheduling a rebuild. Streaming thought, shell, +status, and other message updates that cannot change pending/error semantics +must not churn the task projection. + +### Snapshot and delta delivery + +Extend `task/dto.TaskDTO` with `StatusSummary`. Batch-load summaries while +building boot state, task lists, and workflow snapshots; do not add one query +per task. A missing row is rebuilt from authoritative records and may be +returned as an absent/coarse fallback for the current request rather than +blocking the whole workspace. + +Add internal `TaskStatusSummaryUpdated` and wire action +`task.status_summary.updated`. The gateway routes it to the task's workspace +with the same authorization boundary as task updates. The event carries a +complete replacement summary. Frontend merges compare `revision` and ignore +duplicates or older deliveries. + +### Git monitoring lifecycle + +Today slow/paused polling is inferred from browser session subscriptions. Add +an internal runtime-interest source: a live task execution keeps its workspace +at least in slow mode, explicit focus upgrades it to fast, and the workspace +returns to paused only when neither runtime nor viewer interest exists. Feed +bounded per-repository observations into the summary projector before or with +the existing live snapshot persistence. + +Keep completion/settled Git snapshots authoritative after execution ends. A +temporary poll failure preserves the latest summary. Multi-repository totals +are calculated from a keyed latest-observation set so one repository update +does not erase siblings. + +### Session stream and WebSocket delivery + +Make server subscription membership observable to handlers. A +`session.subscribe` transition from absent to present sends one initial full +snapshot; duplicate subscriptions only acknowledge. `session.focus` updates +polling priority and acknowledges without calling `sendSessionData`. Add +`session.git.refresh` for the selected detail surface and migrate the frontend +away from using focus as a refresh command. + +Split each gateway client's outbound path into: + +- a reserved control queue for request responses and errors; and +- a bounded notification queue for unsolicited state. + +The write pump drains control traffic first while preserving FIFO order within +each class. Notification overload remains bounded and observable. Control +enqueue failure closes the connection instead of silently losing the frame, +allowing the client to reconnect and reconcile. Add metrics/structured logs +for notification drops, control overflow, queue depth, and disconnect reason. + +### Frontend task-summary migration + +Add summary types and map `status_summary` in `lib/kanban/map-task.ts`. Store the +latest summary on each Kanban task and patch it from +`task.status_summary.updated` only when the revision advances. Preserve the +summary when a partial task update omits it. + +Refactor the desktop sidebar and mobile task-switcher sheet to derive: + +- pending flags from `summary.pendingAction`; +- error display from `summary.activeError` plus the existing local + acknowledgement stamp; +- diff stats from `summary.git`; +- session state/activity from the summary; and +- the task-row PR icon from the bounded PR aggregate. + +Remove `useBulkGitStatusSubscription` and the switcher's workspace-wide PR +fetch. Active task/detail consumers retain their session Git and detailed PR +stores. If a summary is missing, render coarse task/session state and omit the +unknown decoration; never restore an inactive subscription. + +### Retry-safe message submission + +Generate one stable `client_message_id` when the user submits and include it +in `message.add` (the backend accepts `message_id` as a compatibility alias). +Keep that ID across reconnect/retry and optimistic/response/notification +hydration. + +On the backend, serialize acceptance by message ID and check for an existing +authorized user message before session-state validation, `on_turn_start`, +message creation, or dispatch. The first accepted request owns the ID. A +duplicate for the same task returns that message; cross-task or unauthorized +reuse is a conflict. Use `CreateMessageWithID` for the first write and reload +after a uniqueness race. Duplicate handling must not repeat lifecycle hooks or +prompt dispatch. + +On timeout/disconnect, wait for bounded response/notification/list +reconciliation and retry the same ID after reconnect when needed. Clear the +composer once acceptance is known. Show **Message send status unknown** only +when reconciliation cannot establish whether the ID was accepted. + +## Tests + +### Backend unit and integration tests + +- Projection repository: portable schema replay, batch reads, monotonic + compare/update, semantic no-op, concurrent source updates, delete cascade, + and missing-row repair. +- Projection derivation: status precedence, error suppression/dismissal, + bounded UTF-8 preview, multi-repository Git aggregation, PR attention state, + and filtering of irrelevant message events. +- Snapshot delivery: boot/task/workflow payloads load summaries in batches and + workspace events carry the complete newer revision. +- Polling: live execution retains slow monitoring with no browser subscriber; + focus upgrades to fast; settle/removal returns to the correct remaining + interest level. +- Gateway: duplicate subscribe/focus does not replay, targeted Git refresh + emits only Git data, notification saturation cannot starve a response, and + control overflow closes explicitly. +- Message submission: duplicate and concurrent duplicate IDs create one row, + run turn-start once, dispatch once, and reject cross-scope reuse. + +### Frontend tests + +- Task mapping and task-event reducers preserve newer summaries and reject + stale revisions or omitted fields. +- Desktop/mobile derivation reads only summary fields while preserving pending, + activity, completion, error, Git, and PR precedence. +- Sidebar mounting and task switching issue no session subscriptions for + inactive tasks. +- Message send keeps one ID through timeout/reconnect, reconciles response and + notification gaps idempotently, and retains a usable composer/model selector. + +## E2E Tests + +- Seed a workspace with at least 27 tasks/sessions, select one task, and record + WebSocket frames. Assert that inactive session IDs never receive + `session.subscribe` and never deliver message, shell, model, MCP, or Git + detail frames to the switcher. +- Switch among five tasks. Assert each switch performs at most the constant + active-session membership/focus work and that counts do not grow with the 27 + task rows. Attach frame counts and byte totals to the Playwright result for + before/after diagnosis without making compression-dependent byte counts the + correctness oracle. +- Drive clarification, recoverable error/dismissal, Git, and PR changes on + inactive tasks. Assert both desktop and `mobile-chrome` rows update through + summary revisions. +- Saturate the notification path with background activity, then publish the + selected session's model configuration and submit a message. Assert the model + selector remains available, the response resolves, and exactly one user + message/turn is present after a forced retry of the same message ID. + +Update the existing session-focus, sidebar-diff, and message-response-gap E2E +tests so they enforce the new transport contract rather than preserving the +old bulk-subscription behavior. The 27-task gateway capture lives in +`apps/web/e2e/tests/session/session-stream-budget.spec.ts` and shares the +diagnostic helper in `apps/web/e2e/helpers/ws-traffic.ts`. + +## Mobile design contract + +- **Desktop outcome / mobile entry:** both surfaces show the same task-summary + state. Desktop uses the sidebar; phone uses the existing session task-switcher + sheet. +- **Nearest exemplar:** + `apps/web/components/task/mobile/session-task-switcher-sheet.tsx` remains the + native mobile entry and continues to render shared `TaskSwitcher` rows. +- **Hierarchy / interaction:** no new mobile control, drawer, gesture, or + navigation layer is introduced. Row taps, dismiss actions, and selection + behavior remain unchanged. +- **Presentation / scroll:** the existing sheet owns scrolling and safe-area + behavior. Summary migration changes data flow only and must not add nested + scroll or viewport overflow. +- **Shared state:** status precedence and row rendering stay shared; the mobile + hook stops rebuilding status from session messages/Git stores. +- **Mobile proof:** `mobile-chrome` exercises pending, error, Git, and PR + summary updates plus repeated task switching with no inactive subscriptions. + +## Implementation waves + +Implementation remains sequential in the user-started session because the +tasks evolve shared task, event, runtime, and WebSocket contracts. + +- [x] [Task 01: Persist task status summaries](task-01-persist-task-status-summaries.md) +- [x] [Task 02: Publish live task status](task-02-publish-live-task-status.md) +- [x] [Task 03: Decouple Git polling from viewers](task-03-decouple-git-polling.md) +- [x] [Task 04: Stabilize session transport](task-04-stabilize-session-transport.md) +- [x] [Task 05: Consume summaries in task switchers](task-05-consume-task-summaries.md) +- [x] [Task 06: Make message submission idempotent](task-06-idempotent-message-submission.md) +- [x] [Task 07: Prove bounded task traffic](task-07-prove-bounded-task-traffic.md) + +## Verification + +```bash +make -C apps/backend test +make -C apps/backend lint +cd apps/web && pnpm exec vitest run +cd apps/web && pnpm run lint +cd apps/web && pnpm run typecheck +cd apps/web && pnpm e2e:run tests/session/session-stream-budget.spec.ts \ + -- --project=chromium +cd apps/web && pnpm e2e:run tests/task/task-status-summary.spec.ts \ + -- --project=chromium +cd apps/web && pnpm e2e:run tests/task/mobile-task-status-summary.spec.ts \ + -- --project=mobile-chrome +cd apps/web && pnpm e2e:run tests/chat/message-send-pressure.spec.ts \ + -- --project=chromium +``` + +## Risks + +- Projection feedback loops are possible if summary events are mistaken for + authoritative task changes. Source filtering and semantic no-op comparison + must keep publication one-way. +- Error and pending semantics currently rely partly on loaded messages. The + projector needs explicit occurrence/dismissal signals and latest-agent-message + timestamps so removing message subscriptions does not regress indicators. +- A browser-independent slow Git baseline changes lifecycle ownership. It must + count live executions once per workspace and release interest on every stop, + failure, cancellation, and recovery path. +- Multi-repository Git and PR updates can arrive independently. The projector + must aggregate from a complete latest-by-repository/PR view rather than from + one event payload. +- Strict control priority can starve notifications under sustained request + load. Drain control first but yield to notifications after a bounded batch; + keep per-class FIFO tests and queue metrics. +- Message ID deduplication must happen before mutable turn-start behavior. A + lookup after `on_turn_start` would still allow a retry to advance workflow or + switch primary sessions twice. +- Traffic E2E can pass accidentally if seeded background sessions emit no + data. Tests must prove the inactive streams are producing server-side events + while asserting those detail frames do not reach the browser. + +## Documentation impact + +This plan adds the internal product contract +`docs/specs/platform/bounded-task-status-delivery.md` and architecture decision +`docs/decisions/2026-08-01-separate-task-summary-session-stream-traffic.md`. +No public documentation changes are expected: commands, settings, public APIs, +and user-visible interaction patterns remain unchanged. diff --git a/docs/plans/bounded-task-status-delivery/task-01-persist-task-status-summaries.md b/docs/plans/bounded-task-status-delivery/task-01-persist-task-status-summaries.md new file mode 100644 index 0000000000..fb335609c0 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-01-persist-task-status-summaries.md @@ -0,0 +1,89 @@ +--- +id: "01-persist-task-status-summaries" +title: "Persist task status summaries" +status: completed +wave: 1 +depends_on: [] +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 01: Persist Task Status Summaries + +## Acceptance + +- A typed, bounded `TaskStatusSummary` can be batch-read and atomically + compared/updated with a monotonic per-task revision; semantic no-ops do not + write or publish a new revision. +- SQLite and Postgres schema replay create the portable summary store, enforce + one row per task, and delete the row with its task. +- Boot state, task-list responses, and workflow snapshots carry summaries via + batched hydration with no per-task query; an absent summary remains a safe + coarse fallback. + +## TDD sequence + +1. RED: add repository contract tests for schema replay, batch reads, + compare/update, no-op behavior, concurrent updates, and cascade deletion. +2. RED: add DTO/boot/list tests for bounded serialization, batch hydration, + missing rows, and omitted-field compatibility. +3. GREEN: implement the typed model, portable repository, keyed update path, + DTO field, and batched loaders. +4. REFACTOR: keep timestamps/revisions outside semantic equality, centralize + JSON validation, and expose narrow provider/repository interfaces. + +## Verification + +```bash +cd apps/backend && go test ./internal/task/statussummary ./internal/task/repository/... ./internal/backendapp/... ./internal/task/dto +``` + +## Files likely touched + +- `apps/backend/internal/task/statussummary/**` +- `apps/backend/internal/task/models/**` +- `apps/backend/internal/task/repository/interface.go` +- `apps/backend/internal/task/repository/sqlite/base_schema.go` +- `apps/backend/internal/task/repository/sqlite/base_migrations.go` +- `apps/backend/internal/task/repository/sqlite/task_status_summary.go` +- `apps/backend/internal/task/repository/sqlite/postgres_schema_test.go` +- `apps/backend/internal/task/dto/dto.go` +- `apps/backend/internal/backendapp/boot_state.go` +- `apps/backend/internal/backendapp/boot_state_routes.go` +- task/workflow list handlers and focused tests + +## Dependencies + +None. + +## Parallelism + +Sequential. Task 02 consumes the persisted contract and projector interface. + +## Inputs + +- Spec sections **Task status summary**, **Persistence guarantees**, and + **Failure modes**. +- ADR `2026-08-01-separate-task-summary-session-stream-traffic.md`. +- Existing portable/replayable migration conventions in + `apps/backend/internal/task/repository/sqlite`. +- Existing batched task enrichment in `apps/backend/internal/backendapp/boot_state.go`. + +## Risks + +- Do not put authoritative message, Git, or PR records into the summary table. +- Do not make task list latency proportional to task count. +- A malformed stored JSON value must be observable and repairable without + preventing the workspace from loading. + +## Verification results + +- RED schema replay test initially failed because the new table was absent. +- `cd apps/backend && go test ./internal/task/statussummary ./internal/task/repository/... ./internal/backendapp/... ./internal/task/dto` — passed (539 tests across 6 packages). +- The focused boot snapshot test confirms summaries are hydrated through the batch path and serialized as `statusSummary`. +- The Postgres replay test is environment-gated and skips when no isolated Postgres DSN is configured. + +## Output contract + +Report RED failures, final schema/model shape, batch-query evidence, exact files +changed, focused test results, migration replay results, and blockers or risks. diff --git a/docs/plans/bounded-task-status-delivery/task-02-publish-live-task-status.md b/docs/plans/bounded-task-status-delivery/task-02-publish-live-task-status.md new file mode 100644 index 0000000000..42ea245f72 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-02-publish-live-task-status.md @@ -0,0 +1,95 @@ +--- +id: "02-publish-live-task-status" +title: "Publish live task status" +status: completed +wave: 2 +depends_on: ["01-persist-task-status-summaries"] +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 02: Publish Live Task Status + +## Acceptance + +- The projector derives lifecycle/activity, pending action, active error, Git, + and PR aggregates from authoritative sources while filtering source events + that cannot change the summary. +- Recoverable-error persistence, dismissal, and newer agent responses produce + explicit projection changes; UTF-8 previews are safe and bounded to 512 + bytes. +- Each semantic change publishes one complete + `task.status_summary.updated` revision to the owning workspace; duplicate or + stale source occurrences produce no event. + +## TDD sequence + +1. RED: add table-driven derivation tests for precedence, error lifecycle, + preview bounds, multi-repository Git, and PR attention aggregation. +2. RED: add event tests proving irrelevant stream/message updates are ignored, + concurrent source changes converge, and one semantic revision is routed to + the correct workspace. +3. GREEN: wire the keyed projector to task/session/activity/pending/error/Git/PR + occurrences and add the internal/WS event types and broadcaster. +4. REFACTOR: isolate source adapters behind provider interfaces and keep event + payloads bounded replacement snapshots. + +## Verification + +```bash +cd apps/backend && go test ./internal/task/statussummary ./internal/task/service/... ./internal/orchestrator/... ./internal/gateway/websocket/... +``` + +## Files likely touched + +- `apps/backend/internal/task/statussummary/**` +- `apps/backend/internal/events/types.go` +- `apps/backend/internal/task/service/service_events.go` +- `apps/backend/internal/orchestrator/event_handlers_agent.go` +- `apps/backend/internal/orchestrator/event_handlers_git.go` +- `apps/backend/internal/orchestrator/turn_activity.go` +- recoverable-error dismissal service/handler files +- `apps/backend/internal/github/service_pr_watch.go` +- `apps/backend/internal/gateway/websocket/task_notifications.go` +- `apps/backend/internal/backendapp/gateway.go` +- `apps/backend/internal/backendapp/helpers.go` + +## Dependencies + +Task 01 supplies storage, types, and batch/rebuild interfaces. + +## Parallelism + +Sequential. Tasks 03 and 05 rely on the live projection behavior. + +## Inputs + +- Spec **Derivation rules** and the authoritative-occurrence mapping in the + plan. +- Existing task pending-action aggregation and foreground-activity enrichment. +- Existing `persistLastAgentError`, error-dismissal, Git snapshot, and + `GitHubTaskPRUpdated` paths. + +## Risks + +- Subscribing to every message update would reproduce the original traffic + problem inside the backend; filter before rebuilding. +- Error acknowledgment local to one browser remains presentation state; only + authoritative dismissal or a newer agent response clears the projection. +- Event publication must occur after the revision is durable. + +## Verification results + +- `cd apps/backend && go test ./internal/task/statussummary` — passed. +- Broad task, gateway, backendapp, lifecycle, and orchestrator integration + packages — passed. +- Projector tests cover bounded error previews, lifecycle/activity/pending + precedence, irrelevant message filtering, multi-repository Git aggregation, + PR aggregation, semantic no-ops, restart state, and workspace event output. +- The projector subscribes to bounded source occurrences only; it does not + subscribe to agent stream, shell, process, model, or MCP subjects. + +## Output contract + +Report source events consumed/ignored, projection semantics, revision/event +counts, focused test results, exact files changed, and unresolved domain gaps. diff --git a/docs/plans/bounded-task-status-delivery/task-03-decouple-git-polling.md b/docs/plans/bounded-task-status-delivery/task-03-decouple-git-polling.md new file mode 100644 index 0000000000..978d8346ea --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-03-decouple-git-polling.md @@ -0,0 +1,87 @@ +--- +id: "03-decouple-git-polling" +title: "Decouple Git polling from viewers" +status: completed +wave: 3 +depends_on: ["02-publish-live-task-status"] +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 03: Decouple Git Polling From Viewers + +## Acceptance + +- A live execution contributes slow workspace Git-monitoring interest even + when no browser subscribes to its session; selected focus upgrades that + workspace to fast mode. +- Runtime/viewer interest is reference-safe across sibling sessions and every + stop, failure, cancellation, reconnect, and recovery path; monitoring pauses + only when neither interest source remains. +- Latest per-repository observations feed the task summary, while settled tasks + retain their persisted completion/live snapshot and a poll failure never + fabricates a clean aggregate. + +## TDD sequence + +1. RED: add lifecycle aggregation cases for runtime-only slow mode, focus fast + mode, sibling sessions, duplicate transitions, and final release. +2. RED: add Git observation tests for repository-keyed aggregation, settle + persistence, and poll failure retention without any WebSocket subscriber. +3. GREEN: add runtime interest to workspace poll-mode calculation and connect + bounded Git observations to the projector. +4. REFACTOR: centralize interest precedence and ensure cleanup paths are + idempotent. + +## Verification + +```bash +cd apps/backend && go test ./internal/agent/runtime/lifecycle/... ./internal/orchestrator/... ./internal/task/statussummary +``` + +## Files likely touched + +- `apps/backend/internal/agent/runtime/lifecycle/**` +- `apps/backend/internal/gateway/websocket/hub_session_mode.go` +- `apps/backend/internal/orchestrator/event_handlers_git.go` +- `apps/backend/internal/orchestrator/task_operations.go` +- `apps/backend/internal/task/statussummary/**` +- related runtime/poll/Git tests + +## Dependencies + +Task 02 supplies the Git-summary observation sink. + +## Parallelism + +Sequential. The switcher subscription removal in Task 05 is safe only after +runtime-owned monitoring exists. + +## Inputs + +- Spec **Persistence guarantees** Git clauses. +- Existing focused/subscribed/paused poll-mode aggregator. +- Existing `UpsertLatestLiveGitSnapshot` and completion snapshot semantics. + +## Risks + +- Leaked runtime interest would poll forever; premature release would freeze + background badges. Exercise every terminal path. +- Count interest by execution/workspace identity, not repeated stream events. +- Preserve multi-repository identity before aggregating numeric totals. + +## Verification results + +- `cd apps/backend && go test ./internal/agent/runtime/lifecycle` — passed. +- Broad backend integration packages — passed. +- Runtime-only executions retain slow workspace monitoring without a browser + subscriber; focus upgrades to fast mode, duplicate interest is idempotent, + and removal/recovery paths release the runtime reference safely. +- Git observations remain keyed by environment/repository and feed the task + summary without making browser session membership responsible for polling. + +## Output contract + +Report the interest state machine, cleanup paths audited, Git freshness +behavior, focused test results, exact files changed, and remaining lifecycle +risks. diff --git a/docs/plans/bounded-task-status-delivery/task-04-stabilize-session-transport.md b/docs/plans/bounded-task-status-delivery/task-04-stabilize-session-transport.md new file mode 100644 index 0000000000..990852aff9 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-04-stabilize-session-transport.md @@ -0,0 +1,93 @@ +--- +id: "04-stabilize-session-transport" +title: "Stabilize session transport" +status: completed +wave: 4 +depends_on: ["03-decouple-git-polling"] +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 04: Stabilize Session Transport + +## Acceptance + +- Correlated responses/errors use a reserved priority queue; notification + saturation cannot silently drop them, and control overflow closes the socket + with an observable reason. +- `session.subscribe` sends a full snapshot only on new membership and + `session.focus` never replays one; repeated requests remain acknowledged and + idempotent. +- `session.git.refresh` refreshes only selected-session Git data, replacing the + frontend's focus-as-refresh workaround without changing focus membership. + +## TDD sequence + +1. RED: saturate notification delivery and prove a correlated response is the + next deliverable control frame; prove control overflow closes explicitly. +2. RED: add duplicate subscribe/focus tests that count full snapshot actions, + plus targeted Git refresh tests that exclude model/message/shell snapshots. +3. GREEN: split client outbound queues, prioritize bounded batches in the write + pump, expose membership transitions, and add the targeted action. +4. GREEN: migrate `refreshSessionData` callers to the targeted Git refresh. +5. REFACTOR: add queue/drop/close telemetry and preserve FIFO order within each + traffic class without permanently starving notifications. + +## Verification + +```bash +cd apps/backend && go test ./internal/gateway/websocket/... +cd apps && pnpm --filter @kandev/web test -- --run lib/ws +``` + +## Files likely touched + +- `apps/backend/internal/gateway/websocket/client.go` +- `apps/backend/internal/gateway/websocket/hub.go` +- `apps/backend/internal/gateway/websocket/hub_session_mode.go` +- `apps/backend/internal/gateway/websocket/client_session_focus_test.go` +- new gateway queue/saturation tests +- shared WebSocket action definitions +- `apps/web/lib/ws/client.ts` +- `apps/web/lib/types/backend.ts` +- active-session Git refresh callers such as Dockview/shared session hooks +- focused frontend WS tests + +## Dependencies + +Task 03 ensures removing viewer interest does not pause live Git monitoring. + +## Parallelism + +Sequential. Task 05 consumes the final subscription contract; Task 06 relies +on response-delivery semantics. + +## Inputs + +- Spec **API and event surface** WebSocket clauses. +- Existing `Client.send`, `WritePump`, `handleSessionSubscribe`, + `handleSessionFocus`, and `sendSessionData` behavior. +- Existing `session-focus-signal.spec.ts` contract, which must be updated. + +## Risks + +- Absolute control priority can starve notifications; use a bounded priority + burst and test fairness. +- A duplicate frontend ref-count subscribe must still receive an ACK even when + no snapshot is replayed. +- Closing on control overflow must release hub membership and trigger normal + client reconciliation. + +## Verification results + +- `cd apps/backend && go test ./internal/gateway/websocket/...` — passed. +- Gateway tests cover duplicate subscribe/focus ACK-only behavior, targeted + Git refresh, reserved control delivery under notification pressure, and + explicit control-queue overflow closure. +- The frontend now uses `session.git.refresh` for selected detail Git refresh; + focus no longer replays a full session snapshot. + +## Output contract + +Report queue semantics/capacities, saturation evidence, subscription snapshot +counts, targeted refresh behavior, focused test results, and telemetry added. diff --git a/docs/plans/bounded-task-status-delivery/task-05-consume-task-summaries.md b/docs/plans/bounded-task-status-delivery/task-05-consume-task-summaries.md new file mode 100644 index 0000000000..73a5519d87 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-05-consume-task-summaries.md @@ -0,0 +1,104 @@ +--- +id: "05-consume-task-summaries" +title: "Consume summaries in task switchers" +status: completed +wave: 5 +depends_on: ["04-stabilize-session-transport"] +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 05: Consume Summaries in Task Switchers + +## Acceptance + +- Task mapping/store handlers keep the newest summary revision, preserve it + when partial task updates omit the field, and reject stale deltas. +- Desktop and mobile rows derive pending, activity, error, Git, and PR status + from the same summary contract while preserving existing icon precedence and + local error acknowledgment. +- Mounting/switching task rows creates no inactive `session.subscribe`, removes + `useBulkGitStatusSubscription`, and does not workspace-fetch detailed PRs for + switcher decoration. + +## TDD sequence + +1. RED: add mapper/reducer tests for hydration, omitted fields, revision + ordering, and reconnect replacement. +2. RED: update desktop/mobile hook and row tests to supply summaries and prove + all existing precedence/error/PR/Git outcomes without message/session-store + fixtures. +3. RED: add a subscription-spy component test proving inactive rows and task + switches do not subscribe. +4. GREEN: add types/handlers, migrate both switchers, remove bulk Git and row PR + detail loads, and keep active detail consumers unchanged. +5. REFACTOR: share summary-to-row derivation and delete obsolete message/Git + aggregation paths that have no remaining consumers. + +## Verification + +```bash +cd apps && pnpm --filter @kandev/web test -- --run \ + lib/kanban/map-task.test.ts \ + components/task/task-session-sidebar.test.tsx \ + components/task/task-session-sidebar-item.test.ts \ + components/task/mobile/session-task-switcher-sheet-hooks.test.ts +cd apps/web && pnpm run typecheck +``` + +## Files likely touched + +- `apps/web/lib/types/http.ts` +- `apps/web/lib/types/backend.ts` +- `apps/web/lib/kanban/map-task.ts` +- `apps/web/lib/kanban/map-task.test.ts` +- Kanban task/store slice types and task WebSocket handlers +- `apps/web/components/task/task-session-sidebar.tsx` +- `apps/web/components/task/task-session-sidebar-item.ts` +- `apps/web/components/task/task-session-sidebar-aggregate.ts` +- `apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts` +- `apps/web/components/task/task-item.tsx` +- task summary/PR icon helpers and focused tests + +## Dependencies + +Tasks 01–04 supply complete snapshots/deltas, independent Git freshness, and +idempotent selected-session transport. + +## Parallelism + +Sequential. Desktop/mobile share derivation and must migrate in one task. + +## Inputs + +- Spec **Derivation rules**, rollout fallback, and mobile scenario. +- Existing `TaskSwitcher`/`TaskItem` shared rendering. +- Existing local error acknowledgment stamps and PR attention-color rules. + +## Risks + +- Do not remove active-detail Git or PR data needed for diffs/tooltips outside + task switchers. +- Missing summaries omit only unknown decorations; they must not appear clean + or trigger a hidden subscription fallback. +- Keep desktop/mobile behavior shared rather than duplicating summary rules. + +## Verification results + +- `cd apps/web && pnpm exec vitest run` — passed (1,011 files; 7,743 tests, 4 skipped). +- `cd apps/web && pnpm run typecheck` — passed. +- `cd apps/web && pnpm run lint` — passed. +- Desktop and mobile task rows now derive Git, PR, error, pending, activity, + and primary-session state from `statusSummary` with coarse-field fallback. +- The sidebar no longer mounts `useBulkGitStatusSubscription`, raw session + message decoration, or workspace-wide PR decoration fetches. Active detail + surfaces retain their session Git/message/PR subscriptions. +- A dedicated Playwright subscription-spy scenario is still part of Task 07; + the component-level behavior is covered by the summary mapper/reducer tests + and source inspection. + +## Output contract + +Report obsolete subscriptions/fetches removed, shared derivation, precedence +coverage, desktop/mobile test results, typecheck, exact files changed, and any +detail-surface exceptions retained. diff --git a/docs/plans/bounded-task-status-delivery/task-06-idempotent-message-submission.md b/docs/plans/bounded-task-status-delivery/task-06-idempotent-message-submission.md new file mode 100644 index 0000000000..92b3d672a9 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-06-idempotent-message-submission.md @@ -0,0 +1,104 @@ +--- +id: "06-idempotent-message-submission" +title: "Make message submission idempotent" +status: completed +wave: 6 +depends_on: ["04-stabilize-session-transport", "05-consume-task-summaries"] +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 06: Make Message Submission Idempotent + +## Acceptance + +- Every in-repository `message.add` caller supplies a stable message ID for one + user intent and retains it through timeout, reconnect, retry, response, and + notification hydration. +- Duplicate/concurrent duplicate IDs in the same authorized task return one + persisted user message and run session checks, turn-start hooks, workflow + transitions, and prompt dispatch at most once; cross-scope reuse is rejected. +- The composer reports success when response/notification/list reconciliation + finds the ID and shows unknown status only after bounded reconciliation + fails; model selection and draft behavior remain intact. + +## TDD sequence + +1. RED: add backend duplicate, concurrent duplicate, uniqueness-race, + cross-task, and post-`on_turn_start` session-switch cases with explicit hook + and dispatch counters. +2. RED: add frontend tests proving one generated ID survives request timeout, + reconnect retry, dropped notification, and duplicate response hydration. +3. GREEN: serialize backend acceptance before mutable hooks, use + `CreateMessageWithID`, reload races, and return accepted duplicates early. +4. GREEN: centralize client submission/reconciliation and migrate every direct + `message.add` caller to the stable-ID helper. +5. REFACTOR: keep optimistic/response/notification upserts idempotent and make + terminal error classification deterministic. + +## Verification + +```bash +cd apps/backend && go test ./internal/task/handlers/... ./internal/task/service/... ./internal/task/repository/... +cd apps && pnpm --filter @kandev/web test -- --run \ + hooks/use-message-handler.test.ts \ + lib/chat/message-send-error.test.ts +``` + +## Files likely touched + +- `apps/backend/internal/task/handlers/message_handlers.go` +- `apps/backend/internal/task/handlers/message_handlers_test.go` +- `apps/backend/internal/task/service/service_messages.go` +- message repository/race tests as needed +- `apps/web/hooks/use-message-handler.ts` +- `apps/web/hooks/use-message-handler.test.ts` +- `apps/web/lib/chat/message-send-error.ts` +- chat input/composer send flow +- direct `message.add` callers in review, comments, plans, Office, and + passthrough surfaces +- focused caller tests + +## Dependencies + +Task 04 supplies deterministic control delivery/reconnect behavior. Task 05 +removes the background traffic source before end-to-end send verification. + +## Parallelism + +Sequential. Backend and frontend must agree on the message-ID contract before +Task 07 exercises retries. + +## Inputs + +- Spec **Retry-safe message submission** and uncertain-send failure mode. +- Existing `CreateMessageWithID` service path and response hydration in + `use-message-handler.ts`. +- Existing message-added gap E2E behavior. + +## Risks + +- The duplicate check must run before session-state and turn-start mutation. +- A uniqueness conflict after a concurrent first write must reload and return + the accepted row rather than dispatching again. +- Generated IDs belong to one intent; creating a new ID on retry defeats the + contract. + +## Verification results + +- Backend message handler/service/repository integration packages — passed. +- `cd apps/web && pnpm exec vitest run` — passed (1,011 files; 7,743 tests, 4 skipped). +- Every in-repository direct `message.add` UI caller now supplies a stable + `client_message_id`; timeout/connection-closed reconciliation retries the + exact same ID and upserts the accepted message. +- Backend acceptance is serialized per ID, checks an existing authorized row + before session/turn-start side effects, and reloads after a uniqueness race. +- The remaining limitation is the approved crash window: exactly-once + external agent execution cannot be guaranteed across a complete backend + process crash. + +## Output contract + +Report wire contract, serialization strategy, all migrated callers, hook/ +dispatch count evidence, backend/frontend test results, and any crash-window +limitations retained from the spec. diff --git a/docs/plans/bounded-task-status-delivery/task-07-prove-bounded-task-traffic.md b/docs/plans/bounded-task-status-delivery/task-07-prove-bounded-task-traffic.md new file mode 100644 index 0000000000..758f87fb15 --- /dev/null +++ b/docs/plans/bounded-task-status-delivery/task-07-prove-bounded-task-traffic.md @@ -0,0 +1,137 @@ +--- +id: "07-prove-bounded-task-traffic" +title: "Prove bounded task traffic" +status: completed +wave: 7 +depends_on: + - "03-decouple-git-polling" + - "04-stabilize-session-transport" + - "05-consume-task-summaries" + - "06-idempotent-message-submission" +plan: "plan.md" +spec: "../../specs/platform/bounded-task-status-delivery.md" +--- + +# Task 07: Prove Bounded Task Traffic + +## Acceptance + +- A 27-task WebSocket capture proves zero inactive session subscriptions/detail + frames and constant per-switch subscription/focus work; Playwright attaches + frame/byte totals for diagnosis. +- Inactive clarification, error/dismissal, Git, and PR changes update desktop + and mobile rows through summary revisions with existing precedence. +- Under deliberate notification pressure, the selected model selector remains + usable and retrying one message ID produces one persisted message/turn with a + resolved send result. + +## TDD sequence + +1. RED: replace old E2E assumptions that require bulk Git subscriptions or + focus-triggered snapshots with assertions for the new bounded contract. +2. RED: add deterministic server-side inactive activity and verify the browser + did not receive its detail frames; fail if the activity source was not + exercised. +3. RED: add desktop/mobile summary updates and notification-pressure message + retry scenarios. +4. GREEN: fix integration wiring only; do not weaken frame classification, + task-count, activity-source, or duplicate-message assertions. +5. REFACTOR: centralize WebSocket capture/byte accounting helpers and attach + concise diagnostics on pass/failure. + +## Verification + +```bash +cd apps/web && pnpm e2e:run tests/session/session-stream-budget.spec.ts \ + -- --project=chromium +cd apps/web && pnpm e2e:run tests/task/task-status-summary.spec.ts \ + -- --project=chromium +cd apps/web && pnpm e2e:run tests/task/mobile-task-status-summary.spec.ts \ + -- --project=mobile-chrome +cd apps/web && pnpm e2e:run tests/chat/message-send-pressure.spec.ts \ + -- --project=chromium +make -C apps/backend test +cd apps/web && pnpm run typecheck +``` + +## Files likely touched + +- `apps/web/e2e/tests/session/session-stream-budget.spec.ts` +- `apps/web/e2e/helpers/ws-traffic.ts` +- `apps/web/e2e/tests/task/task-status-summary.spec.ts` +- `apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts` +- `apps/web/e2e/tests/chat/message-send-pressure.spec.ts` +- `apps/web/e2e/tests/session/session-focus-signal.spec.ts` +- `apps/web/e2e/tests/task/sidebar-diff-stats.spec.ts` +- `apps/web/e2e/tests/chat/message-add-ws-gap.spec.ts` +- `apps/web/e2e/tests/chat/mobile-message-add-ws-gap.spec.ts` +- WebSocket capture/drop and task/session seeding helpers +- plan/task status fields after verification + +## Dependencies + +Tasks 03–06 must be complete so the tests observe final polling, transport, +switcher, and message contracts. + +## Parallelism + +Sequential final integration/QA task. + +## Inputs + +- The captured incident baseline: 700 frames, 3.23 MB, 74 subscribes, and 47 + unsubscribes in five seconds for 27 sessions. +- Every scenario in the approved spec. +- Existing frame-drop helpers and model/message/sidebar E2E suites. + +## Risks + +- A quiet seed would make the isolation test meaningless; assert background + activity occurred server-side. +- Byte totals vary with compression/build data and are diagnostic, while + inactive-session identity and O(1) subscription counts are hard assertions. +- Mobile tests must use the existing sheet and assert no layout/overflow + regression while status changes arrive. + +## Verification results + +The implementation-level backend and frontend verification is complete: + +- `make -C apps/backend lint` — passed with 0 issues. +- Broad backend task/gateway/backendapp/lifecycle/orchestrator tests — passed. +- `cd apps/web && pnpm run typecheck` — passed. +- `cd apps/web && pnpm run lint` — passed. +- `cd apps/web && pnpm exec vitest run` — passed (1,011 files; 7,743 tests, 4 skipped). +- `cd apps/web && pnpm e2e:run --host tests/task/sidebar-diff-stats.spec.ts` — passed + (1 test; 7.2s), confirming persisted diff badges survive a backend restart for + an inactive sidebar task. + +- `cd apps/web && pnpm e2e:run --host --no-build + tests/session/session-stream-budget.spec.ts` — passed (1 test; 9.0s). + The 27-task capture measured 479 gateway frames / 86,243 bytes across five + task switches, with 5 `session.subscribe` frames, 4 `session.unsubscribe` + frames, and zero inactive-session detail frames. + +- `cd apps/web && pnpm e2e:run --host --no-build + tests/task/task-status-summary.spec.ts` — passed (1 test; 2.7s), confirming + an inactive desktop row receives clarification, error, and PR revisions + while another task remains selected. +- `cd apps/web && pnpm e2e:run --host --no-build + tests/task/mobile-task-status-summary.spec.ts` — passed (1 test; 2.8s), + confirming the native mobile task switcher receives the same bounded status + revisions without horizontal overflow. +- `cd apps/web && pnpm e2e:run --host --no-build + tests/chat/message-send-pressure.spec.ts` — passed (1 test; 12.6s), + confirming 80 streamed tool-call notifications do not hide the model + selector and a dropped `message.add` response reconciles to one persisted + user message and one new turn. + +The dedicated 27-task capture and summary-pressure scenarios are now complete; +their byte totals remain diagnostic while inactive-session detail isolation and +constant subscription work are the correctness assertions. + +## Output contract + +Report exact frame/subscription/byte measurements, inactive-frame assertions, +desktop/mobile results, message/turn counts, broad verification commands, +exact files changed, and any residual traffic sources. diff --git a/docs/specs/INDEX.md b/docs/specs/INDEX.md index 027f03b30e..14458988ed 100644 --- a/docs/specs/INDEX.md +++ b/docs/specs/INDEX.md @@ -43,6 +43,7 @@ Product-wide capabilities that are not tied to a single feature area. | [plugins — marketplace](plugins/marketplace.md) | building | | [semantic-notifications](platform/notifications.md) | shipped | | [workspace-git-status](platform/workspace-git-status.md) | shipped | +| [bounded-task-status-delivery](platform/bounded-task-status-delivery.md) | approved | ## tasks/ — task & workflow model diff --git a/docs/specs/platform/bounded-task-status-delivery.md b/docs/specs/platform/bounded-task-status-delivery.md new file mode 100644 index 0000000000..5689463198 --- /dev/null +++ b/docs/specs/platform/bounded-task-status-delivery.md @@ -0,0 +1,188 @@ +--- +status: implemented +created: 2026-08-01 +owner: kandev +--- + +# Bounded Task Status Delivery + +## Why + +Task rows currently obtain compact status indicators by observing large, +session-owned streams. With many agents working, one browser receives messages, +shell activity, model updates, MCP state, and Git events from sessions that are +not open. Switching tasks rebuilds those subscriptions. The resulting traffic +can delay or drop request responses, producing an unknown message-send result +and temporarily hiding active-session controls such as the model selector. + +Task-level navigation needs a bounded status contract. Session detail still +needs rich streams, but opening a workspace must not make every session a +detail surface. + +## What + +- Every task snapshot may carry a `status_summary` containing the complete set + of runtime facts needed by desktop and mobile task switchers. +- The backend derives that summary from authoritative task, session, message, + Git, and pull-request state. It is a rebuildable read model, not a second + source of truth. +- Summary updates use the existing workspace task feed. Task rows never + subscribe to a session merely to obtain a badge. +- Full session snapshots and live session notifications are delivered only to + explicitly opened session detail surfaces. +- Repeated subscribe/focus requests do not replay full session state. Git + refresh has a targeted action that does not alter focus. +- Correlated WebSocket responses and errors are prioritized over unsolicited + notifications and cannot be silently dropped by notification pressure. +- `message.add` uses a stable client-generated message ID so an uncertain send + can be reconciled or retried without creating or dispatching a duplicate. +- Existing desktop and mobile status/icon precedence remains unchanged. + +## Task status summary + +The wire field is `status_summary`; the frontend maps it to `statusSummary`. +The initial contract is: + +| Field | Meaning | Bound | +| ---------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------ | +| `revision`, `updated_at` | Monotonic task-local version and projection time | Constant | +| `primary_session` | Primary session ID and lifecycle state | One session | +| `foreground_activity`, `active_subagent_count` | Existing task-level busy aggregate | Constant | +| `pending_action` | `permission`, `clarification`, or absent | Constant | +| `active_error` | Session ID, stable error stamp, occurrence time, and safe preview | One preview, at most 512 UTF-8 bytes | +| `git` | Aggregate additions, deletions, changed files, ahead, and behind | Numeric totals only | +| `pull_request` | Count, bounded representative identity, and aggregate display state | Constant regardless of PR count | + +`pull_request.aggregate_state` is one of `failure`, `blocked`, `pending`, +`awaiting_review`, `ready`, `passing`, `draft`, `merged`, `closed`, or +`neutral`. It preserves the existing most-attention-worthy task-row rule. + +The summary never contains message bodies, transcript entries, file names, +patches, shell output, model lists, MCP payloads, or an unbounded array of +sessions, repositories, or pull requests. Existing flat task runtime fields may +remain during migration, but switchers use the summary when present. + +## Derivation rules + +- Pending permission outranks pending clarification for the row's primary + state icon. Both outrank generating/background activity, which outranks + coarse lifecycle state. This is the existing task-row precedence. +- `active_error` is independent of the primary state icon. It represents the + newest relevant recoverable agent error and clears after an authoritative + dismissal or a newer agent response according to the existing error rules. +- Git totals aggregate the latest observation for every repository in the + task. A multi-repository update must not expose a partial replacement that + forgets unchanged repositories. +- Pull-request state aggregates open PRs before terminal PRs and chooses the + most attention-worthy current status. Full PR details remain owned by the + GitHub domain and are loaded only by surfaces that need them. +- A semantic no-op does not increment `revision` or emit an update. +- Clients ignore a summary delta whose revision is not newer than the stored + revision. + +## API and event surface + +- Boot state, task-list responses, and workflow snapshots include the latest + `status_summary` without per-task queries. +- `task.status_summary.updated` is workspace-scoped and carries `task_id`, + `workspace_id`, and the complete replacement summary. It uses the same + authorization and subscription boundary as other task updates. +- `session.subscribe` sends the full initial session snapshot only when that + client newly joins the session. A duplicate subscribe only acknowledges the + request. +- `session.focus` changes focus/poll priority and acknowledges the request; it + does not replay a session snapshot. +- `session.git.refresh` requests a fresh Git observation for the selected + session without changing focus or subscription membership. +- WebSocket request responses/errors use a reserved control path. If the + server cannot enqueue control traffic, it closes the connection so the + client enters explicit reconnect/reconciliation instead of waiting on a + response that was silently discarded. +- Web clients send a stable `client_message_id` with `message.add` (the + backend also accepts `message_id` as a compatibility alias). The first + accepted request owns that ID. A retry in the same authorized task returns + the persisted message and skips session-state transitions, turn-start hooks, + message creation, and prompt dispatch. Reuse outside that scope is rejected. + +## Persistence guarantees + +- The latest task status summary is stored by task ID with workspace ID, + revision, JSON payload, and update time using migrations supported by both + SQLite and Postgres. +- Summary persistence and revision changes are serialized per task. A + compare-and-update or equivalent transaction prevents concurrent source + events from publishing duplicate revisions or losing a newer value. +- Missing rows are rebuilt from authoritative records. List and boot loaders + batch summary reads and may batch repairs; they do not perform an N+1 query. +- Live Git observations remain coalesced before persistence/publication. + Running executions maintain the slow monitoring baseline independently of + browser subscribers; active focus may request fast monitoring. Settled tasks + retain the latest stable snapshot. +- Message IDs remain stable through reconnect, retry, response hydration, and + notification hydration. Duplicate notifications and responses upsert the + same frontend message. + +## Failure modes + +- If projection fails, the last valid summary remains visible, the failure is + logged with task/source context, and the next semantic source event or + authoritative rebuild can repair it. +- If a summary delta is dropped, reconnect or a task-list/workflow refresh + supplies the complete current summary. The browser does not fall back to + background session subscriptions. +- If Git monitoring fails, the summary retains the last observation and does + not claim a clean tree from missing data. +- If a message response is interrupted, the client reconciles the same + `client_message_id`/persisted message ID from the response, notification, or + message list, then retries that ID when needed. It reports an unknown outcome only after bounded + reconciliation cannot determine acceptance. +- Notification overload may coalesce or drop replaceable notifications, but + it cannot silently discard a correlated response/error. +- If `status_summary` is temporarily absent during rollout, task rows use the + existing coarse task fields and omit unavailable decorations; they do not + subscribe to inactive sessions. + +## Scenarios + +- **GIVEN** a workspace with 27 tasks and one selected session, **WHEN** the + task switcher loads, **THEN** no inactive session is subscribed and no + inactive message, shell, model, MCP, or Git stream is delivered for a row. +- **GIVEN** the same workspace, **WHEN** the user switches tasks repeatedly, + **THEN** subscription work is proportional to the sessions opened/closed by + each switch and does not grow with the number of workspace tasks. +- **GIVEN** a background task asks a question, encounters a recoverable error, + changes its Git tree, or receives a PR update, **WHEN** its summary revision + arrives, **THEN** desktop and mobile rows update without a session + subscription. +- **GIVEN** a recoverable error is dismissed or followed by a newer agent + response, **WHEN** the projector processes that occurrence, **THEN** the + independent error indicator clears on both task switchers. +- **GIVEN** notification traffic saturates its queue, **WHEN** the selected + session sends `message.add`, **THEN** the correlated response is delivered + first or the connection closes for deterministic reconciliation. +- **GIVEN** the first message response becomes uncertain, **WHEN** the client + retries the same `client_message_id`, **THEN** exactly one user message is stored and + the duplicate request does not dispatch a second prompt. +- **GIVEN** many background sessions are active, **WHEN** the selected agent + publishes model configuration, **THEN** the selected chat retains its model + selector and can submit a follow-up message. +- **GIVEN** a phone viewport, **WHEN** task summaries change, **THEN** the + existing task-switcher sheet shows the same badges and precedence as the + desktop sidebar without new navigation, scroll, or touch behavior. + +## Out of scope + +- Moving full transcripts, diffs, shell output, model configuration, or MCP + state into tasks. +- Replacing authoritative session, message, Git, or GitHub persistence. +- Redesigning desktop or mobile task-switcher layout and interactions. +- Preventing detail surfaces such as Office or explicit multi-session views + from subscribing to sessions they intentionally display. +- Guaranteeing external agent prompt execution exactly once across a complete + backend process crash; this contract prevents duplicate handler dispatch on + client retry. +- Treating a larger timeout or queue capacity as the fix. + +## Implementation plan + +See [`../../plans/bounded-task-status-delivery/plan.md`](../../plans/bounded-task-status-delivery/plan.md).