From 9be979827d784b803348ce460ff8df393d52016f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Fri, 31 Jul 2026 09:01:22 +0100 Subject: [PATCH] fix: sync quick chats and their names across devices (#2085) Co-authored-by: Claude Opus 5 (1M context) --- .../backend/internal/backendapp/boot_state.go | 134 +-------- .../handlers/quick_chat_list_handlers_test.go | 134 +++++++++ .../internal/task/handlers/task_handlers.go | 4 +- .../task/handlers/task_http_handlers.go | 45 +++ .../task/service/quick_chat_sessions.go | 160 +++++++++++ .../task/service/quick_chat_sessions_test.go | 260 ++++++++++++++++++ .../internal/task/service/service_events.go | 3 + .../service_office_integration_test.go | 12 +- apps/web/app/page.tsx | 38 +-- .../config-chat/use-config-chat.test.ts | 2 + .../components/config-chat/use-config-chat.ts | 26 +- .../quick-chat/quick-chat-dialog.tsx | 2 +- .../quick-chat/quick-chat-modal.test.ts | 13 +- .../quick-chat/quick-chat-provider.tsx | 4 + .../quick-chat/quick-chat-session-view.tsx | 4 + .../quick-chat/use-quick-chat-modal.test.ts | 76 ++++- .../quick-chat/use-quick-chat-modal.ts | 31 ++- apps/web/e2e/helpers/pr-asset-capture.test.ts | 66 +++++ apps/web/e2e/helpers/pr-asset-capture.ts | 13 +- .../chat/quick-chat-cross-device.spec.ts | 160 +++++++++++ apps/web/e2e/tests/chat/quick-chat-helpers.ts | 82 ++++++ apps/web/e2e/tests/chat/quick-chat.spec.ts | 83 +----- .../web/hooks/use-ensure-task-session.test.ts | 64 +++++ apps/web/hooks/use-ensure-task-session.ts | 44 +++ apps/web/hooks/use-quick-chat-resync.test.ts | 149 ++++++++++ apps/web/hooks/use-quick-chat-resync.ts | 59 ++++ apps/web/lib/api/domains/workspace-api.ts | 37 ++- apps/web/lib/quick-chat/map-sessions.test.ts | 45 +++ apps/web/lib/quick-chat/map-sessions.ts | 20 ++ apps/web/lib/quick-chat/rename.test.ts | 86 ++++++ apps/web/lib/quick-chat/rename.ts | 70 +++++ apps/web/lib/state/default-state.ts | 12 +- apps/web/lib/state/hydration/hydrator.ts | 8 +- .../state/slices/ui/quick-chat-sync.test.ts | 218 +++++++++++++++ .../lib/state/slices/ui/quick-chat-sync.ts | 129 +++++++++ apps/web/lib/state/slices/ui/types.ts | 10 + apps/web/lib/state/slices/ui/ui-slice.ts | 42 ++- apps/web/lib/state/store.ts | 10 +- apps/web/lib/types/backend.ts | 3 + apps/web/lib/ws/handlers/quick-chat.test.ts | 95 +++++++ apps/web/lib/ws/handlers/quick-chat.ts | 62 +++++ .../web/lib/ws/handlers/tasks-archive.test.ts | 2 + .../lib/ws/handlers/tasks-quick-chat.test.ts | 69 +++++ .../tasks-walkthrough-cleanup.test.ts | 2 + .../web/lib/ws/handlers/tasks.test-helpers.ts | 2 + apps/web/lib/ws/handlers/tasks.ts | 19 +- apps/web/vitest.config.ts | 5 +- docs/public/developer-tools.md | 2 + 48 files changed, 2321 insertions(+), 295 deletions(-) create mode 100644 apps/backend/internal/task/handlers/quick_chat_list_handlers_test.go create mode 100644 apps/backend/internal/task/service/quick_chat_sessions.go create mode 100644 apps/backend/internal/task/service/quick_chat_sessions_test.go create mode 100644 apps/web/e2e/helpers/pr-asset-capture.test.ts create mode 100644 apps/web/e2e/tests/chat/quick-chat-cross-device.spec.ts create mode 100644 apps/web/e2e/tests/chat/quick-chat-helpers.ts create mode 100644 apps/web/hooks/use-ensure-task-session.test.ts create mode 100644 apps/web/hooks/use-ensure-task-session.ts create mode 100644 apps/web/hooks/use-quick-chat-resync.test.ts create mode 100644 apps/web/hooks/use-quick-chat-resync.ts create mode 100644 apps/web/lib/quick-chat/map-sessions.test.ts create mode 100644 apps/web/lib/quick-chat/map-sessions.ts create mode 100644 apps/web/lib/quick-chat/rename.test.ts create mode 100644 apps/web/lib/quick-chat/rename.ts create mode 100644 apps/web/lib/state/slices/ui/quick-chat-sync.test.ts create mode 100644 apps/web/lib/state/slices/ui/quick-chat-sync.ts create mode 100644 apps/web/lib/ws/handlers/quick-chat.test.ts create mode 100644 apps/web/lib/ws/handlers/quick-chat.ts create mode 100644 apps/web/lib/ws/handlers/tasks-quick-chat.test.ts diff --git a/apps/backend/internal/backendapp/boot_state.go b/apps/backend/internal/backendapp/boot_state.go index f5d1c9c4d2..629277f166 100644 --- a/apps/backend/internal/backendapp/boot_state.go +++ b/apps/backend/internal/backendapp/boot_state.go @@ -3,8 +3,6 @@ package backendapp import ( "context" "net/http" - "sort" - "time" "github.com/kandev/kandev/internal/agent/runtime/lifecycle" agentsettingsdto "github.com/kandev/kandev/internal/agent/settings/dto" @@ -23,8 +21,6 @@ const ( legacyOfficeWorkspaceCookie = "office-active-workspace" bootStateKeySessionID = "sessionId" bootStateKeyWorkspaceID = "workspaceId" - quickChatSessionKindChat = "chat" - quickChatSessionKindConfig = "config" ) // ssoProvidersForBoot lists the plugin-contributed external-login options for @@ -408,80 +404,17 @@ func activeWorkspaceIDFromState(state map[string]any) string { } func (b bootStateBuilder) quickChatSessions(ctx context.Context, workspaceID string) (quickChatBootState, error) { - tasks, err := b.listQuickChatTasks(ctx, workspaceID) + items, err := b.p.taskSvc.ListQuickChatSessions(ctx, workspaceID) if err != nil { return quickChatBootState{}, err } - if len(tasks) == 0 { - return quickChatBootState{sessions: []map[string]any{}}, nil - } - taskIDs := taskIDs(tasks) - primaryByTask, err := b.p.taskSvc.GetPrimarySessionInfoForTasks(ctx, taskIDs) - if err != nil { - return quickChatBootState{}, err - } - - items := make([]quickChatBootSession, 0, len(tasks)) - taskSessions := make(map[string]taskdto.TaskSessionDTO, len(tasks)) - for _, task := range tasks { - if !isRestorableQuickChatTask(task) { - continue - } - primary := primaryByTask[task.ID] - if primary == nil || primary.ID == "" { - continue - } - items = append(items, quickChatBootSession{ - state: mapQuickChatSessionState(task, primary), - taskID: task.ID, - createdAt: task.CreatedAt, - lastActivityAt: quickChatLastActivityAt(task, primary), - }) - taskSessions[primary.ID] = taskdto.FromTaskSession(primary) - } - sort.SliceStable(items, func(i, j int) bool { - if !items[i].lastActivityAt.Equal(items[j].lastActivityAt) { - return items[i].lastActivityAt.After(items[j].lastActivityAt) - } - if !items[i].createdAt.Equal(items[j].createdAt) { - return items[i].createdAt.Before(items[j].createdAt) - } - return items[i].taskID < items[j].taskID - }) - result := make([]map[string]any, 0, len(items)) + sessions := make([]map[string]any, 0, len(items)) + taskSessions := make(map[string]taskdto.TaskSessionDTO, len(items)) for _, item := range items { - result = append(result, item.state) + sessions = append(sessions, mapQuickChatSessionState(item)) + taskSessions[item.SessionID] = taskdto.FromTaskSession(item.Session) } - return quickChatBootState{sessions: result, taskSessions: taskSessions}, nil -} - -func (b bootStateBuilder) listQuickChatTasks(ctx context.Context, workspaceID string) ([]*taskmodels.Task, error) { - const pageSize = 1000 - var all []*taskmodels.Task - for page := 1; ; page++ { - tasks, total, err := b.p.taskSvc.ListTasksByWorkspace(ctx, workspaceID, "", "", "", page, pageSize, "", false, false, true, false) - if err != nil { - return nil, err - } - all = append(all, tasks...) - if len(tasks) == 0 || len(all) >= total { - return all, nil - } - } -} - -type quickChatBootSession struct { - state map[string]any - taskID string - createdAt time.Time - lastActivityAt time.Time -} - -func quickChatLastActivityAt(task *taskmodels.Task, primary *taskmodels.TaskSession) time.Time { - if primary.UpdatedAt.After(task.UpdatedAt) { - return primary.UpdatedAt - } - return task.UpdatedAt + return quickChatBootState{sessions: sessions, taskSessions: taskSessions}, nil } type quickChatBootState struct { @@ -515,59 +448,22 @@ func mergeBootTaskSessionItems(state map[string]any, items map[string]taskdto.Ta taskSessions["items"] = merged } -func taskIDs(tasks []*taskmodels.Task) []string { - ids := make([]string, 0, len(tasks)) - for _, task := range tasks { - if task != nil { - ids = append(ids, task.ID) - } - } - return ids -} - -func isRestorableQuickChatTask(task *taskmodels.Task) bool { - return task != nil && - task.IsEphemeral && - task.WorkflowID == "" && - task.Origin != taskmodels.TaskOriginAutomationRun -} - -func mapQuickChatSessionState(task *taskmodels.Task, primary *taskmodels.TaskSession) map[string]any { +func mapQuickChatSessionState(item taskservice.QuickChatSession) map[string]any { state := map[string]any{ - bootStateKeySessionID: primary.ID, - bootStateKeyWorkspaceID: task.WorkspaceID, - "kind": quickChatSessionKind(task), + bootStateKeySessionID: item.SessionID, + bootStateKeyWorkspaceID: item.WorkspaceID, + "taskId": item.TaskID, + "kind": item.Kind, } - if task.Title != "" && task.Title != "Quick Chat" { - state["name"] = task.Title + if item.Name != "" { + state["name"] = item.Name } - if agentProfileID := quickChatAgentProfileID(task, primary); agentProfileID != "" { - state["agentProfileId"] = agentProfileID + if item.AgentProfileID != "" { + state["agentProfileId"] = item.AgentProfileID } return state } -func quickChatSessionKind(task *taskmodels.Task) string { - if task != nil { - if configMode, ok := task.Metadata["config_mode"].(bool); ok && configMode { - return quickChatSessionKindConfig - } - } - return quickChatSessionKindChat -} - -func quickChatAgentProfileID(task *taskmodels.Task, primary *taskmodels.TaskSession) string { - if task != nil { - if value, ok := task.Metadata[taskmodels.MetaKeyAgentProfileID].(string); ok { - return value - } - } - if primary != nil { - return primary.AgentProfileID - } - return "" -} - func (b bootStateBuilder) addKanbanSnapshotsState( ctx context.Context, state map[string]any, diff --git a/apps/backend/internal/task/handlers/quick_chat_list_handlers_test.go b/apps/backend/internal/task/handlers/quick_chat_list_handlers_test.go new file mode 100644 index 0000000000..d2f5df4ffb --- /dev/null +++ b/apps/backend/internal/task/handlers/quick_chat_list_handlers_test.go @@ -0,0 +1,134 @@ +package handlers + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/service" +) + +// quickChatListRepo serves one restorable quick chat plus rows the tab strip +// must ignore, so the endpoint's filtering and payload shape are pinned. +type quickChatListRepo struct { + mockRepository + tasks []*models.Task + sessions map[string]*models.TaskSession +} + +func (r *quickChatListRepo) ListTasksByWorkspace( + _ context.Context, _, _, _, _ string, _, _ int, _ string, _, _, _, _ bool, +) ([]*models.Task, int, error) { + return r.tasks, len(r.tasks), nil +} + +func (r *quickChatListRepo) GetPrimarySessionInfoByTaskIDs( + _ context.Context, _ []string, +) (map[string]*models.TaskSession, error) { + return r.sessions, nil +} + +// TestHTTPListQuickChatSessions pins the resync endpoint: it returns the +// workspace's restorable quick chats with their sessions attached, so a client +// that missed WS events converges on the server's tab list instead of drifting. +func TestHTTPListQuickChatSessions(t *testing.T) { + gin.SetMode(gin.TestMode) + log := newTestLogger(t) + repo := &quickChatListRepo{ + tasks: []*models.Task{ + { + ID: "task-chat", WorkspaceID: "ws-1", Title: "Renamed Chat", IsEphemeral: true, + Metadata: map[string]interface{}{models.MetaKeyAgentProfileID: "agent-1"}, + }, + // Workflow-bound ephemeral task: never a quick-chat tab. + {ID: "task-workflow", WorkspaceID: "ws-1", WorkflowID: "wf-1", IsEphemeral: true}, + }, + sessions: map[string]*models.TaskSession{ + "task-chat": {ID: "session-chat", TaskID: "task-chat"}, + "task-workflow": {ID: "session-workflow", TaskID: "task-workflow"}, + }, + } + 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 := &TaskHandlers{service: svc, logger: log} + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/workspaces/ws-1/quick-chats", nil) + c.Params = gin.Params{{Key: "id", Value: "ws-1"}} + + h.httpListQuickChatSessions(c) + + assert.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + var body httpListQuickChatSessionsResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + require.Len(t, body.Sessions, 1) + assert.Equal(t, httpQuickChatSession{ + SessionID: "session-chat", + TaskID: "task-chat", + WorkspaceID: "ws-1", + Kind: service.QuickChatKindChat, + Name: "Renamed Chat", + AgentProfileID: "agent-1", + }, body.Sessions[0]) + require.Len(t, body.TaskSessions, 1) + assert.Equal(t, "task-chat", body.TaskSessions[0].TaskID) +} + +// TestHTTPListQuickChatSessionsEmptyIsArray keeps the empty response an array +// rather than null: the client replaces its tab list with this payload, and a +// null would be read as "no data" and leave stale tabs in place. +func TestHTTPListQuickChatSessionsEmptyIsArray(t *testing.T) { + gin.SetMode(gin.TestMode) + log := newTestLogger(t) + repo := &quickChatListRepo{} + 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 := &TaskHandlers{service: svc, logger: log} + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/workspaces/ws-1/quick-chats", nil) + c.Params = gin.Params{{Key: "id", Value: "ws-1"}} + + h.httpListQuickChatSessions(c) + + assert.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `{"sessions":[],"task_sessions":[]}`, rec.Body.String()) +} + +// TestQuickChatRoutesAreRegistered proves the resync endpoint is reachable +// through the real router. Gin resolves routes by path segment, so the GET +// ".../quick-chats" collection must coexist with the POST ".../quick-chat" +// action rather than panicking or shadowing it at registration time. +func TestQuickChatRoutesAreRegistered(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + handlers := &TaskHandlers{logger: newTestLogger(t)} + handlers.registerHTTP(router) + + registered := make(map[string]bool) + for _, route := range router.Routes() { + registered[route.Method+" "+route.Path] = true + } + + assert.True(t, registered["GET /api/v1/workspaces/:id/quick-chats"], "resync route missing") + assert.True(t, registered["POST /api/v1/workspaces/:id/quick-chat"], "start route missing") +} diff --git a/apps/backend/internal/task/handlers/task_handlers.go b/apps/backend/internal/task/handlers/task_handlers.go index c44ff2b30c..5df4c6e8b0 100644 --- a/apps/backend/internal/task/handlers/task_handlers.go +++ b/apps/backend/internal/task/handlers/task_handlers.go @@ -150,8 +150,10 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) { // Session workflow review endpoints api.POST("/sessions/:id/approve", h.httpApproveSession) - // Quick chat endpoint - creates ephemeral task with prepared session + // Quick chat endpoints - create ephemeral task with prepared session, and + // resync the tab strip so clients that missed WS events converge. api.POST("/workspaces/:id/quick-chat", h.httpStartQuickChat) + api.GET("/workspaces/:id/quick-chats", h.httpListQuickChatSessions) // Config chat endpoint - creates ephemeral task with config-mode MCP tools api.POST("/workspaces/:id/config-chat", h.httpStartConfigChat) diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 28a4a9340a..f0ab42604a 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -1645,6 +1645,51 @@ func (h *TaskHandlers) httpStartQuickChat(c *gin.Context) { }) } +// httpQuickChatSession is one restorable quick-chat tab. +type httpQuickChatSession struct { + SessionID string `json:"session_id"` + TaskID string `json:"task_id"` + WorkspaceID string `json:"workspace_id"` + Kind string `json:"kind"` + Name string `json:"name,omitempty"` + AgentProfileID string `json:"agent_profile_id,omitempty"` +} + +// httpListQuickChatSessionsResponse mirrors the quick-chat slice of the boot +// payload so a running client can resync its tab strip without a full reload. +type httpListQuickChatSessionsResponse struct { + Sessions []httpQuickChatSession `json:"sessions"` + TaskSessions []dto.TaskSessionDTO `json:"task_sessions"` +} + +// httpListQuickChatSessions returns the workspace's restorable quick-chat tabs. +// Quick chats are created and closed from any device, so clients poll this on +// (re)connect to converge on the server's list instead of drifting apart. +func (h *TaskHandlers) httpListQuickChatSessions(c *gin.Context) { + workspaceID := c.Param("id") + items, err := h.service.ListQuickChatSessions(c.Request.Context(), workspaceID) + if err != nil { + handleNotFound(c, h.logger, err, "workspace not found") + return + } + response := httpListQuickChatSessionsResponse{ + Sessions: make([]httpQuickChatSession, 0, len(items)), + TaskSessions: make([]dto.TaskSessionDTO, 0, len(items)), + } + for _, item := range items { + response.Sessions = append(response.Sessions, httpQuickChatSession{ + SessionID: item.SessionID, + TaskID: item.TaskID, + WorkspaceID: item.WorkspaceID, + Kind: item.Kind, + Name: item.Name, + AgentProfileID: item.AgentProfileID, + }) + response.TaskSessions = append(response.TaskSessions, dto.FromTaskSession(item.Session)) + } + c.JSON(http.StatusOK, response) +} + // httpStartConfigChatRequest is the request body for starting a config chat session. type httpStartConfigChatRequest struct { AgentProfileID string `json:"agent_profile_id,omitempty"` diff --git a/apps/backend/internal/task/service/quick_chat_sessions.go b/apps/backend/internal/task/service/quick_chat_sessions.go new file mode 100644 index 0000000000..28e937c1b6 --- /dev/null +++ b/apps/backend/internal/task/service/quick_chat_sessions.go @@ -0,0 +1,160 @@ +package service + +import ( + "context" + "sort" + "time" + + "github.com/kandev/kandev/internal/task/models" +) + +// Quick-chat tab kinds. A workspace config chat is a quick chat whose task +// carries the config_mode metadata flag; everything else is a regular chat. +const ( + QuickChatKindChat = "chat" + QuickChatKindConfig = "config" + + // quickChatDefaultTitle is the placeholder title used when a quick chat is + // started without a name. It is not surfaced as a tab label. + quickChatDefaultTitle = "Quick Chat" + + quickChatListPageSize = 1000 +) + +// QuickChatSession is one restorable quick-chat tab: the ephemeral task's +// primary session plus the metadata the UI needs to render its tab. +type QuickChatSession struct { + SessionID string + TaskID string + WorkspaceID string + Kind string + Name string + AgentProfileID string + Session *models.TaskSession + + createdAt time.Time + lastActivityAt time.Time +} + +// ListQuickChatSessions returns the workspace's restorable quick-chat sessions, +// most recently active first. It is the single source of truth for the quick +// chat tab strip: the boot payload and the runtime resync endpoint both read it, +// so a client that reloads and a client that resyncs converge on the same list. +func (s *Service) ListQuickChatSessions(ctx context.Context, workspaceID string) ([]QuickChatSession, error) { + tasks, err := s.listQuickChatTasks(ctx, workspaceID) + if err != nil { + return nil, err + } + if len(tasks) == 0 { + return []QuickChatSession{}, nil + } + ids := make([]string, 0, len(tasks)) + for _, task := range tasks { + if task != nil { + ids = append(ids, task.ID) + } + } + primaryByTask, err := s.GetPrimarySessionInfoForTasks(ctx, ids) + if err != nil { + return nil, err + } + + items := make([]QuickChatSession, 0, len(tasks)) + for _, task := range tasks { + if !IsRestorableQuickChatTask(task) { + continue + } + primary := primaryByTask[task.ID] + if primary == nil || primary.ID == "" { + continue + } + items = append(items, newQuickChatSession(task, primary)) + } + sortQuickChatSessions(items) + return items, nil +} + +func newQuickChatSession(task *models.Task, primary *models.TaskSession) QuickChatSession { + item := QuickChatSession{ + SessionID: primary.ID, + TaskID: task.ID, + WorkspaceID: task.WorkspaceID, + Kind: quickChatSessionKind(task), + AgentProfileID: quickChatAgentProfileID(task, primary), + Session: primary, + createdAt: task.CreatedAt, + lastActivityAt: quickChatLastActivityAt(task, primary), + } + if task.Title != "" && task.Title != quickChatDefaultTitle { + item.Name = task.Title + } + return item +} + +// sortQuickChatSessions orders tabs by most recent activity, falling back to +// creation order and then task ID so the sequence is stable across clients. +func sortQuickChatSessions(items []QuickChatSession) { + sort.SliceStable(items, func(i, j int) bool { + if !items[i].lastActivityAt.Equal(items[j].lastActivityAt) { + return items[i].lastActivityAt.After(items[j].lastActivityAt) + } + if !items[i].createdAt.Equal(items[j].createdAt) { + return items[i].createdAt.Before(items[j].createdAt) + } + return items[i].TaskID < items[j].TaskID + }) +} + +func (s *Service) listQuickChatTasks(ctx context.Context, workspaceID string) ([]*models.Task, error) { + var all []*models.Task + for page := 1; ; page++ { + tasks, total, err := s.ListTasksByWorkspace( + ctx, workspaceID, "", "", "", page, quickChatListPageSize, "", false, false, true, false, + ) + if err != nil { + return nil, err + } + all = append(all, tasks...) + if len(tasks) == 0 || len(all) >= total { + return all, nil + } + } +} + +// IsRestorableQuickChatTask reports whether a task backs a quick-chat tab. +// Workflow-bound and automation-run tasks are ephemeral for other reasons and +// must never surface in the tab strip. +func IsRestorableQuickChatTask(task *models.Task) bool { + return task != nil && + task.IsEphemeral && + task.WorkflowID == "" && + task.Origin != models.TaskOriginAutomationRun +} + +func quickChatLastActivityAt(task *models.Task, primary *models.TaskSession) time.Time { + if primary.UpdatedAt.After(task.UpdatedAt) { + return primary.UpdatedAt + } + return task.UpdatedAt +} + +func quickChatSessionKind(task *models.Task) string { + if task != nil { + if configMode, ok := task.Metadata["config_mode"].(bool); ok && configMode { + return QuickChatKindConfig + } + } + return QuickChatKindChat +} + +func quickChatAgentProfileID(task *models.Task, primary *models.TaskSession) string { + if task != nil { + if value, ok := task.Metadata[models.MetaKeyAgentProfileID].(string); ok { + return value + } + } + if primary != nil { + return primary.AgentProfileID + } + return "" +} diff --git a/apps/backend/internal/task/service/quick_chat_sessions_test.go b/apps/backend/internal/task/service/quick_chat_sessions_test.go new file mode 100644 index 0000000000..ad4f3147ab --- /dev/null +++ b/apps/backend/internal/task/service/quick_chat_sessions_test.go @@ -0,0 +1,260 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/task/models" + v1 "github.com/kandev/kandev/pkg/api/v1" +) + +type quickChatFixture struct { + id string + workspaceID string + workflowID string + title string + agentProfileID string + origin string + metadata map[string]interface{} + updatedAt time.Time + withoutPrimary bool +} + +func seedQuickChatTask(t *testing.T, svc *Service, sqlxDB *sqlx.DB, fixture quickChatFixture) { + t.Helper() + ctx := context.Background() + workspaceID := fixture.workspaceID + if workspaceID == "" { + workspaceID = "ws-qc" + } + metadata := map[string]interface{}{} + if fixture.agentProfileID != "" { + metadata[models.MetaKeyAgentProfileID] = fixture.agentProfileID + } + for key, value := range fixture.metadata { + metadata[key] = value + } + if err := svc.tasks.CreateTask(ctx, &models.Task{ + ID: fixture.id, + WorkspaceID: workspaceID, + WorkflowID: fixture.workflowID, + Title: fixture.title, + State: v1.TaskStateTODO, + Priority: "medium", + IsEphemeral: true, + Origin: fixture.origin, + Metadata: metadata, + }); err != nil { + t.Fatalf("CreateTask(%s): %v", fixture.id, err) + } + // CreateTask stamps its own timestamps; backdate so ordering is deterministic. + if _, err := sqlxDB.ExecContext(ctx, + `UPDATE tasks SET created_at = ?, updated_at = ? WHERE id = ?`, + fixture.updatedAt.Add(-time.Hour), fixture.updatedAt, fixture.id, + ); err != nil { + t.Fatalf("backdate task(%s): %v", fixture.id, err) + } + if fixture.withoutPrimary { + return + } + if err := svc.sessions.CreateTaskSession(ctx, &models.TaskSession{ + ID: fixture.id + "-session", + TaskID: fixture.id, + AgentProfileID: fixture.agentProfileID, + State: models.TaskSessionStateCompleted, + StartedAt: fixture.updatedAt.Add(-time.Hour), + UpdatedAt: fixture.updatedAt, + IsPrimary: true, + }); err != nil { + t.Fatalf("CreateTaskSession(%s): %v", fixture.id, err) + } +} + +// TestListQuickChatSessionsIsWorkspaceScopedAndOrdered pins the contract the +// boot payload and the resync endpoint share: only restorable quick chats for +// the requested workspace, newest activity first. Both clients read this list, +// so any divergence here shows up as different tabs on different devices. +func TestListQuickChatSessionsIsWorkspaceScopedAndOrdered(t *testing.T) { + svc, sqlxDB := createOfficeIntegrationServiceWithDB(t) + ctx := context.Background() + + for _, ws := range []string{"ws-qc", "ws-other"} { + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: ws, Name: ws}); err != nil { + t.Fatalf("CreateWorkspace(%s): %v", ws, err) + } + } + if err := svc.workflows.CreateWorkflow(ctx, &models.Workflow{ + ID: "wf-qc", WorkspaceID: "ws-qc", Name: "Workflow", + }); err != nil { + t.Fatalf("CreateWorkflow: %v", err) + } + + base := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC) + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-old", title: "Older Chat", agentProfileID: "agent-old", + updatedAt: base.Add(-3 * time.Hour), + }) + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-new", title: "Newer Chat", agentProfileID: "agent-new", + updatedAt: base.Add(-time.Hour), + }) + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-config", title: "Config", agentProfileID: "agent-config", + metadata: map[string]interface{}{"config_mode": true}, updatedAt: base, + }) + // Placeholder title is not a tab label. + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-unnamed", title: quickChatDefaultTitle, agentProfileID: "agent-unnamed", + updatedAt: base.Add(-4 * time.Hour), + }) + // Excluded: no primary session, other workspace, automation run, workflow-bound. + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-no-primary", title: "No Primary", updatedAt: base, withoutPrimary: true, + }) + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-foreign", workspaceID: "ws-other", title: "Foreign", updatedAt: base, + }) + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-automation", title: "Automation", updatedAt: base, + origin: models.TaskOriginAutomationRun, + }) + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-workflow", title: "Workflow Ephemeral", updatedAt: base, workflowID: "wf-qc", + }) + + items, err := svc.ListQuickChatSessions(ctx, "ws-qc") + if err != nil { + t.Fatalf("ListQuickChatSessions: %v", err) + } + + gotIDs := make([]string, 0, len(items)) + for _, item := range items { + gotIDs = append(gotIDs, item.SessionID) + } + wantIDs := []string{ + "task-config-session", "task-new-session", "task-old-session", "task-unnamed-session", + } + if len(gotIDs) != len(wantIDs) { + t.Fatalf("session ids = %v, want %v", gotIDs, wantIDs) + } + for i, want := range wantIDs { + if gotIDs[i] != want { + t.Fatalf("session ids = %v, want %v", gotIDs, wantIDs) + } + } + if items[0].Kind != QuickChatKindConfig || items[1].Kind != QuickChatKindChat { + t.Fatalf("kinds = %q/%q, want config/chat", items[0].Kind, items[1].Kind) + } + if items[0].Name != "Config" || items[0].AgentProfileID != "agent-config" { + t.Fatalf("config tab = %#v, want title and agent profile preserved", items[0]) + } + if items[3].Name != "" { + t.Fatalf("placeholder-titled tab name = %q, want empty", items[3].Name) + } + if items[0].WorkspaceID != "ws-qc" || items[0].Session == nil { + t.Fatalf("tab payload = %#v, want workspace and session attached", items[0]) + } +} + +// TestListQuickChatSessionsEmptyWorkspace guards the empty case: a client that +// resyncs into a workspace with no quick chats must get an empty list (which +// clears its stale tabs), not an error it would silently ignore. +func TestListQuickChatSessionsEmptyWorkspace(t *testing.T) { + svc := createOfficeIntegrationService(t) + ctx := context.Background() + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: "ws-empty", Name: "Empty"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + items, err := svc.ListQuickChatSessions(ctx, "ws-empty") + if err != nil { + t.Fatalf("ListQuickChatSessions: %v", err) + } + if len(items) != 0 { + t.Fatalf("items = %#v, want empty", items) + } +} + +func TestIsRestorableQuickChatTask(t *testing.T) { + tests := []struct { + name string + task *models.Task + want bool + }{ + {name: "nil", task: nil, want: false}, + {name: "ephemeral chat", task: &models.Task{IsEphemeral: true}, want: true}, + {name: "not ephemeral", task: &models.Task{}, want: false}, + {name: "workflow bound", task: &models.Task{IsEphemeral: true, WorkflowID: "wf"}, want: false}, + { + name: "automation run", + task: &models.Task{IsEphemeral: true, Origin: models.TaskOriginAutomationRun}, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsRestorableQuickChatTask(tt.task); got != tt.want { + t.Fatalf("IsRestorableQuickChatTask() = %v, want %v", got, tt.want) + } + }) + } +} + +// TestQuickChatRenamePublishesTabFields pins the cross-device rename contract: +// updating a quick chat's title must publish a task.updated carrying everything +// a client needs to re-label its tab. Clients restore quick-chat tabs from this +// payload, so dropping any of these fields silently strands renames (and new +// chats) on the device that made them. +func TestQuickChatRenamePublishesTabFields(t *testing.T) { + svc, sqlxDB := createOfficeIntegrationServiceWithDB(t) + ctx := context.Background() + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: "ws-qc", Name: "ws-qc"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + seedQuickChatTask(t, svc, sqlxDB, quickChatFixture{ + id: "task-chat", title: "Claude - Chat 1", agentProfileID: "agent-1", + updatedAt: time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC), + }) + eventBus, ok := svc.eventBus.(*MockEventBus) + if !ok { + t.Fatalf("event bus = %T, want *MockEventBus", svc.eventBus) + } + eventBus.ClearEvents() + + renamed := "My renamed chat" + if _, err := svc.UpdateTask(ctx, "task-chat", &UpdateTaskRequest{Title: &renamed}); err != nil { + t.Fatalf("UpdateTask: %v", err) + } + + var updated map[string]interface{} + for _, event := range eventBus.GetPublishedEvents() { + data, dataOK := event.Data.(map[string]interface{}) + if !dataOK || data["task_id"] != "task-chat" { + continue + } + if event.Type == events.TaskUpdated { + updated = data + } + } + if updated == nil { + t.Fatalf("no task.updated published; events = %#v", eventBus.GetPublishedEvents()) + } + if updated["title"] != renamed { + t.Fatalf("title = %v, want %q", updated["title"], renamed) + } + if updated["is_ephemeral"] != true { + t.Fatalf("is_ephemeral = %v, want true", updated["is_ephemeral"]) + } + if updated["workspace_id"] != "ws-qc" { + t.Fatalf("workspace_id = %v, want ws-qc", updated["workspace_id"]) + } + if updated["primary_session_id"] != "task-chat-session" { + t.Fatalf("primary_session_id = %v, want task-chat-session", updated["primary_session_id"]) + } + if _, has := updated["origin"]; !has { + t.Fatalf("origin missing; restorable-quick-chat filtering needs it") + } +} diff --git a/apps/backend/internal/task/service/service_events.go b/apps/backend/internal/task/service/service_events.go index 8b554fcb5f..8972f31c8f 100644 --- a/apps/backend/internal/task/service/service_events.go +++ b/apps/backend/internal/task/service/service_events.go @@ -361,6 +361,9 @@ func (s *Service) publishTaskEventNow(ctx context.Context, eventType string, tas "created_at": task.CreatedAt.Format(time.RFC3339), "updated_at": task.UpdatedAt.Format(time.RFC3339), "is_ephemeral": task.IsEphemeral, + // Consumers that restore quick-chat tabs filter on origin, so it has to + // travel with the event and not just the HTTP DTO. + "origin": task.Origin, } data["queued_for_step_id"] = task.QueuedForStepID if task.QueuedAt != nil { diff --git a/apps/backend/internal/task/service/service_office_integration_test.go b/apps/backend/internal/task/service/service_office_integration_test.go index 1db0f88405..347e6d2ee6 100644 --- a/apps/backend/internal/task/service/service_office_integration_test.go +++ b/apps/backend/internal/task/service/service_office_integration_test.go @@ -21,6 +21,15 @@ import ( // and toggles foreign_keys=ON, so any code path that lands a row through // the task service is exercised against the real schema. func createOfficeIntegrationService(t *testing.T) *Service { + t.Helper() + svc, _ := createOfficeIntegrationServiceWithDB(t) + return svc +} + +// createOfficeIntegrationServiceWithDB is createOfficeIntegrationService for +// tests that also need raw DB access (e.g. to backdate timestamps that the +// service stamps itself). +func createOfficeIntegrationServiceWithDB(t *testing.T) (*Service, *sqlx.DB) { t.Helper() tmpDir := t.TempDir() dbConn, err := db.OpenSQLite(filepath.Join(tmpDir, "test.db")) @@ -45,7 +54,7 @@ func createOfficeIntegrationService(t *testing.T) *Service { log, _ := logger.NewLogger(logger.LoggingConfig{ Level: "error", Format: "json", OutputPath: "stdout", }) - return NewService(Repos{ + svc := NewService(Repos{ Workspaces: repo, Tasks: repo, TaskRepos: repo, @@ -60,6 +69,7 @@ func createOfficeIntegrationService(t *testing.T) *Service { TaskEnvironments: repo, Reviews: repo, }, NewMockEventBus(), log, RepositoryDiscoveryConfig{}) + return svc, sqlxDB } // TestIntegration_CreateTask_OnboardingShape pins the regression that diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index d5459ae356..07cbe55b10 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -10,6 +10,7 @@ import { listQuickChatSessions, } from "@/lib/api"; import { listWorkspaceTaskPRs } from "@/lib/api/domains/github-api"; +import { toQuickChatSessions } from "@/lib/quick-chat/map-sessions"; import { snapshotToState } from "@/lib/ssr/mapper"; import { mapUserSettingsResponse } from "@/lib/ssr/user-settings"; import { resolveDesiredWorkflowId } from "@/lib/kanban/resolve-workflow"; @@ -52,36 +53,6 @@ function buildUserSettingsState( return { ...mapUserSettingsResponse(resp), workspaceId }; } -function readAgentProfileId( - metadata: Record | null | undefined, -): string | undefined { - if (!metadata || typeof metadata !== "object") return undefined; - const value = metadata.agent_profile_id; - return typeof value === "string" ? value : undefined; -} - -type QuickChatTask = Awaited>["tasks"][number]; - -function mapQuickChatSessions(tasks: QuickChatTask[]): AppState["quickChat"]["sessions"] { - const quickChatUpdatedAt = (task: QuickChatTask) => Date.parse(task.updated_at ?? "") || 0; - - return ( - tasks - .filter((task) => task.primary_session_id) - .filter((task) => task.origin !== "automation_run") - // Legacy Next.js path only receives task.updated_at. The Go boot payload - // sorts by max(task/session updated_at) and is the authoritative SPA path. - .sort((a, b) => quickChatUpdatedAt(b) - quickChatUpdatedAt(a)) - .map((task) => ({ - kind: "chat" as const, - sessionId: task.primary_session_id!, - workspaceId: task.workspace_id, - name: task.title !== "Quick Chat" ? task.title : undefined, - agentProfileId: readAgentProfileId(task.metadata), - })) - ); -} - function buildBaseState( workspaces: ListWorkspacesResponse, userSettingsResponse: UserSettingsResponse | null, @@ -159,7 +130,10 @@ async function loadWorkspaceState({ listRepositories(activeWorkspaceId, undefined, { cache: "no-store" }).catch(() => ({ repositories: [], })), - listQuickChatSessions(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ tasks: [] })), + listQuickChatSessions(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ + sessions: [], + task_sessions: [], + })), ]); // null preserves the user's explicit "All Workflows" choice. const workflowId = resolveDesiredWorkflowId({ @@ -167,7 +141,7 @@ async function loadWorkspaceState({ settingsWorkflowId, workspaceWorkflows: workflowList.workflows, }); - const quickChatSessions = mapQuickChatSessions(quickChatResponse.tasks); + const quickChatSessions = toQuickChatSessions(quickChatResponse.sessions); return { workflowId, diff --git a/apps/web/components/config-chat/use-config-chat.test.ts b/apps/web/components/config-chat/use-config-chat.test.ts index 67f0a7db2b..c816aef844 100644 --- a/apps/web/components/config-chat/use-config-chat.test.ts +++ b/apps/web/components/config-chat/use-config-chat.test.ts @@ -89,6 +89,7 @@ describe("useConfigChat unified launch", () => { WORKSPACE_ID, CONFIG_PROFILE_ID, "config", + TASK_ID, ); expect(renameQuickChatSession).toHaveBeenCalledWith(SESSION_ID, PROMPT); expect(setQuickChatInitialPrompt).toHaveBeenCalledWith(SESSION_ID, PROMPT); @@ -106,6 +107,7 @@ describe("useConfigChat unified launch", () => { WORKSPACE_ID, CONFIG_PROFILE_ID, "config", + TASK_ID, ); expect(openQuickChat).not.toHaveBeenCalled(); expect(setQuickChatInitialPrompt).toHaveBeenCalledWith(SESSION_ID, PROMPT); diff --git a/apps/web/components/config-chat/use-config-chat.ts b/apps/web/components/config-chat/use-config-chat.ts index 17c365680a..96e03de11a 100644 --- a/apps/web/components/config-chat/use-config-chat.ts +++ b/apps/web/components/config-chat/use-config-chat.ts @@ -6,6 +6,7 @@ import { useAppStore, useAppStoreApi } from "@/components/state-provider"; import { updateWorkspaceAction } from "@/app/actions/workspaces"; import { startConfigChat } from "@/lib/api/domains/workspace-api"; import { getQuickChatSetupSessionId } from "@/lib/state/slices/ui/quick-chat-session"; +import { persistQuickChatRename } from "@/lib/quick-chat/rename"; import { agentProfileId as toAgentProfileId, sessionId as toSessionId, @@ -84,11 +85,30 @@ function registerStartedSession({ }); if (openInQuickChat) { store.closeQuickChatSession(getQuickChatSetupSessionId(workspaceId, "config")); - store.openQuickChat(response.session_id, workspaceId, agentProfileId, "config"); + store.openQuickChat( + response.session_id, + workspaceId, + agentProfileId, + "config", + response.task_id, + ); } else { - store.addQuickChatSession(response.session_id, workspaceId, agentProfileId, "config"); + store.addQuickChatSession( + response.session_id, + workspaceId, + agentProfileId, + "config", + response.task_id, + ); } - store.renameQuickChatSession(response.session_id, prompt.slice(0, 40) || "Config Chat"); + // The config-chat endpoint has no title field, so name the tab from the + // opening prompt and save it to the task — otherwise the label would live + // only in this browser and be lost on the next resync. + const derivedName = prompt.slice(0, 40) || "Config Chat"; + store.renameQuickChatSession(response.session_id, derivedName); + void persistQuickChatRename(response.session_id, response.task_id, derivedName).catch( + () => undefined, + ); if (!isPassthrough) store.setQuickChatInitialPrompt(response.session_id, prompt); } diff --git a/apps/web/components/quick-chat/quick-chat-dialog.tsx b/apps/web/components/quick-chat/quick-chat-dialog.tsx index d7cd1b0071..1751a75956 100644 --- a/apps/web/components/quick-chat/quick-chat-dialog.tsx +++ b/apps/web/components/quick-chat/quick-chat-dialog.tsx @@ -102,7 +102,7 @@ export const QuickChatPickerDialog = memo(function QuickChatPickerDialog({ }); onOpenChange(false); // Open the quick chat modal with the new session - openQuickChat(response.session_id, workspaceId); + openQuickChat(response.session_id, workspaceId, undefined, "chat", response.task_id); } catch (error) { toast({ title: "Failed to start quick chat", diff --git a/apps/web/components/quick-chat/quick-chat-modal.test.ts b/apps/web/components/quick-chat/quick-chat-modal.test.ts index c03cfbc497..04947ab26c 100644 --- a/apps/web/components/quick-chat/quick-chat-modal.test.ts +++ b/apps/web/components/quick-chat/quick-chat-modal.test.ts @@ -86,7 +86,7 @@ describe("Quick Chat workspace isolation", () => { }); }); -describe("renameQuickChatSession local persistence", () => { +describe("renameQuickChatSession", () => { beforeEach(() => { window.localStorage.clear(); }); @@ -98,18 +98,21 @@ describe("renameQuickChatSession local persistence", () => { expect(findSession(store)?.name).toBe("My renamed chat"); }); - it("persists the rename to localStorage so it survives reload", () => { + // The name now lives on the backing task title (see persistQuickChatRename). + // Writing it to localStorage here too would let a stale local entry override + // a rename made on another device — the divergence this whole flow fixes. + it("does not pin the name in localStorage", () => { const store = makeStore(); store.getState().openQuickChat(SESSION_ID, WORKSPACE_ID); store.getState().renameQuickChatSession(SESSION_ID, "Persisted name"); - expect(getStoredQuickChatNames()).toEqual({ [SESSION_ID]: "Persisted name" }); + expect(getStoredQuickChatNames()).toEqual({}); }); - it("does not write to storage when the session does not exist in state", () => { + it("ignores a session that does not exist in state", () => { const store = makeStore(); expect(() => store.getState().renameQuickChatSession("ghost-session", "Whatever"), ).not.toThrow(); - expect(getStoredQuickChatNames()).toEqual({}); + expect(findSession(store)).toBeUndefined(); }); }); diff --git a/apps/web/components/quick-chat/quick-chat-provider.tsx b/apps/web/components/quick-chat/quick-chat-provider.tsx index 5fd9583e84..59cb2f6c9d 100644 --- a/apps/web/components/quick-chat/quick-chat-provider.tsx +++ b/apps/web/components/quick-chat/quick-chat-provider.tsx @@ -3,6 +3,7 @@ import { useSyncExternalStore } from "react"; import { useAppStore } from "@/components/state-provider"; import { useSettingsData } from "@/hooks/domains/settings/use-settings-data"; +import { useQuickChatResync } from "@/hooks/use-quick-chat-resync"; import { QuickChatModal } from "./quick-chat-modal"; // SSR-safe client mount detection without useEffect setState @@ -41,6 +42,9 @@ export function QuickChatProvider({ children }: { children: React.ReactNode }) { // Preload agent profiles so they're available when quick chat is opened useSettingsData(true); + // Quick chats are shared across devices: re-read the server's list whenever + // the socket connects so tabs opened or closed elsewhere show up here too. + useQuickChatResync(activeWorkspace); const workspaceId = getWorkspaceId(quickChatSessions, isOpen, activeSessionId, activeWorkspace); diff --git a/apps/web/components/quick-chat/quick-chat-session-view.tsx b/apps/web/components/quick-chat/quick-chat-session-view.tsx index 40780b6cee..8e14b81d71 100644 --- a/apps/web/components/quick-chat/quick-chat-session-view.tsx +++ b/apps/web/components/quick-chat/quick-chat-session-view.tsx @@ -1,6 +1,7 @@ "use client"; import { useAppStore } from "@/components/state-provider"; +import { useEnsureTaskSession } from "@/hooks/use-ensure-task-session"; import { PassthroughTerminal } from "@/components/task/passthrough-terminal"; import type { QuickChatSession } from "@/lib/state/slices/ui/types"; import { QuickChatContent } from "./quick-chat-content"; @@ -23,6 +24,9 @@ type QuickChatSessionViewProps = { }; export function QuickChatSessionView({ session, onInitialPromptSent }: QuickChatSessionViewProps) { + // A tab can arrive from a task event, which carries no session payload. + // Fetch the row on open so such a tab is usable, not just visible. + useEnsureTaskSession(session.sessionId); const isPassthrough = useIsQuickChatPassthrough(session.sessionId); if (isPassthrough) { return ( diff --git a/apps/web/components/quick-chat/use-quick-chat-modal.test.ts b/apps/web/components/quick-chat/use-quick-chat-modal.test.ts index 213e279ce3..9ee1a9c9a9 100644 --- a/apps/web/components/quick-chat/use-quick-chat-modal.test.ts +++ b/apps/web/components/quick-chat/use-quick-chat-modal.test.ts @@ -5,6 +5,7 @@ import { renderHook, act } from "@testing-library/react"; const mockToast = vi.fn(); const mockStartQuickChat = vi.fn(); const mockDeleteTask = vi.fn(); +const mockUpdateTask = vi.fn(); let mockAppState: ReturnType; vi.mock("@/components/state-provider", () => ({ @@ -22,6 +23,7 @@ vi.mock("@/lib/api/domains/workspace-api", () => ({ vi.mock("@/lib/api/domains/kanban-api", () => ({ deleteTask: (...args: unknown[]) => mockDeleteTask(...args), + updateTask: (...args: unknown[]) => mockUpdateTask(...args), })); import { useAgentSelection, useQuickChatModal } from "./use-quick-chat-modal"; @@ -40,6 +42,7 @@ function makeAppState() { sessionId: string; workspaceId: string; kind: "chat" | "config"; + taskId?: string; }>, activeSessionId: "", }, @@ -197,7 +200,14 @@ describe("useAgentSelection — happy path", () => { await result.current.handleSelectAgent("agent-a"); }); - expect(store.openQuickChat).toHaveBeenCalledWith("sess-a", WORKSPACE_ID, "agent-a"); + // taskId is threaded through so closing the tab can delete the right task. + expect(store.openQuickChat).toHaveBeenCalledWith( + "sess-a", + WORKSPACE_ID, + "agent-a", + "chat", + "task-a", + ); expect(store.renameQuickChatSession).toHaveBeenCalledWith("sess-a", expect.any(String)); expect(mockDeleteTask).not.toHaveBeenCalled(); expect(result.current.pendingAgentId).toBeNull(); @@ -270,7 +280,13 @@ describe("useAgentSelection — supersession", () => { await act(async () => { await result.current.handleSelectAgent("agent-b"); }); - expect(store.openQuickChat).toHaveBeenCalledWith("sess-b", WORKSPACE_ID, "agent-b"); + expect(store.openQuickChat).toHaveBeenCalledWith( + "sess-b", + WORKSPACE_ID, + "agent-b", + "chat", + "task-b", + ); // Now A resolves — its orphan task is deleted instead of opening a stale session. await act(async () => { @@ -364,3 +380,59 @@ describe("useAgentSelection — error handling", () => { expect(result.current.pendingAgentId).toBeNull(); }); }); + +describe("useQuickChatModal — renaming", () => { + it("saves the new name to the backing task so other devices pick it up", async () => { + mockUpdateTask.mockResolvedValue(undefined); + mockAppState.quickChat.sessions = [ + { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat", taskId: "task-1" }, + ]; + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + await act(async () => { + result.current.handleRename("session-1", "Renamed"); + await flushPromises(); + }); + + expect(mockAppState.renameQuickChatSession).toHaveBeenCalledWith("session-1", "Renamed"); + expect(mockUpdateTask).toHaveBeenCalledWith("task-1", { title: "Renamed" }); + expect(mockToast).not.toHaveBeenCalled(); + }); + + // The close path resolves the task via taskSessions when the tab itself has + // no taskId; rename must agree, or it silently downgrades to a local-only + // rename for exactly those sessions — and without a toast, since that branch + // resolves rather than rejects. + it("falls back to taskSessions for a tab that carries no taskId", async () => { + mockUpdateTask.mockResolvedValue(undefined); + mockAppState.quickChat.sessions = [ + { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat" }, + ]; + mockAppState.taskSessions.items = { "session-1": { task_id: "task-legacy" } }; + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + await act(async () => { + result.current.handleRename("session-1", "Renamed"); + await flushPromises(); + }); + + expect(mockUpdateTask).toHaveBeenCalledWith("task-legacy", { title: "Renamed" }); + }); + + it("warns that the rename did not sync when the request fails", async () => { + mockUpdateTask.mockRejectedValue(new Error("offline")); + mockAppState.quickChat.sessions = [ + { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat", taskId: "task-1" }, + ]; + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + await act(async () => { + result.current.handleRename("session-1", "Renamed"); + await flushPromises(); + }); + + // The label still changed locally — only the sync failed. + expect(mockAppState.renameQuickChatSession).toHaveBeenCalledWith("session-1", "Renamed"); + expect(mockToast).toHaveBeenCalledWith(expect.objectContaining({ variant: "error" })); + }); +}); diff --git a/apps/web/components/quick-chat/use-quick-chat-modal.ts b/apps/web/components/quick-chat/use-quick-chat-modal.ts index 41551cb6d2..c61d291a96 100644 --- a/apps/web/components/quick-chat/use-quick-chat-modal.ts +++ b/apps/web/components/quick-chat/use-quick-chat-modal.ts @@ -6,6 +6,7 @@ import { useAppStore } from "@/components/state-provider"; import { useToast } from "@/components/toast-provider"; import { startQuickChat, type QuickChatRepositoryInput } from "@/lib/api/domains/workspace-api"; import { isQuickChatSetupSessionId } from "@/lib/state/slices/ui/quick-chat-session"; +import { persistQuickChatRename } from "@/lib/quick-chat/rename"; import type { QuickChatSessionKind } from "@/lib/state/slices/ui/types"; const noop = () => {}; @@ -41,6 +42,20 @@ function useQuickChatStore(workspaceId: string) { type QuickChatStore = ReturnType; +/** + * Resolves a tab's backing task. The tab carries `taskId` on every path that + * introduces it, but sessions restored by older clients only exist in + * `taskSessions`. Both the rename and the close flow must agree here: a missed + * task id silently downgrades a rename to device-local and skips the backend + * delete, leaving an orphaned ephemeral task. + */ +function resolveTaskId(store: QuickChatStore, sessionId: string): string | undefined { + return ( + store.sessions.find((session) => session.sessionId === sessionId)?.taskId ?? + store.taskSessions[sessionId]?.task_id + ); +} + function useWorkspaceQuickChat(store: QuickChatStore) { const sessions = store.sessions; const activeSession = sessions.find((session) => session.sessionId === store.activeSessionId); @@ -116,7 +131,7 @@ export function useAgentSelection(workspaceId: string, store: QuickChatStore) { if (setupSessionId && isQuickChatSetupSessionId(setupSessionId)) { store.closeQuickChatSession(setupSessionId); } - store.openQuickChat(result.sessionId, workspaceId, agentId); + store.openQuickChat(result.sessionId, workspaceId, agentId, "chat", result.taskId); store.renameQuickChatSession(result.sessionId, result.name); } catch (error) { if (latestRequestId.current !== requestId) return; @@ -155,7 +170,7 @@ function useQuickChatSessionClose(store: QuickChatStore, resetPendingStarts: () if (!sessionToClose) return; const sessionId = sessionToClose; setSessionToClose(null); - const taskId = store.taskSessions[sessionId]?.task_id; + const taskId = resolveTaskId(store, sessionId); if (!taskId) { store.closeQuickChatSession(sessionId); return; @@ -176,6 +191,7 @@ function useQuickChatSessionClose(store: QuickChatStore, resetPendingStarts: () } export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = noop) { + const { toast } = useToast(); const store = useQuickChatStore(workspaceId); const { sessions, activeSession } = useWorkspaceQuickChat(store); const [setupKey, setSetupKey] = useState(0); @@ -241,9 +257,18 @@ export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = const handleRename = useCallback( (sessionId: string, name: string) => { if (!sessionId) return; + // Show the new label immediately, then save it to the backing task so + // the user's other devices pick it up over the task.updated event. store.renameQuickChatSession(sessionId, name); + persistQuickChatRename(sessionId, resolveTaskId(store, sessionId), name).catch(() => { + toast({ + title: "Rename saved on this device only", + description: "We could not sync the new name to your other devices.", + variant: "error", + }); + }); }, - [store], + [store, toast], ); return { diff --git a/apps/web/e2e/helpers/pr-asset-capture.test.ts b/apps/web/e2e/helpers/pr-asset-capture.test.ts new file mode 100644 index 0000000000..4f385bf6e0 --- /dev/null +++ b/apps/web/e2e/helpers/pr-asset-capture.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { Page } from "@playwright/test"; +import { PrAssetCapture } from "./pr-asset-capture"; + +function fakePage(): Page { + return { screenshot: vi.fn().mockResolvedValue(undefined) } as unknown as Page; +} + +let outputDir: string; + +beforeEach(() => { + process.env.CAPTURE_PR_ASSETS = "1"; + outputDir = fs.mkdtempSync(path.join(os.tmpdir(), "pr-assets-")); +}); + +afterEach(() => { + delete process.env.CAPTURE_PR_ASSETS; + fs.rmSync(outputDir, { recursive: true, force: true }); +}); + +describe("PrAssetCapture.screenshot", () => { + it("shoots the constructor page by default", async () => { + const primary = fakePage(); + const capture = new PrAssetCapture(primary, "cross-device.spec.ts", { outputDir }); + + await capture.screenshot("desktop"); + + expect(primary.screenshot).toHaveBeenCalledTimes(1); + }); + + // A cross-device spec drives two clients from one capture instance: a second + // instance cannot work, because flush() clears the spec's existing manifest + // entries and the last flush would drop the first screenshot. + it("shoots the page override so one instance can capture several clients", async () => { + const primary = fakePage(); + const secondary = fakePage(); + const capture = new PrAssetCapture(primary, "cross-device.spec.ts", { outputDir }); + + await capture.screenshot("desktop"); + await capture.screenshot("mobile", { page: secondary }); + capture.flush(); + + expect(primary.screenshot).toHaveBeenCalledTimes(1); + expect(secondary.screenshot).toHaveBeenCalledTimes(1); + const manifest = JSON.parse(fs.readFileSync(path.join(outputDir, "manifest.json"), "utf-8")); + expect(manifest.assets.map((asset: { name: string }) => asset.name)).toEqual([ + "desktop", + "mobile", + ]); + }); + + it("captures nothing when CAPTURE_PR_ASSETS is unset", async () => { + delete process.env.CAPTURE_PR_ASSETS; + const primary = fakePage(); + const secondary = fakePage(); + const capture = new PrAssetCapture(primary, "cross-device.spec.ts", { outputDir }); + + await capture.screenshot("desktop", { page: secondary }); + + expect(primary.screenshot).not.toHaveBeenCalled(); + expect(secondary.screenshot).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/e2e/helpers/pr-asset-capture.ts b/apps/web/e2e/helpers/pr-asset-capture.ts index bad7d12950..7fb4365971 100644 --- a/apps/web/e2e/helpers/pr-asset-capture.ts +++ b/apps/web/e2e/helpers/pr-asset-capture.ts @@ -86,14 +86,23 @@ export class PrAssetCapture { } } - async screenshot(name: string, opts?: { caption?: string; fullPage?: boolean }): Promise { + /** + * Captures one asset. `opts.page` overrides the constructor page so a single + * capture instance can shoot several clients in one test (a cross-device spec + * drives two). Using a second instance instead would not work: flush() clears + * this spec's existing manifest entries, so the last flush would win. + */ + async screenshot( + name: string, + opts?: { caption?: string; fullPage?: boolean; page?: Page }, + ): Promise { if (!this.enabled) return; const safeName = sanitizeName(name); const fileName = `${this.testSlug}--${safeName}.png`; const filePath = path.join(this.outputDir, fileName); - await this.page.screenshot({ + await (opts?.page ?? this.page).screenshot({ path: filePath, fullPage: opts?.fullPage ?? false, }); diff --git a/apps/web/e2e/tests/chat/quick-chat-cross-device.spec.ts b/apps/web/e2e/tests/chat/quick-chat-cross-device.spec.ts new file mode 100644 index 0000000000..435d445c35 --- /dev/null +++ b/apps/web/e2e/tests/chat/quick-chat-cross-device.spec.ts @@ -0,0 +1,160 @@ +import type { Browser, BrowserContext, Locator, Page } from "@playwright/test"; +import { test, expect } from "../../fixtures/test-base"; +import { PrAssetCapture } from "../../helpers/pr-asset-capture"; +import { openQuickChatWithAgent, startQuickChatFromSetup } from "./quick-chat-helpers"; + +/** + * Quick chats are shared state: they are created, renamed and closed from any + * device, and every client must converge on the same tab strip. Before this + * suite existed, the list was a one-shot boot-payload snapshot, so two + * long-lived clients silently drifted apart. + * + * "Device B" is a second browser context against the same backend — a distinct + * client with its own store and WebSocket, which is exactly what a phone is. + */ + +const DESKTOP_VIEWPORT = { width: 1440, height: 900 }; +const MOBILE_VIEWPORT = { width: 393, height: 851 }; + +/** + * Opens an independent client against the same backend: its own context means + * its own store, WebSocket and localStorage, which is what makes it a + * meaningful stand-in for the user's other device. + */ +async function openSecondDevice( + browser: Browser, + frontendUrl: string, + backendPort: number, + viewport: { width: number; height: number }, +): Promise<{ page: Page; context: BrowserContext }> { + const context = await browser.newContext({ baseURL: frontendUrl, viewport }); + const page = await context.newPage(); + await page.addInitScript( + ({ port }: { port: number }) => { + localStorage.setItem("kandev.onboarding.completed", "true"); + window.__KANDEV_API_PORT = String(port); + window.__KANDEV_E2E_EXPOSE_STORE__ = true; + }, + { port: backendPort }, + ); + return { page, context }; +} + +/** Opens quick chat on a client that already has at least one chat to restore. */ +async function openExistingQuickChat(page: Page): Promise { + await page.goto("/"); + await page.waitForLoadState("networkidle"); + const modifier = process.platform === "darwin" ? "Meta" : "Control"; + await page.keyboard.press(`${modifier}+Shift+q`); + const dialog = page.getByRole("dialog", { name: "Quick Chat" }); + await expect(dialog).toBeVisible({ timeout: 15_000 }); + return dialog; +} + +function tabNames(dialog: Locator): Promise { + return dialog.getByTestId("quick-chat-tab").locator("span").allTextContents(); +} + +test.describe("Quick Chat cross-device sync", () => { + test("a chat started on one device appears on the other, and renames follow", async ({ + testPage, + backend, + browser, + }, testInfo) => { + test.setTimeout(180_000); + const capture = new PrAssetCapture(testPage, testInfo.file); + + // Device A: desktop. Start one chat so both clients share a baseline. + await testPage.setViewportSize(DESKTOP_VIEWPORT); + const dialogA = await openQuickChatWithAgent(testPage); + await expect(dialogA.getByTestId("quick-chat-tab")).toHaveCount(1); + + // Device B: a second client, opened after that first chat already existed. + const second = await openSecondDevice( + browser, + backend.frontendUrl, + backend.port, + MOBILE_VIEWPORT, + ); + const dialogB = await openExistingQuickChat(second.page); + await expect(dialogB.getByTestId("quick-chat-tab")).toHaveCount(1); + + // Device A starts a second chat while B is already open and idle. B must + // learn about it from the task event alone — no reload, no navigation. + await dialogA.getByLabel("Start new chat").click(); + await startQuickChatFromSetup(dialogA, testPage); + await expect(dialogA.getByTestId("quick-chat-tab")).toHaveCount(2); + + await expect(dialogB.getByTestId("quick-chat-tab")).toHaveCount(2, { timeout: 30_000 }); + + // Renaming on A must re-label the same tab on B, because the name now + // lives on the backing task rather than in A's localStorage. + const renamed = "Renamed from desktop"; + const activeTabA = dialogA.getByTestId("quick-chat-tab").last(); + await activeTabA.dblclick(); + const renameInput = dialogA.locator('[data-testid="quick-chat-tab"] input'); + await expect(renameInput).toBeVisible({ timeout: 5_000 }); + await renameInput.fill(renamed); + await renameInput.press("Enter"); + + await expect + .poll(() => tabNames(dialogB), { timeout: 30_000 }) + .toEqual(expect.arrayContaining([renamed])); + + await capture.screenshot("desktop-quick-chat-tabs", { + caption: "Desktop: two quick chats, the second renamed here", + }); + await capture.screenshot("mobile-quick-chat-tabs", { + page: second.page, + caption: "Mobile, same account: both tabs and the rename arrived live", + }); + capture.flush(); + + await second.context.close(); + }); + + test("closing a chat on one device removes it from the other", async ({ + testPage, + backend, + browser, + }) => { + test.setTimeout(180_000); + + await testPage.setViewportSize(DESKTOP_VIEWPORT); + const dialogA = await openQuickChatWithAgent(testPage); + await dialogA.getByLabel("Start new chat").click(); + await startQuickChatFromSetup(dialogA, testPage); + await expect(dialogA.getByTestId("quick-chat-tab")).toHaveCount(2); + + const second = await openSecondDevice( + browser, + backend.frontendUrl, + backend.port, + DESKTOP_VIEWPORT, + ); + const dialogB = await openExistingQuickChat(second.page); + await expect(dialogB.getByTestId("quick-chat-tab")).toHaveCount(2, { timeout: 30_000 }); + + // Close the second chat on A and confirm the deletion. Each tab holds both + // a label button and a close button, so target the close one by its label. + await dialogA + .getByTestId("quick-chat-tab") + .last() + .getByRole("button", { name: /^Close / }) + .click(); + const confirm = testPage.getByRole("alertdialog"); + await expect(confirm).toBeVisible({ timeout: 10_000 }); + // Target the destructive action exactly; a loose regex plus .last() would + // happily click Cancel if the footer order ever changed. + const confirmDelete = confirm.getByRole("button", { name: "Delete", exact: true }); + await expect(confirmDelete).toHaveCount(1); + await confirmDelete.click(); + await expect(dialogA.getByTestId("quick-chat-tab")).toHaveCount(1, { timeout: 30_000 }); + + // B must drop the tab too rather than keeping a ghost pointing at a task + // the backend has already deleted. + await expect(dialogB.getByTestId("quick-chat-tab")).toHaveCount(1, { timeout: 30_000 }); + + await second.context.close(); + }); +}); diff --git a/apps/web/e2e/tests/chat/quick-chat-helpers.ts b/apps/web/e2e/tests/chat/quick-chat-helpers.ts new file mode 100644 index 0000000000..bba9373c61 --- /dev/null +++ b/apps/web/e2e/tests/chat/quick-chat-helpers.ts @@ -0,0 +1,82 @@ +import { type Locator, type Page } from "@playwright/test"; +import { expect } from "../../fixtures/test-base"; + +/** + * Shared Quick Chat drivers. Kept out of the spec files so several specs + * (single-client behaviour and cross-device sync) can drive the same surface + * without duplicating its eager-init timing workarounds. + */ + +export async function openQuickChatSetup(page: Page, navigateHome = true): Promise { + if (navigateHome) { + await page.goto("/"); + await page.waitForLoadState("networkidle"); + } + + if (navigateHome) { + // Open Quick Chat via keyboard shortcut (Cmd+Shift+Q / Ctrl+Shift+Q). + const modifier = process.platform === "darwin" ? "Meta" : "Control"; + await page.keyboard.press(`${modifier}+Shift+q`); + } else { + await page.getByTestId("sidebar-quick-chat-shortcut").click(); + } + + // Wait for Quick Chat dialog. + const dialog = page.getByRole("dialog", { name: "Quick Chat" }); + await expect(dialog).toBeVisible({ timeout: 10_000 }); + + // If a stale session tab is showing, click "+" to start a fresh setup form. + const setup = dialog.getByTestId("quick-chat-setup"); + if (!(await setup.isVisible({ timeout: 1_000 }).catch(() => false))) { + await dialog.getByLabel("Start new chat").click(); + } + await expect(setup).toBeVisible({ timeout: 5_000 }); + return dialog; +} + +export async function selectAgentIfNeeded(dialog: Locator, page: Page) { + const selector = dialog.getByTestId("agent-profile-selector"); + if ( + await selector + .getByText("Select agent", { exact: false }) + .isVisible() + .catch(() => false) + ) { + await selector.click(); + await page.getByRole("option").first().click(); + } +} + +export async function startQuickChatFromSetup(dialog: Locator, page: Page) { + await selectAgentIfNeeded(dialog, page); + await dialog.getByTestId("quick-chat-start").click(); + + // Wait for chat input to appear AND become editable. Eager init means the + // agent starts during the HTTP request, so the input is briefly disabled + // while the FE store catches up to the RUNNING session state. + const editor = dialog.locator(".tiptap.ProseMirror"); + await expect(editor).toBeVisible({ timeout: 15_000 }); + await expect(editor).toHaveAttribute("contenteditable", "true", { timeout: 30_000 }); +} + +export async function openQuickChatWithAgent(page: Page, navigateHome = true): Promise { + const dialog = await openQuickChatSetup(page, navigateHome); + await startQuickChatFromSetup(dialog, page); + return dialog; +} + +export async function sendQuickChatMessage(dialog: Locator, page: Page, text: string) { + const editor = dialog.locator(".tiptap.ProseMirror"); + const modifier = process.platform === "darwin" ? "Meta" : "Control"; + // With eager init, the agent boots during picker -> tab transition and the + // input can briefly toggle disabled while the FE store catches up. Retry the + // full edit action so fill() cannot race a contenteditable=false flip. + await expect(async () => { + await expect(editor).toHaveAttribute("contenteditable", "true", { timeout: 1_000 }); + await editor.click({ timeout: 1_000 }); + await editor.fill(text, { timeout: 1_000 }); + await expect(editor).toHaveText(text, { timeout: 1_000 }); + await editor.press(`${modifier}+Enter`, { timeout: 1_000 }); + await expect(editor).toHaveText("", { timeout: 2_000 }); + }).toPass({ timeout: 30_000, intervals: [250, 500, 1_000] }); +} diff --git a/apps/web/e2e/tests/chat/quick-chat.spec.ts b/apps/web/e2e/tests/chat/quick-chat.spec.ts index b4f2e376f2..cfb5079b82 100644 --- a/apps/web/e2e/tests/chat/quick-chat.spec.ts +++ b/apps/web/e2e/tests/chat/quick-chat.spec.ts @@ -1,87 +1,20 @@ -import { type Locator, type Page } from "@playwright/test"; +import { type Locator } from "@playwright/test"; import { execFileSync } from "node:child_process"; import path from "node:path"; import { test, expect } from "../../fixtures/test-base"; import { attachAvailableCommandsCapture } from "../../helpers/ws-capture"; +import { + openQuickChatSetup, + openQuickChatWithAgent, + selectAgentIfNeeded, + sendQuickChatMessage, + startQuickChatFromSetup, +} from "./quick-chat-helpers"; /** * Quick Chat E2E tests: basic flow, enhance prompt, queued messages, multi-tab. */ -async function openQuickChatSetup(page: Page, navigateHome = true): Promise { - if (navigateHome) { - await page.goto("/"); - await page.waitForLoadState("networkidle"); - } - - if (navigateHome) { - // Open Quick Chat via keyboard shortcut (Cmd+Shift+Q / Ctrl+Shift+Q). - const modifier = process.platform === "darwin" ? "Meta" : "Control"; - await page.keyboard.press(`${modifier}+Shift+q`); - } else { - await page.getByTestId("sidebar-quick-chat-shortcut").click(); - } - - // Wait for Quick Chat dialog. - const dialog = page.getByRole("dialog", { name: "Quick Chat" }); - await expect(dialog).toBeVisible({ timeout: 10_000 }); - - // If a stale session tab is showing, click "+" to start a fresh setup form. - const setup = dialog.getByTestId("quick-chat-setup"); - if (!(await setup.isVisible({ timeout: 1_000 }).catch(() => false))) { - await dialog.getByLabel("Start new chat").click(); - } - await expect(setup).toBeVisible({ timeout: 5_000 }); - return dialog; -} - -async function selectAgentIfNeeded(dialog: Locator, page: Page) { - const selector = dialog.getByTestId("agent-profile-selector"); - if ( - await selector - .getByText("Select agent", { exact: false }) - .isVisible() - .catch(() => false) - ) { - await selector.click(); - await page.getByRole("option").first().click(); - } -} - -async function startQuickChatFromSetup(dialog: Locator, page: Page) { - await selectAgentIfNeeded(dialog, page); - await dialog.getByTestId("quick-chat-start").click(); - - // Wait for chat input to appear AND become editable. Eager init means the - // agent starts during the HTTP request, so the input is briefly disabled - // while the FE store catches up to the RUNNING session state. - const editor = dialog.locator(".tiptap.ProseMirror"); - await expect(editor).toBeVisible({ timeout: 15_000 }); - await expect(editor).toHaveAttribute("contenteditable", "true", { timeout: 30_000 }); -} - -async function openQuickChatWithAgent(page: Page, navigateHome = true): Promise { - const dialog = await openQuickChatSetup(page, navigateHome); - await startQuickChatFromSetup(dialog, page); - return dialog; -} - -async function sendQuickChatMessage(dialog: Locator, page: Page, text: string) { - const editor = dialog.locator(".tiptap.ProseMirror"); - const modifier = process.platform === "darwin" ? "Meta" : "Control"; - // With eager init, the agent boots during picker -> tab transition and the - // input can briefly toggle disabled while the FE store catches up. Retry the - // full edit action so fill() cannot race a contenteditable=false flip. - await expect(async () => { - await expect(editor).toHaveAttribute("contenteditable", "true", { timeout: 1_000 }); - await editor.click({ timeout: 1_000 }); - await editor.fill(text, { timeout: 1_000 }); - await expect(editor).toHaveText(text, { timeout: 1_000 }); - await editor.press(`${modifier}+Enter`, { timeout: 1_000 }); - await expect(editor).toHaveText("", { timeout: 2_000 }); - }).toPass({ timeout: 30_000, intervals: [250, 500, 1_000] }); -} - async function waitForQuickChatWidth(dialog: Locator) { await expect .poll(() => diff --git a/apps/web/hooks/use-ensure-task-session.test.ts b/apps/web/hooks/use-ensure-task-session.test.ts new file mode 100644 index 0000000000..a7e7ff15b7 --- /dev/null +++ b/apps/web/hooks/use-ensure-task-session.test.ts @@ -0,0 +1,64 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderHook, waitFor } from "@testing-library/react"; + +const mockFetchTaskSession = vi.hoisted(() => vi.fn()); +const mockState = vi.hoisted(() => ({ value: {} as Record })); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: typeof mockState.value) => unknown) => selector(mockState.value), +})); + +vi.mock("@/lib/api/domains/session-api", () => ({ + fetchTaskSession: (...args: unknown[]) => mockFetchTaskSession(...args), +})); + +import { useEnsureTaskSession } from "./use-ensure-task-session"; + +const setTaskSession = vi.fn(); + +function setStoredSessions(items: Record) { + mockState.value = { taskSessions: { items }, setTaskSession }; +} + +beforeEach(() => { + vi.clearAllMocks(); + setStoredSessions({}); + mockFetchTaskSession.mockResolvedValue({ session: { id: "session-1", task_id: "task-1" } }); +}); + +describe("useEnsureTaskSession", () => { + // A tab learned from a task event has no session row, and without one the + // chat renders but cannot subscribe or accept input. + it("fetches and stores a session the client has never seen", async () => { + renderHook(() => useEnsureTaskSession("session-1")); + + await waitFor(() => expect(mockFetchTaskSession).toHaveBeenCalledWith("session-1")); + expect(setTaskSession).toHaveBeenCalledWith({ id: "session-1", task_id: "task-1" }); + }); + + it("does not refetch a session already in the store", () => { + setStoredSessions({ "session-1": { id: "session-1" } }); + + renderHook(() => useEnsureTaskSession("session-1")); + + expect(mockFetchTaskSession).not.toHaveBeenCalled(); + }); + + it("does nothing without a session id", () => { + renderHook(() => useEnsureTaskSession(null)); + + expect(mockFetchTaskSession).not.toHaveBeenCalled(); + }); + + it("requests a given session only once, even if it never arrives", async () => { + mockFetchTaskSession.mockRejectedValue(new Error("deleted elsewhere")); + + const { rerender } = renderHook(() => useEnsureTaskSession("session-1")); + await waitFor(() => expect(mockFetchTaskSession).toHaveBeenCalledTimes(1)); + rerender(); + rerender(); + + expect(mockFetchTaskSession).toHaveBeenCalledTimes(1); + expect(setTaskSession).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/hooks/use-ensure-task-session.ts b/apps/web/hooks/use-ensure-task-session.ts new file mode 100644 index 0000000000..6ae2f12570 --- /dev/null +++ b/apps/web/hooks/use-ensure-task-session.ts @@ -0,0 +1,44 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import { useAppStore } from "@/components/state-provider"; +import { fetchTaskSession } from "@/lib/api/domains/session-api"; + +/** + * Guarantees the store holds the session row for `sessionId`. + * + * A quick chat learned from a task event carries only the tab's identity — the + * event has no session payload. Without the row the tab is inert: `useSession` + * returns null so it never subscribes, and `requireSessionInputMode` rejects + * every send. Fetching lazily, when the user actually opens that tab, keeps the + * cross-device tab strip cheap while making any tab openable regardless of + * which path introduced it. + */ +export function useEnsureTaskSession(sessionId: string | null): void { + const hasSession = useAppStore((state) => + sessionId ? Boolean(state.taskSessions.items[sessionId]) : true, + ); + const setTaskSession = useAppStore((state) => state.setTaskSession); + // Never re-request a session id this hook has already asked for; a chat whose + // task was deleted elsewhere would otherwise refetch on every render. + const requested = useRef>(new Set()); + + useEffect(() => { + if (!sessionId || hasSession || requested.current.has(sessionId)) return; + requested.current.add(sessionId); + + let cancelled = false; + fetchTaskSession(sessionId) + .then((response) => { + if (!cancelled && response.session) setTaskSession(response.session); + }) + .catch(() => { + // The session may be genuinely gone (deleted on another device); the + // tab strip drops it on the next event or resync. + }); + + return () => { + cancelled = true; + }; + }, [sessionId, hasSession, setTaskSession]); +} diff --git a/apps/web/hooks/use-quick-chat-resync.test.ts b/apps/web/hooks/use-quick-chat-resync.test.ts new file mode 100644 index 0000000000..a5d4765f39 --- /dev/null +++ b/apps/web/hooks/use-quick-chat-resync.test.ts @@ -0,0 +1,149 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderHook, waitFor } from "@testing-library/react"; + +const mockListQuickChatSessions = vi.hoisted(() => vi.fn()); +const mockUpdateTask = vi.hoisted(() => vi.fn()); +const mockState = vi.hoisted(() => ({ + value: {} as { + connection: { status: string }; + syncQuickChatSessions: unknown; + setTaskSession: unknown; + }, +})); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: typeof mockState.value) => unknown) => selector(mockState.value), +})); + +vi.mock("@/lib/api/domains/workspace-api", () => ({ + listQuickChatSessions: (...args: unknown[]) => mockListQuickChatSessions(...args), +})); + +vi.mock("@/lib/api/domains/kanban-api", () => ({ + updateTask: (...args: unknown[]) => mockUpdateTask(...args), +})); + +import { useQuickChatResync } from "./use-quick-chat-resync"; +import { getStoredQuickChatNames, setStoredQuickChatName } from "@/lib/local-storage"; + +const syncQuickChatSessions = vi.fn(); +const setTaskSession = vi.fn(); + +function setConnection(status: string) { + mockState.value = { connection: { status }, syncQuickChatSessions, setTaskSession }; +} + +beforeEach(() => { + vi.clearAllMocks(); + window.localStorage.clear(); + mockUpdateTask.mockResolvedValue(undefined); + setConnection("connected"); + mockListQuickChatSessions.mockResolvedValue({ + sessions: [ + { + session_id: "session-1", + task_id: "task-1", + workspace_id: "ws-1", + kind: "chat", + name: "Chat 1", + agent_profile_id: "agent-1", + }, + ], + task_sessions: [{ id: "session-1", task_id: "task-1" }], + }); +}); + +describe("useQuickChatResync", () => { + it("replaces the workspace's tabs with the server's list once connected", async () => { + renderHook(() => useQuickChatResync("ws-1")); + + await waitFor(() => expect(syncQuickChatSessions).toHaveBeenCalledTimes(1)); + expect(syncQuickChatSessions).toHaveBeenCalledWith("ws-1", [ + { + kind: "chat", + sessionId: "session-1", + taskId: "task-1", + workspaceId: "ws-1", + name: "Chat 1", + agentProfileId: "agent-1", + }, + ]); + }); + + // A tab without its session row renders but cannot subscribe or accept + // input, so the rows in the response must land in the store too. + it("stores the session rows that came with the list", async () => { + renderHook(() => useQuickChatResync("ws-1")); + + await waitFor(() => + expect(setTaskSession).toHaveBeenCalledWith({ id: "session-1", task_id: "task-1" }), + ); + }); + + it("waits for the socket before trusting any list", () => { + setConnection("connecting"); + + renderHook(() => useQuickChatResync("ws-1")); + + expect(mockListQuickChatSessions).not.toHaveBeenCalled(); + }); + + it("does nothing without an active workspace", () => { + renderHook(() => useQuickChatResync(null)); + + expect(mockListQuickChatSessions).not.toHaveBeenCalled(); + }); + + it("resyncs again after a reconnect, since events were missed while away", async () => { + const { rerender } = renderHook(() => useQuickChatResync("ws-1")); + await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalledTimes(1)); + + setConnection("reconnecting"); + rerender(); + setConnection("connected"); + rerender(); + + await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalledTimes(2)); + }); + + it("does not refetch on unrelated re-renders of the same connection", async () => { + const { rerender } = renderHook(() => useQuickChatResync("ws-1")); + await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalledTimes(1)); + + rerender(); + rerender(); + + expect(mockListQuickChatSessions).toHaveBeenCalledTimes(1); + }); + + it("leaves existing tabs alone when the resync fails", async () => { + mockListQuickChatSessions.mockRejectedValueOnce(new Error("offline")); + + renderHook(() => useQuickChatResync("ws-1")); + + await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalled()); + expect(syncQuickChatSessions).not.toHaveBeenCalled(); + }); +}); + +describe("useQuickChatResync — legacy rename migration", () => { + it("uploads a browser-only rename so it survives and reaches other devices", async () => { + setStoredQuickChatName("session-1", "My old local name"); + + renderHook(() => useQuickChatResync("ws-1")); + + await waitFor(() => + expect(mockUpdateTask).toHaveBeenCalledWith("task-1", { title: "My old local name" }), + ); + await waitFor(() => expect(getStoredQuickChatNames()).toEqual({})); + }); + + it("does not re-upload a name the server already has", async () => { + setStoredQuickChatName("session-1", "Chat 1"); + + renderHook(() => useQuickChatResync("ws-1")); + + await waitFor(() => expect(syncQuickChatSessions).toHaveBeenCalled()); + expect(mockUpdateTask).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/hooks/use-quick-chat-resync.ts b/apps/web/hooks/use-quick-chat-resync.ts new file mode 100644 index 0000000000..c7e1c6cb2c --- /dev/null +++ b/apps/web/hooks/use-quick-chat-resync.ts @@ -0,0 +1,59 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import { useAppStore } from "@/components/state-provider"; +import { listQuickChatSessions } from "@/lib/api/domains/workspace-api"; +import { getStoredQuickChatNames } from "@/lib/local-storage"; +import { toQuickChatSessions } from "@/lib/quick-chat/map-sessions"; +import { migrateStoredQuickChatNames } from "@/lib/quick-chat/rename"; + +/** + * Keeps this client's quick-chat tabs in step with the server's list. + * + * Live changes arrive over the WebSocket, but a client that was asleep or + * disconnected (a backgrounded phone tab is the common case) misses those + * events entirely and would otherwise keep showing tabs nobody else has — + * and keep missing tabs everyone else has — until a full page reload. + * Re-reading the list whenever the socket (re)connects closes that gap. + */ +export function useQuickChatResync(workspaceId: string | null): void { + const connectionStatus = useAppStore((state) => state.connection.status); + const syncQuickChatSessions = useAppStore((state) => state.syncQuickChatSessions); + const setTaskSession = useAppStore((state) => state.setTaskSession); + // Resync once per connection, not on every unrelated status re-render. + const lastSyncedConnection = useRef(null); + + useEffect(() => { + if (connectionStatus !== "connected") { + lastSyncedConnection.current = null; + return; + } + if (!workspaceId || lastSyncedConnection.current === workspaceId) return; + lastSyncedConnection.current = workspaceId; + + let cancelled = false; + listQuickChatSessions(workspaceId) + .then((response) => { + if (cancelled) return; + const sessions = toQuickChatSessions(response.sessions); + // Store the session rows before the tabs. A tab without its row cannot + // subscribe or accept input (useSession bails, requireSessionInputMode + // throws), so a resync-only tab would otherwise render but be dead. + for (const taskSession of response.task_sessions) { + setTaskSession(taskSession); + } + syncQuickChatSessions(workspaceId, sessions); + // Renames made before names were stored server-side live only in this + // browser; push them up once so they reach the user's other devices. + void migrateStoredQuickChatNames(sessions, getStoredQuickChatNames()); + }) + .catch(() => { + // A failed resync must not clear the user's tabs; retry on next connect. + if (!cancelled) lastSyncedConnection.current = null; + }); + + return () => { + cancelled = true; + }; + }, [connectionStatus, workspaceId, setTaskSession, syncQuickChatSessions]); +} diff --git a/apps/web/lib/api/domains/workspace-api.ts b/apps/web/lib/api/domains/workspace-api.ts index 4c43e79d38..4c0311db41 100644 --- a/apps/web/lib/api/domains/workspace-api.ts +++ b/apps/web/lib/api/domains/workspace-api.ts @@ -6,6 +6,7 @@ import type { ListRepositoryScriptsResponse, Workspace, Repository, + TaskSession, } from "@/lib/types/http"; // Workspace operations @@ -150,18 +151,32 @@ export async function startQuickChat( }); } +export type QuickChatSessionResponse = { + session_id: string; + task_id: string; + workspace_id: string; + kind: "chat" | "config"; + name?: string; + agent_profile_id?: string; +}; + +export type ListQuickChatSessionsResponse = { + sessions: QuickChatSessionResponse[]; + task_sessions: TaskSession[]; +}; + +/** + * Lists the workspace's restorable quick-chat tabs. + * + * Quick chats are created and closed from any device, so this is the same list + * the Go boot payload embeds — clients re-read it on (re)connect to converge on + * the server's tabs instead of drifting apart. + */ export async function listQuickChatSessions(workspaceId: string, options?: ApiRequestOptions) { - return fetchJson<{ - tasks: Array<{ - id: string; - title: string; - workspace_id: string; - primary_session_id?: string | null; - metadata?: Record | null; - origin?: string | null; - updated_at?: string; - }>; - }>(`/api/v1/workspaces/${workspaceId}/tasks?only_ephemeral=true&exclude_config=true`, options); + return fetchJson( + `/api/v1/workspaces/${workspaceId}/quick-chats`, + options, + ); } // Config Chat operations diff --git a/apps/web/lib/quick-chat/map-sessions.test.ts b/apps/web/lib/quick-chat/map-sessions.test.ts new file mode 100644 index 0000000000..6864baef1d --- /dev/null +++ b/apps/web/lib/quick-chat/map-sessions.test.ts @@ -0,0 +1,45 @@ +import { describe, it, expect } from "vitest"; +import { toQuickChatSessions } from "./map-sessions"; + +describe("toQuickChatSessions", () => { + it("maps the response onto store tabs", () => { + expect( + toQuickChatSessions([ + { + session_id: "session-1", + task_id: "task-1", + workspace_id: "ws-1", + kind: "chat", + name: "Chat 1", + agent_profile_id: "agent-1", + }, + ]), + ).toEqual([ + { + kind: "chat", + sessionId: "session-1", + taskId: "task-1", + workspaceId: "ws-1", + name: "Chat 1", + agentProfileId: "agent-1", + }, + ]); + }); + + // Boot hydration and the runtime resync share this mapper. When they had + // their own copies, the boot one dropped task_id, so closing a boot-loaded + // tab skipped the backend delete and orphaned its ephemeral task. + it("always carries taskId, which the close flow needs to delete the task", () => { + const [session] = toQuickChatSessions([ + { session_id: "s", task_id: "t", workspace_id: "w", kind: "config" }, + ]); + + expect(session.taskId).toBe("t"); + expect(session.kind).toBe("config"); + expect(session.name).toBeUndefined(); + }); + + it("returns an empty list unchanged", () => { + expect(toQuickChatSessions([])).toEqual([]); + }); +}); diff --git a/apps/web/lib/quick-chat/map-sessions.ts b/apps/web/lib/quick-chat/map-sessions.ts new file mode 100644 index 0000000000..45e927aae9 --- /dev/null +++ b/apps/web/lib/quick-chat/map-sessions.ts @@ -0,0 +1,20 @@ +import type { QuickChatSessionResponse } from "@/lib/api/domains/workspace-api"; +import type { QuickChatSession } from "@/lib/state/slices/ui/types"; + +/** + * Maps the quick-chat list response onto store tabs. + * + * Shared by boot hydration and the runtime resync. Keeping one mapper matters: + * when these drifted, boot-loaded tabs silently lost `taskId`, so closing one + * skipped the backend delete and left an orphaned ephemeral task behind. + */ +export function toQuickChatSessions(sessions: QuickChatSessionResponse[]): QuickChatSession[] { + return sessions.map((session) => ({ + kind: session.kind, + sessionId: session.session_id, + taskId: session.task_id, + workspaceId: session.workspace_id, + name: session.name, + agentProfileId: session.agent_profile_id, + })); +} diff --git a/apps/web/lib/quick-chat/rename.test.ts b/apps/web/lib/quick-chat/rename.test.ts new file mode 100644 index 0000000000..0e06eaace6 --- /dev/null +++ b/apps/web/lib/quick-chat/rename.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mockUpdateTask = vi.hoisted(() => vi.fn()); + +vi.mock("@/lib/api/domains/kanban-api", () => ({ + updateTask: (...args: unknown[]) => mockUpdateTask(...args), +})); + +import { migrateStoredQuickChatNames, persistQuickChatRename } from "./rename"; +import { getStoredQuickChatNames, setStoredQuickChatName } from "@/lib/local-storage"; + +beforeEach(() => { + vi.clearAllMocks(); + window.localStorage.clear(); + mockUpdateTask.mockResolvedValue(undefined); +}); + +describe("persistQuickChatRename", () => { + it("saves the name to the backing task title so other devices see it", async () => { + await expect(persistQuickChatRename("session-1", "task-1", "Renamed")).resolves.toBe(true); + + expect(mockUpdateTask).toHaveBeenCalledWith("task-1", { title: "Renamed" }); + }); + + it("clears any legacy local entry once the name is stored server-side", async () => { + setStoredQuickChatName("session-1", "Old local name"); + + await persistQuickChatRename("session-1", "task-1", "Renamed"); + + expect(getStoredQuickChatNames()).toEqual({}); + }); + + it("keeps the rename locally when the request fails", async () => { + mockUpdateTask.mockRejectedValueOnce(new Error("offline")); + + await expect(persistQuickChatRename("session-1", "task-1", "Renamed")).rejects.toThrow( + "offline", + ); + expect(getStoredQuickChatNames()).toEqual({ "session-1": "Renamed" }); + }); + + it("falls back to local storage for a tab with no task yet", async () => { + await expect(persistQuickChatRename("setup-session", undefined, "Draft")).resolves.toBe(false); + + expect(mockUpdateTask).not.toHaveBeenCalled(); + expect(getStoredQuickChatNames()).toEqual({ "setup-session": "Draft" }); + }); +}); + +describe("migrateStoredQuickChatNames", () => { + it("uploads a pre-existing local rename so upgrading does not lose it", async () => { + const sessions = [{ sessionId: "session-1", taskId: "task-1", name: "Agent - Chat 1" }]; + + await migrateStoredQuickChatNames(sessions, { "session-1": "My name" }); + + expect(mockUpdateTask).toHaveBeenCalledWith("task-1", { title: "My name" }); + expect(getStoredQuickChatNames()).toEqual({}); + }); + + it("skips names the server already agrees with", async () => { + const sessions = [{ sessionId: "session-1", taskId: "task-1", name: "Same" }]; + + await migrateStoredQuickChatNames(sessions, { "session-1": "Same" }); + + expect(mockUpdateTask).not.toHaveBeenCalled(); + }); + + it("skips sessions with no stored rename", async () => { + const sessions = [{ sessionId: "session-1", taskId: "task-1", name: "Server name" }]; + + await migrateStoredQuickChatNames(sessions, {}); + + expect(mockUpdateTask).not.toHaveBeenCalled(); + }); + + it("retains the local entry when a migration attempt fails, so it retries", async () => { + mockUpdateTask.mockRejectedValueOnce(new Error("offline")); + const sessions = [{ sessionId: "session-1", taskId: "task-1", name: "Server name" }]; + + await expect( + migrateStoredQuickChatNames(sessions, { "session-1": "My name" }), + ).resolves.toBeUndefined(); + + expect(getStoredQuickChatNames()).toEqual({ "session-1": "My name" }); + }); +}); diff --git a/apps/web/lib/quick-chat/rename.ts b/apps/web/lib/quick-chat/rename.ts new file mode 100644 index 0000000000..cd968bb646 --- /dev/null +++ b/apps/web/lib/quick-chat/rename.ts @@ -0,0 +1,70 @@ +import { updateTask } from "@/lib/api/domains/kanban-api"; +import { removeStoredQuickChatName, setStoredQuickChatName } from "@/lib/local-storage"; + +/** + * Persists a quick-chat tab rename to its backing task title. + * + * The title is the shared name: saving it there makes the rename reach every + * other device (the resulting `task.updated` event re-labels their tab), which + * a localStorage-only rename never did. + * + * localStorage is kept purely as a degraded fallback. On success the local + * entry is cleared so it can never pin a stale name over a rename made + * elsewhere; on failure it is written so the user's rename still survives a + * reload on this device. + * + * @returns true when the name reached the backend. + * @throws the underlying request error, so callers can surface it. + */ +export async function persistQuickChatRename( + sessionId: string, + taskId: string | undefined, + name: string, +): Promise { + if (!sessionId) return false; + if (!taskId) { + // An unstarted "New chat" tab has no task yet; keep the name locally. + setStoredQuickChatName(sessionId, name); + return false; + } + try { + await updateTask(taskId, { title: name }); + removeStoredQuickChatName(sessionId); + return true; + } catch (error) { + setStoredQuickChatName(sessionId, name); + throw error; + } +} + +type MigratableSession = { sessionId: string; taskId?: string; name?: string }; + +/** + * Uploads renames made before names were persisted server-side. + * + * Without this, upgrading would silently revert every tab a user had renamed + * back to its auto-generated title. Each migrated entry is dropped from + * localStorage, so this converges after one pass per device. + */ +export async function migrateStoredQuickChatNames( + sessions: MigratableSession[], + storedNames: Record, +): Promise { + const pending = sessions.filter( + (session) => + session.taskId && + storedNames[session.sessionId] && + storedNames[session.sessionId] !== session.name, + ); + await Promise.all( + pending.map((session) => + // Best effort: a failed migration keeps its local entry and retries on + // the next resync. + persistQuickChatRename( + session.sessionId, + session.taskId, + storedNames[session.sessionId], + ).catch(() => undefined), + ), + ); +} diff --git a/apps/web/lib/state/default-state.ts b/apps/web/lib/state/default-state.ts index 20639b4518..c5967e1ab7 100644 --- a/apps/web/lib/state/default-state.ts +++ b/apps/web/lib/state/default-state.ts @@ -17,7 +17,7 @@ import { defaultSystemState, defaultReviewState, } from "./slices"; -import { getStoredQuickChatNames } from "@/lib/local-storage"; +import { applyStoredQuickChatNames } from "@/lib/state/slices/ui/quick-chat-sync"; import type { HydrationState } from "./store"; import { migrateView } from "./slices/ui/ui-slice"; @@ -154,17 +154,9 @@ function mergeQuickChatState(initialState: HydrationState): DefaultState["quickC const quickChat = { ...defaultState.quickChat, ...initialState.quickChat }; if (!initialState.quickChat?.sessions) return quickChat; - const storedNames = getStoredQuickChatNames(); return { ...quickChat, - sessions: initialState.quickChat.sessions.map((session) => { - const localName = storedNames[session.sessionId]; - return { - ...session, - kind: session.kind ?? "chat", - ...(localName ? { name: localName } : {}), - }; - }), + sessions: applyStoredQuickChatNames(initialState.quickChat.sessions), }; } diff --git a/apps/web/lib/state/hydration/hydrator.ts b/apps/web/lib/state/hydration/hydrator.ts index ecc3e40526..d277bd1e88 100644 --- a/apps/web/lib/state/hydration/hydrator.ts +++ b/apps/web/lib/state/hydration/hydrator.ts @@ -1,7 +1,7 @@ import type { Draft } from "immer"; import type { AppState, HydrationState } from "../store"; import { migrateView } from "../slices/ui/ui-slice"; -import { getStoredQuickChatNames } from "@/lib/local-storage"; +import { applyStoredQuickChatNames } from "@/lib/state/slices/ui/quick-chat-sync"; import { deepMerge, mergeSessionMap, mergeLoadingState } from "./merge-strategies"; /** @@ -234,11 +234,7 @@ export function hydrateUI(draft: Draft, state: HydrationState): void { // Local renames live in localStorage and override the SSR-provided name // (which derives from the backend task title). Apply on every hydration // so a renamed chat keeps its local name across reloads and tab switches. - const storedNames = getStoredQuickChatNames(); - draft.quickChat.sessions = state.quickChat.sessions.map((s) => { - const local = storedNames[s.sessionId]; - return { ...s, kind: s.kind ?? "chat", ...(local ? { name: local } : {}) }; - }); + draft.quickChat.sessions = applyStoredQuickChatNames(state.quickChat.sessions); // Validate activeSessionId exists in sessions after merge if ( draft.quickChat.activeSessionId && diff --git a/apps/web/lib/state/slices/ui/quick-chat-sync.test.ts b/apps/web/lib/state/slices/ui/quick-chat-sync.test.ts new file mode 100644 index 0000000000..6502526c9e --- /dev/null +++ b/apps/web/lib/state/slices/ui/quick-chat-sync.test.ts @@ -0,0 +1,218 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { + reconcileQuickChatSessions, + removeQuickChatSessionsForTask, + upsertQuickChatSession, +} from "./quick-chat-sync"; +import { getQuickChatSetupSessionId } from "./quick-chat-session"; +import type { QuickChatSession, QuickChatState } from "./types"; + +const mockStoredNames = vi.hoisted(() => ({ value: {} as Record })); + +vi.mock("@/lib/local-storage", () => ({ + getStoredQuickChatNames: () => mockStoredNames.value, +})); + +const WS = "ws-1"; +const OTHER_WS = "ws-2"; +const SETUP_ID = getQuickChatSetupSessionId(WS, "chat"); + +function chat(sessionId: string, overrides: Partial = {}): QuickChatSession { + return { + kind: "chat", + sessionId, + workspaceId: WS, + taskId: `task-${sessionId}`, + ...overrides, + }; +} + +function state(sessions: QuickChatSession[], overrides: Partial = {}) { + return { isOpen: true, sessions, activeSessionId: null, ...overrides }; +} + +beforeEach(() => { + mockStoredNames.value = {}; +}); + +describe("reconcileQuickChatSessions", () => { + it("adopts tabs the server knows about and drops tabs it does not", () => { + // The reported bug: this client only ever saw "a" and "local", another + // device created "b" and closed "local". + const before = state([chat("a"), chat("local")]); + + const after = reconcileQuickChatSessions(before, WS, [chat("a"), chat("b")]); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["a", "b"]); + }); + + it("takes the server's order for the initial restore", () => { + // Nothing on screen yet, so activity order decides where tabs land. + const after = reconcileQuickChatSessions(state([]), WS, [chat("b"), chat("a")]); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["b", "a"]); + }); + + it("does not reshuffle tabs already on screen when activity order changes", () => { + // The server sorts by latest activity, which moves while sessions run. If a + // reconnect adopted that wholesale, the strip would jump under the cursor. + const before = state([chat("b"), chat("a")], { activeSessionId: "b" }); + + const after = reconcileQuickChatSessions(before, WS, [chat("a"), chat("b")]); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["b", "a"]); + }); + + it("appends chats it has not seen after the tabs already on screen", () => { + const before = state([chat("b"), chat("a")]); + + const after = reconcileQuickChatSessions(before, WS, [chat("new"), chat("a"), chat("b")]); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["b", "a", "new"]); + }); + + it("leaves other workspaces' tabs untouched", () => { + const foreign = chat("foreign", { workspaceId: OTHER_WS }); + const before = state([foreign, chat("a")]); + + const after = reconcileQuickChatSessions(before, WS, []); + + expect(after.sessions).toEqual([foreign]); + }); + + it("keeps an unstarted setup tab, which has no backing task to sync", () => { + const setup: QuickChatSession = { kind: "chat", sessionId: SETUP_ID, workspaceId: WS }; + const before = state([setup, chat("a")], { activeSessionId: SETUP_ID }); + + const after = reconcileQuickChatSessions(before, WS, [chat("a")]); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["a", SETUP_ID]); + expect(after.activeSessionId).toBe(SETUP_ID); + }); + + it("keeps client-only draft state on a tab that survives", () => { + const before = state([chat("a", { initialPrompt: "unsent draft" })]); + + const after = reconcileQuickChatSessions(before, WS, [chat("a")]); + + expect(after.sessions[0].initialPrompt).toBe("unsent draft"); + }); + + it("lets a local rename win over the server's task title", () => { + mockStoredNames.value = { a: "My name for it" }; + const before = state([chat("a")]); + + const after = reconcileQuickChatSessions(before, WS, [chat("a", { name: "Server Title" })]); + + expect(after.sessions[0].name).toBe("My name for it"); + }); + + it("re-points the active tab when the server dropped the one in view", () => { + const before = state([chat("a"), chat("b")], { activeSessionId: "a" }); + + const after = reconcileQuickChatSessions(before, WS, [chat("b")]); + + expect(after.activeSessionId).toBe("b"); + expect(after.isOpen).toBe(true); + }); + + it("closes the modal when the workspace has no tabs left", () => { + const before = state([chat("a")], { activeSessionId: "a" }); + + const after = reconcileQuickChatSessions(before, WS, []); + + expect(after.sessions).toEqual([]); + expect(after.activeSessionId).toBeNull(); + expect(after.isOpen).toBe(false); + }); + + it("leaves a never-selected active tab unset instead of promoting one", () => { + // A background resync must not decide which tab is "current" for a user who + // has not opened quick chat at all. + const before = state([], { isOpen: false, activeSessionId: null }); + + const after = reconcileQuickChatSessions(before, WS, [chat("a"), chat("b")]); + + expect(after.sessions).toHaveLength(2); + expect(after.activeSessionId).toBeNull(); + expect(after.isOpen).toBe(false); + }); + + it("does not disturb an active tab belonging to another workspace", () => { + const foreign = chat("foreign", { workspaceId: OTHER_WS }); + const before = state([foreign, chat("a")], { activeSessionId: "foreign" }); + + const after = reconcileQuickChatSessions(before, WS, []); + + expect(after.activeSessionId).toBe("foreign"); + expect(after.isOpen).toBe(true); + }); +}); + +describe("upsertQuickChatSession", () => { + it("appends a chat started on another device", () => { + const after = upsertQuickChatSession(state([chat("a")]), chat("b")); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["a", "b"]); + }); + + it("never steals focus or opens the modal", () => { + const before = state([chat("a")], { isOpen: false, activeSessionId: "a" }); + + const after = upsertQuickChatSession(before, chat("b")); + + expect(after.isOpen).toBe(false); + expect(after.activeSessionId).toBe("a"); + }); + + it("updates a known tab in place rather than duplicating it", () => { + const before = state([chat("a", { name: "Old" })]); + + const after = upsertQuickChatSession(before, chat("a", { name: "Renamed elsewhere" })); + + expect(after.sessions).toHaveLength(1); + expect(after.sessions[0].name).toBe("Renamed elsewhere"); + }); + + it("keeps this device's rename when a remote update carries the old title", () => { + mockStoredNames.value = { a: "Mine" }; + const before = state([chat("a", { name: "Mine" })]); + + const after = upsertQuickChatSession(before, chat("a", { name: "Server Title" })); + + expect(after.sessions[0].name).toBe("Mine"); + }); +}); + +describe("removeQuickChatSessionsForTask", () => { + it("drops the tab whose task was deleted elsewhere", () => { + const before = state([chat("a"), chat("b")], { activeSessionId: "b" }); + + const after = removeQuickChatSessionsForTask(before, "task-b"); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["a"]); + expect(after.activeSessionId).toBe("a"); + }); + + it("keeps a null active tab null while removing others", () => { + const before = state([chat("a"), chat("b")], { activeSessionId: null }); + + const after = removeQuickChatSessionsForTask(before, "task-b"); + + expect(after.sessions.map((s) => s.sessionId)).toEqual(["a"]); + expect(after.activeSessionId).toBeNull(); + }); + + it("returns the same state when no tab is affected", () => { + const before = state([chat("a")]); + + expect(removeQuickChatSessionsForTask(before, "task-unknown")).toBe(before); + }); + + it("ignores setup tabs, which have no task id", () => { + const setup: QuickChatSession = { kind: "chat", sessionId: SETUP_ID, workspaceId: WS }; + const before = state([setup]); + + expect(removeQuickChatSessionsForTask(before, "task-a")).toBe(before); + }); +}); diff --git a/apps/web/lib/state/slices/ui/quick-chat-sync.ts b/apps/web/lib/state/slices/ui/quick-chat-sync.ts new file mode 100644 index 0000000000..c42fe5a191 --- /dev/null +++ b/apps/web/lib/state/slices/ui/quick-chat-sync.ts @@ -0,0 +1,129 @@ +import { getStoredQuickChatNames } from "@/lib/local-storage"; +import { isQuickChatSetupSessionId } from "./quick-chat-session"; +import type { QuickChatSession, QuickChatState } from "./types"; + +/** + * Applies locally stored tab renames over a server-provided session list. + * + * Renames live in localStorage, so the backend task title is only a fallback. + * Boot hydration and runtime resync both go through here so a reload and a + * WebSocket-driven refresh label the same tab the same way. + */ +export function applyStoredQuickChatNames(sessions: QuickChatSession[]): QuickChatSession[] { + const storedNames = getStoredQuickChatNames(); + return sessions.map((session) => { + const localName = storedNames[session.sessionId]; + return { + ...session, + kind: session.kind ?? "chat", + ...(localName ? { name: localName } : {}), + }; + }); +} + +/** + * Reconciles one workspace's quick-chat tabs against the server's list. + * + * Quick chats are shared state: they are created and closed from any device, + * but a client only ever learned about them from its own boot payload. Without + * this reconcile, two long-lived clients drift — each keeps tabs the other + * never saw, and keeps tabs whose task the other already deleted. + * + * Membership is the server's call; position is not. Tabs already on screen keep + * their order and new ones are appended, because the server sorts by latest + * activity and that changes as sessions run — adopting it wholesale would + * reshuffle the strip under the user's cursor on every reconnect. The activity + * order still decides the initial restore, when there is nothing on screen yet. + * + * Local-only state is preserved: unstarted "New chat" setup tabs (which have no + * backing task yet) and per-session drafts on tabs that survive. + */ +export function reconcileQuickChatSessions( + state: QuickChatState, + workspaceId: string, + serverSessions: QuickChatSession[], +): QuickChatState { + const otherWorkspaces = state.sessions.filter((session) => session.workspaceId !== workspaceId); + const localSetupTabs = state.sessions.filter( + (session) => + session.workspaceId === workspaceId && isQuickChatSetupSessionId(session.sessionId), + ); + const named = applyStoredQuickChatNames(serverSessions); + const serverById = new Map(named.map((session) => [session.sessionId, session])); + + // Tabs still on the server, in the order this client already shows them. + const survivors = state.sessions + .filter( + (session) => session.workspaceId === workspaceId && serverById.has(session.sessionId), + // Client-only fields (e.g. an unsent draft) survive via the spread below. + ) + .map((session) => ({ ...session, ...serverById.get(session.sessionId) })); + const survivorIds = new Set(survivors.map((session) => session.sessionId)); + const added = named.filter((session) => !survivorIds.has(session.sessionId)); + + return withValidActiveSession(state, [ + ...otherWorkspaces, + ...survivors, + ...added, + ...localSetupTabs, + ]); +} + +/** + * Adds or updates a single quick-chat tab observed on the wire. + * + * Passive by design: it never changes which tab is active or opens the modal, + * because the event describes something the user did on another device. + */ +export function upsertQuickChatSession( + state: QuickChatState, + session: QuickChatSession, +): QuickChatState { + const [named] = applyStoredQuickChatNames([session]); + const index = state.sessions.findIndex((item) => item.sessionId === named.sessionId); + if (index === -1) { + return { ...state, sessions: [...state.sessions, named] }; + } + const sessions = [...state.sessions]; + sessions[index] = { ...sessions[index], ...named }; + return { ...state, sessions }; +} + +/** Drops the tabs backed by a task that no longer exists. */ +export function removeQuickChatSessionsForTask( + state: QuickChatState, + taskId: string, +): QuickChatState { + const remaining = state.sessions.filter((session) => session.taskId !== taskId); + if (remaining.length === state.sessions.length) return state; + return withValidActiveSession(state, remaining); +} + +/** + * Re-points `activeSessionId` when the tab it named is gone, mirroring what a + * local tab close does: fall back to another tab in the same workspace, and + * close the modal only when nothing is left to show. + */ +function withValidActiveSession( + state: QuickChatState, + sessions: QuickChatSession[], +): QuickChatState { + const active = state.activeSessionId; + // No tab was ever selected: leave it unset rather than silently promoting one + // on a background resync. Same invariant `hydrateUI` guards on. + if (!active) return { ...state, sessions }; + if (sessions.some((session) => session.sessionId === active)) { + return { ...state, sessions }; + } + const previousWorkspaceId = state.sessions.find( + (session) => session.sessionId === active, + )?.workspaceId; + const fallback = + sessions.find((session) => session.workspaceId === previousWorkspaceId) ?? sessions[0]; + return { + ...state, + sessions, + activeSessionId: fallback?.sessionId ?? null, + isOpen: fallback ? state.isOpen : false, + }; +} diff --git a/apps/web/lib/state/slices/ui/types.ts b/apps/web/lib/state/slices/ui/types.ts index 6fe05d531a..20249630c6 100644 --- a/apps/web/lib/state/slices/ui/types.ts +++ b/apps/web/lib/state/slices/ui/types.ts @@ -91,6 +91,8 @@ export type QuickChatSession = { kind: QuickChatSessionKind; sessionId: string; workspaceId: string; + /** Backing ephemeral task. Absent only on unstarted "New chat" setup tabs. */ + taskId?: string; name?: string; agentProfileId?: string; initialPrompt?: string; @@ -231,17 +233,25 @@ export type UISliceActions = { workspaceId: string, agentProfileId?: string, kind?: QuickChatSessionKind, + taskId?: string, ) => void; addQuickChatSession: ( sessionId: string, workspaceId: string, agentProfileId?: string, kind?: QuickChatSessionKind, + taskId?: string, ) => void; closeQuickChat: () => void; closeQuickChatSession: (sessionId: string) => void; setActiveQuickChatSession: (sessionId: string, workspaceId: string) => void; renameQuickChatSession: (sessionId: string, name: string) => void; + /** Replaces a workspace's quick-chat tabs with the server's authoritative list. */ + syncQuickChatSessions: (workspaceId: string, sessions: QuickChatSession[]) => void; + /** Adds or updates a tab observed on the wire, without stealing focus. */ + upsertQuickChatSessionFromEvent: (session: QuickChatSession) => void; + /** Drops tabs whose backing task was deleted (possibly on another device). */ + removeQuickChatSessionsForTask: (taskId: string) => void; setQuickChatInitialPrompt: (sessionId: string, prompt?: string) => void; setSessionFailureNotification: (n: SessionFailureNotification | null) => void; setTaskDeletedNotification: (n: TaskDeletedNotification | null) => void; diff --git a/apps/web/lib/state/slices/ui/ui-slice.ts b/apps/web/lib/state/slices/ui/ui-slice.ts index 0b001c6709..0b33ee67ac 100644 --- a/apps/web/lib/state/slices/ui/ui-slice.ts +++ b/apps/web/lib/state/slices/ui/ui-slice.ts @@ -3,7 +3,6 @@ import { getStoredCollapsedSubtaskParents, setLocalStorage, setStoredCollapsedSubtaskParents, - setStoredQuickChatName, setStoredAutoScrollEnabled, setStoredAutoScrollTop, } from "@/lib/local-storage"; @@ -19,8 +18,13 @@ import { buildSidebarViewActions } from "./sidebar-view-actions"; import { DEFAULT_VIEW } from "./sidebar-view-builtins"; import type { SidebarView, SortSpec } from "./sidebar-view-types"; import type { SystemHealthResponse } from "@/lib/types/health"; -import type { ActiveDocument, UISlice, UISliceState } from "./types"; +import type { ActiveDocument, QuickChatSession, UISlice, UISliceState } from "./types"; import { getQuickChatSetupSessionId } from "./quick-chat-session"; +import { + reconcileQuickChatSessions, + removeQuickChatSessionsForTask, + upsertQuickChatSession, +} from "./quick-chat-sync"; /** Default sidebar view state: the single built-in "All tasks" view, active, no draft. */ function createDefaultSidebarState(): UISliceState["sidebarViews"] { @@ -307,6 +311,7 @@ function buildOpenQuickChatAction(set: ImmerSet) { workspaceId: string, agentProfileId?: string, kind: "chat" | "config" = "chat", + taskId?: string, ) => set((draft) => { if (!sessionId) { @@ -331,8 +336,9 @@ function buildOpenQuickChatAction(set: ImmerSet) { if (existing) { if (existing.workspaceId !== workspaceId) return; if (agentProfileId) existing.agentProfileId = agentProfileId; + if (taskId) existing.taskId = taskId; } else { - draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind }); + draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind, taskId }); } draft.quickChat.isOpen = true; draft.quickChat.activeSessionId = sessionId; @@ -347,6 +353,7 @@ function buildQuickChatActions(set: ImmerSet) { workspaceId: string, agentProfileId?: string, kind: "chat" | "config" = "chat", + taskId?: string, ) => set((draft) => { const activeWorkspaceId = draft.quickChat.sessions.find( @@ -360,8 +367,9 @@ function buildQuickChatActions(set: ImmerSet) { if (existing) { if (existing.workspaceId !== workspaceId) return; if (agentProfileId) existing.agentProfileId = agentProfileId; + if (taskId) existing.taskId = taskId; } else { - draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind }); + draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind, taskId }); } if (shouldActivate) draft.quickChat.activeSessionId = sessionId; }), @@ -391,17 +399,25 @@ function buildQuickChatActions(set: ImmerSet) { if (!session || session.workspaceId !== workspaceId) return; draft.quickChat.activeSessionId = sessionId; }), - renameQuickChatSession: (sessionId: string, name: string) => { - let renamed = false; + // Optimistic only. Persisting the name is `persistQuickChatRename`'s job, + // so the backing task title stays the shared source of truth. + renameQuickChatSession: (sessionId: string, name: string) => set((draft) => { const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId); - if (session) { - session.name = name; - renamed = true; - } - }); - if (renamed) setStoredQuickChatName(sessionId, name); - }, + if (session) session.name = name; + }), + syncQuickChatSessions: (workspaceId: string, sessions: QuickChatSession[]) => + set((draft) => { + draft.quickChat = reconcileQuickChatSessions(draft.quickChat, workspaceId, sessions); + }), + upsertQuickChatSessionFromEvent: (session: QuickChatSession) => + set((draft) => { + draft.quickChat = upsertQuickChatSession(draft.quickChat, session); + }), + removeQuickChatSessionsForTask: (taskId: string) => + set((draft) => { + draft.quickChat = removeQuickChatSessionsForTask(draft.quickChat, taskId); + }), setQuickChatInitialPrompt: (sessionId: string, prompt?: string) => set((draft) => { const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId); diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts index f18e129dcd..2c9daaae70 100644 --- a/apps/web/lib/state/store.ts +++ b/apps/web/lib/state/store.ts @@ -332,13 +332,11 @@ export type AppState = KanbanSlice & { setSystemHealth: (response: SystemHealthResponse) => void; setSystemHealthLoading: (loading: boolean) => void; invalidateSystemHealth: () => void; - openQuickChat: ( - sessionId: string, - workspaceId: string, - agentProfileId?: string, - kind?: UISliceTypes.QuickChatSessionKind, - ) => void; + openQuickChat: UIA["openQuickChat"]; addQuickChatSession: UIA["addQuickChatSession"]; + syncQuickChatSessions: UIA["syncQuickChatSessions"]; + upsertQuickChatSessionFromEvent: UIA["upsertQuickChatSessionFromEvent"]; + removeQuickChatSessionsForTask: UIA["removeQuickChatSessionsForTask"]; closeQuickChat: () => void; closeQuickChatSession: (sessionId: string) => void; setActiveQuickChatSession: (sessionId: string, workspaceId: string) => void; diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index a9831653ae..809fba26d1 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -74,6 +74,7 @@ export type KanbanUpdatePayload = { export type TaskEventPayload = { task_id: string; + workspace_id?: string; workflow_id: string; old_workflow_id?: string | null; workflow_step_id: string; @@ -106,6 +107,8 @@ export type TaskEventPayload = { archived_at?: string | null; updated_at?: string; is_ephemeral: boolean; + /** Task origin (e.g. "manual", "automation_run"). */ + origin?: string; parent_id?: string | null; metadata?: Record | null; /** Deletion reason on task.deleted (e.g. "pr_approved_by_user"). Absent otherwise. */ diff --git a/apps/web/lib/ws/handlers/quick-chat.test.ts b/apps/web/lib/ws/handlers/quick-chat.test.ts new file mode 100644 index 0000000000..0dd771e974 --- /dev/null +++ b/apps/web/lib/ws/handlers/quick-chat.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect, vi } from "vitest"; +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { TaskEventPayload } from "@/lib/types/backend"; +import { quickChatSessionFromTaskEvent, syncQuickChatFromTaskEvent } from "./quick-chat"; + +function payload(overrides: Partial = {}): TaskEventPayload { + return { + task_id: "task-1", + workspace_id: "ws-1", + workflow_id: "", + workflow_step_id: "", + title: "Claude - Chat 1", + is_ephemeral: true, + primary_session_id: "session-1", + metadata: { agent_profile_id: "agent-1" }, + ...overrides, + } as TaskEventPayload; +} + +function makeStore() { + const upsertQuickChatSessionFromEvent = vi.fn(); + const removeQuickChatSessionsForTask = vi.fn(); + return { + store: { + getState: () => ({ upsertQuickChatSessionFromEvent, removeQuickChatSessionsForTask }), + } as unknown as StoreApi, + upsertQuickChatSessionFromEvent, + removeQuickChatSessionsForTask, + }; +} + +describe("quickChatSessionFromTaskEvent", () => { + it("maps a quick-chat task event onto a tab", () => { + expect(quickChatSessionFromTaskEvent(payload())).toEqual({ + kind: "chat", + sessionId: "session-1", + workspaceId: "ws-1", + taskId: "task-1", + name: "Claude - Chat 1", + agentProfileId: "agent-1", + }); + }); + + it("marks a config-mode task as a config tab", () => { + const session = quickChatSessionFromTaskEvent( + payload({ metadata: { config_mode: true, agent_profile_id: "agent-1" } }), + ); + + expect(session?.kind).toBe("config"); + }); + + it("leaves the placeholder title unnamed so the tab falls back to its default", () => { + expect(quickChatSessionFromTaskEvent(payload({ title: "Quick Chat" }))?.name).toBeUndefined(); + }); + + it.each([ + ["a non-ephemeral task", { is_ephemeral: false }], + ["a workflow-bound ephemeral task", { workflow_id: "wf-1" }], + ["an automation run", { origin: "automation_run" }], + ["a task with no primary session yet", { primary_session_id: null }], + ["an event without a workspace", { workspace_id: undefined }], + ])("ignores %s", (_label, overrides) => { + expect(quickChatSessionFromTaskEvent(payload(overrides))).toBeNull(); + }); +}); + +describe("syncQuickChatFromTaskEvent", () => { + it("upserts a quick chat observed on the wire", () => { + const { store, upsertQuickChatSessionFromEvent } = makeStore(); + + syncQuickChatFromTaskEvent(store, payload()); + + expect(upsertQuickChatSessionFromEvent).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: "session-1", taskId: "task-1" }), + ); + }); + + it("removes the tab when the quick chat is archived", () => { + const { store, upsertQuickChatSessionFromEvent, removeQuickChatSessionsForTask } = makeStore(); + + syncQuickChatFromTaskEvent(store, payload({ archived_at: "2026-07-30T12:00:00Z" })); + + expect(removeQuickChatSessionsForTask).toHaveBeenCalledWith("task-1"); + expect(upsertQuickChatSessionFromEvent).not.toHaveBeenCalled(); + }); + + it("does nothing for an ephemeral task that is not a quick chat", () => { + const { store, upsertQuickChatSessionFromEvent } = makeStore(); + + syncQuickChatFromTaskEvent(store, payload({ workflow_id: "wf-1" })); + + expect(upsertQuickChatSessionFromEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/lib/ws/handlers/quick-chat.ts b/apps/web/lib/ws/handlers/quick-chat.ts new file mode 100644 index 0000000000..9cd7fbe380 --- /dev/null +++ b/apps/web/lib/ws/handlers/quick-chat.ts @@ -0,0 +1,62 @@ +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { QuickChatSession } from "@/lib/state/slices/ui/types"; +import type { TaskEventPayload } from "@/lib/types/backend"; + +const QUICK_CHAT_PLACEHOLDER_TITLE = "Quick Chat"; + +function readMetadataString( + metadata: Record | null | undefined, + key: string, +): string | undefined { + const value = metadata?.[key]; + return typeof value === "string" && value ? value : undefined; +} + +/** + * Maps a task lifecycle event onto a quick-chat tab, or null when the task does + * not back one. + * + * Mirrors the backend's restorable-quick-chat rules (see + * `IsRestorableQuickChatTask`): ephemeral, not workflow-bound, not an + * automation run. A task with no primary session yet is skipped — the tab is + * keyed by session id, and a later event carries it once the agent launches. + */ +export function quickChatSessionFromTaskEvent(payload: TaskEventPayload): QuickChatSession | null { + if (!payload.is_ephemeral) return null; + if (payload.workflow_id) return null; + if (payload.origin === "automation_run") return null; + const sessionId = payload.primary_session_id; + const workspaceId = payload.workspace_id; + if (!sessionId || !workspaceId) return null; + + const configMode = payload.metadata?.config_mode === true; + return { + kind: configMode ? "config" : "chat", + sessionId, + workspaceId, + taskId: payload.task_id, + name: + payload.title && payload.title !== QUICK_CHAT_PLACEHOLDER_TITLE ? payload.title : undefined, + agentProfileId: readMetadataString(payload.metadata, "agent_profile_id"), + }; +} + +/** + * Reflects a quick chat started (or renamed) on another device into this + * client's tab strip. Ephemeral tasks are skipped by the kanban handlers, so + * without this a quick chat only ever existed on the device that created it. + */ +export function syncQuickChatFromTaskEvent( + store: StoreApi, + payload: TaskEventPayload, +): void { + // An archived quick chat is gone from the tab strip just like a deleted one. + if (payload.archived_at) { + store.getState().removeQuickChatSessionsForTask(payload.task_id); + return; + } + const session = quickChatSessionFromTaskEvent(payload); + if (!session) return; + store.getState().upsertQuickChatSessionFromEvent(session); +} diff --git a/apps/web/lib/ws/handlers/tasks-archive.test.ts b/apps/web/lib/ws/handlers/tasks-archive.test.ts index 9826d594e4..b075a80862 100644 --- a/apps/web/lib/ws/handlers/tasks-archive.test.ts +++ b/apps/web/lib/ws/handlers/tasks-archive.test.ts @@ -29,6 +29,8 @@ function makeStore(initial: Partial = {}) { setActiveSessionAuto: vi.fn(), removeTaskFromSidebarPrefs: vi.fn(), setTaskDeletedNotification: vi.fn(), + upsertQuickChatSessionFromEvent: vi.fn(), + removeQuickChatSessionsForTask: vi.fn(), setOfficeRefetchTrigger: vi.fn(), ...initial, } as unknown as AppState; diff --git a/apps/web/lib/ws/handlers/tasks-quick-chat.test.ts b/apps/web/lib/ws/handlers/tasks-quick-chat.test.ts new file mode 100644 index 0000000000..df79cbdeec --- /dev/null +++ b/apps/web/lib/ws/handlers/tasks-quick-chat.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it, vi } from "vitest"; +import type { AppState } from "@/lib/state/store"; +import { registerTasksHandlers } from "./tasks"; +import { makeDeletedMessage, makeStore } from "./tasks.test-helpers"; + +vi.mock("@/lib/recent-tasks", () => ({ removeRecentTask: vi.fn() })); + +type Handlers = ReturnType; +type UpsertAction = "task.created" | "task.updated"; + +/** Dispatches an upsert event without narrowing the handler union to `never`. */ +function dispatchUpsert( + handlers: Handlers, + action: UpsertAction, + payload: Record, +) { + const handler = handlers[action] as ((message: unknown) => void) | undefined; + handler?.({ id: "msg-1", type: "notification", action, payload }); +} + +const QUICK_CHAT_PAYLOAD = { + task_id: "qc-task", + workspace_id: "ws-1", + workflow_id: "", + workflow_step_id: "", + title: "Claude - Chat 1", + is_ephemeral: true, + primary_session_id: "qc-session", + metadata: { agent_profile_id: "agent-1" }, +}; + +/** + * Quick chats are ephemeral tasks, which the kanban handlers deliberately skip. + * These pin that they are still routed into the shared tab strip — without it a + * quick chat only ever exists on the device that created it. + */ +describe("task lifecycle events drive the quick-chat tab strip", () => { + it.each(["task.created", "task.updated"] as const)( + "%s adds a quick chat started on another device", + (action) => { + const store = makeStore(); + const handlers = registerTasksHandlers(store); + + dispatchUpsert(handlers, action, QUICK_CHAT_PAYLOAD); + + expect(store.getState().upsertQuickChatSessionFromEvent).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: "qc-session", taskId: "qc-task" }), + ); + }, + ); + + it("keeps quick chats off the kanban board", () => { + const store = makeStore(); + const handlers = registerTasksHandlers(store); + + dispatchUpsert(handlers, "task.created", QUICK_CHAT_PAYLOAD); + + expect(store.getState().kanban.tasks).toHaveLength(0); + }); + + it("task.deleted drops the tab for a quick chat closed elsewhere", () => { + const store = makeStore({ environmentIdBySessionId: {} } as unknown as Partial); + const handlers = registerTasksHandlers(store); + + handlers["task.deleted"]?.(makeDeletedMessage({ task_id: "qc-task" })); + + expect(store.getState().removeQuickChatSessionsForTask).toHaveBeenCalledWith("qc-task"); + }); +}); diff --git a/apps/web/lib/ws/handlers/tasks-walkthrough-cleanup.test.ts b/apps/web/lib/ws/handlers/tasks-walkthrough-cleanup.test.ts index c5e288b948..9871e7dd2b 100644 --- a/apps/web/lib/ws/handlers/tasks-walkthrough-cleanup.test.ts +++ b/apps/web/lib/ws/handlers/tasks-walkthrough-cleanup.test.ts @@ -39,6 +39,8 @@ function makeStore() { }, removeTaskFromSidebarPrefs: vi.fn(), setTaskDeletedNotification: vi.fn(), + upsertQuickChatSessionFromEvent: vi.fn(), + removeQuickChatSessionsForTask: vi.fn(), } as unknown as AppState; const listeners = new Set(); diff --git a/apps/web/lib/ws/handlers/tasks.test-helpers.ts b/apps/web/lib/ws/handlers/tasks.test-helpers.ts index dd95fe5f0c..f22e906de6 100644 --- a/apps/web/lib/ws/handlers/tasks.test-helpers.ts +++ b/apps/web/lib/ws/handlers/tasks.test-helpers.ts @@ -47,6 +47,8 @@ export function makeStore(initial: Partial = {}) { }), removeTaskFromSidebarPrefs: vi.fn(), setTaskDeletedNotification: vi.fn(), + upsertQuickChatSessionFromEvent: vi.fn(), + removeQuickChatSessionsForTask: vi.fn(), ...initial, } as unknown as AppState; diff --git a/apps/web/lib/ws/handlers/tasks.ts b/apps/web/lib/ws/handlers/tasks.ts index a0e6cb8a07..56726f0971 100644 --- a/apps/web/lib/ws/handlers/tasks.ts +++ b/apps/web/lib/ws/handlers/tasks.ts @@ -15,6 +15,7 @@ import { clearPinnedSessionIfOverridden, shouldPreservePinnedSessionForTask, } from "@/lib/ws/handlers/agent-session"; +import { syncQuickChatFromTaskEvent } from "@/lib/ws/handlers/quick-chat"; type KanbanTask = KanbanState["tasks"][number]; const lifecycleDebug = createDebugLogger("task-lifecycle:ws"); @@ -344,8 +345,12 @@ type TaskUpsertMessage = TaskCreatedMessage | TaskStateChangedMessage; type TaskUpsertAction = "task.created" | "task.state_changed"; function handleTaskUpdated(store: StoreApi, message: TaskUpdatedMessage): void { - // Skip ephemeral tasks (e.g., quick chat) - they shouldn't appear on the Kanban board - if (message.payload.is_ephemeral) return; + // Ephemeral tasks never reach the Kanban board, but quick chats are shared + // across devices — mirror them into the tab strip before bailing out. + if (message.payload.is_ephemeral) { + syncQuickChatFromTaskEvent(store, message.payload); + return; + } // Capture the previous primary session id BEFORE the upsert so we can // detect a primary-session swap (e.g. workflow profile switch reusing a @@ -415,8 +420,11 @@ function handleTaskUpsert( store: StoreApi, message: TaskUpsertMessage, ): void { - // Skip ephemeral tasks (e.g., quick chat) - they shouldn't appear on the Kanban board - if (message.payload.is_ephemeral) return; + // See handleTaskUpdated: off the board, but still a quick-chat tab. + if (message.payload.is_ephemeral) { + syncQuickChatFromTaskEvent(store, message.payload); + return; + } const beforeState = store.getState(); store.setState((state) => @@ -434,6 +442,9 @@ export function registerTasksHandlers(store: StoreApi): WsHandlers { "task.deleted": (message) => { const deletedId = message.payload.task_id; removeRecentTask(deletedId); + // A quick chat closed on another device must not linger here as a tab + // pointing at a task the backend already deleted. + store.getState().removeQuickChatSessionsForTask(deletedId); const currentState = store.getState(); const sessionIds = (currentState.taskSessionsByTask.itemsByTaskId[deletedId] ?? []).map( diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts index 5f60d7caaa..8934208956 100644 --- a/apps/web/vitest.config.ts +++ b/apps/web/vitest.config.ts @@ -22,7 +22,10 @@ export default mergeConfig( }, }, setupFiles: ["./vitest.setup.ts"], - exclude: ["e2e/**", "node_modules/**"], + // `e2e/**/*.spec.ts` belongs to Playwright, but plain unit tests for the + // e2e helpers themselves (`*.test.ts`) still run here — excluding the + // whole tree would let them sit in the repo without ever executing. + exclude: ["e2e/**/*.spec.ts", "e2e/fixtures/**", "e2e/pages/**", "node_modules/**"], pool: "threads", maxWorkers, }, diff --git a/docs/public/developer-tools.md b/docs/public/developer-tools.md index f0ccf7e2d8..53cfdf2cc1 100644 --- a/docs/public/developer-tools.md +++ b/docs/public/developer-tools.md @@ -39,6 +39,8 @@ Each selected repository gets an isolated worktree from the chosen branch. Uncom Quick Chat supports multiple tabs, tab renaming, and **+** to open another ordinary-chat setup. Structured profiles show ACP chat; CLI-passthrough profiles show their PTY interface. The desktop window is resizable, while mobile uses a full-screen view. +Your chats and their names are shared by every browser and device signed in to the same Kandev instance. Starting, renaming, or closing a chat on one device updates the others, and a device that was offline catches up when it reconnects. + Closing a real chat tab permanently deletes its conversation, hidden backing task data, and associated worktree. There is no undo. Kandev also deletes abandoned chats after seven days; cleanup runs when the backend starts and then once per day. Only chats whose session is `RUNNING` or `IDLE` are protected from age-based cleanup. Old `CREATED`, `STARTING`, or `WAITING_FOR_INPUT` chats can expire, so do not use Quick Chat for durable work. If **Start chat** is disabled, select a profile and finish every repository/branch row. If a repository is missing, confirm that it belongs to the current workspace and refresh the repository configuration. Use a normal task when the result must remain visible on a board or become a reviewed PR.